Sparse Matrices¶

class diofant.matrices.sparse.MutableSparseMatrix(*args)[source]

A sparse matrix (a matrix with a large number of zero elements).

Examples

>>> SparseMatrix(2, 2, range(4))
Matrix([
[0, 1],
[2, 3]])
>>> SparseMatrix(2, 2, {(1, 1): 2})
Matrix([
[0, 0],
[0, 2]])

col_join(other)[source]

Returns B augmented beneath A (row-wise joining):

[A]
[B]


Examples

>>> A = SparseMatrix(ones(3))
>>> A
Matrix([
[1, 1, 1],
[1, 1, 1],
[1, 1, 1]])
>>> B = SparseMatrix.eye(3)
>>> B
Matrix([
[1, 0, 0],
[0, 1, 0],
[0, 0, 1]])
>>> C = A.col_join(B); C
Matrix([
[1, 1, 1],
[1, 1, 1],
[1, 1, 1],
[1, 0, 0],
[0, 1, 0],
[0, 0, 1]])
>>> C == A.col_join(Matrix(B))
True


Joining along columns is the same as appending rows at the end of the matrix:

>>> C == A.row_insert(A.rows, Matrix(B))
True

col_op(j, f)[source]

In-place operation on col j using two-arg functor whose args are interpreted as (self[i, j], i) for i in range(self.rows).

Examples

>>> M = SparseMatrix.eye(3)*2
>>> M[1, 0] = -1
>>> M.col_op(1, lambda v, i: v + 2*M[i, 0]); M
Matrix([
[ 2, 4, 0],
[-1, 0, 0],
[ 0, 0, 2]])

col_swap(i, j)[source]

Swap, in place, columns i and j.

Examples

>>> S = SparseMatrix.eye(3); S[2, 1] = 2
>>> S.col_swap(1, 0); S
Matrix([
[0, 1, 0],
[1, 0, 0],
[2, 0, 1]])

fill(value)[source]

Fill self with the given value.

Notes

Unless many values are going to be deleted (i.e. set to zero) this will create a matrix that is slower than a dense matrix in operations.

Examples

>>> M = SparseMatrix.zeros(3); M
Matrix([
[0, 0, 0],
[0, 0, 0],
[0, 0, 0]])
>>> M.fill(1); M
Matrix([
[1, 1, 1],
[1, 1, 1],
[1, 1, 1]])

row_join(other)[source]

Returns B appended after A (column-wise augmenting):

[A B]


Examples

>>> A = SparseMatrix(((1, 0, 1), (0, 1, 0), (1, 1, 0)))
>>> A
Matrix([
[1, 0, 1],
[0, 1, 0],
[1, 1, 0]])
>>> B = SparseMatrix(((1, 0, 0), (0, 1, 0), (0, 0, 1)))
>>> B
Matrix([
[1, 0, 0],
[0, 1, 0],
[0, 0, 1]])
>>> C = A.row_join(B); C
Matrix([
[1, 0, 1, 1, 0, 0],
[0, 1, 0, 0, 1, 0],
[1, 1, 0, 0, 0, 1]])
>>> C == A.row_join(Matrix(B))
True


Joining at row ends is the same as appending columns at the end of the matrix:

>>> C == A.col_insert(A.cols, B)
True

row_op(i, f)[source]

In-place operation on row i using two-arg functor whose args are interpreted as (self[i, j], j).

Examples

>>> M = SparseMatrix.eye(3)*2
>>> M[0, 1] = -1
>>> M.row_op(1, lambda v, j: v + 2*M[0, j]); M
Matrix([
[2, -1, 0],
[4,  0, 0],
[0,  0, 2]])


row_swap(i, j)[source]

Swap, in place, columns i and j.

Examples

>>> S = SparseMatrix.eye(3); S[2, 1] = 2
>>> S.row_swap(1, 0); S
Matrix([
[0, 1, 0],
[1, 0, 0],
[0, 2, 1]])

zip_row_op(i, k, f)[source]

In-place operation on row i using two-arg functor whose args are interpreted as (self[i, j], self[k, j]).

Examples

>>> M = SparseMatrix.eye(3)*2
>>> M[0, 1] = -1
>>> M.zip_row_op(1, 0, lambda v, u: v + 2*u); M
Matrix([
[2, -1, 0],
[4,  0, 0],
[0,  0, 2]])


diofant.matrices.sparse.SparseMatrix
class diofant.matrices.sparse.SparseMatrixBase(*args)[source]

A sparse matrix base class.

CL

Alternate faster representation

LDLdecomposition()[source]

Returns the LDL Decomposition (matrices L and D) of matrix A, such that L * D * L.T == A. A must be a square, symmetric, positive-definite and non-singular.

This method eliminates the use of square root and ensures that all the diagonal entries of L are 1.

Examples

