CsrArray

Struct CsrArray 

Source
pub struct CsrArray<T>
where T: Float + Add<Output = T> + Sub<Output = T> + Mul<Output = T> + Div<Output = T> + Debug + Copy + 'static,
{ /* private fields */ }
Expand description

CSR Array format - Compressed Sparse Row matrix representation

The CSR (Compressed Sparse Row) format is one of the most popular sparse matrix formats, storing a sparse array using three arrays:

  • data: array of non-zero values in row-major order
  • indices: column indices of the non-zero values
  • indptr: row pointers; indptr[i] is the index into data/indices where row i starts

The CSR format is particularly efficient for:

  • ✅ Matrix-vector multiplications (A * x)
  • ✅ Matrix-matrix multiplications with other sparse matrices
  • ✅ Row-wise operations and row slicing
  • ✅ Iterating over non-zero elements row by row
  • ✅ Adding and subtracting sparse matrices

But less efficient for:

  • ❌ Column-wise operations and column slicing
  • ❌ Inserting or modifying individual elements after construction
  • ❌ Operations that require column access patterns

§Memory Layout

For a matrix with m rows, n columns, and nnz non-zero elements:

  • data: length nnz - stores the actual non-zero values
  • indices: length nnz - stores column indices for each non-zero value
  • indptr: length m+1 - stores cumulative count of non-zeros per row

§Examples

§Basic Construction and Access

use scirs2_sparse::csr_array::CsrArray;
use scirs2_sparse::SparseArray;

// Create a 3x3 matrix:
// [1.0, 0.0, 2.0]
// [0.0, 3.0, 0.0]
// [4.0, 0.0, 5.0]
let rows = vec![0, 0, 1, 2, 2];
let cols = vec![0, 2, 1, 0, 2];
let data = vec![1.0, 2.0, 3.0, 4.0, 5.0];
let matrix = CsrArray::from_triplets(&rows, &cols, &data, (3, 3), false).unwrap();

// Access elements
assert_eq!(matrix.get(0, 0), 1.0);
assert_eq!(matrix.get(0, 1), 0.0);  // Zero element
assert_eq!(matrix.get(1, 1), 3.0);

// Get matrix properties
assert_eq!(matrix.shape(), (3, 3));
assert_eq!(matrix.nnz(), 5);

§Matrix Operations

use scirs2_sparse::csr_array::CsrArray;
use scirs2_sparse::SparseArray;
use ndarray::Array1;

let rows = vec![0, 1, 2];
let cols = vec![0, 1, 2];
let data = vec![2.0, 3.0, 4.0];
let matrix = CsrArray::from_triplets(&rows, &cols, &data, (3, 3), false).unwrap();

// Matrix-vector multiplication
let x = Array1::from_vec(vec![1.0, 2.0, 3.0]);
let y = matrix.dot_vector(&x.view()).unwrap();
assert_eq!(y[0], 2.0);  // 2.0 * 1.0
assert_eq!(y[1], 6.0);  // 3.0 * 2.0
assert_eq!(y[2], 12.0); // 4.0 * 3.0

§Format Conversion

use scirs2_sparse::csr_array::CsrArray;
use scirs2_sparse::SparseArray;

let rows = vec![0, 1];
let cols = vec![0, 1];
let data = vec![1.0, 2.0];
let csr = CsrArray::from_triplets(&rows, &cols, &data, (2, 2), false).unwrap();

// Convert to dense array
let dense = csr.to_array();
assert_eq!(dense[[0, 0]], 1.0);
assert_eq!(dense[[1, 1]], 2.0);

// Convert to other sparse formats
let coo = csr.to_coo();
let csc = csr.to_csc();

Implementations§

Source§

impl<T> CsrArray<T>
where T: Float + Add<Output = T> + Sub<Output = T> + Mul<Output = T> + Div<Output = T> + Debug + Copy + 'static,

Source

pub fn new( data: Array1<T>, indices: Array1<usize>, indptr: Array1<usize>, shape: (usize, usize), ) -> SparseResult<Self>

Creates a new CSR array from raw components

§Arguments
  • data - Array of non-zero values
  • indices - Column indices of non-zero values
  • indptr - Index pointers for the start of each row
  • shape - Shape of the sparse array
§Returns

A new CsrArray

§Errors

Returns an error if the data is not consistent

Source

pub fn from_triplets( rows: &[usize], cols: &[usize], data: &[T], shape: (usize, usize), sorted: bool, ) -> SparseResult<Self>

