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 length m + 1.
  • col_indices, an array of integers with length nnz.
  • values, an array of values with length nnz.

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 in col_indices that holds the column indices in row i.
  • For an entry represented by the index idx, col_indices[idx] stores its column index and values[idx] stores its value.

The following invariants must be upheld and are enforced by the data structure:

  • row_offsets[0] == 0
  • row_offsets[m] == nnz
  • row_offsets is monotonically increasing.
  • 0 <= col_indices[idx] < n for all idx < 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.

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 rows in the matrix.

The number of columns in the matrix.

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.

The non-zero values defining part of the CSR format.

Mutable access to the non-zero values.

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)]);

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.

Panics

Panics if row index is out of bounds.

Mutable row access for the given row index.

Panics

Panics if row index is out of bounds.

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.

An iterator over rows in the matrix.

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.

pub fn get_entry(
    &self,
    row_index: usize,
    col_index: usize
) -> Option<SparseEntry<'_, T>>

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>>

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.

pub fn index_entry(
    &self,
    row_index: usize,
    col_index: usize
) -> SparseEntry<'_, T>

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>

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.

Compute the transpose of the matrix.

Trait Implementations

The resulting type after applying the + operator.

Performs the + operation. Read more

The resulting type after applying the + operator.

Performs the + operation. Read more

The resulting type after applying the + operator.

Performs the + operation. Read more

The resulting type after applying the + operator.

Performs the + operation. Read more

Returns a copy of the value. Read more

Performs copy-assignment from source. Read more

Formats the value using the given formatter. Read more

The resulting type after applying the / operator.

Performs the / operation. Read more

The resulting type after applying the / operator.

Performs the / operation. Read more

The resulting type after applying the / operator.

Performs the / operation. Read more

The resulting type after applying the / operator.

Performs the / operation. Read more

Performs the /= operation. Read more

Performs the /= operation. Read more

Performs the conversion.

Performs the conversion.

Performs the conversion.

Performs the conversion.

Performs the conversion.

Performs the conversion.

Expose dense or sparse access to the matrix.

The resulting type after applying the * operator.

Performs the * operation. Read more

The resulting type after applying the * operator.

Performs the * operation. Read more

The resulting type after applying the * operator.

Performs the * operation. Read more

The resulting type after applying the * operator.

Performs the * operation. Read more

The resulting type after applying the * operator.

Performs the * operation. Read more

The resulting type after applying the * operator.

Performs the * operation. Read more

The resulting type after applying the * operator.

Performs the * operation. Read more

The resulting type after applying the * operator.

Performs the * operation. Read more

The resulting type after applying the * operator.

Performs the * operation. Read more

The resulting type after applying the * operator.

Performs the * operation. Read more

The resulting type after applying the * operator.

Performs the * operation. Read more

The resulting type after applying the * operator.

Performs the * operation. Read more

The resulting type after applying the * operator.

Performs the * operation. Read more

The resulting type after applying the * operator.

Performs the * operation. Read more

The resulting type after applying the * operator.

Performs the * operation. Read more

The resulting type after applying the * operator.

Performs the * operation. Read more

The resulting type after applying the * operator.

Performs the * operation. Read more

The resulting type after applying the * operator.

Performs the * operation. Read more

The resulting type after applying the * operator.

Performs the * operation. Read more

The resulting type after applying the * operator.

Performs the * operation. Read more

The resulting type after applying the * operator.

Performs the * operation. Read more

The resulting type after applying the * operator.

Performs the * operation. Read more

The resulting type after applying the * operator.

Performs the * operation. Read more

The resulting type after applying the * operator.

Performs the * operation. Read more

The resulting type after applying the * operator.

Performs the * operation. Read more

The resulting type after applying the * operator.

Performs the * operation. Read more

The resulting type after applying the * operator.

Performs the * operation. Read more

The resulting type after applying the * operator.

Performs the * operation. Read more

The resulting type after applying the * operator.

Performs the * operation. Read more

The resulting type after applying the * operator.

Performs the * operation. Read more

The resulting type after applying the * operator.

Performs the * operation. Read more

The resulting type after applying the * operator.

Performs the * operation. Read more

The resulting type after applying the * operator.

Performs the * operation. Read more

The resulting type after applying the * operator.

Performs the * operation. Read more

The resulting type after applying the * operator.

Performs the * operation. Read more

The resulting type after applying the * operator.

Performs the * operation. Read more

The resulting type after applying the * operator.

Performs the * operation. Read more

The resulting type after applying the * operator.

Performs the * operation. Read more

The resulting type after applying the * operator.

Performs the * operation. Read more

The resulting type after applying the * operator.

Performs the * operation. Read more

Performs the *= operation. Read more

Performs the *= operation. Read more

The resulting type after applying the - operator.

Performs the unary - operation. Read more

The resulting type after applying the - operator.

Performs the unary - operation. Read more

This method tests for self and other values to be equal, and is used by ==. Read more

This method tests for !=.

Number of non-zero elements in the matrix.

Retrieve the triplets that identify the coefficients of the sparse matrix.

The resulting type after applying the - operator.

Performs the - operation. Read more

The resulting type after applying the - operator.

Performs the - operation. Read more

The resulting type after applying the - operator.

Performs the - operation. Read more

The resulting type after applying the - operator.

Performs the - operation. Read more

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

Performs the conversion.

Performs the conversion.

Should always be Self

The inverse inclusion map: attempts to construct self from the equivalent element of its superset. Read more

Checks if self is actually part of its subset T (and can be converted to it).

Use with care! Same as self.to_subset but without any property checks. Always succeeds.

The inclusion map: converts self to the equivalent element of its superset.

The resulting type after obtaining ownership.

Creates owned data from borrowed data, usually by cloning. Read more

🔬 This is a nightly-only experimental API. (toowned_clone_into)

recently added

Uses borrowed data to replace owned data, usually by cloning. Read more

The type returned in the event of a conversion error.

Performs the conversion.

The type returned in the event of a conversion error.

Performs the conversion.