### Create Sparse Vectors Source: https://docs.rs/sprs/0.11.5/sprs/type.CsVecViewI.html Examples of creating owned, borrowing, and general sparse vectors using different storage types. ```rust // Creating a sparse owned vector let owned = CsVec::new(10, vec![0, 4], vec![-4, 2]); // Creating a sparse borrowing vector with `I = u16` let borrow = CsVecViewI::new(10, &[0_u16, 4], &[-4, 2]); // Creating a general sparse vector with different storage types let mixed = CsVecBase::new(10, &[0_u64, 4] as &[_], vec![-4, 2]); ``` -------------------------------- ### Asserting Option values Source: https://docs.rs/sprs/0.11.5/sprs/linalg/etree/type.Parent.html Example usage of assertions for Option values. ```rust assert_eq!(res, None); assert_eq!(shared, 6); ``` -------------------------------- ### Strategy::find_start_vertex Source: https://docs.rs/sprs/0.11.5/sprs/linalg/ordering/start/struct.PseudoPeripheral.html Finds a start vertex for the ordering strategy given the current state of the matrix and visited vertices. ```APIDOC ## fn find_start_vertex(&mut self, visited: &[bool], degrees: &[usize], mat: &CsMatViewI<'_, N, I, Iptr>) -> usize ### Description Finds a start vertex using the pseudoperipheral strategy. This function must be called with at least one unvisited vertex remaining. ### Parameters - **visited** (&[bool]) - A slice indicating which vertices have already been visited. - **degrees** (&[usize]) - A slice containing the degrees of the vertices. - **mat** (&CsMatViewI<'_, N, I, Iptr>) - A view of the sparse matrix. ### Returns - **usize** - The index of the found start vertex. ``` -------------------------------- ### Implement Strategy for Next Source: https://docs.rs/sprs/0.11.5/sprs/linalg/ordering/start/struct.Next.html The trait implementation for Next, defining the logic to find the next starting vertex. This function must be called with at least one unvisited vertex remaining. ```rust impl Strategy for Next where N: PartialEq, I: SpIndex, Iptr: SpIndex, { fn find_start_vertex( &mut self, visited: &[bool], _degrees: &[usize], _mat: &CsMatViewI<'_, N, I, Iptr>, ) -> usize } ``` -------------------------------- ### Define the Strategy trait Source: https://docs.rs/sprs/0.11.5/sprs/linalg/ordering/start/trait.Strategy.html The core trait definition for selecting a starting vertex, requiring an implementation of find_start_vertex. ```rust pub trait Strategy where N: PartialEq, I: SpIndex, Iptr: SpIndex, { // Required method fn find_start_vertex( &mut self, visited: &[bool], degrees: &[usize], mat: &CsMatViewI<'_, N, I, Iptr>, ) -> usize; } ``` -------------------------------- ### Tree Navigation and Query Methods Source: https://docs.rs/sprs/0.11.5/sprs/linalg/etree/type.ParentsOwned.html Methods for querying the structure of the tree, such as retrieving parents, checking for roots, and getting the total node count. ```APIDOC ### pub fn get_parent(&self, node: usize) -> Option Get the parent of a node. Returns None if the node is a root. Panics if node is out of bounds. ### pub fn is_root(&self, node: usize) -> bool Test whether a node is a root. Panics if node is out of bounds. ### pub fn nb_nodes(&self) -> usize The number of nodes in this tree. ``` -------------------------------- ### Get Threading Strategy Source: https://docs.rs/sprs/0.11.5/sprs/smmp/fn.thread_threading_strategy.html Returns the current ThreadingStrategy configuration. ```rust pub fn thread_threading_strategy() -> ThreadingStrategy ``` -------------------------------- ### get<'a>(&'a self, index: usize) Source: https://docs.rs/sprs/0.11.5/sprs/type.CsVecViewI.html Accesses an element at a specific index with logarithmic complexity. ```APIDOC ## pub fn get<'a>(&'a self, index: usize) -> Option<&'a N> ### Description Access element at given index, with logarithmic complexity. ``` -------------------------------- ### Access indptr view Source: https://docs.rs/sprs/0.11.5/sprs/type.CsMatViewI.html Retrieve the indptr view to access outer dimension offsets. This example demonstrates accessing row 3 of an identity matrix. ```rust use sprs::{CsMat}; let eye : CsMat = CsMat::eye(5); // get the element of row 3 // there is only one element in this row, with a column index of 3 // and a value of 1. let range = eye.indptr().outer_inds_sz(3); assert_eq!(range.start, 3); assert_eq!(range.end, 4); assert_eq!(eye.indices()[range.start], 3); assert_eq!(eye.data()[range.start], 1.); ``` -------------------------------- ### Construct Sparse Matrices with CsMatBase Source: https://docs.rs/sprs/0.11.5/sprs/type.CsMatViewI.html Demonstrates creating owned, borrowed, and mixed-storage sparse matrices using the CsMatBase constructor. ```rust // This creates an owned matrix let owned_matrix = CsMat::new((2, 2), vec![0, 1, 1], vec![1], vec![4_u8]); // This creates a matrix which only borrows the elements let borrow_matrix = CsMatView::new((2, 2), &[0, 1, 1], &[1], &[4_u8]); // A combination of storage types may also be used for a // general sparse matrix let mixed_matrix = CsMatBase::new((2, 2), &[0, 1, 1] as &[_], vec![1_i64].into_boxed_slice(), vec![4_u8]); ``` -------------------------------- ### FFI Usage with proper_indptr Source: https://docs.rs/sprs/0.11.5/sprs/struct.IndPtrBase.html Demonstrates the recommended approach for FFI using the proper_indptr method directly from CsMatBase. ```rust let mat: sprs::CsMat = sprs::CsMat::eye(5); let mid = mat.view().middle_outer_views(1, 2); let ptr = { let indptr_proper = mid.proper_indptr(); println!( "ptr {:?} is valid as long as _indptr_proper_owned is in scope", indptr_proper.as_ptr() ); indptr_proper.as_ptr() }; // This line is UB. // println!("ptr deref: {}", *ptr); ``` -------------------------------- ### Solve a linear system with BiCGSTAB Source: https://docs.rs/sprs/0.11.5/sprs/linalg/bicgstab/index.html Demonstrates solving a sparse linear system using the BiCGSTAB solver with specified tolerance and iteration limits. ```rust use sprs::{CsMatI, CsVecI}; use sprs::linalg::bicgstab::BiCGSTAB; let a = CsMatI::new_csc( (4, 4), vec![0, 2, 4, 6, 8], vec![0, 3, 1, 2, 1, 2, 0, 3], vec![1.0, 2., 21., 6., 6., 2., 2., 8.], ); // Solve Ax=b let tol = 1e-60; let max_iter = 50; let b = CsVecI::new(4, vec![0, 1, 2, 3], vec![1.0; 4]); let x0 = CsVecI::new(4, vec![0, 1, 2, 3], vec![1.0, 1.0, 1.0, 1.0]); let res = BiCGSTAB::<'_, f64, _, _>::solve( a.view(), x0.view(), b.view(), tol, max_iter, ) .unwrap(); let b_recovered = &a * &res.x(); println!("Iteration count {:?}", res.iteration_count()); println!("Soft restart count {:?}", res.soft_restart_count()); println!("Hard restart count {:?}", res.hard_restart_count()); // Make sure the solved values match expectation for (input, output) in b.to_dense().iter().zip(b_recovered.to_dense().iter()) { assert!( (1.0 - input / output).abs() < tol, "Solved output did not match input" ); } ``` -------------------------------- ### fn mm_display(&self) -> Displayable<&Self> Source: https://docs.rs/sprs/0.11.5/sprs/num_matrixmarket/trait.MatrixMarketDisplay.html Returns a Displayable wrapper for the current object, allowing it to be formatted for Matrix Market output. ```APIDOC ## fn mm_display(&self) -> Displayable<&Self> ### Description Creates a `Displayable` wrapper for the implementing type, which can then be used to format the object according to the Matrix Market specification. ### Signature `fn mm_display(&self) -> Displayable<&Self>` ### Returns - **Displayable<&Self>** - A wrapper object that implements the `Display` trait for Matrix Market formatting. ``` -------------------------------- ### Write a sparse matrix to Matrix Market format Source: https://docs.rs/sprs/0.11.5/sprs/io/fn.write_matrix_market.html Demonstrates saving a 5x5 identity matrix to a specified file path using the Matrix Market format. ```rust use sprs::{CsMat}; let save_path = "/tmp/identity5.mm"; let eye : CsMat = CsMat::eye(5); sprs::io::write_matrix_market(&save_path, &eye)?; ``` -------------------------------- ### Direct Sparse Matrix Construction Source: https://docs.rs/sprs/0.11.5/sprs/index.html Create sparse matrices directly using CsMat constructors for better efficiency. ```rust use sprs::{CsMat, CsVec}; let eye : CsMat = CsMat::eye(3); let a = CsMat::new_csc((3, 3), vec![0, 2, 4, 5], vec![0, 1, 0, 2, 2], vec![1., 2., 3., 4., 5.]); ``` -------------------------------- ### cuthill_mckee_custom Function Signature Source: https://docs.rs/sprs/0.11.5/sprs/linalg/ordering/fn.cuthill_mckee_custom.html The function signature for cuthill_mckee_custom, requiring a sparse matrix view, a starting vertex strategy, and a directed ordering preference. ```rust pub fn cuthill_mckee_custom( mat: CsMatViewI<'_, N, I, Iptr>, starting_strategy: S, directed_ordering: D, ) -> Ordering where N: PartialEq, I: SpIndex, Iptr: SpIndex, S: Strategy, D: DirectedOrdering, ``` -------------------------------- ### Constructing a block sparse matrix Source: https://docs.rs/sprs/0.11.5/sprs/fn.bmat.html Demonstrates creating a block diagonal matrix using bmat with two identity matrices. ```rust use sprs::CsMat; let a = CsMat::::eye(3); let b = CsMat::::eye(4); let c = sprs::bmat(&[[Some(a.view()), None], [None, Some(b.view())]]); assert_eq!(c.rows(), 7); ``` -------------------------------- ### vstack Source: https://docs.rs/sprs/0.11.5/sprs/fn.vstack.html Construct a sparse matrix by vertically stacking other matrices. ```APIDOC ## fn vstack ### Description Construct a sparse matrix by vertically stacking other matrices. ### Signature `pub fn vstack<'a, N, I, Iptr, MatArray>(mats: &MatArray) -> CsMatI` ### Constraints - **N**: 'a + Clone + Default - **I**: 'a + SpIndex - **Iptr**: 'a + SpIndex - **MatArray**: AsRef<[CsMatViewI<'a, N, I, Iptr>]> ### Parameters - **mats** (MatArray) - A reference to an array or slice of sparse matrix views to be stacked vertically. ``` -------------------------------- ### Option and method usage Source: https://docs.rs/sprs/0.11.5/sprs/linalg/etree/type.Parent.html Returns None if the option is None, otherwise returns the provided option. Note that arguments are eagerly evaluated. ```rust let x = Some(2); let y: Option<&str> = None; assert_eq!(x.and(y), None); let x: Option = None; let y = Some("foo"); assert_eq!(x.and(y), None); let x = Some(2); let y = Some("foo"); assert_eq!(x.and(y), Some("foo")); let x: Option = None; let y: Option<&str> = None; assert_eq!(x.and(y), None); ``` -------------------------------- ### Constructing a Sparse Matrix via Triplet Format Source: https://docs.rs/sprs/0.11.5/sprs/index.html Use TriMat to build a matrix from triplets, then convert it to a CsMat for computation. ```rust use sprs::{CsMat, TriMat}; let mut a = TriMat::new((4, 4)); a.add_triplet(0, 0, 3.0_f64); a.add_triplet(1, 2, 2.0); a.add_triplet(3, 0, -2.0); // This matrix type does not allow computations, and must to // converted to a compatible sparse type, using for example let b: CsMat<_> = a.to_csr(); ``` -------------------------------- ### Create an Identity Matrix Source: https://docs.rs/sprs/0.11.5/sprs/struct.CsMatBase.html Constructs an identity matrix in CSR or CSC format and demonstrates basic multiplication with a sparse vector. ```rust use sprs::{CsMat, CsVec}; let eye = CsMat::eye(5); assert!(eye.is_csr()); let x = CsVec::new(5, vec![0, 2, 4], vec![1., 2., 3.]); let y = &eye * &x; assert_eq!(x, y); ``` ```rust use sprs::{CsMat, CsVec}; let eye = CsMat::eye_csc(5); assert!(eye.is_csc()); let x = CsVec::new(5, vec![0, 2, 4], vec![1., 2., 3.]); let y = &eye * &x; assert_eq!(x, y); ``` -------------------------------- ### Mapping Option values Source: https://docs.rs/sprs/0.11.5/sprs/linalg/etree/type.Parent.html Demonstrates mapping an Option to a new value, returning None if the original is None. ```rust let x: Option<&str> = None; assert_eq!(x.map(|s| s.len()), None); ``` -------------------------------- ### Option or method usage Source: https://docs.rs/sprs/0.11.5/sprs/linalg/etree/type.Parent.html Returns the option if it contains a value, otherwise returns the provided option. Arguments are eagerly evaluated. ```rust let x = Some(2); let y = None; assert_eq!(x.or(y), Some(2)); let x = None; let y = Some(100); assert_eq!(x.or(y), Some(100)); let x = Some(2); let y = Some(100); assert_eq!(x.or(y), Some(2)); let x: Option = None; let y = None; assert_eq!(x.or(y), None); ``` -------------------------------- ### view Source: https://docs.rs/sprs/0.11.5/sprs/type.CsMatViewI.html Returns a view into the current matrix. ```APIDOC ## pub fn view(&self) -> CsMatViewI<'_, N, I, Iptr> ### Description Return a view into the current matrix. ``` -------------------------------- ### Product of Option values Source: https://docs.rs/sprs/0.11.5/sprs/linalg/etree/type.Parent.html Demonstrates how the product of an iterator of Options returns None if any element is None. ```rust let total: Option = nums.iter().map(|w| w.parse::().ok()).product(); assert_eq!(total, None); ``` -------------------------------- ### csmat_binop_same_storage_raw Source: https://docs.rs/sprs/0.11.5/sprs/binop/fn.csmat_binop_same_storage_raw.html Performs a binary operation on two compressed sparse matrices with identical storage, writing the result into preallocated buffers. ```APIDOC ## csmat_binop_same_storage_raw ### Description Raw implementation of a scalar binary operation for compressed sparse matrices sharing the same storage. The output arrays are assumed to be preallocated. ### Signature `pub fn csmat_binop_same_storage_raw(lhs: CsMatViewI<'_, Lhs, I, Iptr>, rhs: CsMatViewI<'_, Rhs, I, Iptr>, binop: F, out_indptr: &mut [Iptr], out_indices: &mut [I], out_data: &mut [Res]) -> usize` ### Parameters - **lhs** (CsMatViewI) - The left-hand side sparse matrix view. - **rhs** (CsMatViewI) - The right-hand side sparse matrix view. - **binop** (F) - The binary operation function (Fn(&Lhs, &Rhs) -> Res). - **out_indptr** (&mut [Iptr]) - Preallocated output index pointers. - **out_indices** (&mut [I]) - Preallocated output indices. - **out_data** (&mut [Res]) - Preallocated output data buffer. ### Returns - **usize** - The number of non-zero (nnz) elements in the result. ``` -------------------------------- ### Option iter_mut usage Source: https://docs.rs/sprs/0.11.5/sprs/linalg/etree/type.Parent.html Demonstrates the behavior of iter_mut on an empty Option. ```rust let mut x: Option = None; assert_eq!(x.iter_mut().next(), None); ``` -------------------------------- ### Default implementation for Option Source: https://docs.rs/sprs/0.11.5/sprs/linalg/etree/type.Parent.html Returns None when calling the default method on an Option. ```rust let opt: Option = Option::default(); assert!(opt.is_none()); ``` -------------------------------- ### Iterate Over Sparse Vector Source: https://docs.rs/sprs/0.11.5/sprs/type.CsVecViewI.html Demonstrates iterating over the non-zero values of a sparse vector. ```rust use sprs::CsVec; let v = CsVec::new(5, vec![0, 2, 4], vec![1., 2., 3.]); let mut iter = v.iter(); assert_eq!(iter.next(), Some((0, &1.))); assert_eq!(iter.next(), Some((2, &2.))); assert_eq!(iter.next(), Some((4, &3.))); assert_eq!(iter.next(), None); ``` -------------------------------- ### Reversed::new Source: https://docs.rs/sprs/0.11.5/sprs/linalg/ordering/order/struct.Reversed.html Creates a new instance of the Reversed struct. ```APIDOC ## pub fn new() -> Self ### Description Creates a new instance of this conceptual enum variant. ### Signature `pub fn new() -> Reversed` ``` -------------------------------- ### fn hstack Source: https://docs.rs/sprs/0.11.5/sprs/fn.hstack.html Constructs a sparse matrix by horizontally stacking other matrices. ```APIDOC ## fn hstack ### Description Construct a sparse matrix by horizontally stacking other matrices. ### Signature `pub fn hstack<'a, N, I, Iptr, MatArray>(mats: &MatArray) -> CsMatI` ### Parameters - **mats** (MatArray) - A reference to an array or slice of `CsMatViewI` objects to be stacked horizontally. ### Returns - **CsMatI** - A new sparse matrix containing the horizontally stacked input matrices. ``` -------------------------------- ### product Source: https://docs.rs/sprs/0.11.5/sprs/struct.TriMatIter.html Iterates over the entire iterator, multiplying all the elements. ```APIDOC ## fn product

