sisl.SparseCSR

class sisl.SparseCSR(arg1, dim=1, dtype=None, nnzpr=20, nnz=None, **kwargs)

Bases: 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 if nnz > nr * nnzpr.

This class may be instantiated by verious means.

  • SparseCSR(S) where S is a scipy.sparse matrix

  • SparseCSR((M,N)[, dtype]) the shape of the sparse matrix (equivalent to SparseCSR((M,N,1)[, dtype]).

  • SparseCSR((M,N), dim=K, [, dtype]) the shape of the sparse matrix (equivalent to SparseCSR((M,N,K)[, dtype]).

  • SparseCSR((M,N,K)[, dtype]) creating a sparse matrix with M rows, N columns and K elements per sparse element.

  • SparseCSR((data, ptr, indices), [shape, dtype]) creating a sparse matrix with specific data as would be used when creating scipy.sparse.csr_matrix.

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 supplied

  • nnz (int, optional) – initial total number of non-zero elements This quantity has precedence over nnzpr

Plotting

plot

Plotting functions for the SparseCSR class.

plot.atomicmatrix([dim, isc, ...])

Builds a AtomicMatrixPlot by setting the value of "matrix" to the current object.

Methods

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 (in-place action)

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 routine

edges(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[, dtype])

Combine multiple single-dimension sparse matrices into one SparseCSR matrix

iter_nnz([row])

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(*spmats[, dtype, dim, value])

Create a SparseCSR with constant fill value in all places that spmats have nonzeros

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

toarray()

Return a dense numpy.ndarray which has 3 dimensions (self.shape)

tocsr([dim])

Convert dimension dim into a csr_matrix format

todense()

Return a dense numpy.ndarray which 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 matrix

translate_columns(old, new[, rows, clean])

Takes all old columns and translates them to new.

transpose([sort])

Create the transposed sparse matrix

Attributes

ptr

ncol

col

data

Data contained in the sparse matrix (numpy array of elements)

dim

The extra dimensionality of the sparse matrix (elements per matrix element)

dkind

The data-type in the sparse matrix (in str)

dtype

The data-type in the sparse matrix

finalized

Whether the contained data is finalized and non-used elements have been removed

nnz

Number of non-zero elements in the sparse matrix

shape

The shape of the sparse matrix

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.

copy(dims=None, dtype=None)[source]

A deepcopy of the sparse matrix

Parameters:
  • dims (int or 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.

delete_columns(columns, keep_shape=False)[source]

Delete all columns in columns (in-place action)

Parameters:
  • columns (int or array_like) – columns to delete from the sparse pattern

  • keep_shape (bool, optional) – whether the shape of the object should be retained, if True all higher columns will be shifted according to the number of columns deleted below, if False, only the elements will be deleted.

diagonal()[source]

Return the diagonal elements from the matrix

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)

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

Parameters:
  • row (int or list of int) – the edges are returned only for the given row

  • exclude (int or list of int, optional) – remove edges which are in the exclude list.

eliminate_zeros(atol: float = 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

classmethod fromsp(*sps, 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:
  • *sps (sparse-matrix) – any sparse matrix which can convert to a scipy.sparse.csr_matrix matrix

  • dtype (numpy.dtype, optional) – data-type to store in the matrix, default to largest dtype for the passed sparse matrices

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 and c 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

nonzero(rows=None, only_cols: bool = False)[source]

Row and column indices where non-zero elements exists

Parameters:
  • rows (int or array_like of int, optional) – only return the tuples for the requested rows, default is all rows

  • only_cols (bool, optional) – only return the non-zero columns

plot.atomicmatrix(dim: int = 0, isc: int | None = None, fill_value: float | None = None, geometry: Geometry | None = None, atom_lines: bool | dict = False, orbital_lines: bool | dict = False, sc_lines: bool | dict = False, color_pixels: bool = True, colorscale: Colorscale | None = 'RdBu', crange: tuple[float, float] | None = None, cmid: float | None = None, text: str | None = None, textfont: dict | None = {}, set_labels: bool = False, constrain_axes: bool = True, arrows: list[dict] = [], backend: str = 'plotly') AtomicMatrixPlot

Builds a AtomicMatrixPlot by 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 – If the matrix has a third dimension (e.g. spin), which index to plot in that third dimension.

  • isc – 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 – If the matrix is sparse, the value to use for the missing entries.

  • geometry – 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 – 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 – 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 – 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 – Whether to color the pixels of the matrix according to the colorscale.

  • colorscale – The colorscale to use to color the pixels.

  • crange – The minimum and maximum values of the colorscale.

  • cmid – The midpoint of the colorscale. If crange is 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 – If provided, show text of pixel value with the specified format. E.g. text=”.3f” shows the value with three decimal places.

  • textfont – The font to use for the text. This is a dictionary that may contain the keys “family”, “size”, “color”.

  • set_labels – 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 Atom is the index of the atom and l and m are the quantum numbers of the orbital.

  • constrain_axes – Whether to set the ranges of the axes to exactly fit the matrix.

  • backend – The backend to use for plotting.

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(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 (int or array_like) – column indices to scale

  • scale (float or array_like) – scale value for each value (if array-like it has to have the same dimension as the sparsity dimension)

  • rows (int or array_like, optional) – only scale the column values that exists in these rows, default to all

classmethod sparsity_union(*spmats, dtype=None, dim=None, value=0)[source]

Create a SparseCSR with constant fill value in all places that spmats have nonzeros

By default the returned matrix will be sorted.

Parameters:
  • spmats (SparseCSR or csr_matrix) – SparseCSRs to find the sparsity pattern union of.

  • dtype (dtype, optional) – Output dtype. If not given, use the result dtype of the spmats.

  • dim (int, optional) – If given, the returned SparseCSR will have this as dim. By default the first given spmat decides the dimension.

  • value (scalar, default 0) – The used fill value.

spsame(other)[source]

Check whether two sparse matrices have the same non-zero elements

Parameters:

other (SparseCSR)

Returns:

bool – true if the same non-zero elements are in the matrices (but not necessarily the same values)

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

toarray()[source]

Return a dense numpy.ndarray which has 3 dimensions (self.shape)

tocsr(dim=0, **kwargs)[source]

Convert dimension dim into a csr_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)

transform(matrix, dtype=None)[source]

Apply a linear transformation \(R^n \rightarrow R^m\) to the \(n\)-dimensional elements of the sparse matrix

Notes

The transformation matrix does not act on the rows and columns, only on the final dimension of the matrix.

Parameters:
  • matrix (array_like) – transformation matrix of shape \(m \times n\), \(n\) should correspond to the number of elements in self.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 (int or array_like) – old column indices

  • new (int or array_like) – new column indices

  • rows (int or array_like) – only translate columns for the given rows

  • clean (bool, optional) – whether the new translated columns, outside the shape, should be deleted or not (default delete)

transpose(sort=True)[source]

Create the transposed sparse matrix

Parameters:

sort (bool, optional) – 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.

Returns:

object – an equivalent sparse matrix with transposed matrix elements

col
property data

Data contained in the sparse matrix (numpy array of elements)

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

property finalized

Whether the contained data is finalized and non-used elements have been removed

ncol
property nnz

Number of non-zero elements in the sparse matrix

plot

Plotting functions for the SparseCSR class.

ptr
property shape

The shape of the sparse matrix