>>> A = SparseMatrix(((25, 15, -5), (15, 18, 0), (-5, 0, 11)))
>>> L, D = A.LDLdecomposition()
>>> L
Matrix([
[   1,   0, 0],
[ 3/5,   1, 0],
[-1/5, 1/3, 1]])
>>> D
Matrix([
[25, 0, 0],
[ 0, 9, 0],
[ 0, 0, 9]])
>>> L * D * L.T == A
True

RL

Alternate faster representation

add(other)[source]

Add two sparse matrices with dictionary representation.

Examples

>>> SparseMatrix(eye(3)).add(SparseMatrix(ones(3)))
Matrix([
[2, 1, 1],
[1, 2, 1],
[1, 1, 2]])
Matrix([
[0, 0, 0],
[0, 0, 0],
[0, 0, 0]])


Only the non-zero elements are stored, so the resulting dictionary that is used to represent the sparse matrix is empty:

>>> _._smat
{}

applyfunc(f)[source]

Apply a function to each element of the matrix.

Examples

>>> m = SparseMatrix(2, 2, lambda i, j: i*2+j)
>>> m
Matrix([
[0, 1],
[2, 3]])
>>> m.applyfunc(lambda i: 2*i)
Matrix([
[0, 2],
[4, 6]])

as_immutable()[source]

Returns an Immutable version of this Matrix.

as_mutable()[source]

Returns a mutable version of this matrix.

Examples

>>> X = ImmutableMatrix([[1, 2], [3, 4]])
>>> Y = X.as_mutable()
>>> Y[1, 1] = 5 # Can set values in Y
>>> Y
Matrix([
[1, 2],
[3, 5]])

cholesky()[source]

Returns the Cholesky decomposition L of a matrix A such that L * L.T = A

A must be a square, symmetric, positive-definite and non-singular matrix

Examples

>>> A = SparseMatrix(((25, 15, -5), (15, 18, 0), (-5, 0, 11)))
>>> A.cholesky()
Matrix([
[ 5, 0, 0],
[ 3, 3, 0],
[-1, 1, 3]])
>>> A.cholesky() * A.cholesky().T == A
True

col_list()[source]

Returns a column-sorted list of non-zero elements of the matrix.

Examples

>>> SparseMatrix(((1, 2), (3, 4)))
Matrix([
[1, 2],
[3, 4]])
>>> _.CL
[(0, 0, 1), (1, 0, 3), (0, 1, 2), (1, 1, 4)]

extract(rowsList, colsList)[source]

Return a submatrix by specifying a list of rows and columns. Negative indices can be given. All indices must be in the range -n <= i < n where n is the number of rows or columns.

Examples

>>> m = Matrix(4, 3, range(12))
>>> m
Matrix([
[0,  1,  2],
[3,  4,  5],
[6,  7,  8],
[9, 10, 11]])
>>> m.extract([0, 1, 3], [0, 1])
Matrix([
[0,  1],
[3,  4],
[9, 10]])


Rows or columns can be repeated:

>>> m.extract([0, 0, 1], [-1])
Matrix([
[2],
[2],
[5]])


Every other row can be taken by using range to provide the indices:

>>> m.extract(range(0, m.rows, 2), [-1])
Matrix([
[2],
[8]])

classmethod eye(n)[source]

Return an n x n identity matrix.

has(*patterns)[source]

Test whether any subexpression matches any of the patterns.

Examples

>>> A = SparseMatrix(((1, x), (0.2, 3)))
>>> A.has(x)
True
>>> A.has(y)
False
>>> A.has(Float)
True

is_hermitian

Checks if the matrix is Hermitian.

In a Hermitian matrix element i,j is the complex conjugate of element j,i.

Examples

>>> a = SparseMatrix([[1, I], [-I, 1]])
>>> a
Matrix([
[ 1, I],
[-I, 1]])
>>> a.is_hermitian
True
>>> a[0, 0] = 2*I
>>> a.is_hermitian
False
>>> a[0, 0] = x
>>> a.is_hermitian
>>> a[0, 1] = a[1, 0]*I
>>> a.is_hermitian
False

is_symmetric(simplify=True)[source]

Return True if self is symmetric.

Examples

>>> M = SparseMatrix(eye(3))
>>> M.is_symmetric()
True
>>> M[0, 2] = 1
>>> M.is_symmetric()
False

liupc()[source]

Liu’s algorithm, for pre-determination of the Elimination Tree of the given matrix, used in row-based symbolic Cholesky factorization.

Examples

>>> S = SparseMatrix([
... [1, 0, 3, 2],
... [0, 0, 1, 0],
... [4, 0, 0, 5],
... [0, 6, 7, 0]])
>>> S.liupc()
([[0], [], [0], [1, 2]], [4, 3, 4, 4])


References

Symbolic Sparse Cholesky Factorization using Elimination Trees, Jeroen Van Grondelle (1999)

multiply(other)[source]

Fast multiplication exploiting the sparsity of the matrix.

Examples

