Sparse n-dimensional arrays for the PyData ecosystem with multiple backend implementations
—
Functions for creating sparse arrays from various inputs, including construction of special matrices, conversion from dense arrays, and generation of arrays with specific patterns.
Create sparse arrays with specific shapes and initial values.
def asarray(obj, /, *, dtype=None, format="coo", copy=False, device=None):
"""
Convert input to sparse array.
Parameters:
- obj: array-like, input data (numpy array, list, existing sparse array)
- dtype: data type for result array
- format: str, output sparse format (default: "coo")
- copy: bool, whether to copy input data (default: False)
- device: str, device constraint (default: None)
Returns:
Sparse array representation of input
"""
def zeros(shape, dtype=float, format="coo", *, device=None, **kwargs):
"""
Create sparse array filled with zeros.
Parameters:
- shape: tuple, shape of output array
- dtype: data type for array elements
- format: str, sparse format (default: "coo")
- device: str, device constraint (default: None)
- **kwargs: additional format-specific arguments
Returns:
Sparse array of zeros with given shape
"""
def ones(shape, dtype=float, format="coo", *, device=None, **kwargs):
"""
Create sparse array filled with ones.
Parameters:
- shape: tuple, shape of output array
- dtype: data type for array elements
- format: str, sparse format (default: "coo")
- device: str, device constraint (default: None)
- **kwargs: additional format-specific arguments
Returns:
Sparse array of ones with given shape
"""
def full(shape, fill_value, dtype=None, format="coo", order="C", *, device=None, **kwargs):
"""
Create sparse array filled with specified value.
Parameters:
- shape: tuple, shape of output array
- fill_value: scalar, value to fill array with
- dtype: data type for array elements
- format: str, sparse format (default: "coo")
- order: str, memory layout order (default: "C")
- device: str, device constraint (default: None)
- **kwargs: additional format-specific arguments
Returns:
Sparse array filled with fill_value
"""
def empty(shape, dtype=float, format="coo", *, device=None, **kwargs):
"""
Create uninitialized sparse array.
Parameters:
- shape: tuple, shape of output array
- dtype: data type for array elements
- format: str, sparse format (default: "coo")
- device: str, device constraint (default: None)
- **kwargs: additional format-specific arguments
Returns:
Empty sparse array with given shape
"""Create arrays with the same shape and properties as existing arrays.
def zeros_like(a, dtype=None, shape=None, format=None, *, device=None, **kwargs):
"""
Create sparse array of zeros with same shape as input.
Parameters:
- a: sparse array, template for shape and properties
- dtype: data type, defaults to same as input array
- shape: tuple, override shape (default: None, use input shape)
- format: str, output format (default: None, use input format)
- device: str, device constraint (default: None)
- **kwargs: additional format-specific arguments
Returns:
Sparse array of zeros matching input shape
"""
def ones_like(a, dtype=None, shape=None, format=None, *, device=None, **kwargs):
"""
Create sparse array of ones with same shape as input.
Parameters:
- a: sparse array, template for shape and properties
- dtype: data type, defaults to same as input array
- shape: tuple, override shape (default: None, use input shape)
- format: str, output format (default: None, use input format)
- device: str, device constraint (default: None)
- **kwargs: additional format-specific arguments
Returns:
Sparse array of ones matching input shape
"""
def full_like(a, fill_value, dtype=None, shape=None, format=None, *, device=None, **kwargs):
"""
Create sparse array filled with value, same shape as input.
Parameters:
- a: sparse array, template for shape and properties
- fill_value: scalar, value to fill array with
- dtype: data type, defaults to same as input array
- shape: tuple, override shape (default: None, use input shape)
- format: str, output format (default: None, use input format)
- device: str, device constraint (default: None)
- **kwargs: additional format-specific arguments
Returns:
Sparse array filled with fill_value matching input shape
"""
def empty_like(a, dtype=None, shape=None, format=None, *, device=None, **kwargs):
"""
Create uninitialized sparse array with same shape as input.
Parameters:
- a: sparse array, template for shape and properties
- dtype: data type, defaults to same as input array
- shape: tuple, override shape (default: None, use input shape)
- format: str, output format (default: None, use input format)
- device: str, device constraint (default: None)
- **kwargs: additional format-specific arguments
Returns:
Empty sparse array matching input shape
"""Create commonly used mathematical matrices in sparse format.
def eye(N, M=None, k=0, dtype=float, format="coo", *, device=None, **kwargs):
"""
Create sparse identity matrix.
Parameters:
- N: int, number of rows
- M: int, number of columns (defaults to N for square matrix)
- k: int, diagonal offset (0=main diagonal, >0=upper, <0=lower)
- dtype: data type for matrix elements
- format: str, sparse format (default: "coo")
- device: str, device constraint (default: None)
- **kwargs: additional format-specific arguments
Returns:
Sparse identity matrix with ones on specified diagonal
"""Generate sparse arrays with random values and sparsity patterns.
def random(shape, density=None, nnz=None, random_state=None, data_rvs=None, format="coo", fill_value=None, idx_dtype=None, **kwargs):
"""
Generate sparse array with random values.
Parameters:
- shape: tuple, shape of output array
- density: float, fraction of elements to be non-zero (default: 0.01 when nnz not specified)
- nnz: int, exact number of non-zero elements (mutually exclusive with density)
- random_state: int or RandomState, seed for reproducible generation
- data_rvs: callable, function to generate random values (default: uniform [0,1))
- format: str, output format (default: "coo")
- fill_value: scalar, fill value for the array (default: None)
- idx_dtype: dtype, data type for indices (default: None)
- **kwargs: additional format-specific arguments
Returns:
Sparse array with random non-zero elements at random positions
"""Convert arrays to specific sparse formats.
def as_coo(x, shape=None, fill_value=None, idx_dtype=None):
"""
Convert input to COO format sparse array.
Parameters:
- x: array-like, input to convert (SparseArray, numpy.ndarray, scipy.sparse, Iterable)
- shape: tuple, shape of output array (default: None, infer from input)
- fill_value: scalar, fill value (default: None)
- idx_dtype: dtype, data type for indices (default: None)
Returns:
COO format sparse array
"""
def asCOO(x):
"""
Alias for as_coo - convert input to COO format.
Parameters:
- x: array-like, input to convert
Returns:
COO format sparse array
"""import sparse
import numpy as np
# Create arrays with specific values
zeros_array = sparse.zeros((100, 100)) # 100x100 zeros
ones_array = sparse.ones((50, 50), dtype=int) # 50x50 ones
full_array = sparse.full((10, 20), 3.14) # 10x20 filled with pi
# Create identity matrices
identity = sparse.eye(5) # 5x5 identity
rectangular_eye = sparse.eye(3, 5, k=1) # 3x5 with ones on super-diagonal
print(f"Identity matrix shape: {identity.shape}")
print(f"Identity nnz: {identity.nnz}") # 5 non-zero elements# Create template array
template = sparse.random((20, 30), density=0.1)
# Create arrays matching template shape
template_zeros = sparse.zeros_like(template)
template_ones = sparse.ones_like(template, dtype=int)
template_full = sparse.full_like(template, -1.5)
print(f"All arrays have shape: {template.shape}")
print(f"Template zeros nnz: {template_zeros.nnz}") # 0
print(f"Template ones nnz: {template_ones.nnz}") # 600 (20*30)# Generate random sparse arrays with different densities
sparse_1_percent = sparse.random((1000, 1000), density=0.01, random_state=42)
sparse_10_percent = sparse.random((100, 100), density=0.1, dtype=int)
print(f"1% density array - nnz: {sparse_1_percent.nnz}") # ~10,000
print(f"10% density array - nnz: {sparse_10_percent.nnz}") # ~1,000
# Reproducible random generation
rng_array1 = sparse.random((50, 50), density=0.05, random_state=123)
rng_array2 = sparse.random((50, 50), density=0.05, random_state=123)
print(f"Arrays are identical: {np.array_equal(rng_array1.data, rng_array2.data)}")# Convert NumPy arrays to sparse
dense_matrix = np.array([[1, 0, 3], [0, 2, 0], [4, 0, 0]])
sparse_matrix = sparse.asarray(dense_matrix)
# Convert with specific data type
sparse_int = sparse.asarray(dense_matrix, dtype=np.int32)
print(f"Original density: {np.count_nonzero(dense_matrix) / dense_matrix.size:.1%}")
print(f"Sparse nnz: {sparse_matrix.nnz}")
print(f"Sparse density: {sparse_matrix.density:.1%}")# Create in specific formats
coo_array = sparse.as_coo([[1, 0], [0, 2]]) # Force COO format
also_coo = sparse.asCOO([[1, 0], [0, 2]]) # Alternative name
# Random arrays in different formats
random_coo = sparse.random((100, 100), format='coo', density=0.05)
random_gcxs = sparse.random((100, 100), format='gcxs', density=0.05)
print(f"COO format: {type(random_coo).__name__}")
print(f"GCXS format: {type(random_gcxs).__name__}")Install with Tessl CLI
npx tessl i tessl/pypi-sparse