Create a CSR array from triplet format (COO-like)

This function creates a CSR (Compressed Sparse Row) array from coordinate triplets. The triplets represent non-zero elements as (row, column, value) tuples.

§Arguments
  • rows - Row indices of non-zero elements
  • cols - Column indices of non-zero elements
  • data - Values of non-zero elements
  • shape - Shape of the sparse array (nrows, ncols)
  • sorted - Whether the triplets are already sorted by (row, col). If false, sorting will be performed.
§Returns

A new CsrArray containing the sparse matrix

§Errors

Returns an error if:

  • rows, cols, and data have different lengths
  • Any index is out of bounds for the given shape
  • The resulting data structure is inconsistent
§Examples

Create a simple 3x3 sparse matrix:

use scirs2_sparse::csr_array::CsrArray;
use scirs2_sparse::SparseArray;

// Create a 3x3 matrix with the following structure:
// [1.0, 0.0, 2.0]
// [0.0, 3.0, 0.0]
// [4.0, 0.0, 5.0]
let rows = vec![0, 0, 1, 2, 2];
let cols = vec![0, 2, 1, 0, 2];
let data = vec![1.0, 2.0, 3.0, 4.0, 5.0];
let shape = (3, 3);

let matrix = CsrArray::from_triplets(&rows, &cols, &data, shape, false).unwrap();
assert_eq!(matrix.get(0, 0), 1.0);
assert_eq!(matrix.get(0, 1), 0.0);
assert_eq!(matrix.get(1, 1), 3.0);

Create an empty sparse matrix:

use scirs2_sparse::csr_array::CsrArray;
use scirs2_sparse::SparseArray;

let rows: Vec<usize> = vec![];
let cols: Vec<usize> = vec![];
let data: Vec<f64> = vec![];
let shape = (5, 5);

let matrix = CsrArray::from_triplets(&rows, &cols, &data, shape, false).unwrap();
assert_eq!(matrix.nnz(), 0);
assert_eq!(matrix.shape(), (5, 5));

Handle duplicate entries (they will be preserved):

use scirs2_sparse::csr_array::CsrArray;
use scirs2_sparse::SparseArray;

// Multiple entries at the same position
let rows = vec![0, 0];
let cols = vec![0, 0];
let data = vec![1.0, 2.0];
let shape = (2, 2);

let matrix = CsrArray::from_triplets(&rows, &cols, &data, shape, false).unwrap();
// Note: CSR format preserves duplicates; use sum_duplicates() to combine them
assert_eq!(matrix.nnz(), 2);
Source

pub fn get_data(&self) -> &Array1<T>

Get the raw data array

Source

pub fn get_indices(&self) -> &Array1<usize>

Get the raw indices array

Source

pub fn get_indptr(&self) -> &Array1<usize>

Get the raw indptr array

Source

pub fn nrows(&self) -> usize

Get the number of rows

Source

pub fn ncols(&self) -> usize

Get the number of columns

Source

pub fn shape(&self) -> (usize, usize)

Get the shape (rows, cols)

Trait Implementations§

Source§

impl<F: Float + NumAssign + Sum + 'static + Debug> AsLinearOperator<F> for CsrArray<F>

Source§

fn as_linear_operator(&self) -> Box<dyn LinearOperator<F>>

Convert to a linear operator
Source§

impl<T> Clone for CsrArray<T>
where T: Float + Add<Output = T> + Sub<Output = T> + Mul<Output = T> + Div<Output = T> + Debug + Copy + 'static + Clone,

Source§

fn clone(&self) -> CsrArray<T>

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<T> Debug for CsrArray<T>
where T: Float + Add<Output = T> + Sub<Output = T> + Mul<Output = T> + Div<Output = T> + Debug + Copy + 'static,

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<T> SparseArray<T> for CsrArray<T>
where T: Float + Add<Output = T> + Sub<Output = T> + Mul<Output = T> + Div<Output = T> + Debug + Copy + 'static,

Source§

fn shape(&self) -> (usize, usize)

Returns the shape of the sparse array.
Source§

fn nnz(&self) -> usize

Returns the number of stored (non-zero) elements.
Source§

fn dtype(&self) -> &str

Returns the data type of the sparse array.
Source§

fn to_array(&self) -> Array2<T>

Returns a view of the sparse array as a dense ndarray.
Source§

