egttools.analytical.sed_analytical.lil_matrix

class lil_matrix(arg1, shape=None, dtype=None, copy=False, *, maxprint=None)[source]

Bases: spmatrix, _lil_base

Row-based LIst of Lists sparse matrix.

This is a structure for constructing sparse matrices incrementally. Note that inserting a single item can take linear time in the worst case; to construct the matrix efficiently, make sure the items are pre-sorted by index, per row.

Warning

SciPy sparse is shifting from a sparse matrix interface to a sparse array interface. In the next few releases we expect to deprecate the sparse matrix interface. For documentation of the matrix interface, see the spmatrix interface docs. For guidance on converting existing code to sparse arrays, see Migration from spmatrix to sparray.

This can be instantiated in several ways:
lil_matrix(D)

where D is a 2-D ndarray

lil_matrix(S)

with another sparse array or matrix S (equivalent to S.tolil())

lil_matrix((M, N), [dtype])

to construct an empty matrix with shape (M, N) dtype is optional, defaulting to dtype=’d’.

data

LIL format data array of the matrix

Type:

ndarray

rows

LIL format row index array of the matrix

Type:

ndarray

dtype

Data type of the matrix

Type:

dtype

shape

Shape of the matrix

Type:

2-tuple

ndim

Number of dimensions (this is always 2)

Type:

int

format

Three letter code for the format of the matrix storage, e.g. ‘lil’

Type:

str

nnz

Number of values stored in the matrix

Type:

int

size

Number of values stored in the matrix

Type:

int

T

The transpose of the matrix

Type:

lil_matrix

mT

The transpose of the matrix

Type:

lil_array

Notes

Sparse matrices can be used in arithmetic operations: they support addition, subtraction, multiplication, division, and matrix power.

Advantages of the LIL format
  • supports flexible slicing

  • changes to the matrix sparsity structure are efficient

Disadvantages of the LIL format
  • arithmetic operations LIL + LIL are slow (consider CSR or CSC)

  • slow column slicing (consider CSC)

  • slow matrix vector products (consider CSR or CSC)

Intended Usage
  • LIL is a convenient format for constructing sparse matrices

  • once a matrix has been constructed, convert to CSR or CSC format for fast arithmetic and matrix vector operations

  • consider using the COO format when constructing large matrices

Data Structure
  • An array (self.rows) of rows, each of which is a sorted list of column indices of non-zero elements.

  • The corresponding nonzero values are stored in similar fashion in self.data.

Methods

asformat

Return this array/matrix in the passed format.

asfptype

Upcast matrix to a floating point format (if necessary)

astype

Cast the array/matrix elements to a specified type.

conj

Element-wise complex conjugation.

conjugate

Element-wise complex conjugation.

copy

Returns a copy of this array/matrix.

count_nonzero

Number of non-zero entries.

diagonal

Returns the kth diagonal of the array/matrix.

dot

Ordinary dot product.

getH

Return the Hermitian transpose of this matrix.

get_shape

Get the shape of the matrix

getcol

Returns a copy of column j of the matrix, as an (m x 1) sparse matrix (column vector).

getformat

Matrix storage format

getmaxprint

Maximum number of elements to display when printed.

getnnz

Number of stored values, including explicit zeros.

getrow

Returns a copy of row i of the matrix, as a (1 x n) sparse matrix (row vector).

getrowview

Returns a view of the 'i'th row (without copying).

maximum

Element-wise maximum between this and another array/matrix.

mean

Compute the arithmetic mean along the specified axis.

minimum

Element-wise minimum between this and another array/matrix.

multiply

Element-wise multiplication by another array/matrix.

nonzero

Nonzero indices of the array/matrix.

power

Element-wise power.

reshape

Gives a new shape to a sparse array/matrix without changing its data.

resize

Resize the array/matrix in-place to dimensions given by shape.

set_shape

Set the shape of the matrix in-place

setdiag

Set diagonal or off-diagonal elements of the array/matrix.

