SparseCSR¶
-
class
sisl.
SparseCSR
(arg1, dim=1, dtype=None, nnzpr=20, nnz=None, **kwargs)¶ Bases:
numpy.lib.mixins.NDArrayOperatorsMixin
A compressed sparse row matrix, slightly different than
csr_matrix
.This class holds all required information regarding the CSR matrix format.
Note that this sparse matrix of data does not retain the number of columns in the matrix, i.e. it has no way of determining whether the input is correct.
This sparse matrix class tries to resemble the
csr_matrix
as much as possible with the difference of this class being multi-dimensional.Creating a new sparse matrix is much similar to the
scipy
equivalent.nnz
is only used ifnnz > nr * nnzpr
.This class may be instantiated by verious means.
SparseCSR(S)
whereS
is a :module:`scipy.sparse` matrixSparseCSR((M,N)[, dtype])
the shape of the sparse matrix (equivalent toSparseCSR((M,N,1)[, dtype])
.SparseCSR((M,N), dim=K, [, dtype])
the shape of the sparse matrix (equivalent toSparseCSR((M,N,K)[, dtype])
.SparseCSR((M,N,K)[, dtype])
creating a sparse matrix withM
rows,N
columns andK
elements per sparse element.
Additionally these parameters control the creation of the sparse matrix.
- Parameters
arg1 (tuple) – various initialization methods as described above
dim (int, optional) – number of elements stored per sparse element, only used if (M,N) is passed
dtype (numpy.dtype, optional) – data type of the matrix, defaults to
numpy.float64
nnzpr (int, optional) – initial number of non-zero elements per row. Only used if
nnz
is not suppliednnz (int, optional) – initial total number of non-zero elements This quantity has precedence over nnzpr
-
ncol
¶ number of entries per row
- Type
int-array,
self.shape[0]
-
ptr
¶ pointer index in the 1D column indices of the corresponding row
- Type
int-array,
self.shape[0]+1
-
col
¶ column indices of the sparse elements
- Type
int-array
-
data
¶ the data in the sparse matrix
-
finalized
¶ whether the sparse matrix is finalized and non-set elements are removed
- Type
boolean
Attributes
__array_priority__
__dict__
__doc__
__hash__
__module__
__slots__
__weakref__
list of weak references to the object (if defined)
_finalized
_nnz
_ns
_shape
Data contained in the sparse matrix (numpy array of elements)
The extra dimensionality of the sparse matrix (elements per matrix element)
The data-type in the sparse matrix (in str)
The data-type in the sparse matrix
Whether the contained data is finalized and non-used elements have been removed
Number of non-zero elements in the sparse matrix
The shape of the sparse matrix
Methods
_SparseCSR__init_shape
(arg1[, dim, dtype, …])__abs__
()__add__
(other)__and__
(other)__array_ufunc__
(ufunc, method, *inputs, **kwargs)__contains__
(key)Check whether a sparse index is non-zero
__delattr__
Implement delattr(self, name).
__delitem__
(key)Remove items from the sparse patterns
__dir__
Default dir() implementation.
__divmod__
(other)__eq__
(other)__floordiv__
(other)__format__
Default object formatter.
__ge__
(other)__getattribute__
Return getattr(self, name).
__getitem__
(key)Intrinsic sparse matrix retrieval of a non-zero element
__getstate__
()Return dictionary with the current state (finalizing the object may reduce memory footprint)
__gt__
(other)__iadd__
(other)__iand__
(other)__ifloordiv__
(other)__ilshift__
(other)__imatmul__
(other)__imod__
(other)__imul__
(other)__init__
(arg1[, dim, dtype, nnzpr, nnz])Initialize a new sparse CSR matrix
__init_subclass__
This method is called when a class is subclassed.
__invert__
()__ior__
(other)__ipow__
(other)__irshift__
(other)__isub__
(other)__iter__
([row])Iterations of the non-zero elements, returns a tuple of row and column with non-zero elements
__itruediv__
(other)__ixor__
(other)__le__
(other)__len__
()Number of rows in the sparse matrix
__lshift__
(other)__lt__
(other)__matmul__
(other)__mod__
(other)__mul__
(other)__ne__
(other)__neg__
()__new__
Create and return a new object.
__or__
(other)__pos__
()__pow__
(other)__radd__
(other)__rand__
(other)__rdivmod__
(other)__reduce__
Helper for pickle.
__reduce_ex__
Helper for pickle.
__repr__
()Return repr(self).
__rfloordiv__
(other)__rlshift__
(other)__rmatmul__
(other)__rmod__
(other)__rmul__
(other)__ror__
(other)__rpow__
(other)__rrshift__
(other)__rshift__
(other)__rsub__
(other)__rtruediv__
(other)__rxor__
(other)__setattr__
Implement setattr(self, name, value).
__setitem__
(key, data)Intrinsic sparse matrix assignment of the item.
__setstate__
(state)Reset state of the object
__sizeof__
Size of object in memory, in bytes.
__str__
()Representation of the sparse matrix model
__sub__
(other)__subclasshook__
Abstract classes can override this to customize issubclass().
__truediv__
(other)__xor__
(other)_clean_columns
()Remove all intrinsic columns that are not defined in the sparse matrix
_extend
(i, j[, ret_indices])Extends the sparsity pattern to retain elements j in row i
_extend_empty
(i, n)Extends the sparsity pattern to retain elements j in row i
_get
(i, j)Retrieves the data pointer arrays of the elements, if it is non-existing, it will return
-1
_get_only
(i, j)Retrieves the data pointer arrays of the elements, only return elements in the sparse array
_slice2list
(slc, axis)Convert a slice to a list depending on the provided details
align
(other)Aligns this sparse matrix with the sparse elements of the other sparse matrix
copy
([dims, dtype])A deepcopy of the sparse matrix
delete_columns
(columns[, keep_shape])Delete all columns in columns
diagonal
()Return the diagonal elements from the matrix
diags
(diagonals[, offsets, dim, dtype])Create a
SparseCSR
with diagonal elements with the same shape as the routineedges
(row[, exclude])Retrieve edges (connections) of a given row or list of row’s
eliminate_zeros
([atol])Remove all zero elememts from the sparse matrix
empty
([keep_nnz])Delete all sparse information from the sparsity pattern
finalize
([sort])Finalizes the sparse matrix by removing all non-set elements
fromsp
(*sps, **kwargs)iter_nnz
([row])Iterations of the non-zero elements, returns a tuple of row and column with non-zero elements
nonzero
([row, only_col])Row and column indices where non-zero elements exists
remove
(indices)Return a new sparse CSR matrix with all the indices removed
scale_columns
(col, scale)Scale all values with certain column values with a number
spsame
(other)Check whether two sparse matrices have the same non-zero elements
sub
(indices)Create a new sparse CSR matrix with the data only for the given rows and columns
sum
([axis])Calculate the sum, if axis is
None
the sum of all elements are returned, else a new sparse matrix is returnedtocsr
([dim])Convert dimension
dim
into acsr_matrix
formattodense
()Return a dense
numpy.ndarray
which has 3 dimensions (self.shape)translate_columns
(old, new[, clean])Takes all old columns and translates them to new.
-
align
(other)[source]¶ Aligns this sparse matrix with the sparse elements of the other sparse matrix
Routine for ensuring that all non-zero elements in other are also in this object.
I.e. this will, possibly, change the sparse elements in-place.
A
ValueError
will be raised if the shapes are not mergeable.- Parameters
other (SparseCSR) – the other sparse matrix to align.
-
col
¶
-
copy
(dims=None, dtype=None)[source]¶ A deepcopy of the sparse matrix
- Parameters
dims (array-like, optional) – which dimensions to store in the copy, defaults to all.
dtype (
numpy.dtype
) – this defaults to the dtype of the object, but one may change it if supplied.
-
property
data
¶ Data contained in the sparse matrix (numpy array of elements)
-
diags
(diagonals, offsets=0, dim=None, dtype=None)[source]¶ Create a
SparseCSR
with diagonal elements with the same shape as the routine- Parameters
diagonals (scalar or array_like) – the diagonal values, if scalar the
shape
must be present.offsets (scalar or array_like) – the offsets from the diagonal for each of the components (defaults to the diagonal)
dim (int, optional) – the extra dimension of the new diagonal matrix (default to the current extra dimension)
dtype (numpy.dtype, optional) – the data-type to create (default to
numpy.float64
)
-
property
dim
¶ The extra dimensionality of the sparse matrix (elements per matrix element)
-
property
dkind
¶ The data-type in the sparse matrix (in str)
-
property
dtype
¶ The data-type in the sparse matrix
-
edges
(row, exclude=None)[source]¶ Retrieve edges (connections) of a given row or list of row’s
The returned edges are unique and sorted (see
numpy.unique
).
-
eliminate_zeros
(atol=0.0)[source]¶ Remove all zero elememts from the sparse matrix
This is an in-place operation
- Parameters
atol (float, optional) – absolute tolerance below this value will be considered 0.
-
empty
(keep_nnz=False)[source]¶ Delete all sparse information from the sparsity pattern
Essentially this deletes all entries.
- Parameters
keep_nnz (boolean, optional) – if
True
keeps the sparse elements as is. I.e. it will merely set the stored sparse elements to zero. This may be advantagegous when re-constructing a new sparse matrix from an old sparse matrix
-
finalize
(sort=True)[source]¶ Finalizes the sparse matrix by removing all non-set elements
One may still interact with the sparse matrix as one would previously.
NOTE: This is mainly an internal used routine to ensure data structure when converting to
csr_matrix
- Parameters
sort (bool, optional) – sort the column indices for each row
-
property
finalized
¶ Whether the contained data is finalized and non-used elements have been removed
-
iter_nnz
(row=None)[source]¶ Iterations of the non-zero elements, returns a tuple of row and column with non-zero elements
An iterator returning the current row index and the corresponding column index.
>>> for r, c in self:
In the above case
r
andc
are rows and columns such that>>> self[r, c]
returns the non-zero element of the sparse matrix.
- Parameters
row (int or array_like of int) – only loop on the given row(s) default to all rows
-
ncol
¶
-
property
nnz
¶ Number of non-zero elements in the sparse matrix
-
ptr
¶
-
remove
(indices)[source]¶ Return a new sparse CSR matrix with all the indices removed
- Parameters
indices (array_like) – the indices of the rows and columns that are removed in the sparse pattern
-
scale_columns
(col, scale)[source]¶ Scale all values with certain column values with a number
This will multiply all values with certain column values with scale
\[M[:, cols] *= scale\]This is an in-place operation.
-
property
shape
¶ The shape of the sparse matrix
-
sub
(indices)[source]¶ Create a new sparse CSR matrix with the data only for the given rows and columns
All rows and columns in indices are retained, everything else is removed.
- Parameters
indices (array_like) – the indices of the rows and columns that are retained in the sparse pattern
-
sum
(axis=None)[source]¶ Calculate the sum, if axis is
None
the sum of all elements are returned, else a new sparse matrix is returned- Parameters
axis (int, optional) – which axis to perform the sum of. If
None
the element sum is returned, if either0
or1
is passed a vector is returned, and for2
it returns a new sparse matrix with the last dimension reduced to 1 (summed).
:raises NotImplementedError : when
axis = 1
:
-
tocsr
(dim=0, **kwargs)[source]¶ Convert dimension
dim
into acsr_matrix
format- Parameters
dim (int, optional) – dimension of the data returned in a scipy sparse matrix format
**kwargs – arguments passed to the
csr_matrix
routine
-
todense
()[source]¶ Return a dense
numpy.ndarray
which has 3 dimensions (self.shape)