sparse#

class sparse(arr, copy=False, vector_size=None)[source]#

Create a sparse array that can be used for array-like arithmetic operations (i.e., +, -, *, /) of sparse 1 or 2-dimensional arrays.

Data is stored internally as dictionaries (1d array) or a list of dictionaries (2d array). For 2d arrays, each dictionary represents a row of chemical data for a given phase. This data structure is specialized for storing chemical data within a limited set of phases; it allows for fast indexing and math operations while saving storage space.

For example, one can define thousands of chemicals and yet only encounter 2 chemicals within an arbitrary stream; instead of storing thousands of 0s within an array, the sparse array stores 2 values within a dictionary. This advantage also allows for caching mixture properties with minimal overhead in data storage and computation time.

These sparce arrays are meant for simple mathematical operations. For a broader range of matrix operations, it is recommended to convert to Numpy arrays or Scipy sparce arrays.

Parameters:

arr (array-like) – Structure to be converted to a sparse array.

Examples

Create a sparse array from an array-like object:

>>> from thermosteam.base import sparse
>>> sa = sparse([[0, 1, 2], [3, 2, 0]])
>>> sa
sparse([[0., 1., 2.],
        [3., 2., 0.]])

Create a sparse array from a list of dictionaries of index-nonzero value pairs:

>>> sa = sparse(
...     [{1: 1, 2: 2},
...      {0: 3, 1: 2}],
...     vector_size=3,
... )
>>> sa
sparse([[0., 1., 2.],
        [3., 2., 0.]])

Sparse arrays support arithmetic operations just like dense arrays:

>>> sa * sa
sparse([[0., 1., 4.],
        [9., 4., 0.]])

Sparse arrays assume sparsity across columns (0-axis) but not across rows. For this reason, indexing rows will return sparse arrays while indexing columns will return NumPy dense arrays:

>>> sa[0]
sparse([0., 1., 2.])
>>> sa[:, 0]
array([0., 3.])

Sparse arrays also support logical operations:

>>> sa = sparse([[True, False, True, False],
...              [False, True, True, False]])
>>> sa ^ True # XOR
sparse([[False,  True, False,  True],
        [ True, False, False,  True]])