fn toarray(&self) -> Array2<T>

Returns a dense copy of the sparse array.
Source§

fn to_coo(&self) -> SparseResult<Box<dyn SparseArray<T>>>

Returns a sparse array in COO format.
Source§

fn to_csr(&self) -> SparseResult<Box<dyn SparseArray<T>>>

Returns a sparse array in CSR format.
Source§

fn to_csc(&self) -> SparseResult<Box<dyn SparseArray<T>>>

Returns a sparse array in CSC format.
Source§

fn to_dok(&self) -> SparseResult<Box<dyn SparseArray<T>>>

Returns a sparse array in DOK format.
Source§

fn to_lil(&self) -> SparseResult<Box<dyn SparseArray<T>>>

Returns a sparse array in LIL format.
Source§

fn to_dia(&self) -> SparseResult<Box<dyn SparseArray<T>>>

Returns a sparse array in DIA format.
Source§

fn to_bsr(&self) -> SparseResult<Box<dyn SparseArray<T>>>

Returns a sparse array in BSR format.
Source§

fn add( &self, other: &dyn SparseArray<T>, ) -> SparseResult<Box<dyn SparseArray<T>>>

Element-wise addition.
Source§

fn sub( &self, other: &dyn SparseArray<T>, ) -> SparseResult<Box<dyn SparseArray<T>>>

Element-wise subtraction.
Source§

fn mul( &self, other: &dyn SparseArray<T>, ) -> SparseResult<Box<dyn SparseArray<T>>>

Element-wise multiplication.
Source§

fn div( &self, other: &dyn SparseArray<T>, ) -> SparseResult<Box<dyn SparseArray<T>>>

Element-wise division.
Source§

fn dot( &self, other: &dyn SparseArray<T>, ) -> SparseResult<Box<dyn SparseArray<T>>>

Matrix multiplication.
Source§

fn dot_vector(&self, other: &ArrayView1<'_, T>) -> SparseResult<Array1<T>>

Matrix-vector multiplication.
Source§

fn transpose(&self) -> SparseResult<Box<dyn SparseArray<T>>>

Transpose the sparse array.
Source§

fn copy(&self) -> Box<dyn SparseArray<T>>

Return a copy of the sparse array with the specified elements.
Source§

fn get(&self, i: usize, j: usize) -> T

Get a value at the specified position.
Source§

fn set(&mut self, i: usize, j: usize, value: T) -> SparseResult<()>

Set a value at the specified position.
Source§

fn eliminate_zeros(&mut self)

Eliminate zeros from the sparse array.
Source§

fn sort_indices(&mut self)

Sort indices of the sparse array.
Source§

fn sorted_indices(&self) -> Box<dyn SparseArray<T>>

Return a sorted copy of this sparse array.
Source§

fn has_sorted_indices(&self) -> bool

Check if indices are sorted.
Source§

fn sum(&self, axis: Option<usize>) -> SparseResult<SparseSum<T>>

Sum the sparse array elements. Read more
Source§

fn max(&self) -> T

Compute the maximum value of the sparse array elements.
Source§

fn min(&self) -> T

Compute the minimum value of the sparse array elements.
Source§

fn find(&self) -> (Array1<usize>, Array1<usize>, Array1<T>)

Return the indices and values of the nonzero elements.
Source§

fn slice( &self, row_range: (usize, usize), col_range: (usize, usize), ) -> SparseResult<Box<dyn SparseArray<T>>>

Return a slice of the sparse array.
Source§

fn as_any(&self) -> &dyn Any

Returns the concrete type of the array for downcasting.
Source§

fn get_indptr(&self) -> Option<&Array1<usize>>

Returns the indptr array for CSR/CSC formats. For formats that don’t have indptr, returns None.
Source§

fn indptr(&self) -> Option<&Array1<usize>>

Returns the indptr array for CSR/CSC formats. For formats that don’t have indptr, returns None.

Auto Trait Implementations§

§

impl<T> Freeze for CsrArray<T>

§

impl<T> RefUnwindSafe for CsrArray<T>
where T: RefUnwindSafe,

§

impl<T> Send for CsrArray<T>
where T: Send,

§

impl<T> Sync for CsrArray<T>
where T: Sync,

§

impl<T> Unpin for CsrArray<T>

§

impl<T> UnwindSafe for CsrArray<T>
where T: RefUnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

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

fn clone_into(&self, target: &mut T)

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

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V