sisl.SparseCSR
- class sisl.SparseCSR
Bases:
NDArrayOperatorsMixinA compressed sparse row matrix, slightly different than
csr_array.This class holds all required information regarding the CSR matrix format.
Note that this sparse array 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 array class tries to resemble the
csr_arrayas much as possible with the difference of this class being multi-dimensional.Creating a new sparse array is much similar to the
scipyequivalent.nnzis only used ifnnz > nr * nnzpr.This class may be instantiated by verious means.
SparseCSR(S)whereSis ascipy.sparsematrixSparseCSR((M,N)[, dtype])the shape of the sparse array (equivalent toSparseCSR((M,N,1)[, dtype]).SparseCSR((M,N), dim=K, [, dtype])the shape of the sparse array (equivalent toSparseCSR((M,N,K)[, dtype]).SparseCSR((M,N,K)[, dtype])creating a sparse array withMrows,Ncolumns andKelements per sparse element.SparseCSR((data, ptr, indices), [shape, dtype])creating a sparse array with specific data as would be used when creatingscipy.sparse.csr_array.
Additionally these parameters control the creation of the sparse array.
- Parameters:
arg1 (
tuple) – various initialization methods as described abovedim (
int, optional) – number of elements stored per sparse element, only used if (M,N) is passeddtype (
numpy.dtype, optional) – data type of the matrix, defaults tonumpy.float64nnzpr (
int, optional) – initial number of non-zero elements per row. Only used ifnnzis not suppliednnz (
int, optional) – initial total number of non-zero elements This quantity has precedence over nnzpr
Plotting
Plotting functions for the
SparseCSRclass.plot.atomicmatrix([dim, isc, ...])Builds a
AtomicMatrixPlotby setting the value of "matrix" to the current object.Methods
align(other)Aligns this sparse array with the sparse elements of the other sparse array
astype(dtype[, copy])Convert the stored data-type to something else
copy([dims, dtype])A deepcopy of the sparse array
delete_columns(cols[, keep_shape])Delete all columns in columns (in-place action)
diagonal()Return the diagonal elements from the matrix
diags(diagonals[, offsets, dim, dtype])Create a
SparseCSRwith diagonal elements with the same shape as the routinedistribute([dist, op])Distribute the rows of csr according to dist, moving each element to its owner.
edges(rows[, exclude])Retrieve edges (connections) of given rows
eliminate_zeros([atol])Remove all zero elememts from the sparse array
empty([keep_nnz])Delete all sparse information from the sparsity pattern
finalize([sort])Finalizes the sparse array by removing all non-set elements
fromsp(sparse_matrices[, dtype])Combine multiple single-dimension sparse matrices into one SparseCSR matrix
iter_nnz([rows])Iterations of the non-zero elements, returns a tuple of row and column with non-zero elements
nonzero([rows, only_cols])Row and column indices where non-zero elements exists
remove(indices)Return a new sparse CSR matrix with all the indices removed
scale_columns(cols, scale[, rows])Scale all values with certain column values with a number
sparsity_union(sparse_matrices[, dtype, ...])Create a
SparseCSRwith constant fill value in all places that sparse_matrices have nonzerosspsame(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
toarray()Return a dense
numpy.ndarraywhich has 3 dimensions (self.shape)tocsr([dim])todense()Return a dense
numpy.ndarraywhich has 3 dimensions (self.shape)transform(matrix[, dtype])Apply a linear transformation \(R^n \rightarrow R^m\) to the \(n\)-dimensional elements of the sparse array
translate_columns(old, new[, rows, clean])Takes all old columns and translates them to new.
transpose([sort])Create the transposed sparse array
Attributes
int-array, column indices of the sparse elements
Data contained in the sparse array (numpy array of elements)
The extra dimensionality of the sparse array (elements per matrix element)
The data-type in the sparse array (in str)
The data-type in the sparse array
Whether the contained data is finalized and non-used elements have been removed
int-array,
self.shape[0]number of entries per rowNumber of non-zero elements in the sparse array
int-array,
self.shape[0]+1pointer index in the 1D column indices of the corresponding rowThe shape of the sparse array
- classmethod fromsp(sparse_matrices, dtype=None)[source]
Combine multiple single-dimension sparse matrices into one SparseCSR matrix
The different sparse matrices need not have the same sparsity pattern.
- Parameters:
sparse_matrices (OrSequence[SparseMatrix]) – any sparse array which can convert to a
scipy.sparse.csr_arraymatrixdtype (
numpy.dtype, optional) – data-type to store in the matrix, default to largestdtypefor the passed sparse matrices
- classmethod sparsity_union(sparse_matrices, dtype=None, dim=None, value=0)[source]
Create a
SparseCSRwith constant fill value in all places that sparse_matrices have nonzerosBy default the returned matrix will be sorted.
- Parameters:
sparse_matrices (OrSequence[SparseMatrix]) – SparseCSRs to find the sparsity pattern union of.
dtype (
dtype, optional) – Output dtype. If not given, use the result dtype of the spmats.dim (Optional[int]) – If given, the returned SparseCSR will have this as dim. By default the first sparse array in sparse_matrices determines the resulting 3rd dimension.
value (float) – The used fill value.
- Return type:
Self
- align(other)[source]
Aligns this sparse array with the sparse elements of the other sparse array
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
ValueErrorwill be raised if the shapes are not mergeable.- Parameters:
other (
SparseCSR) – the other sparse array to align.
- astype(dtype, copy=True)[source]
Convert the stored data-type to something else
- Parameters:
dtype – the new dtype for the sparse array
copy (bool) – copy when needed, or do not copy when not needed.
- Return type:
Self
- copy(dims=None, dtype=None)[source]
A deepcopy of the sparse array
- Parameters:
dims (Optional[SeqOrScalarInt]) – 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.
- delete_columns(cols, keep_shape=False)[source]
Delete all columns in columns (in-place action)
- Parameters:
- diags(diagonals, offsets=0, dim=None, dtype=None)[source]
Create a
SparseCSRwith diagonal elements with the same shape as the routine- Parameters:
diagonals (
scalarorndarray) – the diagonal values, if scalar theshapemust be present.offsets (
scalarorndarray) – the offsets from the diagonal for each of the components (defaults to the diagonal)dim (Optional[int]) – the extra dimension of the new diagonal matrix (default to the current extra dimension)
dtype (
numpy.dtype, optional) – the data-type to create (default tonumpy.float64)
- distribute(dist=None, op='single')
Distribute the rows of csr according to dist, moving each element to its owner.
SparseCSR’s implementation of the__sisl_distribute__protocol; call it throughdist(csr)in code that should work for any distributable object.This is the assembly step of the deferred scheme: structural changes only bump an epoch, and the communication happens here, once, at the point a consumer needs a coherent matrix. Afterwards every rank holds exactly the rows dist assigns it, and nothing else. The matrix keeps its full shape.
Ranks may write to rows they do not own; those entries are shipped to the owner. The same holds when dist differs from the distribution the matrix was previously assembled with: every stored element is shipped to its new owner. All ranks must call this together – it is collective.
- Parameters:
csr (SparseCSR) – the matrix to distribute, it is changed in place
dist (Distribution | None) – the distribution of the rows. Defaults to the distribution csr was last distributed with.
op (str) – how to merge entries several ranks wrote to the same position.
"single"keeps one of them,"sum"sums them – which is what accumulating contributions into a matrix needs.
- Returns:
csr itself, assembled in place.
- Return type:
- edges(rows, exclude=None)[source]
Retrieve edges (connections) of given rows
The returned edges are unique and sorted (see
numpy.unique).- Parameters:
rows (SeqOrScalarInt) – the edges are returned only for the given row
exclude (Optional[SeqOrScalarInt]) – remove edges which are in the exclude list.
- eliminate_zeros(atol=0.0)[source]
Remove all zero elememts from the sparse array
This is an in-place operation
- empty(keep_nnz=False)[source]
Delete all sparse information from the sparsity pattern
Essentially this deletes all entries.
- finalize(sort=True)[source]
Finalizes the sparse array by removing all non-set elements
One may still interact with the sparse array as one would previously.
NOTE: This is mainly an internal used routine to ensure data structure when converting to
csr_array
- iter_nnz(rows=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
randcare rows and columns such that>>> self[r, c]
returns the non-zero element of the sparse array.
- Parameters:
row (
intorndarrayofint) – only loop on the given row(s) default to all rowsrows (Optional[SeqOrScalarInt])
- nonzero(rows=None, only_cols=False)[source]
Row and column indices where non-zero elements exists
- Parameters:
rows (Optional[SeqOrScalarInt]) – only return the tuples for the requested rows, default is all rows
only_cols (bool) – only return the non-zero columns
- plot.atomicmatrix(dim=0, isc=None, fill_value=None, geometry=None, atom_lines=False, orbital_lines=False, sc_lines=False, color_pixels=True, colorscale='RdBu', crange=None, cmid=None, text=None, textfont={}, set_labels=False, constrain_axes=True, arrows=[], backend='plotly')
Builds a
AtomicMatrixPlotby setting the value of “matrix” to the current object.Plots a (possibly sparse) matrix where rows and columns are either orbitals or atoms.
- Parameters:
dim (int) – If the matrix has a third dimension (e.g. spin), which index to plot in that third dimension.
isc (Optional[int]) – If the matrix contains data for an auxiliary supercell, the index of the cell to plot. If None, the whole matrix is plotted.
fill_value (Optional[float]) – If the matrix is sparse, the value to use for the missing entries.
geometry (Union[Geometry, None]) – Only needed if the matrix does not contain a geometry (e.g. it is a numpy array) and separator lines or labels are requested.
atom_lines (Union[bool, dict]) – If a boolean, whether to draw lines separating atom blocks, using default styles. If a dict, draws the lines with the specified plotly line styles.
orbital_lines (Union[bool, dict]) – If a boolean, whether to draw lines separating blocks of orbital sets, using default styles. If a dict, draws the lines with the specified plotly line styles.
sc_lines (Union[bool, dict]) – If a boolean, whether to draw lines separating the supercells, using default styles. If a dict, draws the lines with the specified plotly line styles.
color_pixels (bool) – Whether to color the pixels of the matrix according to the colorscale.
colorscale (Optional[Colorscale]) – The colorscale to use to color the pixels.
crange (Optional[tuple[float, float]]) – The minimum and maximum values of the colorscale.
cmid (Optional[float]) –
The midpoint of the colorscale. If
crangeis provided, this is ignored.If None and crange is also None, the midpoint is set to 0 if the data contains both positive and negative values.
text (Optional[str]) – If provided, show text of pixel value with the specified format. E.g. text=”.3f” shows the value with three decimal places.
textfont (Optional[dict]) – The font to use for the text. This is a dictionary that may contain the keys “family”, “size”, “color”.
set_labels (bool) – Whether to set the axes labels to the atom/orbital that each row and column corresponds to. For orbitals the labels will be of the form “Atom: (l, m)”, where
Atomis the index of the atom and l and m are the quantum numbers of the orbital.constrain_axes (bool) – Whether to set the ranges of the axes to exactly fit the matrix.
backend (str) – The backend to use for plotting.
- Return type:
- remove(indices)[source]
Return a new sparse CSR matrix with all the indices removed
- Parameters:
indices (SeqOrScalarInt) – the indices of the rows and columns that are removed in the sparse pattern
- Return type:
Self
- scale_columns(cols, scale, rows=None)[source]
Scale all values with certain column values with a number
This will multiply all values with certain column values with
scale\[\mathbf M\[\mathrm{rows}, \mathrm{cols}\] *= \mathrm{scale}\]This is an in-place operation.
- Parameters:
cols (SeqOrScalarInt) – column indices to scale
scale (SeqOrScalarFloat) – scale value for each value (if array-like it has to have the same dimension as the sparsity dimension)
rows (Optional[SeqOrScalarInt]) – only scale the column values that exists in these rows, default to all
- 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 (SeqOrScalarInt) – the indices of the rows and columns that are retained in the sparse pattern
- Return type:
Self
- toarray()[source]
Return a dense
numpy.ndarraywhich has 3 dimensions (self.shape)
- todense()[source]
Return a dense
numpy.ndarraywhich has 3 dimensions (self.shape)
- transform(matrix, dtype=None)[source]
Apply a linear transformation \(R^n \rightarrow R^m\) to the \(n\)-dimensional elements of the sparse array
Notes
The transformation matrix does not act on the rows and columns, only on the final dimension of the matrix.
- Parameters:
matrix (
ndarray) – transformation matrix of shape \(m \times n\), \(n\) should correspond to the number of elements inself.shape[2]dtype (
numpy.dtype, optional) – defaults to the common dtype of the object and the transformation matrix
- translate_columns(old, new, rows=None, clean=True)[source]
Takes all old columns and translates them to new.
- Parameters:
old (SeqOrScalarInt) – old column indices
new (SeqOrScalarInt) – new column indices
rows (Optional[SeqOrScalarInt]) – only translate columns for the given rows
clean (bool) – whether the new translated columns, outside the shape, should be deleted or not (default delete)
- transpose(sort=True)[source]
Create the transposed sparse array
- Parameters:
sort (bool) – the returned columns for the transposed structure will be sorted if this is true, default
Notes
The components for each sparse element are not changed in this method.
- property dkind
The data-type in the sparse array (in str)
- property dtype
The data-type in the sparse array
- property finalized: bool
Whether the contained data is finalized and non-used elements have been removed