>>> A, B = SparseMatrix(ones(4, 3)), SparseMatrix(ones(3, 4))
>>> A.multiply(B) == 3*ones(4)
True

nnz()[source]

Returns the number of non-zero elements in Matrix.

reshape(rows, cols)[source]

Reshape matrix while retaining original size.

Examples

>>> S = SparseMatrix(4, 2, range(8))
>>> S.reshape(2, 4)
Matrix([
[0, 1, 2, 3],
[4, 5, 6, 7]])

row_list()[source]

Returns a row-sorted list of non-zero elements of the matrix.

Examples

>>> a = SparseMatrix(((1, 2), (3, 4)))
>>> a
Matrix([
[1, 2],
[3, 4]])
>>> a.RL
[(0, 0, 1), (0, 1, 2), (1, 0, 3), (1, 1, 4)]

row_structure_symbolic_cholesky()[source]

Symbolic cholesky factorization, for pre-determination of the non-zero structure of the Cholesky factororization.

Examples

>>> S = SparseMatrix([
... [1, 0, 3, 2],
... [0, 0, 1, 0],
... [4, 0, 0, 5],
... [0, 6, 7, 0]])
>>> S.row_structure_symbolic_cholesky()
[[0], [], [0], [1, 2]]


References

Symbolic Sparse Cholesky Factorization using Elimination Trees, Jeroen Van Grondelle (1999)

scalar_multiply(scalar)[source]

Scalar element-wise multiplication

solve(rhs, method='LDL')[source]

Return solution to self*soln = rhs using given inversion method.

solve_least_squares(rhs, method='LDL')[source]

Return the least-square fit to the data.

By default the cholesky_solve routine is used (method=’CH’); other methods of matrix inversion can be used.

Examples

>>> A = Matrix([1, 2, 3])
>>> B = Matrix([2, 3, 4])
>>> S = SparseMatrix(A.row_join(B))
>>> S
Matrix([
[1, 2],
[2, 3],
[3, 4]])


If each line of S represent coefficients of Ax + By and x and y are [2, 3] then S*xy is:

>>> r = S*Matrix([2, 3]); r
Matrix([
[ 8],
[13],
[18]])


But let’s add 1 to the middle value and then solve for the least-squares value of xy:

>>> xy = S.solve_least_squares(Matrix([8, 14, 18])); xy
Matrix([
[ 5/3],
[10/3]])


The error is given by S*xy - r:

>>> S*xy - r
Matrix([
[1/3],
[1/3],
[1/3]])
>>> _.norm().evalf(2)
0.58


If a different xy is used, the norm will be higher:

>>> xy += ones(2, 1)/10
>>> (S*xy - r).norm().evalf(2)
1.5

tolist()[source]

Convert this sparse matrix into a list of nested Python lists.

Examples

>>> a = SparseMatrix(((1, 2), (3, 4)))
>>> a.tolist()
[[1, 2], [3, 4]]


When there are no rows then it will not be possible to tell how many columns were in the original matrix:

>>> SparseMatrix(ones(0, 3)).tolist()
[]

classmethod zeros(r, c=None)[source]

Return an r x c matrix of zeros, square if c is omitted.

ImmutableSparseMatrix Class Reference¶

class diofant.matrices.immutable.ImmutableSparseMatrix(*args)[source]

Create an immutable version of a sparse matrix.

Examples

>>> ImmutableSparseMatrix(1, 1, {})
Matrix([[0]])
>>> ImmutableSparseMatrix(eye(3))
Matrix([
[1, 0, 0],
[0, 1, 0],
[0, 0, 1]])
>>> _[0, 0] = 42
Traceback (most recent call last):
...
TypeError: Cannot set values of ImmutableSparseMatrix
>>> _.shape
(3, 3)

is_zero

Checks if a matrix is a zero matrix.

A matrix is zero if every element is zero. A matrix need not be square to be considered zero. The empty matrix is zero by the principle of vacuous truth. For a matrix that may or may not be zero (e.g. contains a symbol), this will be None

Examples

>>> a = Matrix([[0, 0], [0, 0]])
>>> b = zeros(3, 4)
>>> c = Matrix([[0, 1], [0, 0]])
>>> d = Matrix([])
>>> e = Matrix([[x, 0], [0, 0]])
>>> a.is_zero
True
>>> b.is_zero
True
>>> c.is_zero
False
>>> d.is_zero
True
>>> e.is_zero

subs(*args, **kwargs)

Return a new matrix with subs applied to each entry.

Examples

>>> SparseMatrix(1, 1, [x])
Matrix([[x]])
>>> _.subs({x: y})
Matrix([[y]])
>>> Matrix(_).subs({y: x})
Matrix([[x]])

xreplace(rule)

Return a new matrix with xreplace applied to each entry.

Examples

>>> SparseMatrix(1, 1, [x])
Matrix([[x]])
>>> _.xreplace({x: y})
Matrix([[y]])
>>> Matrix(_).xreplace({y: x})
Matrix([[x]])