sum

Sum the array/matrix elements over a given axis.

toarray

Return a dense ndarray representation of this sparse array/matrix.

tobsr

Convert this array/matrix to Block Sparse Row format.

tocoo

Convert this array/matrix to COOrdinate format.

tocsc

Convert this array/matrix to Compressed Sparse Column format.

tocsr

Convert this array/matrix to Compressed Sparse Row format.

todense

Return a dense representation of this sparse matrix.

todia

Convert this array/matrix to sparse DIAgonal format.

todok

Convert this array/matrix to Dictionary Of Keys format.

tolil

Convert this array/matrix to List of Lists format.

trace

Returns the sum along diagonals of the sparse array/matrix.

transpose

Reverses the dimensions of the sparse array/matrix.

Attributes

T

Transpose.

format

Format string for matrix.

imag

mT

Matrix transpose.

ndim

nnz

Number of stored values, including explicit zeros.

real

shape

Shape of the matrix

size

Number of stored values.

classmethod __class_getitem__(arg, /)

Return a parametrized wrapper around the ~scipy.sparse.spmatrix type.

Added in version 1.16.0.

Returns:

alias – A parametrized ~scipy.sparse.spmatrix type.

Return type:

types.GenericAlias

Examples

>>> import numpy as np
>>> from scipy.sparse import coo_matrix
>>> coo_matrix[np.int8]
scipy.sparse._coo.coo_matrix[numpy.int8]
__abs__()
__add__(other)
__bool__()
__eq__(other)

Return self==value.

__ge__(other)

Return self>=value.

__getitem__(key)
__gt__(other)

Return self>value.

__iadd__(other)
__imul__(other)
__init__(arg1, shape=None, dtype=None, copy=False, *, maxprint=None)
__isub__(other)
__iter__()
__itruediv__(other)
__le__(other)

Return self<=value.

__len__()
__lt__(other)

Return self<value.

__matmul__(other)
__mul__(other)
__ne__(other)

Return self!=value.

__neg__()
__pow__(power)
__radd__(other)
__repr__()

Return repr(self).

__rmatmul__(other)
__rmul__(other)
__round__(ndigits=0)
__rsub__(other)
__rtruediv__(other)
__setitem__(key, x)
__str__()

Return str(self).

__sub__(other)
__truediv__(other)
asformat(format, copy=False)

Return this array/matrix in the passed format.

Parameters:
  • format ({str, None}) – The desired sparse format (“csr”, “csc”, “lil”, “dok”, “array”, …) or None for no conversion.

  • copy (bool, optional) – If True, the result is guaranteed to not share data with self.

Returns:

A – This array/matrix in the passed format.

Return type:

array/matrix

asfptype()

Upcast matrix to a floating point format (if necessary)

astype(dtype, casting='unsafe', copy=True)

Cast the array/matrix elements to a specified type.

