Skip to main content

SparseTensor

Struct SparseTensor 

Source
pub struct SparseTensor<T: Scalar> { /* private fields */ }
Expand description

An N-dimensional sparse tensor stored in COO (coordinate) format.

Each non-zero element is represented by its coordinates (one index per dimension) and the corresponding value.

§Examples

let st = SparseTensor::new(
    vec![vec![0, 1], vec![1, 2]],
    vec![3.0_f64, 7.0],
    vec![3, 4],
).unwrap();
assert_eq!(st.nnz(), 2);
assert_eq!(st.ndim(), 2);

Implementations§

Source§

impl<T: Scalar> SparseTensor<T>

Source

pub fn new( indices: Vec<Vec<usize>>, values: Vec<T>, shape: Vec<usize>, ) -> Result<Self>

Create a sparse tensor from explicit index lists, values, and shape.

indices must have one entry per dimension, and each inner vec must have the same length as values. All indices must be in-bounds for the corresponding dimension of shape.

§Errors

Returns CoreError::InvalidArgument when lengths are inconsistent or indices are out of bounds.

Source

pub fn from_dense(tensor: &Tensor<T>) -> Self

Build a sparse tensor from a dense Tensor, keeping only non-zero entries (where value != T::zero()).

§Examples
let t = Tensor::from_vec(vec![0.0, 1.0, 0.0, 2.0], vec![2, 2]).unwrap();
let st = SparseTensor::from_dense(&t);
assert_eq!(st.nnz(), 2);
Source

pub fn zeros(shape: Vec<usize>) -> Self

Create an empty sparse tensor (no stored elements) with the given shape.

§Examples
let st = SparseTensor::<f64>::zeros(vec![4, 5]);
assert_eq!(st.nnz(), 0);
assert_eq!(st.shape(), &[4, 5]);
Source

pub fn nnz(&self) -> usize

Number of stored (non-zero) elements.

Source

pub fn shape(&self) -> &[usize]

Shape of the full dense tensor.

Source

pub fn ndim(&self) -> usize

Number of dimensions (rank).

Source

pub fn density(&self) -> f64

Fraction of elements that are stored: nnz / total_elements.

Returns 0.0 for a tensor with zero total elements.

Source

pub fn values(&self) -> &[T]

Slice of stored values.

Source

pub fn indices(&self) -> &[Vec<usize>]

Slice of index vectors (one per dimension).

Source

pub fn to_dense(&self) -> Result<Tensor<T>>

Expand this sparse tensor into a fully materialised dense Tensor.

Duplicate coordinates are summed (call coalesce first if you want canonical form).

§Errors

Returns an error if the resulting dense tensor would be invalid (should not happen for a well-formed SparseTensor).

Source

pub fn add(&self, other: &SparseTensor<T>) -> Result<SparseTensor<T>>

Element-wise addition of two sparse tensors with the same shape.

The result may contain duplicate indices; call coalesce to merge them.

§Errors

Returns CoreError::DimensionMismatch if shapes differ.

Source

pub fn scalar_mul(&self, scalar: T) -> SparseTensor<T>

Multiply every stored value by a scalar.

§Examples
let st = SparseTensor::new(
    vec![vec![0, 1], vec![0, 1]],
    vec![2.0_f64, 3.0],
    vec![2, 2],
).unwrap();
let scaled = st.scalar_mul(10.0);
assert_eq!(scaled.values(), &[20.0, 30.0]);
Source

pub fn sparse_matmul(&self, other: &SparseTensor<T>) -> Result<SparseTensor<T>>

Sparse-sparse matrix multiplication (2D tensors only).

Computes self @ other where self is (M, K) and other is (K, N). The result is an (M, N) sparse tensor.

§Errors

Returns an error if either tensor is not 2D or inner dimensions do not match.

Source

pub fn sparse_dense_matmul(&self, dense: &Tensor<T>) -> Result<Tensor<T>>

Multiply a sparse 2D tensor by a dense Tensor (matrix-matrix product).

self is (M, K) and dense is (K, N). Returns a dense (M, N) tensor.

§Errors

Returns an error if self is not 2D, dense is not 2D, or inner dimensions do not match.

Source

pub fn transpose(&self) -> Result<SparseTensor<T>>

Transpose a 2D sparse tensor (swap row and column indices).

§Errors

Returns CoreError::InvalidArgument if the tensor is not 2D.

Source

pub fn coalesce(&mut self)

Merge duplicate indices by summing their values, and sort entries in lexicographic order of their coordinates.

After coalescing, every coordinate tuple appears at most once and entries with a value of zero are removed.

Trait Implementations§

Source§

impl<T: Clone + Scalar> Clone for SparseTensor<T>

Source§

fn clone(&self) -> SparseTensor<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 + Scalar> Debug for SparseTensor<T>

Source§

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

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl<T> Freeze for SparseTensor<T>

§

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

§

impl<T> Send for SparseTensor<T>

§

impl<T> Sync for SparseTensor<T>

§

impl<T> Unpin for SparseTensor<T>
where T: Unpin,

§

impl<T> UnsafeUnpin for SparseTensor<T>

§

impl<T> UnwindSafe for SparseTensor<T>
where T: UnwindSafe,

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