(self) -> P ### Description Iterates over the entire iterator, multiplying all the elements. ``` -------------------------------- ### Create Identity Matrix in CSC Format Source: https://docs.rs/sprs/0.11.5/sprs/type.CsMatI.html Creates an identity matrix stored in CSC format. ```rust use sprs::{CsMat, CsVec}; let eye = CsMat::eye_csc(5); assert!(eye.is_csc()); let x = CsVec::new(5, vec![0, 2, 4], vec![1., 2., 3.]); let y = &eye * &x; assert_eq!(x, y); ``` -------------------------------- ### FFI Usage with to_proper Source: https://docs.rs/sprs/0.11.5/sprs/struct.IndPtrBase.html Demonstrates the correct and incorrect usage of to_proper for FFI, ensuring the Cow remains in scope to keep the pointer valid. ```rust let mat: sprs::CsMat = sprs::CsMat::eye(5); let mid = mat.view().middle_outer_views(1, 2); let ptr = { let indptr = mid.indptr(); // needed for lifetime let indptr_proper = indptr.to_proper(); println!( "ptr {:?} is valid as long as _indptr_proper_owned is in scope", indptr_proper.as_ptr() ); indptr_proper.as_ptr() }; // This line is UB. // println!("ptr deref: {}", *ptr); ``` -------------------------------- ### Storage Access Methods Source: https://docs.rs/sprs/0.11.5/sprs/type.CsMatViewI.html Methods to access the underlying storage components of the sparse matrix. ```APIDOC ## Storage Access Methods ### Methods - **storage() -> CompressedStorage**: Returns the underlying storage type. - **indptr() -> IndPtrView<'_, Iptr>**: Returns the array of offsets. - **indices() -> &[I]**: Returns the inner dimension location for each non-zero value. - **data() -> &[N]**: Returns the non-zero values. - **into_raw_storage() -> (IptrStorage, IndStorage, DataStorage)**: Destructs the matrix and returns the raw storage containers. ``` -------------------------------- ### write_matrix_market_to_bufwrite Source: https://docs.rs/sprs/0.11.5/sprs/io/index.html Writes a sparse matrix into the matrix market format using a buffer writer. ```APIDOC ## write_matrix_market_to_bufwrite ### Description Writes a sparse matrix into the matrix market format using a buffer writer. ``` -------------------------------- ### Iterate over matching non-zero elements with nnz_zip Source: https://docs.rs/sprs/0.11.5/sprs/vec/trait.SparseIterTools.html Use nnz_zip to iterate over the intersection of non-zero elements from two sparse vectors, useful for dot products. ```rust use sprs::CsVec; use sprs::vec::SparseIterTools; let v0 = CsVec::new(5, vec![0, 2, 4], vec![1., 2., 3.]); let v1 = CsVec::new(5, vec![1, 2, 3], vec![-1., -2., -3.]); let mut nnz_zip = v0.iter().nnz_zip(v1.iter()); assert_eq!(nnz_zip.next(), Some((2, &2., &-2.))); assert_eq!(nnz_zip.next(), None); ``` -------------------------------- ### Summing Option values Source: https://docs.rs/sprs/0.11.5/sprs/linalg/etree/type.Parent.html Shows how the sum of an iterator of Options short-circuits to None if any element is None. ```rust let words = vec!["have", "a", "great", "day"]; let total: Option = words.iter().map(|w| w.find('a')).sum(); assert_eq!(total, Some(5)); let words = vec!["have", "a", "good", "day"]; let total: Option = words.iter().map(|w| w.find('a')).sum(); assert_eq!(total, None); ``` -------------------------------- ### Storage and Transformation Methods Source: https://docs.rs/sprs/0.11.5/sprs/struct.CsMatBase.html Methods for managing matrix storage, transposing, and converting matrix types. ```APIDOC ## into_raw_storage() Destructs the matrix and returns its raw storage containers (indptr, indices, data). ## is_csc() / is_csr() Checks if the matrix is in CSC or CSR storage format. ## transpose_mut() / transpose_into() / transpose_view() Provides various ways to transpose the matrix (in-place or as a view). ## to_owned() Creates a deep copy of the matrix. ## to_inner_onehot() Generates a one-hot matrix by compressing the inner dimension. ## to_other_types() Clones the matrix with different integer types for indices and indptr. ## view() Returns a view into the current matrix. ``` -------------------------------- ### Matrix Dimension and Property Methods Source: https://docs.rs/sprs/0.11.5/sprs/struct.CsMatBase.html Methods to retrieve the dimensions, shape, and density properties of the sparse matrix. ```APIDOC ## rows() Returns the number of rows in the matrix. ## cols() Returns the number of columns in the matrix. ## shape() Returns the shape of the matrix as a tuple (rows, cols). ## nnz() Returns the number of non-zero elements stored in the matrix. ## density() Returns the density of the matrix (non-zero elements / total elements). ## outer_dims() Returns the number of outer dimensions (rows for CSR, cols for CSC). ## inner_dims() Returns the number of inner dimensions (cols for CSR, rows for CSC). ``` -------------------------------- ### Iterate over non-zero elements with nnz_or_zip Source: https://docs.rs/sprs/0.11.5/sprs/vec/trait.SparseIterTools.html Use nnz_or_zip to iterate over the union of non-zero elements from two sparse vectors, useful for vector addition. ```rust use sprs::CsVec; use sprs::vec::NnzEither; use sprs::vec::SparseIterTools; let v0 = CsVec::new(5, vec![0, 2, 4], vec![1., 2., 3.]); let v1 = CsVec::new(5, vec![1, 2, 3], vec![-1., -2., -3.]); let mut nnz_or_iter = v0.iter().nnz_or_zip(v1.iter()); assert_eq!(nnz_or_iter.next(), Some(NnzEither::Left((0, &1.)))); assert_eq!(nnz_or_iter.next(), Some(NnzEither::Right((1, &-1.)))); assert_eq!(nnz_or_iter.next(), Some(NnzEither::Both((2, &2., &-2.)))); assert_eq!(nnz_or_iter.next(), Some(NnzEither::Right((3, &-3.)))); assert_eq!(nnz_or_iter.next(), Some(NnzEither::Left((4, &3.)))); assert_eq!(nnz_or_iter.next(), None); ``` -------------------------------- ### Consuming iterator for Option Source: https://docs.rs/sprs/0.11.5/sprs/linalg/etree/type.Parent.html Demonstrates converting an Option into an iterator using into_iter. ```rust let x = Some("string"); let v: Vec<&str> = x.into_iter().collect(); assert_eq!(v, ["string"]); let x = None; let v: Vec<&str> = x.into_iter().collect(); assert!(v.is_empty()); ``` -------------------------------- ### CsMatBase::new Source: https://docs.rs/sprs/0.11.5/sprs/struct.CsMatBase.html Creates a new CSR sparse matrix from provided storage components. ```APIDOC ## pub fn new(shape: (usize, usize), indptr: IptrStorage, indices: IStorage, data: DStorage) -> Self ### Description Creates a new CSR sparse matrix. This constructor can be used to construct all sparse matrix types by utilizing type aliases to constrain the resulting type. ### Parameters - **shape** ((usize, usize)) - The dimensions of the matrix. - **indptr** (IptrStorage) - The index pointers for the sparse storage. - **indices** (IStorage) - The column indices for the non-zero elements. - **data** (DStorage) - The values of the non-zero elements. ``` -------------------------------- ### into_raw_storage Source: https://docs.rs/sprs/0.11.5/sprs/struct.CsVecBase.html Destructs the vector object and returns its storage containers. ```APIDOC ## pub fn into_raw_storage(self) -> (IStorage, DStorage) ### Description Destruct the vector object and recycle its storage containers. ``` -------------------------------- ### pub fn permute_rows(mat: CsMatViewI<'_, N, I, Iptr>, perm: PermViewI<'_, I>) -> CsMatI Source: https://docs.rs/sprs/0.11.5/sprs/fn.permute_rows.html Computes the matrix resulting from the product P * A. ```APIDOC ## permute_rows ### Description Compute the matrix resulting from the product P * A, where P is a permutation matrix and A is a sparse matrix. ### Signature `pub fn permute_rows(mat: CsMatViewI<'_, N, I, Iptr>, perm: PermViewI<'_, I>) -> CsMatI` ### Parameters - **mat** (CsMatViewI<'_, N, I, Iptr>) - The input sparse matrix A. - **perm** (PermViewI<'_, I>) - The permutation view P. ### Returns - **CsMatI** - The resulting sparse matrix. ``` -------------------------------- ### PseudoPeripheral::new Source: https://docs.rs/sprs/0.11.5/sprs/linalg/ordering/start/struct.PseudoPeripheral.html Creates a new instance of the PseudoPeripheral strategy. ```APIDOC ## pub fn new() -> Self ### Description Creates a new instance of the PseudoPeripheral strategy. ### Returns - **Self** - A new instance of the PseudoPeripheral struct. ``` -------------------------------- ### ParentsOwned::new Source: https://docs.rs/sprs/0.11.5/sprs/linalg/etree/type.ParentsOwned.html Creates a new tree instance with all nodes initialized as roots. ```APIDOC ### pub fn new(nb_nodes: usize) -> Self Creates a new tree with all nodes set as root. ``` -------------------------------- ### Option xor method usage Source: https://docs.rs/sprs/0.11.5/sprs/linalg/etree/type.Parent.html Returns Some if exactly one of the two options is Some, otherwise returns None. ```rust let x = Some(2); let y: Option = None; assert_eq!(x.xor(y), Some(2)); let x: Option = None; let y = Some(2); assert_eq!(x.xor(y), Some(2)); let x = Some(2); let y = Some(2); assert_eq!(x.xor(y), None); let x: Option = None; let y: Option = None; assert_eq!(x.xor(y), None); ``` -------------------------------- ### into_csc Source: https://docs.rs/sprs/0.11.5/sprs/struct.CsMatBase.html Converts the matrix to CSC format. If already in CSC, returns the matrix by value. ```APIDOC ## pub fn into_csc(self) -> Self ### Description Create a new CSC matrix equivalent to this one. If this matrix is CSR, it is converted to CSC. If this matrix is CSC, it is returned by value. ``` -------------------------------- ### CsVecBase Methods Source: https://docs.rs/sprs/0.11.5/sprs/struct.CsVecBase.html Methods available for interacting with and modifying sparse vectors. ```APIDOC ## view_mut() ### Description Returns a mutable view of the sparse vector. ## get_mut(index: usize) ### Description Accesses the element at the given index with logarithmic complexity, returning a mutable reference if found. ## map_inplace(f: F) ### Description Applies a function to each non-zero element in-place. ## iter_mut() ### Description Provides a mutable iterator over the non-zero values of the sparse vector, preserving the sparse structure. ## unit_normalize() ### Description Divides the vector by its own L2-norm. The zero vector remains unchanged. ``` -------------------------------- ### col_view(&self) Source: https://docs.rs/sprs/0.11.5/sprs/type.CsVecViewI.html Views the sparse vector as a single-column matrix. ```APIDOC ## pub fn col_view( &self, ) -> CsMatBase, &'_ [I], &'_ [N], Iptr> ### Description View this vector as a matrix with only one column. ``` -------------------------------- ### Matrix Metadata Methods Source: https://docs.rs/sprs/0.11.5/sprs/type.CsMatViewI.html Methods to retrieve basic information about the matrix dimensions and storage properties. ```APIDOC ## Matrix Metadata Methods ### Methods - **rows() -> usize**: Returns the number of rows. - **cols() -> usize**: Returns the number of columns. - **shape() -> Shape**: Returns the matrix shape as (rows, cols). - **nnz() -> usize**: Returns the number of non-zero elements. - **density() -> f64**: Returns the matrix density. - **is_csc() -> bool**: Returns true if the matrix is in CSC storage format. ``` -------------------------------- ### CsMatBase::try_new Source: https://docs.rs/sprs/0.11.5/sprs/struct.CsMatBase.html Attempts to create a new CSR sparse matrix with validation. ```APIDOC ## pub fn try_new(shape: (usize, usize), indptr: IptrStorage, indices: IStorage, data: DStorage) -> Result ### Description Attempts to create a new CSR sparse matrix, returning a Result that includes the original storage if validation fails. ``` -------------------------------- ### CsMatBase::new_csc Source: https://docs.rs/sprs/0.11.5/sprs/struct.CsMatBase.html Creates a new CSC sparse matrix from provided storage components. ```APIDOC ## pub fn new_csc(shape: (usize, usize), indptr: IptrStorage, indices: IStorage, data: DStorage) -> Self ### Description Creates a new CSC sparse matrix. See `new` for the CSR equivalent. ``` -------------------------------- ### read_matrix_market_from_bufread Source: https://docs.rs/sprs/0.11.5/sprs/io/fn.read_matrix_market_from_bufread.html Reads a sparse matrix in the Matrix Market format from an io::BufRead and returns a corresponding triplet matrix. ```APIDOC ## Function: read_matrix_market_from_bufread ### Description Reads a sparse matrix in the Matrix Market format from an `io::BufRead` and returns a corresponding `TriMatI` triplet matrix. Currently, only general matrices are supported. ### Signature `pub fn read_matrix_market_from_bufread(reader: &mut R) -> Result, IoError>` ### Parameters - **reader** (&mut R) - A mutable reference to a type implementing `BufRead`. ### Constraints - **I**: `SpIndex` - **N**: `PrimitiveKind + Clone + Neg + MatrixMarketRead + MatrixMarketConjugate` - **R**: `BufRead + ?Sized` ### Returns - **Result, IoError>** - Returns the parsed triplet matrix on success, or an `IoError` if reading fails. ``` -------------------------------- ### Destruct matrix into raw storage Source: https://docs.rs/sprs/0.11.5/sprs/type.CsMatViewI.html Consume the matrix and return its underlying storage containers. ```rust use sprs::{CsMat}; let (indptr, indices, data) = CsMat::::eye(3).into_raw_storage(); assert_eq!(indptr, vec![0, 1, 2, 3]); assert_eq!(indices, vec![0, 1, 2]); assert_eq!(data, vec![1, 1, 1]); ``` -------------------------------- ### csmat_binop_same_storage_raw Function Signature Source: https://docs.rs/sprs/0.11.5/sprs/binop/fn.csmat_binop_same_storage_raw.html The function signature for performing raw binary operations on sparse matrices. It requires preallocated output arrays and returns the number of non-zero elements. ```rust pub fn csmat_binop_same_storage_raw( lhs: CsMatViewI<'_, Lhs, I, Iptr>, rhs: CsMatViewI<'_, Rhs, I, Iptr>, binop: F, out_indptr: &mut [Iptr], out_indices: &mut [I], out_data: &mut [Res], ) -> usize where Lhs: Zero, Rhs: Zero, Res: Zero, I: SpIndex, Iptr: SpIndex, F: Fn(&Lhs, &Rhs) -> Res, ``` -------------------------------- ### write_matrix_market_sym Source: https://docs.rs/sprs/0.11.5/sprs/io/index.html Writes a symmetric sparse matrix into the matrix market format. ```APIDOC ## write_matrix_market_sym ### Description Writes a symmetric sparse matrix into the matrix market format. ``` -------------------------------- ### write_matrix_market_to_bufwrite function signature Source: https://docs.rs/sprs/0.11.5/sprs/io/fn.write_matrix_market_to_bufwrite.html The function signature for writing a sparse matrix to a buffer using the Matrix Market format. ```rust pub fn write_matrix_market_to_bufwrite<'a, N, I, M, W>( writer: &mut W, mat: M, ) -> Result<(), Error> where I: 'a + SpIndex + Display, N: 'a + PrimitiveKind + MatrixMarketDisplay, for<'n> Displayable<&'n N>: Display, M: IntoIterator + SparseMat, W: Write + ?Sized, ``` -------------------------------- ### mul_mat_same_storage Function Signature Source: https://docs.rs/sprs/0.11.5/sprs/binop/fn.mul_mat_same_storage.html Defines the generic constraints and parameters for performing sparse matrix multiplication with identical storage types. ```rust pub fn mul_mat_same_storage( lhs: &Mat1, rhs: &Mat2, ) -> CsMatI where Lhs: Zero, Rhs: Zero, Res: Zero + Clone, for<'r> &'r Lhs: Mul<&'r Rhs, Output = Res>, I: SpIndex, Iptr: SpIndex, Mat1: SpMatView, Mat2: SpMatView, ``` -------------------------------- ### pub fn transform_mat_papt(mat: CsMatViewI<'_, N, I, Iptr>, perm: PermViewI<'_, I>) -> CsMatI Source: https://docs.rs/sprs/0.11.5/sprs/fn.transform_mat_papt.html Computes the square matrix resulting from the product P * A * P^T. ```APIDOC ## transform_mat_papt ### Description Computes the square matrix resulting from the product P * A * P^T. ### Signature `pub fn transform_mat_papt(mat: CsMatViewI<'_, N, I, Iptr>, perm: PermViewI<'_, I>) -> CsMatI` ### Parameters - **mat** (CsMatViewI<'_, N, I, Iptr>) - The input sparse matrix A. - **perm** (PermViewI<'_, I>) - The permutation matrix P. ### Returns - **CsMatI** - The resulting square matrix. ``` -------------------------------- ### print_nnz_pattern Source: https://docs.rs/sprs/0.11.5/sprs/visu/index.html Prints the non-zero pattern of a sparse matrix to the console. ```APIDOC ## print_nnz_pattern ### Description Prints the non-zero pattern of a sparse matrix. ``` -------------------------------- ### write_matrix_market Source: https://docs.rs/sprs/0.11.5/sprs/io/fn.write_matrix_market.html Writes a sparse matrix into the matrix market format. ```APIDOC ## Function: write_matrix_market ### Description Writes a sparse matrix into the matrix market format. ### Signature `pub fn write_matrix_market<'a, N, I, M, P>(path: P, mat: M) -> Result<(), Error>` ### Parameters - **path** (P: AsRef) - The file path where the matrix will be saved. - **mat** (M: IntoIterator + SparseMat) - The sparse matrix to be written. ### Example ```rust use sprs::{CsMat}; let save_path = "/tmp/identity5.mm"; let eye : CsMat = CsMat::eye(5); sprs::io::write_matrix_market(&save_path, &eye)?; ``` ``` -------------------------------- ### Into trait implementation Source: https://docs.rs/sprs/0.11.5/sprs/io/enum.IoError.html Provides the into method for type conversion. ```rust fn into(self) -> U ``` -------------------------------- ### Data Access Methods Source: https://docs.rs/sprs/0.11.5/sprs/struct.CsMatBase.html Methods for accessing individual elements or the underlying storage arrays. ```APIDOC ## get(i: usize, j: usize) Access the element at row i and column j. Returns Option<&N>. ## indptr() Returns the array of offsets for the indices and data slices. ## proper_indptr() Returns an indptr representation suitable for FFI. ## indices() Returns the inner dimension location for each non-zero value. ## data() Returns the slice of non-zero values. ``` -------------------------------- ### Matrix Transformations Source: https://docs.rs/sprs/0.11.5/sprs/type.CsMatI.html Methods for transposing, converting, or cloning the matrix. ```APIDOC ## pub fn transpose_mut(&mut self) Transposes the matrix in place. ## pub fn transpose_into(self) -> Self Transposes the matrix and returns the result. ## pub fn to_owned(&self) -> CsMatI Returns an owned version of the matrix, performing a deep copy if necessary. ``` -------------------------------- ### transpose_into Source: https://docs.rs/sprs/0.11.5/sprs/type.CsMatViewI.html Transposes the matrix and returns the result. ```APIDOC ## pub fn transpose_into(self) -> Self ### Description Transpose a matrix in place. No allocation required (this is simply a storage order change). ``` -------------------------------- ### Product of Option values Source: https://docs.rs/sprs/0.11.5/sprs/linalg/etree/type.Parent.html Calculates the product of elements in an iterator of Options, returning None if any element is None. ```rust let nums = vec!["5", "10", "1", "2"]; let total: Option = nums.iter().map(|w| w.parse::().ok()).product(); assert_eq!(total, Some(100)); let nums = vec!["5", "10", "one", "2"]; ``` -------------------------------- ### From trait implementation Source: https://docs.rs/sprs/0.11.5/sprs/io/enum.IoError.html Provides the from method for identity conversion. ```rust fn from(t: T) -> T ``` -------------------------------- ### Collect iterator of Options Source: https://docs.rs/sprs/0.11.5/sprs/linalg/etree/type.Parent.html Demonstrates collecting an iterator of Options into an Option of a collection, returning None if any element is None. ```rust let items = vec![0_u16, 1, 2]; let res: Option> = items .iter() .map(|x| x.checked_add(1)) .collect(); assert_eq!(res, Some(vec![1, 2, 3])); ``` ```rust let items = vec![2_u16, 1, 0]; let res: Option> = items .iter() .map(|x| x.checked_sub(1)) .collect(); assert_eq!(res, None); ``` ```rust let items = vec![3_u16, 2, 1, 10]; let mut shared = 0; let res: Option> = items .iter() .map(|x| { shared += x; x.checked_sub(2) }) .collect(); ``` -------------------------------- ### Expect a value from Option Source: https://docs.rs/sprs/0.11.5/sprs/linalg/etree/type.Parent.html Returns the contained value or panics with a custom message if the Option is None. ```rust let x = Some("value"); assert_eq!(x.expect("fruits are healthy"), "value"); ``` ```rust let x: Option<&str> = None; x.expect("fruits are healthy"); // panics with `fruits are healthy` ``` ```rust let item = slice.get(0) .expect("slice should not be empty"); ``` -------------------------------- ### Matrix-Matrix Multiplication and Addition Source: https://docs.rs/sprs/0.11.5/sprs/index.html Perform arithmetic operations between two sparse matrices. ```rust use sprs::{CsMat, CsVec}; let eye = CsMat::eye(3); let a = CsMat::new_csc((3, 3), vec![0, 2, 4, 5], vec![0, 1, 0, 2, 2], vec![1., 2., 3., 4., 5.]); let b = &eye * &a; assert_eq!(a, b.to_csc()); ``` -------------------------------- ### fn dim(&self) -> usize Source: https://docs.rs/sprs/0.11.5/sprs/vec/trait.VecDim.html Returns the dimension of the vector. ```APIDOC ## fn dim(&self) -> usize ### Description Returns the dimension of the vector as a usize value. ### Signature `fn dim(&self) -> usize` ### Returns - **usize**: The dimension of the vector. ``` -------------------------------- ### any Source: https://docs.rs/sprs/0.11.5/sprs/struct.TriMatIter.html Tests if any element of the iterator matches a predicate. ```APIDOC ## fn any(&mut self, f: F) -> bool ### Description Tests if any element of the iterator matches a predicate. ``` -------------------------------- ### Create Identity Matrix in CSR Format Source: https://docs.rs/sprs/0.11.5/sprs/type.CsMatI.html Creates an identity matrix stored in CSR format. ```rust use sprs::{CsMat, CsVec}; let eye = CsMat::eye(5); assert!(eye.is_csr()); let x = CsVec::new(5, vec![0, 2, 4], vec![1., 2., 3.]); let y = &eye * &x; assert_eq!(x, y); ``` -------------------------------- ### vstack function signature Source: https://docs.rs/sprs/0.11.5/sprs/fn.vstack.html The function signature for vertically stacking sparse matrices, requiring matrices to share the same index and pointer types. ```rust pub fn vstack<'a, N, I, Iptr, MatArray>(mats: &MatArray) -> CsMatI where N: 'a + Clone + Default, I: 'a + SpIndex, Iptr: 'a + SpIndex, MatArray: AsRef<[CsMatViewI<'a, N, I, Iptr>]>, ``` -------------------------------- ### row_view(&self) Source: https://docs.rs/sprs/0.11.5/sprs/type.CsVecViewI.html Views the sparse vector as a single-row matrix. ```APIDOC ## pub fn row_view( &self, ) -> CsMatBase, &'_ [I], &'_ [N], Iptr> ### Description View this vector as a matrix with only one row. ``` -------------------------------- ### cuthill_mckee_custom Source: https://docs.rs/sprs/0.11.5/sprs/linalg/ordering/index.html A customized Cuthill-McKee algorithm for matrix reordering. ```APIDOC ## cuthill_mckee_custom ### Description A customized Cuthill-McKee algorithm used to reorder the rows and columns of a sparse matrix to reduce its bandwidth. ``` -------------------------------- ### DStack Methods Source: https://docs.rs/sprs/0.11.5/sprs/stack/struct.DStack.html Methods available for the DStack structure to manage elements on left and right stacks. ```APIDOC ## DStack ### with_capacity(n: usize) -> Self Creates a new double stack with a fixed capacity of n elements. ### capacity() -> usize Returns the total capacity of the DStack. ### push_left(value: I) Adds a value to the left stack. ### push_right(value: I) Adds a value to the right stack. ### pop_left() -> Option Removes and returns the top value from the left stack. ### pop_right() -> Option Removes and returns the top value from the right stack. ### is_left_empty() -> bool Checks if the left stack is empty. ### is_right_empty() -> bool Checks if the right stack is empty. ### clear_left() Clears all elements from the left stack. ### clear_right() Clears all elements from the right stack. ### iter_right() -> Iter<'_, I> Returns an iterator over the right stack. ### push_left_on_right() Transfers all values from the left stack to the right stack. ### push_right_on_left() Transfers all values from the right stack to the left stack. ``` -------------------------------- ### write_matrix_market_sym function signature Source: https://docs.rs/sprs/0.11.5/sprs/io/fn.write_matrix_market_sym.html The function signature for writing a symmetric sparse matrix to a file path. ```rust pub fn write_matrix_market_sym<'a, N, I, M, P>( path: P, mat: M, sym: SymmetryMode, ) -> Result<(), Error> where I: 'a + SpIndex + Display, N: 'a + PrimitiveKind + MatrixMarketDisplay, for<'n> Displayable<&'n N>: Display, M: IntoIterator + SparseMat, P: AsRef, ``` -------------------------------- ### reduce(self, other: Option, f: F) -> Option Source: https://docs.rs/sprs/0.11.5/sprs/linalg/etree/type.Parent.html Reduces two options into one, using the provided function if both are Some. If only one is Some, that value is returned; if both are None, None is returned. ```APIDOC ## pub fn reduce(self, other: Option, f: F) -> Option ### Description Reduces two options into one, using the provided function if both are Some. If only one is Some, that value is returned; if both are None, None is returned. ### Signature `pub fn reduce(self, other: Option, f: F) -> Option` where T: Into, U: Into, F: FnOnce(T, U) -> R ### Note This is a nightly-only experimental API (`option_reduce`). ``` -------------------------------- ### csmat_binop Function Signature Source: https://docs.rs/sprs/0.11.5/sprs/binop/fn.csmat_binop.html The function signature for applying a binary operation to two sparse matrices with matching storage. ```rust pub fn csmat_binop( lhs: CsMatViewI<'_, Lhs, I, Iptr>, rhs: CsMatViewI<'_, Rhs, I, Iptr>, binop: F, ) -> CsMatI where Lhs: Zero, Rhs: Zero, Res: Zero + Clone, I: SpIndex, Iptr: SpIndex, F: Fn(&Lhs, &Rhs) -> Res, ```