Parameters:
  • dtype (str or numpy dtype) – Typecode or data-type to which to cast the data.

  • casting ({'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional) – Controls what kind of data casting may occur. Defaults to ‘unsafe’ for backwards compatibility. ‘no’ means the data types should not be cast at all. ‘equiv’ means only byte-order changes are allowed. ‘safe’ means only casts which can preserve values are allowed. ‘same_kind’ means only safe casts or casts within a kind, like float64 to float32, are allowed. ‘unsafe’ means any data conversions may be done.

  • copy (bool, optional) – If copy is False, the result might share some memory with this array/matrix. If copy is True, it is guaranteed that the result and this array/matrix do not share any memory.

Returns:

This array/matrix with data type dtype.

Return type:

array/matrix

conj(copy=True)

Element-wise complex conjugation.

If the array/matrix is of non-complex data type and copy is False, this method does nothing and the data is not copied.

Parameters:

copy (bool, optional) – If True, the result is guaranteed to not share data with self.

Returns:

A – The element-wise complex conjugate.

Return type:

sparse array/matrix

conjugate(copy=True)

Element-wise complex conjugation.

If the array/matrix is of non-complex data type and copy is False, this method does nothing and the data is not copied.

Parameters:

copy (bool, optional) – If True, the result is guaranteed to not share data with self.

Returns:

A – The element-wise complex conjugate.

Return type:

sparse array/matrix

copy()

Returns a copy of this array/matrix.

No data/indices will be shared between the returned value and current array/matrix.

Returns:

A copy of this array/matrix.

Return type:

sparse array/matrix

count_nonzero(axis=None)

Number of non-zero entries.

This is equivalent to:

np.count_nonzero(a.toarray(), axis=axis)

Unlike the nnz property, which return the number of stored entries (the length of the data attribute), this method counts the actual number of non-zero entries in data.

Duplicate entries are summed before counting.

Parameters:

axis ({-2, -1, 0, 1, None} optional) –

Count nonzeros for the whole array, or along a specified axis.

Added in version 1.15.0.

Returns:

A reduced array (no axis axis) holding the number of nonzero values for each of the indices of the nonaxis dimensions.

Return type:

numpy array

Notes

If you want to count nonzero and explicit zero stored values (e.g. nnz) along an axis, two fast idioms are provided by numpy functions for the common CSR, CSC, COO formats.

For the major axis in CSR (rows) and CSC (cols) use np.diff:

>>> import numpy as np
>>> import scipy as sp
>>> A = sp.sparse.csr_array([[4, 5, 0], [7, 0, 0]])
>>> major_axis_stored_values = np.diff(A.indptr)  # -> np.array([2, 1])

For the minor axis in CSR (cols) and CSC (rows) use numpy.bincount with minlength A.shape[1] for CSR and A.shape[0] for CSC:

>>> csr_minor_stored_values = np.bincount(A.indices, minlength=A.shape[1])

For COO, use the minor axis approach for either axis:

>>> A = A.tocoo()
>>> coo_axis0_stored_values = np.bincount(A.coords[0], minlength=A.shape[1])
>>> coo_axis1_stored_values = np.bincount(A.coords[1], minlength=A.shape[0])

Examples

>>> A = sp.sparse.csr_array([[4, 5, 0], [7, 0, 0]])
>>> A.count_nonzero(axis=0)
array([2, 1, 0])
diagonal(k=0)

Returns the kth diagonal of the array/matrix.

Parameters:

k (int, optional) –

Which diagonal to get, corresponding to elements a[i, i+k]. Default: 0 (the main diagonal).

Added in version 1.0.

Returns:

d – The specified diagonal of the array/matrix.

Return type:

ndarray

See also

numpy.diagonal

Equivalent numpy function.

Examples

>>> from scipy.sparse import csr_array
>>> A = csr_array([[1, 2, 0], [0, 0, 3], [4, 0, 5]])
>>> A.diagonal()
array([1, 0, 5])
>>> A.diagonal(k=1)
array([2, 3])
dot(other)

Ordinary dot product.

Parameters:

other (array_like or sparse array) – Array to take dot product with.

Returns:

Result of dot product. The type depends on other:

  • If other is a scalar, the result is a sparse array/matrix.

  • If other is an ndarray, the result is an ndarray.

Return type:

sparse array/matrix or ndarray

Examples

>>> import numpy as np
>>> from scipy.sparse import csr_array
>>> A = csr_array([[1, 2, 0], [0, 0, 3], [4, 0, 5]])
>>> v = np.array([1, 0, -1])
>>> A.dot(v)
array([ 1, -3, -1], dtype=int64)
getH()

Return the Hermitian transpose of this matrix.

See also

numpy.matrix.getH

NumPy’s implementation of getH for matrices

get_shape()

Get the shape of the matrix

getcol(j)

Returns a copy of column j of the matrix, as an (m x 1) sparse matrix (column vector).

getformat()

Matrix storage format

getmaxprint()

Maximum number of elements to display when printed.

getnnz(axis=None)

Number of stored values, including explicit zeros.

Parameters:

axis (None, 0, or 1) – Select between the number of values across the whole array, in each column, or in each row.

getrow(i)

Returns a copy of row i of the matrix, as a (1 x n) sparse matrix (row vector).

getrowview(i)

Returns a view of the ‘i’th row (without copying).

Parameters:

i (int) – Row to return view of.

Returns:

A view of the ‘i’th row.

Return type:

lil_array or lil_matrix

maximum(other)

Element-wise maximum between this and another array/matrix.

Parameters:

other (array_like or sparse array) – Array to compare against.

Returns:

Result of element-wise minimum. The type depends on other:

  • If other is a scalar, the result is a sparse array/matrix.

  • If other is an ndarray, the result is an ndarray.

Return type:

sparse array/matrix or ndarray

mean(axis=None, dtype=None, out=None)

Compute the arithmetic mean along the specified axis.

Returns the average of the array/matrix elements. The average is taken over all elements in the array/matrix by default, otherwise over the specified axis. float64 intermediate and return values are used for integer inputs.

Parameters:
  • axis ({-2, -1, 0, 1, None} optional) – Axis along which the mean is computed. The default is to compute the mean of all elements in the array/matrix (i.e., axis = None).

  • dtype (data-type, optional) –

    Type to use in computing the mean. For integer inputs, the default is float64; for floating point inputs, it is the same as the input dtype.

    Added in version 0.18.0.

  • out (np.matrix, optional) –

    Alternative output matrix in which to place the result. It must have the same shape as the expected output, but the type of the output values will be cast if necessary.

    Added in version 0.18.0.

Returns:

m – Mean along the specified axis.

Return type:

np.matrix

See also

numpy.matrix.mean

NumPy’s implementation of ‘mean’ for matrices

minimum(other)

Element-wise minimum between this and another array/matrix.

Parameters:

other (array_like or sparse array) – Array to compare against.

Returns:

Result of element-wise minimum. The type depends on other:

  • If other is a scalar, the result is a sparse array/matrix.

  • If other is an ndarray, the result is an ndarray.

Return type:

sparse array/matrix or ndarray

multiply(other)

Element-wise multiplication by another array/matrix.

Parameters:

other (sparse array or array_like) – Array to multiply by.

Returns:

Result of element-wise multiplication.

Return type:

sparse array/matrix

nonzero()

Nonzero indices of the array/matrix.

Returns:

  • row (ndarray) – Row indices of non-zero elements.

  • col (ndarray) – Column indices of non-zero elements.

Examples

>>> from scipy.sparse import csr_array
>>> A = csr_array([[1, 2, 0], [0, 0, 3], [4, 0, 5]])
>>> A.nonzero()
(array([0, 0, 1, 2, 2], dtype=int32), array([0, 1, 2, 0, 2], dtype=int32))
power(n, dtype=None)

Element-wise power.

Parameters:
  • n (scalar) – n is a non-zero scalar (nonzero avoids dense ones creation) If zero power is desired, special case it to use numpy.ones

  • dtype (dtype, optional) – If dtype is not specified, the current dtype will be preserved.

Returns:

Result of raising all elements to the power n.

Return type:

csr array/matrix

reshape(self, shape, order='C', copy=False)

Gives a new shape to a sparse array/matrix without changing its data.

Parameters:
  • *shape (int) – Integers specifying the new shape. The new shape should be compatible with the original shape.

  • order ({'C', 'F'}, optional) – Read the elements using this index order. ‘C’ means to read and write the elements using C-like index order; e.g., read entire first row, then second row, etc. ‘F’ means to read and write the elements using Fortran-like index order; e.g., read entire first column, then second column, etc.

  • copy (bool, optional) – Indicates whether or not attributes of self should be copied whenever possible. The degree to which attributes are copied varies depending on the type of sparse array being used.

Returns:

reshaped – A sparse array/matrix with the given shape, not necessarily of the same format as the current object.

Return type:

sparse array/matrix

See also

numpy.reshape

NumPy’s implementation of ‘reshape’ for ndarrays

resize(*shape)

Resize the array/matrix in-place to dimensions given by shape.

Any elements that lie within the new shape will remain at the same indices, while non-zero elements lying outside the new shape are removed.

Parameters:

*shape (int) – number of rows and columns in the new array/matrix

Notes

The semantics are not identical to numpy.ndarray.resize or numpy.resize. Here, the same data will be maintained at each index before and after reshape, if that index is within the new bounds. In numpy, resizing maintains contiguity of the array, moving elements around in the logical array but not within a flattened representation.

We give no guarantees about whether the underlying data attributes (arrays, etc.) will be modified in place or replaced with new objects.

set_shape(shape)

Set the shape of the matrix in-place

setdiag(values, k=0)

Set diagonal or off-diagonal elements of the array/matrix.

Parameters:
  • values (array_like) –

    New values of the diagonal elements.

    Values may have any length. If the diagonal is longer than values, then the remaining diagonal entries will not be set. If values are longer than the diagonal, then the remaining values are ignored.

    If a scalar value is given, all of the diagonal is set to it.

  • k (int, optional) – Which off-diagonal to set, corresponding to elements a[i,i+k]. Default: 0 (the main diagonal).

sum(axis=None, dtype=None, out=None)

Sum the array/matrix elements over a given axis.

Parameters:
  • axis ({-2, -1, 0, 1, None} optional) – Axis along which the sum is computed. The default is to compute the sum of all the array/matrix elements, returning a scalar (i.e., axis = None).

  • dtype (dtype, optional) –

    The type of the returned array/matrix and of the accumulator in which the elements are summed. The dtype of a is used by default unless a has an integer dtype of less precision than the default platform integer. In that case, if a is signed then the platform integer is used while if a is unsigned then an unsigned integer of the same precision as the platform integer is used.

    Added in version 0.18.0.

  • out (np.matrix, optional) –

    Alternative output matrix in which to place the result. It must have the same shape as the expected output, but the type of the output values will be cast if necessary.

    Added in version 0.18.0.

Returns:

sum_along_axis – A matrix with the same shape as self, with the specified axis removed.

Return type:

np.matrix

See also

numpy.matrix.sum

NumPy’s implementation of ‘sum’ for matrices

toarray(order=None, out=None)

Return a dense ndarray representation of this sparse array/matrix.

Parameters:
  • order ({'C', 'F'}, optional) – Whether to store multidimensional data in C (row-major) or Fortran (column-major) order in memory. The default is ‘None’, which provides no ordering guarantees. Cannot be specified in conjunction with the out argument.

  • out (ndarray, 2-D, optional) – If specified, uses this array as the output buffer instead of allocating a new array to return. The provided array must have the same shape and dtype as the sparse array/matrix on which you are calling the method. For most sparse types, out is required to be memory contiguous (either C or Fortran ordered).

Returns:

arr – An array with the same shape and containing the same data represented by the sparse array/matrix, with the requested memory order. If out was passed, the same object is returned after being modified in-place to contain the appropriate values.

Return type:

ndarray, 2-D

tobsr(blocksize=None, copy=False)

Convert this array/matrix to Block Sparse Row format.

Parameters:
  • blocksize (tuple of ints, optional) – When blocksize=(R, C) is provided, it will be used for construction of the bsr_array/matrix.

  • copy (bool, option) – With copy=False, the data/indices may be shared between this array/matrix and the resultant bsr_array/matrix.

Returns:

The converted array/matrix in BSR format.

Return type:

bsr array/matrix

tocoo(copy=False)

Convert this array/matrix to COOrdinate format.

Parameters:

copy (bool, optional) – With copy=False, the data/indices may be shared between this array/matrix and the resultant coo_array/matrix.

Returns:

The converted array/matrix in COO format.

Return type:

coo array/matrix

tocsc(copy=False)

Convert this array/matrix to Compressed Sparse Column format.

Parameters:

copy (bool, optional) – With copy=False, the data/indices may be shared between this array/matrix and the resultant csc_array/matrix.

Returns:

The converted array/matrix in CSC format.

Return type:

csc array/matrix

tocsr(copy=False)

Convert this array/matrix to Compressed Sparse Row format.

Parameters:

copy (bool, optional) – With copy=False, the data/indices may be shared between this array/matrix and the resultant csr_array/matrix.

Returns:

The converted array/matrix in CSR format.

Return type:

csr array/matrix

todense(order=None, out=None)

Return a dense representation of this sparse matrix.

Parameters:
  • order ({'C', 'F'}, optional) – Whether to store multi-dimensional data in C (row-major) or Fortran (column-major) order in memory. The default is ‘None’, which provides no ordering guarantees. Cannot be specified in conjunction with the out argument.

  • out (ndarray, 2-D, optional) – If specified, uses this array (or numpy.matrix) as the output buffer instead of allocating a new array to return. The provided array must have the same shape and dtype as the sparse matrix on which you are calling the method.

Returns:

arr – A NumPy matrix object with the same shape and containing the same data represented by the sparse matrix, with the requested memory order. If out was passed and was an array (rather than a numpy.matrix), it will be filled with the appropriate values and returned wrapped in a numpy.matrix object that shares the same memory.

Return type:

numpy.matrix, 2-D

todia(copy=False)

Convert this array/matrix to sparse DIAgonal format.

Parameters:

copy (bool, optional) – With copy=False, the data/indices may be shared between this array/matrix and the resultant dia_array/matrix.

Returns:

The converted array/matrix in DIA format.

Return type:

dia array/matrix

todok(copy=False)

Convert this array/matrix to Dictionary Of Keys format.

Parameters:

copy (bool, optional) – With copy=False, the data/indices may be shared between this array/matrix and the resultant dok_array/matrix.

Returns:

The converted array/matrix in DOK format.

Return type:

dok array/matrix

tolil(copy=False)

Convert this array/matrix to List of Lists format.

Parameters:

copy (bool, optional) – With copy=False, the data/indices may be shared between this array/matrix and the resultant lil_array/matrix.

Returns:

The converted array/matrix in LIL format.

Return type:

lil array/matrix

trace(offset=0)

Returns the sum along diagonals of the sparse array/matrix.

Parameters:

offset (int, optional) – Which diagonal to get, corresponding to elements a[i, i+offset]. Default: 0 (the main diagonal).

Returns:

The sum of the specified diagonal of the array/matrix.

Return type:

scalar

transpose(axes=None, copy=False)

Reverses the dimensions of the sparse array/matrix.

Parameters:
  • axes (None, optional) – This argument is in the signature solely for NumPy compatibility reasons. Do not pass in anything except for the default value.

  • copy (bool, optional) – Indicates whether or not attributes of self should be copied whenever possible. The degree to which attributes are copied varies depending on the type of sparse array/matrix being used.

Returns:

p – The transpose of the array/matrix.

Return type:

sparse array/matrix

See also

numpy.transpose

NumPy’s implementation of ‘transpose’ for ndarrays

Notes

If self is a csr_array or a csc_array, then this will return a csc_array or a csr_array, respectively.

property T

Transpose.

__abstractmethods__ = frozenset({})
__annotations__ = {}
__array_priority__ = 10.1
__hash__ = None
__slots__ = ()
property format: str

Format string for matrix.

property imag
property mT

Matrix transpose.

See also

scipy.sparse.matrix_transpose

equivalent function

property ndim: int
property nnz: int

Number of stored values, including explicit zeros.

See also

count_nonzero

Number of non-zero entries

property real
property shape

Shape of the matrix

property size: int

Number of stored values.

See also

count_nonzero

Number of non-zero values.