modelparameters.sympy.matrices package

Subpackages

Submodules

modelparameters.sympy.matrices.common module

Basic methods common to all matrices to be used when creating more advanced matrices (e.g., matrices over rings, etc.).

class modelparameters.sympy.matrices.common.MatrixArithmetic[source]

Bases: MatrixRequired

Provides basic matrix arithmetic operations. Should not be instantiated directly.

multiply_elementwise(other)[source]

Return the Hadamard product (elementwise product) of A and B

Examples

>>> from ..matrices import Matrix
>>> A = Matrix([[0, 1, 2], [3, 4, 5]])
>>> B = Matrix([[1, 10, 100], [100, 10, 1]])
>>> A.multiply_elementwise(B)
Matrix([
[  0, 10, 200],
[300, 40,   5]])

See also

cross, dot, multiply

class modelparameters.sympy.matrices.common.MatrixCommon[source]

Bases: MatrixArithmetic, MatrixOperations, MatrixProperties, MatrixSpecial, MatrixShaping

All common matrix operations including basic arithmetic, shaping, and special matrices like zeros, and eye.

exception modelparameters.sympy.matrices.common.MatrixError[source]

Bases: Exception

class modelparameters.sympy.matrices.common.MatrixOperations[source]

Bases: MatrixRequired

Provides basic matrix shape and elementwise operations. Should not be instantiated directly.

property C

By-element conjugation.

property H

Return Hermite conjugate.

Examples

>>> from .. import Matrix, I
>>> m = Matrix((0, 1 + I, 2, 3))
>>> m
Matrix([
[    0],
[1 + I],
[    2],
[    3]])
>>> m.H
Matrix([[0, 1 - I, 2, 3]])

See also

conjugate

By-element conjugation

D

Dirac conjugation

property T

Matrix transposition.

adjoint()[source]

Conjugate transpose or Hermitian conjugation.

applyfunc(f)[source]

Apply a function to each element of the matrix.

Examples

>>> from .. import Matrix
>>> m = Matrix(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_real_imag()[source]

Returns a tuple containing the (real, imaginary) part of matrix.

conjugate()[source]

Return the by-element conjugation.

Examples

>>> from ..matrices import SparseMatrix
>>> from .. import I
>>> a = SparseMatrix(((1, 2 + I), (3, 4), (I, -I)))
>>> a
Matrix([
[1, 2 + I],
[3,     4],
[I,    -I]])
>>> a.C
Matrix([
[ 1, 2 - I],
[ 3,     4],
[-I,     I]])

See also

transpose

Matrix transposition

H

Hermite conjugation

D

Dirac conjugation

doit(**kwargs)[source]
evalf(prec=None, **options)[source]

Apply evalf() to each element of self.

expand(deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints)[source]

Apply core.function.expand to each entry of the matrix.

Examples

>>> from ..abc import x
>>> from ..matrices import Matrix
>>> Matrix(1, 1, [x*(x+1)])
Matrix([[x*(x + 1)]])
>>> _.expand()
Matrix([[x**2 + x]])
n(prec=None, **options)

Apply evalf() to each element of self.

permute(perm, orientation='rows', direction='forward')[source]

Permute the rows or columns of a matrix by the given list of swaps.

Parameters:
  • perm (a permutation. This may be a list swaps (e.g., [[1, 2], [0, 3]]),) – or any valid input to the Permutation constructor, including a Permutation() itself. If perm is given explicitly as a list of indices or a Permutation, direction has no effect.

  • orientation (('rows' or 'cols') whether to permute the rows or the columns) –

  • direction (('forward', 'backward') whether to apply the permutations from) – the start of the list first, or from the back of the list first

Examples

>>> from ..matrices import eye
>>> M = eye(3)
>>> M.permute([[0, 1], [0, 2]], orientation='rows', direction='forward')
Matrix([
[0, 0, 1],
[1, 0, 0],
[0, 1, 0]])
>>> from ..matrices import eye
>>> M = eye(3)
>>> M.permute([[0, 1], [0, 2]], orientation='rows', direction='backward')
Matrix([
[0, 1, 0],
[0, 0, 1],
[1, 0, 0]])
permute_cols(swaps, direction='forward')[source]

Alias for self.permute(swaps, orientation=’cols’, direction=direction)

See also

permute

permute_rows(swaps, direction='forward')[source]

Alias for self.permute(swaps, orientation=’rows’, direction=direction)

See also

permute

refine(assumptions=True)[source]

Apply refine to each element of the matrix.

Examples

>>> from .. import Symbol, Matrix, Abs, sqrt, Q
>>> x = Symbol('x')
>>> Matrix([[Abs(x)**2, sqrt(x**2)],[sqrt(x**2), Abs(x)**2]])
Matrix([
[ Abs(x)**2, sqrt(x**2)],
[sqrt(x**2),  Abs(x)**2]])
>>> _.refine(Q.real(x))
Matrix([
[  x**2, Abs(x)],
[Abs(x),   x**2]])
replace(F, G, map=False)[source]

Replaces Function F in Matrix entries with Function G.

Examples

>>> from .. import symbols, Function, Matrix
>>> F, G = symbols('F, G', cls=Function)
>>> M = Matrix(2, 2, lambda i, j: F(i+j)) ; M
Matrix([
[F(0), F(1)],
[F(1), F(2)]])
>>> N = M.replace(F,G)
>>> N
Matrix([
[G(0), G(1)],
[G(1), G(2)]])
simplify(ratio=1.7, measure=<function count_ops>)[source]

Apply simplify to each element of the matrix.

Examples

>>> from ..abc import x, y
>>> from .. import sin, cos
>>> from ..matrices import SparseMatrix
>>> SparseMatrix(1, 1, [x*sin(y)**2 + x*cos(y)**2])
Matrix([[x*sin(y)**2 + x*cos(y)**2]])
>>> _.simplify()
Matrix([[x]])
subs(*args, **kwargs)[source]

Return a new matrix with subs applied to each entry.

Examples

>>> from ..abc import x, y
>>> from ..matrices import SparseMatrix, Matrix
>>> SparseMatrix(1, 1, [x])
Matrix([[x]])
>>> _.subs(x, y)
Matrix([[y]])
>>> Matrix(_).subs(y, x)
Matrix([[x]])
trace()[source]

Returns the trace of a square matrix i.e. the sum of the diagonal elements.

Examples

>>> from .. import Matrix
>>> A = Matrix(2, 2, [1, 2, 3, 4])
>>> A.trace()
5
transpose()[source]

Returns the transpose of the matrix.

Examples

>>> from .. import Matrix
>>> A = Matrix(2, 2, [1, 2, 3, 4])
>>> A.transpose()
Matrix([
[1, 3],
[2, 4]])
>>> from .. import Matrix, I
>>> m=Matrix(((1, 2+I), (3, 4)))
>>> m
Matrix([
[1, 2 + I],
[3,     4]])
>>> m.transpose()
Matrix([
[    1, 3],
[2 + I, 4]])
>>> m.T == m.transpose()
True

See also

conjugate

By-element conjugation

xreplace(rule)[source]

Return a new matrix with xreplace applied to each entry.

Examples

>>> from ..abc import x, y
>>> from ..matrices import SparseMatrix, Matrix
>>> SparseMatrix(1, 1, [x])
Matrix([[x]])
>>> _.xreplace({x: y})
Matrix([[y]])
>>> Matrix(_).xreplace({y: x})
Matrix([[x]])
class modelparameters.sympy.matrices.common.MatrixProperties[source]

Bases: MatrixRequired

Provides basic properties of a matrix.

atoms(*types)[source]

Returns the atoms that form the current object.

Examples

>>> from ..abc import x, y
>>> from ..matrices import Matrix
>>> Matrix([[x]])
Matrix([[x]])
>>> _.atoms()
{x}
property free_symbols

Returns the free symbols within the matrix.

Examples

>>> from ..abc import x
>>> from ..matrices import Matrix
>>> Matrix([[x], [1]]).free_symbols
{x}
has(*patterns)[source]

Test whether any subexpression matches any of the patterns.

Examples

>>> from .. import Matrix, SparseMatrix, Float
>>> from ..abc import x, y
>>> A = Matrix(((1, x), (0.2, 3)))
>>> B = SparseMatrix(((1, x), (0.2, 3)))
>>> A.has(x)
True
>>> A.has(y)
False
>>> A.has(Float)
True
>>> B.has(x)
True
>>> B.has(y)
False
>>> B.has(Float)
True
property is_Identity
is_anti_symmetric(simplify=True)[source]

Check if matrix M is an antisymmetric matrix, that is, M is a square matrix with all M[i, j] == -M[j, i].

When simplify=True (default), the sum M[i, j] + M[j, i] is simplified before testing to see if it is zero. By default, the SymPy simplify function is used. To use a custom function set simplify to a function that accepts a single argument which returns a simplified expression. To skip simplification, set simplify to False but note that although this will be faster, it may induce false negatives.

Examples

>>> from .. import Matrix, symbols
>>> m = Matrix(2, 2, [0, 1, -1, 0])
>>> m
Matrix([
[ 0, 1],
[-1, 0]])
>>> m.is_anti_symmetric()
True
>>> x, y = symbols('x y')
>>> m = Matrix(2, 3, [0, 0, x, -y, 0, 0])
>>> m
Matrix([
[ 0, 0, x],
[-y, 0, 0]])
>>> m.is_anti_symmetric()
False
>>> from ..abc import x, y
>>> m = Matrix(3, 3, [0, x**2 + 2*x + 1, y,
...                   -(x + 1)**2 , 0, x*y,
...                   -y, -x*y, 0])

Simplification of matrix elements is done by default so even though two elements which should be equal and opposite wouldn’t pass an equality test, the matrix is still reported as anti-symmetric:

>>> m[0, 1] == -m[1, 0]
False
>>> m.is_anti_symmetric()
True

If ‘simplify=False’ is used for the case when a Matrix is already simplified, this will speed things up. Here, we see that without simplification the matrix does not appear anti-symmetric:

>>> m.is_anti_symmetric(simplify=False)
False

But if the matrix were already expanded, then it would appear anti-symmetric and simplification in the is_anti_symmetric routine is not needed:

>>> m = m.expand()
>>> m.is_anti_symmetric(simplify=False)
True
is_diagonal()[source]

Check if matrix is diagonal, that is matrix in which the entries outside the main diagonal are all zero.

Examples

>>> from .. import Matrix, diag
>>> m = Matrix(2, 2, [1, 0, 0, 2])
>>> m
Matrix([
[1, 0],
[0, 2]])
>>> m.is_diagonal()
True
>>> m = Matrix(2, 2, [1, 1, 0, 2])
>>> m
Matrix([
[1, 1],
[0, 2]])
>>> m.is_diagonal()
False
>>> m = diag(1, 2, 3)
>>> m
Matrix([
[1, 0, 0],
[0, 2, 0],
[0, 0, 3]])
>>> m.is_diagonal()
True

See also

is_lower, is_upper, is_diagonalizable, diagonalize

property is_hermitian

Checks if the matrix is Hermitian.

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

Examples

>>> from ..matrices import Matrix
>>> from .. import I
>>> from ..abc import x
>>> a = Matrix([[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
property is_lower

Check if matrix is a lower triangular matrix. True can be returned even if the matrix is not square.

Examples

>>> from .. import Matrix
>>> m = Matrix(2, 2, [1, 0, 0, 1])
>>> m
Matrix([
[1, 0],
[0, 1]])
>>> m.is_lower
True
>>> m = Matrix(4, 3, [0, 0, 0, 2, 0, 0, 1, 4 , 0, 6, 6, 5])
>>> m
Matrix([
[0, 0, 0],
[2, 0, 0],
[1, 4, 0],
[6, 6, 5]])
>>> m.is_lower
True
>>> from ..abc import x, y
>>> m = Matrix(2, 2, [x**2 + y, y**2 + x, 0, x + y])
>>> m
Matrix([
[x**2 + y, x + y**2],
[       0,    x + y]])
>>> m.is_lower
False
property is_lower_hessenberg

Checks if the matrix is in the lower-Hessenberg form.

The lower hessenberg matrix has zero entries above the first superdiagonal.

Examples

>>> from ..matrices import Matrix
>>> a = Matrix([[1, 2, 0, 0], [5, 2, 3, 0], [3, 4, 3, 7], [5, 6, 1, 1]])
>>> a
Matrix([
[1, 2, 0, 0],
[5, 2, 3, 0],
[3, 4, 3, 7],
[5, 6, 1, 1]])
>>> a.is_lower_hessenberg
True
property is_square

Checks if a matrix is square.

A matrix is square if the number of rows equals the number of columns. The empty matrix is square by definition, since the number of rows and the number of columns are both zero.

Examples

>>> from .. import Matrix
>>> a = Matrix([[1, 2, 3], [4, 5, 6]])
>>> b = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
>>> c = Matrix([])
>>> a.is_square
False
>>> b.is_square
True
>>> c.is_square
True
is_symbolic()[source]

Checks if any elements contain Symbols.

Examples

>>> from ..matrices import Matrix
>>> from ..abc import x, y
>>> M = Matrix([[x, y], [1, 0]])
>>> M.is_symbolic()
True
is_symmetric(simplify=True)[source]

Check if matrix is symmetric matrix, that is square matrix and is equal to its transpose.

By default, simplifications occur before testing symmetry. They can be skipped using ‘simplify=False’; while speeding things a bit, this may however induce false negatives.

Examples

>>> from .. import Matrix
>>> m = Matrix(2, 2, [0, 1, 1, 2])
>>> m
Matrix([
[0, 1],
[1, 2]])
>>> m.is_symmetric()
True
>>> m = Matrix(2, 2, [0, 1, 2, 0])
>>> m
Matrix([
[0, 1],
[2, 0]])
>>> m.is_symmetric()
False
>>> m = Matrix(2, 3, [0, 0, 0, 0, 0, 0])
>>> m
Matrix([
[0, 0, 0],
[0, 0, 0]])
>>> m.is_symmetric()
False
>>> from ..abc import x, y
>>> m = Matrix(3, 3, [1, x**2 + 2*x + 1, y, (x + 1)**2 , 2, 0, y, 0, 3])
>>> m
Matrix([
[         1, x**2 + 2*x + 1, y],
[(x + 1)**2,              2, 0],
[         y,              0, 3]])
>>> m.is_symmetric()
True

If the matrix is already simplified, you may speed-up is_symmetric() test by using ‘simplify=False’.

>>> bool(m.is_symmetric(simplify=False))
False
>>> m1 = m.expand()
>>> m1.is_symmetric(simplify=False)
True
property is_upper

Check if matrix is an upper triangular matrix. True can be returned even if the matrix is not square.

Examples

>>> from .. import Matrix
>>> m = Matrix(2, 2, [1, 0, 0, 1])
>>> m
Matrix([
[1, 0],
[0, 1]])
>>> m.is_upper
True
>>> m = Matrix(4, 3, [5, 1, 9, 0, 4 , 6, 0, 0, 5, 0, 0, 0])
>>> m
Matrix([
[5, 1, 9],
[0, 4, 6],
[0, 0, 5],
[0, 0, 0]])
>>> m.is_upper
True
>>> m = Matrix(2, 3, [4, 2, 5, 6, 1, 1])
>>> m
Matrix([
[4, 2, 5],
[6, 1, 1]])
>>> m.is_upper
False
property is_upper_hessenberg

Checks if the matrix is the upper-Hessenberg form.

The upper hessenberg matrix has zero entries below the first subdiagonal.

Examples

>>> from ..matrices import Matrix
>>> a = Matrix([[1, 4, 2, 3], [3, 4, 1, 7], [0, 2, 3, 4], [0, 0, 1, 3]])
>>> a
Matrix([
[1, 4, 2, 3],
[3, 4, 1, 7],
[0, 2, 3, 4],
[0, 0, 1, 3]])
>>> a.is_upper_hessenberg
True
property 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

>>> from .. import Matrix, zeros
>>> from ..abc import x
>>> 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
values()[source]

Return non-zero values of self.

class modelparameters.sympy.matrices.common.MatrixRequired[source]

Bases: object

All subclasses of matrix objects must implement the required matrix properties listed here.

cols = None
rows = None
shape = None
class modelparameters.sympy.matrices.common.MatrixShaping[source]

Bases: MatrixRequired

Provides basic matrix shaping and extracting of submatrices

col(j)[source]

Elementary column selector.

Examples

>>> from .. import eye
>>> eye(2).col(0)
Matrix([
[1],
[0]])

See also

row, col_op, col_swap, col_del, col_join, col_insert

col_del(col)[source]

Delete the specified column.

col_insert(pos, other)[source]

Insert one or more columns at the given column position.

Examples

>>> from .. import zeros, ones
>>> M = zeros(3)
>>> V = ones(3, 1)
>>> M.col_insert(1, V)
Matrix([
[0, 1, 0, 0],
[0, 1, 0, 0],
[0, 1, 0, 0]])

See also

col, row_insert

col_join(other)[source]

Concatenates two matrices along self’s last and other’s first row.

Examples

>>> from .. import zeros, ones
>>> M = zeros(3)
>>> V = ones(1, 3)
>>> M.col_join(V)
Matrix([
[0, 0, 0],
[0, 0, 0],
[0, 0, 0],
[1, 1, 1]])

See also

col, row_join

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

>>> from .. import Matrix
>>> 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]])

RowsList or colsList can also be a list of booleans, in which case the rows or columns corresponding to the True values will be selected:

>>> m.extract([0, 1, 2, 3], [True, False, True])
Matrix([
[0,  2],
[3,  5],
[6,  8],
[9, 11]])
get_diag_blocks()[source]

Obtains the square sub-matrices on the main diagonal of a square matrix.

Useful for inverting symbolic matrices or solving systems of linear equations which may be decoupled by having a block diagonal structure.

Examples

>>> from .. import Matrix
>>> from ..abc import x, y, z
>>> A = Matrix([[1, 3, 0, 0], [y, z*z, 0, 0], [0, 0, x, 0], [0, 0, 0, 0]])
>>> a1, a2, a3 = A.get_diag_blocks()
>>> a1
Matrix([
[1,    3],
[y, z**2]])
>>> a2
Matrix([[x]])
>>> a3
Matrix([[0]])
classmethod hstack(*args)[source]

Return a matrix formed by joining args horizontally (i.e. by repeated application of row_join).

Examples

>>> from ..matrices import Matrix, eye
>>> Matrix.hstack(eye(2), 2*eye(2))
Matrix([
[1, 0, 2, 0],
[0, 1, 0, 2]])
reshape(rows, cols)[source]

Reshape the matrix. Total number of elements must remain the same.

Examples

>>> from .. import Matrix
>>> m = Matrix(2, 3, lambda i, j: 1)
>>> m
Matrix([
[1, 1, 1],
[1, 1, 1]])
>>> m.reshape(1, 6)
Matrix([[1, 1, 1, 1, 1, 1]])
>>> m.reshape(3, 2)
Matrix([
[1, 1],
[1, 1],
[1, 1]])
row(i)[source]

Elementary row selector.

Examples

>>> from .. import eye
>>> eye(2).row(0)
Matrix([[1, 0]])

See also

col, row_op, row_swap, row_del, row_join, row_insert

row_del(row)[source]

Delete the specified row.

row_insert(pos, other)[source]

Insert one or more rows at the given row position.

Examples

>>> from .. import zeros, ones
>>> M = zeros(3)
>>> V = ones(1, 3)
>>> M.row_insert(1, V)
Matrix([
[0, 0, 0],
[1, 1, 1],
[0, 0, 0],
[0, 0, 0]])

See also

row, col_insert

row_join(other)[source]

Concatenates two matrices along self’s last and rhs’s first column

Examples

>>> from .. import zeros, ones
>>> M = zeros(3)
>>> V = ones(3, 1)
>>> M.row_join(V)
Matrix([
[0, 0, 0, 1],
[0, 0, 0, 1],
[0, 0, 0, 1]])

See also

row, col_join

property shape

The shape (dimensions) of the matrix as the 2-tuple (rows, cols).

Examples

>>> from ..matrices import zeros
>>> M = zeros(2, 3)
>>> M.shape
(2, 3)
>>> M.rows
2
>>> M.cols
3
tolist()[source]

Return the Matrix as a nested Python list.

Examples

>>> from .. import Matrix, ones
>>> m = Matrix(3, 3, range(9))
>>> m
Matrix([
[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
>>> m.tolist()
[[0, 1, 2], [3, 4, 5], [6, 7, 8]]
>>> ones(3, 0).tolist()
[[], [], []]

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

>>> ones(0, 3).tolist()
[]
vec()[source]

Return the Matrix converted into a one column matrix by stacking columns

Examples

>>> from .. import Matrix
>>> m=Matrix([[1, 3], [2, 4]])
>>> m
Matrix([
[1, 3],
[2, 4]])
>>> m.vec()
Matrix([
[1],
[2],
[3],
[4]])

See also

vech

classmethod vstack(*args)[source]

Return a matrix formed by joining args vertically (i.e. by repeated application of col_join).

Examples

>>> from ..matrices import Matrix, eye
>>> Matrix.vstack(eye(2), 2*eye(2))
Matrix([
[1, 0],
[0, 1],
[2, 0],
[0, 2]])
class modelparameters.sympy.matrices.common.MatrixSpecial[source]

Bases: MatrixRequired

Construction of special matrices

classmethod diag(*args, **kwargs)[source]

Returns a matrix with the specified diagonal. If matrices are passed, a block-diagonal matrix is created.

kwargs

rowsrows of the resulting matrix; computed if

not given.

colscolumns of the resulting matrix; computed if

not given.

cls : class for the resulting matrix

Examples

>>> from ..matrices import Matrix
>>> Matrix.diag(1, 2, 3)
Matrix([
[1, 0, 0],
[0, 2, 0],
[0, 0, 3]])
>>> Matrix.diag([1, 2, 3])
Matrix([
[1, 0, 0],
[0, 2, 0],
[0, 0, 3]])

The diagonal elements can be matrices; diagonal filling will continue on the diagonal from the last element of the matrix:

>>> from ..abc import x, y, z
>>> a = Matrix([x, y, z])
>>> b = Matrix([[1, 2], [3, 4]])
>>> c = Matrix([[5, 6]])
>>> Matrix.diag(a, 7, b, c)
Matrix([
[x, 0, 0, 0, 0, 0],
[y, 0, 0, 0, 0, 0],
[z, 0, 0, 0, 0, 0],
[0, 7, 0, 0, 0, 0],
[0, 0, 1, 2, 0, 0],
[0, 0, 3, 4, 0, 0],
[0, 0, 0, 0, 5, 6]])

A given band off the diagonal can be made by padding with a vertical or horizontal “kerning” vector:

>>> hpad = Matrix(0, 2, [])
>>> vpad = Matrix(2, 0, [])
>>> Matrix.diag(vpad, 1, 2, 3, hpad) + Matrix.diag(hpad, 4, 5, 6, vpad)
Matrix([
[0, 0, 4, 0, 0],
[0, 0, 0, 5, 0],
[1, 0, 0, 0, 6],
[0, 2, 0, 0, 0],
[0, 0, 3, 0, 0]])

The type of the resulting matrix can be affected with the cls keyword.

>>> type(Matrix.diag(1))
<class 'sympy.matrices.dense.MutableDenseMatrix'>
>>> from ..matrices import ImmutableMatrix
>>> type(Matrix.diag(1, cls=ImmutableMatrix))
<class 'sympy.matrices.immutable.ImmutableDenseMatrix'>
classmethod eye(rows, cols=None, **kwargs)[source]

Returns an identity matrix.

Parameters:
  • rows (rows of the matrix) –

  • cols (cols of the matrix (if None, cols=rows)) –

  • kwargs

  • ======

  • cls (class of the returned matrix) –

classmethod jordan_block(*args, **kwargs)[source]

Returns a Jordan block with the specified size and eigenvalue. You may call jordan_block with two args (size, eigenvalue) or with keyword arguments.

kwargs

size : rows and columns of the matrix rows : rows of the matrix (if None, rows=size) cols : cols of the matrix (if None, cols=size) eigenvalue : value on the diagonal of the matrix band : position of off-diagonal 1s. May be ‘upper’ or

‘lower’. (Default: ‘upper’)

cls : class of the returned matrix

Examples

>>> from .. import Matrix
>>> from ..abc import x
>>> Matrix.jordan_block(4, x)
Matrix([
[x, 1, 0, 0],
[0, x, 1, 0],
[0, 0, x, 1],
[0, 0, 0, x]])
>>> Matrix.jordan_block(4, x, band='lower')
Matrix([
[x, 0, 0, 0],
[1, x, 0, 0],
[0, 1, x, 0],
[0, 0, 1, x]])
>>> Matrix.jordan_block(size=4, eigenvalue=x)
Matrix([
[x, 1, 0, 0],
[0, x, 1, 0],
[0, 0, x, 1],
[0, 0, 0, x]])
classmethod ones(rows, cols=None, **kwargs)[source]

Returns a matrix of ones.

Parameters:
  • rows (rows of the matrix) –

  • cols (cols of the matrix (if None, cols=rows)) –

  • kwargs

  • ======

  • cls (class of the returned matrix) –

classmethod zeros(rows, cols=None, **kwargs)[source]

Returns a matrix of zeros.

Parameters:
  • rows (rows of the matrix) –

  • cols (cols of the matrix (if None, cols=rows)) –

  • kwargs

  • ======

  • cls (class of the returned matrix) –

exception modelparameters.sympy.matrices.common.NonSquareMatrixError[source]

Bases: ShapeError

exception modelparameters.sympy.matrices.common.ShapeError[source]

Bases: ValueError, MatrixError

Wrong matrix shape

modelparameters.sympy.matrices.common.a2idx(j, n=None)[source]

Return integer after making positive and validating against n.

modelparameters.sympy.matrices.common.classof(A, B)[source]

Get the type of the result when combining matrices of different types.

Currently the strategy is that immutability is contagious.

Examples

>>> from .. import Matrix, ImmutableMatrix
>>> from .matrices import classof
>>> M = Matrix([[1, 2], [3, 4]]) # a Mutable Matrix
>>> IM = ImmutableMatrix([[1, 2], [3, 4]])
>>> classof(M, IM)
<class 'sympy.matrices.immutable.ImmutableDenseMatrix'>

modelparameters.sympy.matrices.dense module

class modelparameters.sympy.matrices.dense.DenseMatrix[source]

Bases: MatrixBase

as_immutable()[source]

Returns an Immutable version of this Matrix

as_mutable()[source]

Returns a mutable version of this matrix

Examples

>>> from .. import ImmutableMatrix
>>> 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]])
equals(other, failing_expression=False)[source]

Applies equals to corresponding elements of the matrices, trying to prove that the elements are equivalent, returning True if they are, False if any pair is not, and None (or the first failing expression if failing_expression is True) if it cannot be decided if the expressions are equivalent or not. This is, in general, an expensive operation.

Examples

>>> from ..matrices import Matrix
>>> from ..abc import x
>>> from .. import cos
>>> A = Matrix([x*(x - 1), 0])
>>> B = Matrix([x**2 - x, 0])
>>> A == B
False
>>> A.simplify() == B.simplify()
True
>>> A.equals(B)
True
>>> A.equals(2)
False

See also

sympy.core.expr.equals

is_MatrixExpr = False
modelparameters.sympy.matrices.dense.GramSchmidt(vlist, orthonormal=False)[source]

Apply the Gram-Schmidt process to a set of vectors.

see: http://en.wikipedia.org/wiki/Gram%E2%80%93Schmidt_process

modelparameters.sympy.matrices.dense.Matrix

alias of MutableDenseMatrix

class modelparameters.sympy.matrices.dense.MutableDenseMatrix(*args, **kwargs)[source]

Bases: DenseMatrix, MatrixBase

as_mutable()[source]

Returns a mutable version of this matrix

Examples

>>> from .. import ImmutableMatrix
>>> 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]])
col_del(i)[source]

Delete the given column.

Examples

>>> from ..matrices import eye
>>> M = eye(3)
>>> M.col_del(1)
>>> M
Matrix([
[1, 0],
[0, 0],
[0, 1]])

See also

col, row_del

col_op(j, f)[source]

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

Examples

>>> from ..matrices import eye
>>> M = eye(3)
>>> M.col_op(1, lambda v, i: v + 2*M[i, 0]); M
Matrix([
[1, 2, 0],
[0, 1, 0],
[0, 0, 1]])

See also

col, row_op

col_swap(i, j)[source]

Swap the two given columns of the matrix in-place.

Examples

>>> from ..matrices import Matrix
>>> M = Matrix([[1, 0], [1, 0]])
>>> M
Matrix([
[1, 0],
[1, 0]])
>>> M.col_swap(0, 1)
>>> M
Matrix([
[0, 1],
[0, 1]])

See also

col, row_swap

copyin_list(key, value)[source]

Copy in elements from a list.

Parameters:
  • key (slice) – The section of this matrix to replace.

  • value (iterable) – The iterable to copy values from.

Examples

>>> from ..matrices import eye
>>> I = eye(3)
>>> I[:2, 0] = [1, 2] # col
>>> I
Matrix([
[1, 0, 0],
[2, 1, 0],
[0, 0, 1]])
>>> I[1, :2] = [[3, 4]]
>>> I
Matrix([
[1, 0, 0],
[3, 4, 0],
[0, 0, 1]])

See also

copyin_matrix

copyin_matrix(key, value)[source]

Copy in values from a matrix into the given bounds.

Parameters:
  • key (slice) – The section of this matrix to replace.

  • value (Matrix) – The matrix to copy values from.

Examples

>>> from ..matrices import Matrix, eye
>>> M = Matrix([[0, 1], [2, 3], [4, 5]])
>>> I = eye(3)
>>> I[:3, :2] = M
>>> I
Matrix([
[0, 1, 0],
[2, 3, 0],
[4, 5, 1]])
>>> I[0, 1] = M
>>> I
Matrix([
[0, 0, 1],
[2, 2, 3],
[4, 4, 5]])

See also

copyin_list

fill(value)[source]

Fill the matrix with the scalar value.

See also

zeros, ones

row_del(i)[source]

Delete the given row.

Examples

>>> from ..matrices import eye
>>> M = eye(3)
>>> M.row_del(1)
>>> M
Matrix([
[1, 0, 0],
[0, 0, 1]])

See also

row, col_del

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

>>> from ..matrices import eye
>>> M = eye(3)
>>> M.row_op(1, lambda v, j: v + 2*M[0, j]); M
Matrix([
[1, 0, 0],
[2, 1, 0],
[0, 0, 1]])

See also

row, zip_row_op, col_op

row_swap(i, j)[source]

Swap the two given rows of the matrix in-place.

Examples

>>> from ..matrices import Matrix
>>> M = Matrix([[0, 1], [1, 0]])
>>> M
Matrix([
[0, 1],
[1, 0]])
>>> M.row_swap(0, 1)
>>> M
Matrix([
[1, 0],
[0, 1]])

See also

row, col_swap

simplify(ratio=1.7, measure=<function count_ops>)[source]

Applies simplify to the elements of a matrix in place.

This is a shortcut for M.applyfunc(lambda x: simplify(x, ratio, measure))

See also

sympy.simplify.simplify.simplify

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

>>> from ..matrices import eye
>>> M = eye(3)
>>> M.zip_row_op(1, 0, lambda v, u: v + 2*u); M
Matrix([
[1, 0, 0],
[2, 1, 0],
[0, 0, 1]])

See also

row, row_op, col_op

modelparameters.sympy.matrices.dense.MutableMatrix

alias of MutableDenseMatrix

modelparameters.sympy.matrices.dense.casoratian(seqs, n, zero=True)[source]

Given linear difference operator L of order ‘k’ and homogeneous equation Ly = 0 we want to compute kernel of L, which is a set of ‘k’ sequences: a(n), b(n), … z(n).

Solutions of L are linearly independent iff their Casoratian, denoted as C(a, b, …, z), do not vanish for n = 0.

Casoratian is defined by k x k determinant:

+  a(n)     b(n)     . . . z(n)     +
|  a(n+1)   b(n+1)   . . . z(n+1)   |
|    .         .     .        .     |
|    .         .       .      .     |
|    .         .         .    .     |
+  a(n+k-1) b(n+k-1) . . . z(n+k-1) +

It proves very useful in rsolve_hyper() where it is applied to a generating set of a recurrence to factor out linearly dependent solutions and return a basis:

>>> from .. import Symbol, casoratian, factorial
>>> n = Symbol('n', integer=True)

Exponential and factorial are linearly independent:

>>> casoratian([2**n, factorial(n)], n) != 0
True
modelparameters.sympy.matrices.dense.diag(*values, **kwargs)[source]

Create a sparse, diagonal matrix from a list of diagonal values.

Notes

When arguments are matrices they are fitted in resultant matrix.

The returned matrix is a mutable, dense matrix. To make it a different type, send the desired class for keyword cls.

Examples

>>> from ..matrices import diag, Matrix, ones
>>> diag(1, 2, 3)
Matrix([
[1, 0, 0],
[0, 2, 0],
[0, 0, 3]])
>>> diag(*[1, 2, 3])
Matrix([
[1, 0, 0],
[0, 2, 0],
[0, 0, 3]])

The diagonal elements can be matrices; diagonal filling will continue on the diagonal from the last element of the matrix:

>>> from ..abc import x, y, z
>>> a = Matrix([x, y, z])
>>> b = Matrix([[1, 2], [3, 4]])
>>> c = Matrix([[5, 6]])
>>> diag(a, 7, b, c)
Matrix([
[x, 0, 0, 0, 0, 0],
[y, 0, 0, 0, 0, 0],
[z, 0, 0, 0, 0, 0],
[0, 7, 0, 0, 0, 0],
[0, 0, 1, 2, 0, 0],
[0, 0, 3, 4, 0, 0],
[0, 0, 0, 0, 5, 6]])

When diagonal elements are lists, they will be treated as arguments to Matrix:

>>> diag([1, 2, 3], 4)
Matrix([
[1, 0],
[2, 0],
[3, 0],
[0, 4]])
>>> diag([[1, 2, 3]], 4)
Matrix([
[1, 2, 3, 0],
[0, 0, 0, 4]])

A given band off the diagonal can be made by padding with a vertical or horizontal “kerning” vector:

>>> hpad = ones(0, 2)
>>> vpad = ones(2, 0)
>>> diag(vpad, 1, 2, 3, hpad) + diag(hpad, 4, 5, 6, vpad)
Matrix([
[0, 0, 4, 0, 0],
[0, 0, 0, 5, 0],
[1, 0, 0, 0, 6],
[0, 2, 0, 0, 0],
[0, 0, 3, 0, 0]])

The type is mutable by default but can be made immutable by setting the mutable flag to False:

>>> type(diag(1))
<class 'sympy.matrices.dense.MutableDenseMatrix'>
>>> from ..matrices import ImmutableMatrix
>>> type(diag(1, cls=ImmutableMatrix))
<class 'sympy.matrices.immutable.ImmutableDenseMatrix'>

See also

eye

modelparameters.sympy.matrices.dense.eye(*args, **kwargs)[source]

Create square identity matrix n x n

See also

diag, zeros, ones

modelparameters.sympy.matrices.dense.hessian(f, varlist, constraints=[])[source]

Compute Hessian matrix for a function f wrt parameters in varlist which may be given as a sequence or a row/column vector. A list of constraints may optionally be given.

Examples

>>> from .. import Function, hessian, pprint
>>> from ..abc import x, y
>>> f = Function('f')(x, y)
>>> g1 = Function('g')(x, y)
>>> g2 = x**2 + 3*y
>>> pprint(hessian(f, (x, y), [g1, g2]))
[                   d               d            ]
[     0        0    --(g(x, y))     --(g(x, y))  ]
[                   dx              dy           ]
[                                                ]
[     0        0        2*x              3       ]
[                                                ]
[                     2               2          ]
[d                   d               d           ]
[--(g(x, y))  2*x   ---(f(x, y))   -----(f(x, y))]
[dx                   2            dy dx         ]
[                   dx                           ]
[                                                ]
[                     2               2          ]
[d                   d               d           ]
[--(g(x, y))   3   -----(f(x, y))   ---(f(x, y)) ]
[dy                dy dx              2          ]
[                                   dy           ]

References

http://en.wikipedia.org/wiki/Hessian_matrix

See also

sympy.matrices.mutable.Matrix.jacobian, wronskian

modelparameters.sympy.matrices.dense.jordan_cell(eigenval, n)[source]

Create a Jordan block:

Examples

>>> from ..matrices import jordan_cell
>>> from ..abc import x
>>> jordan_cell(x, 4)
Matrix([
[x, 1, 0, 0],
[0, x, 1, 0],
[0, 0, x, 1],
[0, 0, 0, x]])
modelparameters.sympy.matrices.dense.list2numpy(l, dtype=<class 'object'>)[source]

Converts python list of SymPy expressions to a NumPy array.

See also

matrix2numpy

modelparameters.sympy.matrices.dense.matrix2numpy(m, dtype=<class 'object'>)[source]

Converts SymPy’s matrix to a NumPy array.

See also

list2numpy

modelparameters.sympy.matrices.dense.matrix_multiply_elementwise(A, B)[source]

Return the Hadamard product (elementwise product) of A and B

>>> from ..matrices import matrix_multiply_elementwise
>>> from ..matrices import Matrix
>>> A = Matrix([[0, 1, 2], [3, 4, 5]])
>>> B = Matrix([[1, 10, 100], [100, 10, 1]])
>>> matrix_multiply_elementwise(A, B)
Matrix([
[  0, 10, 200],
[300, 40,   5]])

See also

__mul__

modelparameters.sympy.matrices.dense.ones(*args, **kwargs)[source]

Returns a matrix of ones with rows rows and cols columns; if cols is omitted a square matrix will be returned.

See also

zeros, eye, diag

modelparameters.sympy.matrices.dense.randMatrix(r, c=None, min=0, max=99, seed=None, symmetric=False, percent=100, prng=None)[source]

Create random matrix with dimensions r x c. If c is omitted the matrix will be square. If symmetric is True the matrix must be square. If percent is less than 100 then only approximately the given percentage of elements will be non-zero.

The pseudo-random number generator used to generate matrix is chosen in the following way.

  • If prng is supplied, it will be used as random number generator. It should be an instance of random.Random, or at least have randint and shuffle methods with same signatures.

  • if prng is not supplied but seed is supplied, then new random.Random with given seed will be created;

  • otherwise, a new random.Random with default seed will be used.

Examples

>>> from ..matrices import randMatrix
>>> randMatrix(3) 
[25, 45, 27]
[44, 54,  9]
[23, 96, 46]
>>> randMatrix(3, 2) 
[87, 29]
[23, 37]
[90, 26]
>>> randMatrix(3, 3, 0, 2) 
[0, 2, 0]
[2, 0, 1]
[0, 0, 1]
>>> randMatrix(3, symmetric=True) 
[85, 26, 29]
[26, 71, 43]
[29, 43, 57]
>>> A = randMatrix(3, seed=1)
>>> B = randMatrix(3, seed=2)
>>> A == B 
False
>>> A == randMatrix(3, seed=1)
True
>>> randMatrix(3, symmetric=True, percent=50) 
[0, 68, 43]
[0, 68,  0]
[0, 91, 34]
modelparameters.sympy.matrices.dense.rot_axis1(theta)[source]

Returns a rotation matrix for a rotation of theta (in radians) about the 1-axis.

Examples

>>> from .. import pi
>>> from ..matrices import rot_axis1

A rotation of pi/3 (60 degrees):

>>> theta = pi/3
>>> rot_axis1(theta)
Matrix([
[1,          0,         0],
[0,        1/2, sqrt(3)/2],
[0, -sqrt(3)/2,       1/2]])

If we rotate by pi/2 (90 degrees):

>>> rot_axis1(pi/2)
Matrix([
[1,  0, 0],
[0,  0, 1],
[0, -1, 0]])

See also

rot_axis2

Returns a rotation matrix for a rotation of theta (in radians) about the 2-axis

rot_axis3

Returns a rotation matrix for a rotation of theta (in radians) about the 3-axis

modelparameters.sympy.matrices.dense.rot_axis2(theta)[source]

Returns a rotation matrix for a rotation of theta (in radians) about the 2-axis.

Examples

>>> from .. import pi
>>> from ..matrices import rot_axis2

A rotation of pi/3 (60 degrees):

>>> theta = pi/3
>>> rot_axis2(theta)
Matrix([
[      1/2, 0, -sqrt(3)/2],
[        0, 1,          0],
[sqrt(3)/2, 0,        1/2]])

If we rotate by pi/2 (90 degrees):

>>> rot_axis2(pi/2)
Matrix([
[0, 0, -1],
[0, 1,  0],
[1, 0,  0]])

See also

rot_axis1

Returns a rotation matrix for a rotation of theta (in radians) about the 1-axis

rot_axis3

Returns a rotation matrix for a rotation of theta (in radians) about the 3-axis

modelparameters.sympy.matrices.dense.rot_axis3(theta)[source]

Returns a rotation matrix for a rotation of theta (in radians) about the 3-axis.

Examples

>>> from .. import pi
>>> from ..matrices import rot_axis3

A rotation of pi/3 (60 degrees):

>>> theta = pi/3
>>> rot_axis3(theta)
Matrix([
[       1/2, sqrt(3)/2, 0],
[-sqrt(3)/2,       1/2, 0],
[         0,         0, 1]])

If we rotate by pi/2 (90 degrees):

>>> rot_axis3(pi/2)
Matrix([
[ 0, 1, 0],
[-1, 0, 0],
[ 0, 0, 1]])

See also

rot_axis1

Returns a rotation matrix for a rotation of theta (in radians) about the 1-axis

rot_axis2

Returns a rotation matrix for a rotation of theta (in radians) about the 2-axis

modelparameters.sympy.matrices.dense.symarray(prefix, shape, **kwargs)[source]

Create a numpy ndarray of symbols (as an object array).

The created symbols are named prefix_i1_i2_… You should thus provide a non-empty prefix if you want your symbols to be unique for different output arrays, as SymPy symbols with identical names are the same object.

Parameters:
  • prefix (string) – A prefix prepended to the name of every symbol.

  • shape (int or tuple) – Shape of the created array. If an int, the array is one-dimensional; for more than one dimension the shape must be a tuple.

  • **kwargs (dict) – keyword arguments passed on to Symbol

Examples

These doctests require numpy.

>>> from .. import symarray
>>> symarray('', 3)
[_0 _1 _2]

If you want multiple symarrays to contain distinct symbols, you must provide unique prefixes:

>>> a = symarray('', 3)
>>> b = symarray('', 3)
>>> a[0] == b[0]
True
>>> a = symarray('a', 3)
>>> b = symarray('b', 3)
>>> a[0] == b[0]
False

Creating symarrays with a prefix:

>>> symarray('a', 3)
[a_0 a_1 a_2]

For more than one dimension, the shape must be given as a tuple:

>>> symarray('a', (2, 3))
[[a_0_0 a_0_1 a_0_2]
 [a_1_0 a_1_1 a_1_2]]
>>> symarray('a', (2, 3, 2))
[[[a_0_0_0 a_0_0_1]
  [a_0_1_0 a_0_1_1]
  [a_0_2_0 a_0_2_1]]

 [[a_1_0_0 a_1_0_1]
  [a_1_1_0 a_1_1_1]
  [a_1_2_0 a_1_2_1]]]

For setting assumptions of the underlying Symbols:

>>> [s.is_real for s in symarray('a', 2, real=True)]
[True, True]
modelparameters.sympy.matrices.dense.wronskian(functions, var, method='bareiss')[source]

Compute Wronskian for [] of functions

                 | f1       f2        ...   fn      |
                 | f1'      f2'       ...   fn'     |
                 |  .        .        .      .      |
W(f1, ..., fn) = |  .        .         .     .      |
                 |  .        .          .    .      |
                 |  (n)      (n)            (n)     |
                 | D   (f1) D   (f2)  ...  D   (fn) |

see: http://en.wikipedia.org/wiki/Wronskian

See also

sympy.matrices.mutable.Matrix.jacobian, hessian

modelparameters.sympy.matrices.dense.zeros(*args, **kwargs)[source]

Returns a matrix of zeros with rows rows and cols columns; if cols is omitted a square matrix will be returned.

See also

ones, eye, diag

modelparameters.sympy.matrices.densearith module

Fundamental arithmetic of dense matrices. The dense matrix is stored as a list of lists.

modelparameters.sympy.matrices.densearith.add(matlist1, matlist2, K)[source]

Adds matrices row-wise.

Examples

>>> from .densearith import add
>>> from .. import ZZ
>>> e = [
... [ZZ(12), ZZ(78)],
... [ZZ(56), ZZ(79)]]
>>> f = [
... [ZZ(1), ZZ(2)],
... [ZZ(3), ZZ(4)]]
>>> g = [
... [ZZ.zero, ZZ.zero],
... [ZZ.zero, ZZ.zero]]
>>> add(e, f, ZZ)
[[13, 80], [59, 83]]
>>> add(f, g, ZZ)
[[1, 2], [3, 4]]

See also

addrow

modelparameters.sympy.matrices.densearith.addrow(row1, row2, K)[source]

Adds two rows of a matrix element-wise.

Examples

>>> from .densearith import addrow
>>> from .. import ZZ
>>> a = [ZZ(12), ZZ(34), ZZ(56)]
>>> b = [ZZ(14), ZZ(56), ZZ(63)]
>>> c = [ZZ(0), ZZ(0), ZZ(0)]
>>> addrow(a, b, ZZ)
[26, 90, 119]
>>> addrow(b, c, ZZ)
[14, 56, 63]
modelparameters.sympy.matrices.densearith.mulmatmat(matlist1, matlist2, K)[source]

Multiplies two matrices by multiplying each row with each column at a time. The multiplication of row and column is done with mulrowcol.

Firstly, the second matrix is converted from a list of rows to a list of columns using zip and then multiplication is done.

Examples

>>> from .densearith import mulmatmat
>>> from .. import ZZ
>>> from .densetools import eye
>>> a = [
... [ZZ(3), ZZ(4)],
... [ZZ(5), ZZ(6)]]
>>> b = [
... [ZZ(1), ZZ(2)],
... [ZZ(7), ZZ(8)]]
>>> c = eye(2, ZZ)
>>> mulmatmat(a, b, ZZ)
[[31, 38], [47, 58]]
>>> mulmatmat(a, c, ZZ)
[[3, 4], [5, 6]]

See also

mulrowcol

modelparameters.sympy.matrices.densearith.mulmatscaler(matlist, scaler, K)[source]

Performs scaler matrix multiplication one row at at time. The row-scaler multiplication is done using mulrowscaler.

Examples

>>> from .. import ZZ
>>> from .densearith import mulmatscaler
>>> a = [
... [ZZ(3), ZZ(7), ZZ(4)],
... [ZZ(2), ZZ(4), ZZ(5)],
... [ZZ(6), ZZ(2), ZZ(3)]]
>>> mulmatscaler(a, ZZ(1), ZZ)
[[3, 7, 4], [2, 4, 5], [6, 2, 3]]

See also

mulscalerrow

modelparameters.sympy.matrices.densearith.mulrowcol(row, col, K)[source]

Multiplies two lists representing row and column element-wise.

Gotcha: Here the column is represented as a list contrary to the norm where it is represented as a list of one element lists. The reason is that the theoretically correct approach is too expensive. This problem is expected to be removed later as we have a good data structure to facilitate column operations.

Examples

>>> from .densearith import mulrowcol
>>> from .. import ZZ
>>> a = [ZZ(2), ZZ(4), ZZ(6)]
>>> mulrowcol(a, a, ZZ)
56
modelparameters.sympy.matrices.densearith.mulrowscaler(row, scaler, K)[source]

Performs the scaler-row multiplication element-wise.

Examples

>>> from .. import ZZ
>>> from .densearith import mulrowscaler
>>> a = [ZZ(3), ZZ(4), ZZ(5)]
>>> mulrowscaler(a, 2, ZZ)
[6, 8, 10]
modelparameters.sympy.matrices.densearith.negate(matlist, K)[source]

Negates the elements of a matrix row-wise.

Examples

>>> from .densearith import negate
>>> from .. import ZZ
>>> a = [
... [ZZ(2), ZZ(3)],
... [ZZ(4), ZZ(5)]]
>>> b = [
... [ZZ(0), ZZ(0)],
... [ZZ(0), ZZ(0)]]
>>> negate(a, ZZ)
[[-2, -3], [-4, -5]]
>>> negate(b, ZZ)
[[0, 0], [0, 0]]

See also

negaterow

modelparameters.sympy.matrices.densearith.negaterow(row, K)[source]

Negates a row element-wise.

Examples

>>> from .densearith import negaterow
>>> from .. import ZZ
>>> a = [ZZ(2), ZZ(3), ZZ(4)]
>>> b = [ZZ(0), ZZ(0), ZZ(0)]
>>> negaterow(a, ZZ)
[-2, -3, -4]
>>> negaterow(b, ZZ)
[0, 0, 0]
modelparameters.sympy.matrices.densearith.sub(matlist1, matlist2, K)[source]

Subtracts two matrices by first negating the second matrix and then adding it to first matrix.

Examples

>>> from .densearith import sub
>>> from .. import ZZ
>>> e = [
... [ZZ(12), ZZ(78)],
... [ZZ(56), ZZ(79)]]
>>> f = [
... [ZZ(1), ZZ(2)],
... [ZZ(3), ZZ(4)]]
>>> g = [
... [ZZ.zero, ZZ.zero],
... [ZZ.zero, ZZ.zero]]
>>> sub(e, f, ZZ)
[[11, 76], [53, 75]]
>>> sub(f, g, ZZ)
[[1, 2], [3, 4]]

See also

negate, negaterow

modelparameters.sympy.matrices.densesolve module

Solution of equations using dense matrices.

The dense matrix is stored as a list of lists.

modelparameters.sympy.matrices.densesolve.LDL(matlist, K)[source]

Performs the LDL decomposition of a hermitian matrix and returns L, D and transpose of L. Only applicable to rational entries.

Examples

>>> from .densesolve import LDL
>>> from .. import QQ
>>> a = [
... [QQ(4), QQ(12), QQ(-16)],
... [QQ(12), QQ(37), QQ(-43)],
... [QQ(-16), QQ(-43), QQ(98)]]
>>> LDL(a, QQ)
([[1, 0, 0], [3, 1, 0], [-4, 5, 1]], [[4, 0, 0], [0, 1, 0], [0, 0, 9]], [[1, 3, -4], [0, 1, 5], [0, 0, 1]])
modelparameters.sympy.matrices.densesolve.LU(matlist, K, reverse=0)[source]

It computes the LU decomposition of a matrix and returns L and U matrices.

Examples

>>> from .densesolve import LU
>>> from .. import QQ
>>> a = [
... [QQ(1), QQ(2), QQ(3)],
... [QQ(2), QQ(-4), QQ(6)],
... [QQ(3), QQ(-9), QQ(-3)]]
>>> LU(a, QQ)
([[1, 0, 0], [2, 1, 0], [3, 15/8, 1]], [[1, 2, 3], [0, -8, 0], [0, 0, -12]])
modelparameters.sympy.matrices.densesolve.LU_solve(matlist, variable, constant, K)[source]

Solves a system of equations using LU decomposition given a matrix of coefficients, a vector of variables and a vector of constants.

Examples

>>> from .densesolve import LU_solve
>>> from .. import QQ
>>> from .. import Dummy
>>> x, y, z = Dummy('x'), Dummy('y'), Dummy('z')
>>> coefficients = [
... [QQ(2), QQ(-1), QQ(-2)],
... [QQ(-4), QQ(6), QQ(3)],
... [QQ(-4), QQ(-2), QQ(8)]]
>>> variables = [
... [x],
... [y],
... [z]]
>>> constants = [
... [QQ(-1)],
... [QQ(13)],
... [QQ(-6)]]
>>> LU_solve(coefficients, variables, constants, QQ)
[[2], [3], [1]]
modelparameters.sympy.matrices.densesolve.backward_substitution(upper_triangle, variable, constant, K)[source]

Performs forward substitution given a lower triangular matrix, a vector of variables and a vector constants.

Examples

>>> from .densesolve import backward_substitution
>>> from .. import QQ
>>> from .. import Dummy
>>> x, y, z = Dummy('x'), Dummy('y'), Dummy('z')
>>> a = [
... [QQ(2), QQ(-1), QQ(-2)],
... [QQ(0), QQ(4), QQ(-1)],
... [QQ(0), QQ(0), QQ(3)]]
>>> variables = [
... [x],
... [y],
... [z]]
>>> constants = [
... [QQ(-1)],
... [QQ(11)],
... [QQ(3)]]
>>> backward_substitution(a, variables, constants, QQ)
[[2], [3], [1]]
modelparameters.sympy.matrices.densesolve.cholesky(matlist, K)[source]

Performs the cholesky decomposition of a Hermitian matrix and returns L and it’s conjugate transpose.

Examples

>>> from .densesolve import cholesky
>>> from .. import QQ
>>> cholesky([[QQ(25), QQ(15), QQ(-5)], [QQ(15), QQ(18), QQ(0)], [QQ(-5), QQ(0), QQ(11)]], QQ)
([[5, 0, 0], [3, 3, 0], [-1, 1, 3]], [[5, 3, -1], [0, 3, 1], [0, 0, 3]])

See also

cholesky_solve

modelparameters.sympy.matrices.densesolve.cholesky_solve(matlist, variable, constant, K)[source]

Solves a system of equations using Cholesky decomposition given a matrix of coefficients, a vector of variables and a vector of constants.

Examples

>>> from .densesolve import cholesky_solve
>>> from .. import QQ
>>> from .. import Dummy
>>> x, y, z = Dummy('x'), Dummy('y'), Dummy('z')
>>> coefficients = [
... [QQ(25), QQ(15), QQ(-5)],
... [QQ(15), QQ(18), QQ(0)],
... [QQ(-5), QQ(0), QQ(11)]]
>>> variables = [
... [x],
... [y],
... [z]]
>>> coefficients = [
... [QQ(2)],
... [QQ(3)],
... [QQ(1)]]
>>> cholesky_solve([[QQ(25), QQ(15), QQ(-5)], [QQ(15), QQ(18), QQ(0)], [QQ(-5), QQ(0), QQ(11)]], [[x], [y], [z]], [[QQ(2)], [QQ(3)], [QQ(1)]], QQ)
[[-1/225], [23/135], [4/45]]
modelparameters.sympy.matrices.densesolve.forward_substitution(lower_triangle, variable, constant, K)[source]

Performs forward substitution given a lower triangular matrix, a vector of variables and a vector of constants.

Examples

>>> from .densesolve import forward_substitution
>>> from .. import QQ
>>> from .. import Dummy
>>> x, y, z = Dummy('x'), Dummy('y'), Dummy('z')
>>> a = [
... [QQ(1), QQ(0), QQ(0)],
... [QQ(-2), QQ(1), QQ(0)],
... [QQ(-2), QQ(-1), QQ(1)]]
>>> variables = [
... [x],
... [y],
... [z]]
>>> constants = [
... [QQ(-1)],
... [QQ(13)],
... [QQ(-6)]]
>>> forward_substitution(a, variables, constants, QQ)
[[-1], [11], [3]]
modelparameters.sympy.matrices.densesolve.lower_triangle(matlist, K)[source]

Transforms a given matrix to a lower triangle matrix by performing row operations on it.

Examples

>>> from .densesolve import lower_triangle
>>> from .. import QQ
>>> a = [
... [QQ(4,1), QQ(12,1), QQ(-16)],
... [QQ(12,1), QQ(37,1), QQ(-43,1)],
... [QQ(-16,1), QQ(-43,1), QQ(98,1)]]
>>> lower_triangle(a, QQ)
[[1, 0, 0], [3, 1, 0], [-4, 5, 1]]

See also

LU

modelparameters.sympy.matrices.densesolve.row_echelon(matlist, K)[source]

Returns the row echelon form of a matrix with diagonal elements reduced to 1.

Examples

>>> from .densesolve import row_echelon
>>> from .. import QQ
>>> a = [
... [QQ(3), QQ(7), QQ(4)],
... [QQ(2), QQ(4), QQ(5)],
... [QQ(6), QQ(2), QQ(3)]]
>>> row_echelon(a, QQ)
[[1, 7/3, 4/3], [0, 1, -7/2], [0, 0, 1]]

See also

rref

modelparameters.sympy.matrices.densesolve.rref(matlist, K)[source]

Returns the reduced row echelon form of a Matrix.

Examples

>>> from .densesolve import rref
>>> from .. import QQ
>>> a = [
... [QQ(1), QQ(2), QQ(1)],
... [QQ(-2), QQ(-3), QQ(1)],
... [QQ(3), QQ(5), QQ(0)]]
>>> rref(a, QQ)
[[1, 0, -5], [0, 1, 3], [0, 0, 0]]

See also

row_echelon

modelparameters.sympy.matrices.densesolve.rref_solve(matlist, variable, constant, K)[source]

Solves a system of equations using reduced row echelon form given a matrix of coefficients, a vector of variables and a vector of constants.

Examples

>>> from .densesolve import rref_solve
>>> from .. import QQ
>>> from .. import Dummy
>>> x, y, z = Dummy('x'), Dummy('y'), Dummy('z')
>>> coefficients = [
... [QQ(25), QQ(15), QQ(-5)],
... [QQ(15), QQ(18), QQ(0)],
... [QQ(-5), QQ(0), QQ(11)]]
>>> constants = [
... [QQ(2)],
... [QQ(3)],
... [QQ(1)]]
>>> variables = [
... [x],
... [y],
... [z]]
>>> rref_solve(coefficients, variables, constants, QQ)
[[-1/225], [23/135], [4/45]]

See also

row_echelon, augment

modelparameters.sympy.matrices.densesolve.upper_triangle(matlist, K)[source]

Transforms a given matrix to an upper triangle matrix by performing row operations on it.

Examples

>>> from .densesolve import upper_triangle
>>> from .. import QQ
>>> a = [
... [QQ(4,1), QQ(12,1), QQ(-16,1)],
... [QQ(12,1), QQ(37,1), QQ(-43,1)],
... [QQ(-16,1), QQ(-43,1), QQ(98,1)]]
>>> upper_triangle(a, QQ)
[[4, 12, -16], [0, 1, 5], [0, 0, 9]]

See also

LU

modelparameters.sympy.matrices.densetools module

Fundamental operations of dense matrices. The dense matrix is stored as a list of lists

modelparameters.sympy.matrices.densetools.augment(matlist, column, K)[source]

Augments a matrix and a column.

Examples

>>> from .densetools import augment
>>> from .. import ZZ
>>> a = [
... [ZZ(3), ZZ(7), ZZ(4)],
... [ZZ(2), ZZ(4), ZZ(5)],
... [ZZ(6), ZZ(2), ZZ(3)]]
>>> b = [
... [ZZ(4)],
... [ZZ(5)],
... [ZZ(6)]]
>>> augment(a, b, ZZ)
[[3, 7, 4, 4], [2, 4, 5, 5], [6, 2, 3, 6]]
modelparameters.sympy.matrices.densetools.col(matlist, i)[source]

Returns the ith column of a matrix Note: Currently very expensive

Examples

>>> from .densetools import col
>>> from .. import ZZ
>>> a = [
... [ZZ(3), ZZ(7), ZZ(4)],
... [ZZ(2), ZZ(4), ZZ(5)],
... [ZZ(6), ZZ(2), ZZ(3)]]
>>> col(a, 1)
[[7], [4], [2]]
modelparameters.sympy.matrices.densetools.conjugate(matlist, K)[source]

Returns the conjugate of a matrix row-wise.

Examples

>>> from .densetools import conjugate
>>> from .. import ZZ
>>> a = [
... [ZZ(3), ZZ(2), ZZ(6)],
... [ZZ(7), ZZ(4), ZZ(2)],
... [ZZ(4), ZZ(5), ZZ(3)]]
>>> conjugate(a, ZZ)
[[3, 2, 6], [7, 4, 2], [4, 5, 3]]

See also

conjugate_row

modelparameters.sympy.matrices.densetools.conjugate_row(row, K)[source]

Returns the conjugate of a row element-wise

Examples

>>> from .densetools import conjugate_row
>>> from .. import ZZ
>>> a = [ZZ(3), ZZ(2), ZZ(6)]
>>> conjugate_row(a, ZZ)
[3, 2, 6]
modelparameters.sympy.matrices.densetools.conjugate_transpose(matlist, K)[source]

Returns the conjugate-transpose of a matrix

Examples

>>> from .. import ZZ
>>> from .densetools import conjugate_transpose
>>> a = [
... [ZZ(3), ZZ(7), ZZ(4)],
... [ZZ(2), ZZ(4), ZZ(5)],
... [ZZ(6), ZZ(2), ZZ(3)]]
>>> conjugate_transpose(a, ZZ)
[[3, 2, 6], [7, 4, 2], [4, 5, 3]]
modelparameters.sympy.matrices.densetools.eye(n, K)[source]

Returns an identity matrix of size n.

Examples

>>> from .densetools import eye
>>> from .. import ZZ
>>> eye(3, ZZ)
[[1, 0, 0], [0, 1, 0], [0, 0, 1]]
modelparameters.sympy.matrices.densetools.isHermitian(matlist, K)[source]

Checks whether matrix is hermitian

Examples

>>> from .densetools import isHermitian
>>> from .. import QQ
>>> a = [
... [QQ(2,1), QQ(-1,1), QQ(-1,1)],
... [QQ(0,1), QQ(4,1), QQ(-1,1)],
... [QQ(0,1), QQ(0,1), QQ(3,1)]]
>>> isHermitian(a, QQ)
False
modelparameters.sympy.matrices.densetools.row(matlist, i)[source]

Returns the ith row of a matrix

Examples

>>> from .densetools import row
>>> from .. import ZZ
>>> a = [
... [ZZ(3), ZZ(7), ZZ(4)],
... [ZZ(2), ZZ(4), ZZ(5)],
... [ZZ(6), ZZ(2), ZZ(3)]]
>>> row(a, 2)
[6, 2, 3]
modelparameters.sympy.matrices.densetools.rowadd(matlist, index1, index2, k, K)[source]

Adds the index1 row with index2 row which in turn is multiplied by k

modelparameters.sympy.matrices.densetools.rowmul(matlist, index, k, K)[source]

Multiplies index row with k

modelparameters.sympy.matrices.densetools.rowswap(matlist, index1, index2, K)[source]

Returns the matrix with index1 row and index2 row swapped

modelparameters.sympy.matrices.densetools.trace(matlist, K)[source]

Returns the trace of a matrix.

Examples

>>> from .densetools import trace, eye
>>> from .. import ZZ
>>> a = [
... [ZZ(3), ZZ(7), ZZ(4)],
... [ZZ(2), ZZ(4), ZZ(5)],
... [ZZ(6), ZZ(2), ZZ(3)]]
>>> b = eye(4, ZZ)
>>> trace(a, ZZ)
10
>>> trace(b, ZZ)
4
modelparameters.sympy.matrices.densetools.transpose(matlist, K)[source]

Returns the transpose of a matrix

Examples

>>> from .densetools import transpose
>>> from .. import ZZ
>>> a = [
... [ZZ(3), ZZ(7), ZZ(4)],
... [ZZ(2), ZZ(4), ZZ(5)],
... [ZZ(6), ZZ(2), ZZ(3)]]
>>> transpose(a, ZZ)
[[3, 2, 6], [7, 4, 2], [4, 5, 3]]

modelparameters.sympy.matrices.immutable module

class modelparameters.sympy.matrices.immutable.ImmutableDenseMatrix(*args, **kwargs)[source]

Bases: DenseMatrix, MatrixExpr

Create an immutable version of a matrix.

Examples

>>> from .. import eye
>>> from ..matrices import ImmutableMatrix
>>> ImmutableMatrix(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 ImmutableDenseMatrix
property cols
default_assumptions = {'algebraic': False, 'commutative': False, 'complex': False, 'composite': False, 'even': False, 'imaginary': False, 'integer': False, 'irrational': False, 'negative': False, 'noninteger': False, 'nonnegative': False, 'nonpositive': False, 'nonzero': False, 'odd': False, 'positive': False, 'prime': False, 'rational': False, 'real': False, 'transcendental': False, 'zero': False}
is_algebraic = False
is_commutative = False
is_complex = False
is_composite = False
is_even = False
is_imaginary = False
is_integer = False
is_irrational = False
is_negative = False
is_noninteger = False
is_nonnegative = False
is_nonpositive = False
is_nonzero = False
is_odd = False
is_positive = False
is_prime = False
is_rational = False
is_real = False
is_transcendental = False
property 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

>>> from .. import Matrix, zeros
>>> from ..abc import x
>>> 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
property rows
property shape

The shape (dimensions) of the matrix as the 2-tuple (rows, cols).

Examples

>>> from ..matrices import zeros
>>> M = zeros(2, 3)
>>> M.shape
(2, 3)
>>> M.rows
2
>>> M.cols
3
modelparameters.sympy.matrices.immutable.ImmutableMatrix

alias of ImmutableDenseMatrix

class modelparameters.sympy.matrices.immutable.ImmutableSparseMatrix(*args, **kwargs)[source]

Bases: SparseMatrix, Basic

Create an immutable version of a sparse matrix.

Examples

>>> from .. import eye
>>> from .immutable import ImmutableSparseMatrix
>>> 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)
default_assumptions = {}
is_Matrix = True
modelparameters.sympy.matrices.immutable.sympify_matrix(arg)[source]

modelparameters.sympy.matrices.matrices module

class modelparameters.sympy.matrices.matrices.DeferredVector(name, **assumptions)[source]

Bases: Symbol, NotIterable

A vector whose components are deferred (e.g. for use with lambdify)

Examples

>>> from .. import DeferredVector, lambdify
>>> X = DeferredVector( 'X' )
>>> X
X
>>> expr = (X[0] + 2, X[2] + 3)
>>> func = lambdify( X, expr)
>>> func( [1, 2, 3] )
(3, 6)
default_assumptions = {}
name
class modelparameters.sympy.matrices.matrices.MatrixBase[source]

Bases: MatrixDeprecated, MatrixCalculus, MatrixEigen, MatrixCommon

Base class for matrix objects.

property D

Return Dirac conjugate (if self.rows == 4).

Examples

>>> from .. import Matrix, I, eye
>>> m = Matrix((0, 1 + I, 2, 3))
>>> m.D
Matrix([[0, 1 - I, -2, -3]])
>>> m = (eye(4) + I*eye(4))
>>> m[0, 3] = 2
>>> m.D
Matrix([
[1 - I,     0,      0,      0],
[    0, 1 - I,      0,      0],
[    0,     0, -1 + I,      0],
[    2,     0,      0, -1 + I]])

If the matrix does not have 4 rows an AttributeError will be raised because this property is only defined for matrices with 4 rows.

>>> Matrix(eye(2)).D
Traceback (most recent call last):
...
AttributeError: Matrix has no attribute D.

See also

conjugate

By-element conjugation

H

Hermite conjugation

LDLdecomposition()[source]

Returns the LDL Decomposition (L, D) of matrix A, such that L * D * L.T == A This method eliminates the use of square root. Further this ensures that all the diagonal entries of L are 1. A must be a square, symmetric, positive-definite and non-singular matrix.

Examples

>>> from ..matrices import Matrix, eye
>>> A = Matrix(((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.inv() == eye(A.rows)
True
LDLsolve(rhs)[source]

Solves Ax = B using LDL decomposition, for a general square and non-singular matrix.

For a non-square matrix with rows > cols, the least squares solution is returned.

Examples

>>> from ..matrices import Matrix, eye
>>> A = eye(2)*2
>>> B = Matrix([[1, 2], [3, 4]])
>>> A.LDLsolve(B) == B/2
True
LUdecomposition(iszerofunc=<function _iszero>, simpfunc=None, rankcheck=False)[source]

Returns (L, U, perm) where L is a lower triangular matrix with unit diagonal, U is an upper triangular matrix, and perm is a list of row swap index pairs. If A is the original matrix, then A = (L*U).permuteBkwd(perm), and the row permutation matrix P such that P*A = L*U can be computed by P=eye(A.row).permuteFwd(perm).

See documentation for LUCombined for details about the keyword argument rankcheck, iszerofunc, and simpfunc.

Examples

>>> from .. import Matrix
>>> a = Matrix([[4, 3], [6, 3]])
>>> L, U, _ = a.LUdecomposition()
>>> L
Matrix([
[  1, 0],
[3/2, 1]])
>>> U
Matrix([
[4,    3],
[0, -3/2]])
LUdecompositionFF()[source]

Compute a fraction-free LU decomposition.

Returns 4 matrices P, L, D, U such that PA = L D**-1 U. If the elements of the matrix belong to some integral domain I, then all elements of L, D and U are guaranteed to belong to I.

Reference
  • W. Zhou & D.J. Jeffrey, “Fraction-free matrix factors: new forms for LU and QR factors”. Frontiers in Computer Science in China, Vol 2, no. 1, pp. 67-80, 2008.

LUdecomposition_Simple(iszerofunc=<function _iszero>, simpfunc=None, rankcheck=False)[source]

Compute an lu decomposition of m x n matrix A, where P*A = L*U

  • L is m x m lower triangular with unit diagonal

  • U is m x n upper triangular

  • P is an m x m permutation matrix

Returns an m x n matrix lu, and an m element list perm where each element of perm is a pair of row exchange indices.

The factors L and U are stored in lu as follows: The subdiagonal elements of L are stored in the subdiagonal elements of lu, that is lu[i, j] = L[i, j] whenever i > j. The elements on the diagonal of L are all 1, and are not explicitly stored. U is stored in the upper triangular portion of lu, that is lu[i ,j] = U[i, j] whenever i <= j. The output matrix can be visualized as:

Matrix([

[u, u, u, u], [l, u, u, u], [l, l, u, u], [l, l, l, u]])

where l represents a subdiagonal entry of the L factor, and u represents an entry from the upper triangular entry of the U factor.

perm is a list row swap index pairs such that if A is the original matrix, then A = (L*U).permuteBkwd(perm), and the row permutation matrix P such that P*A = L*U can be computed by soP=eye(A.row).permuteFwd(perm).

The keyword argument rankcheck determines if this function raises a ValueError when passed a matrix whose rank is strictly less than min(num rows, num cols). The default behavior is to decompose a rank deficient matrix. Pass rankcheck=True to raise a ValueError instead. (This mimics the previous behavior of this function).

The keyword arguments iszerofunc and simpfunc are used by the pivot search algorithm. iszerofunc is a callable that returns a boolean indicating if its input is zero, or None if it cannot make the determination. simpfunc is a callable that simplifies its input. The default is simpfunc=None, which indicate that the pivot search algorithm should not attempt to simplify any candidate pivots. If simpfunc fails to simplify its input, then it must return its input instead of a copy.

When a matrix contains symbolic entries, the pivot search algorithm differs from the case where every entry can be categorized as zero or nonzero. The algorithm searches column by column through the submatrix whose top left entry coincides with the pivot position. If it exists, the pivot is the first entry in the current search column that iszerofunc guarantees is nonzero. If no such candidate exists, then each candidate pivot is simplified if simpfunc is not None. The search is repeated, with the difference that a candidate may be the pivot if iszerofunc() cannot guarantee that it is nonzero. In the second search the pivot is the first candidate that iszerofunc can guarantee is nonzero. If no such candidate exists, then the pivot is the first candidate for which iszerofunc returns None. If no such candidate exists, then the search is repeated in the next column to the right. The pivot search algorithm differs from the one in rref(), which relies on _find_reasonable_pivot(). Future versions of LUdecomposition_simple() may use _find_reasonable_pivot().

LUsolve(rhs, iszerofunc=<function _iszero>)[source]

Solve the linear system Ax = rhs for x where A = self.

This is for symbolic matrices, for real or complex ones use mpmath.lu_solve or mpmath.qr_solve.

QRdecomposition()[source]

Return Q, R where A = Q*R, Q is orthogonal and R is upper triangular.

Examples

This is the example from wikipedia:

>>> from .. import Matrix
>>> A = Matrix([[12, -51, 4], [6, 167, -68], [-4, 24, -41]])
>>> Q, R = A.QRdecomposition()
>>> Q
Matrix([
[ 6/7, -69/175, -58/175],
[ 3/7, 158/175,   6/175],
[-2/7,    6/35,  -33/35]])
>>> R
Matrix([
[14,  21, -14],
[ 0, 175, -70],
[ 0,   0,  35]])
>>> A == Q*R
True

QR factorization of an identity matrix:

>>> A = Matrix([[1, 0, 0], [0, 1, 0], [0, 0, 1]])
>>> Q, R = A.QRdecomposition()
>>> Q
Matrix([
[1, 0, 0],
[0, 1, 0],
[0, 0, 1]])
>>> R
Matrix([
[1, 0, 0],
[0, 1, 0],
[0, 0, 1]])
QRsolve(b)[source]

Solve the linear system ‘Ax = b’.

‘self’ is the matrix ‘A’, the method argument is the vector ‘b’. The method returns the solution vector ‘x’. If ‘b’ is a matrix, the system is solved for each column of ‘b’ and the return value is a matrix of the same shape as ‘b’.

This method is slower (approximately by a factor of 2) but more stable for floating-point arithmetic than the LUsolve method. However, LUsolve usually uses an exact arithmetic, so you don’t need to use QRsolve.

This is mainly for educational purposes and symbolic matrices, for real (or complex) matrices use mpmath.qr_solve.

add(b)[source]

Return self + b

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

>>> from ..matrices import Matrix
>>> A = Matrix(((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
Matrix([
[25, 15, -5],
[15, 18,  0],
[-5,  0, 11]])
cholesky_solve(rhs)[source]

Solves Ax = B using Cholesky decomposition, for a general square non-singular matrix. For a non-square matrix with rows > cols, the least squares solution is returned.

condition_number()[source]

Returns the condition number of a matrix.

This is the maximum singular value divided by the minimum singular value

Examples

>>> from .. import Matrix, S
>>> A = Matrix([[1, 0, 0], [0, 10, 0], [0, 0, S.One/10]])
>>> A.condition_number()
100

See also

singular_values

copy()[source]

Returns the copy of a matrix.

Examples

>>> from .. import Matrix
>>> A = Matrix(2, 2, [1, 2, 3, 4])
>>> A.copy()
Matrix([
[1, 2],
[3, 4]])
cross(b)[source]

Return the cross product of self and b relaxing the condition of compatible dimensions: if each has 3 elements, a matrix of the same type and shape as self will be returned. If b has the same shape as self then common identities for the cross product (like a x b = - b x a) will hold.

See also

dot, multiply, multiply_elementwise

diagonal_solve(rhs)[source]

Solves Ax = B efficiently, where A is a diagonal Matrix, with non-zero diagonal entries.

Examples

>>> from ..matrices import Matrix, eye
>>> A = eye(2)*2
>>> B = Matrix([[1, 2], [3, 4]])
>>> A.diagonal_solve(B) == B/2
True
dot(b)[source]

Return the dot product of Matrix self and b relaxing the condition of compatible dimensions: if either the number of rows or columns are the same as the length of b then the dot product is returned. If self is a row or column vector, a scalar is returned. Otherwise, a list of results is returned (and in that case the number of columns in self must match the length of b).

Examples

>>> from .. import Matrix
>>> M = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
>>> v = [1, 1, 1]
>>> M.row(0).dot(v)
6
>>> M.col(0).dot(v)
12
>>> M.dot(v)
[6, 15, 24]

See also

cross, multiply, multiply_elementwise

dual()[source]

Returns the dual of a matrix, which is:

(1/2)*levicivita(i, j, k, l)*M(k, l) summed over indices k and l

Since the levicivita method is anti_symmetric for any pairwise exchange of indices, the dual of a symmetric matrix is the zero matrix. Strictly speaking the dual defined here assumes that the ‘matrix’ M is a contravariant anti_symmetric second rank tensor, so that the dual is a covariant second rank tensor.

exp()[source]

Return the exponentiation of a square matrix.

gauss_jordan_solve(b, freevar=False)[source]

Solves Ax = b using Gauss Jordan elimination.

There may be zero, one, or infinite solutions. If one solution exists, it will be returned. If infinite solutions exist, it will be returned parametrically. If no solutions exist, It will throw ValueError.

Parameters:
  • b (Matrix) – The right hand side of the equation to be solved for. Must have the same number of rows as matrix A.

  • freevar (List) – If the system is underdetermined (e.g. A has more columns than rows), infinite solutions are possible, in terms of an arbitrary values of free variables. Then the index of the free variables in the solutions (column Matrix) will be returned by freevar, if the flag freevar is set to True.

Returns:

  • x (Matrix) – The matrix that will satisfy Ax = B. Will have as many rows as matrix A has columns, and as many columns as matrix B.

  • params (Matrix) – If the system is underdetermined (e.g. A has more columns than rows), infinite solutions are possible, in terms of an arbitrary parameters. These arbitrary parameters are returned as params Matrix.

Examples

>>> from .. import Matrix
>>> A = Matrix([[1, 2, 1, 1], [1, 2, 2, -1], [2, 4, 0, 6]])
>>> b = Matrix([7, 12, 4])
>>> sol, params = A.gauss_jordan_solve(b)
>>> sol
Matrix([
[-2*_tau0 - 3*_tau1 + 2],
[                 _tau0],
[           2*_tau1 + 5],
[                 _tau1]])
>>> params
Matrix([
[_tau0],
[_tau1]])
>>> A = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 10]])
>>> b = Matrix([3, 6, 9])
>>> sol, params = A.gauss_jordan_solve(b)
>>> sol
Matrix([
[-1],
[ 2],
[ 0]])
>>> params
Matrix(0, 1, [])

References

inv(method=None, **kwargs)[source]

Return the inverse of a matrix.

CASE 1: If the matrix is a dense matrix.

Return the matrix inverse using the method indicated (default is Gauss elimination).

Parameters:

method (('GE', 'LU', or 'ADJ')) –

Notes

According to the method keyword, it calls the appropriate method:

GE …. inverse_GE(); default LU …. inverse_LU() ADJ … inverse_ADJ()

Raises:
  • ValueError – If the determinant of the matrix is zero.

  • CASE 2 – If the matrix is a sparse matrix.:

  • Return the matrix inverse using Cholesky or LDL (default).

  • kwargs

  • ======

:raises method : (‘CH’, ‘LDL’):

Notes

According to the method keyword, it calls the appropriate method:

LDL … inverse_LDL(); default CH …. inverse_CH()

Raises:

ValueError – If the determinant of the matrix is zero.

inv_mod(m)[source]

Returns the inverse of the matrix K (mod m), if it exists.

Method to find the matrix inverse of K (mod m) implemented in this function:

  • Compute mathrm{adj}(K) = mathrm{cof}(K)^t, the adjoint matrix of K.

  • Compute r = 1/mathrm{det}(K) pmod m.

  • K^{-1} = rcdot mathrm{adj}(K) pmod m.

Examples

>>> from .. import Matrix
>>> A = Matrix(2, 2, [1, 2, 3, 4])
>>> A.inv_mod(5)
Matrix([
[3, 1],
[4, 2]])
>>> A.inv_mod(3)
Matrix([
[1, 1],
[0, 1]])
inverse_ADJ(iszerofunc=<function _iszero>)[source]

Calculates the inverse using the adjugate matrix and a determinant.

inverse_GE(iszerofunc=<function _iszero>)[source]

Calculates the inverse using Gaussian elimination.

inverse_LU(iszerofunc=<function _iszero>)[source]

Calculates the inverse using LU decomposition.

is_Matrix = True
is_nilpotent()[source]

Checks if a matrix is nilpotent.

A matrix B is nilpotent if for some integer k, B**k is a zero matrix.

Examples

>>> from .. import Matrix
>>> a = Matrix([[0, 0, 0], [1, 0, 0], [1, 1, 0]])
>>> a.is_nilpotent()
True
>>> a = Matrix([[1, 0, 1], [1, 0, 0], [1, 1, 0]])
>>> a.is_nilpotent()
False
key2bounds(keys)[source]

Converts a key with potentially mixed types of keys (integer and slice) into a tuple of ranges and raises an error if any index is out of self’s range.

See also

key2ij

key2ij(key)[source]

Converts key into canonical form, converting integers or indexable items into valid integers for self’s range or returning slices unchanged.

See also

key2bounds

lower_triangular_solve(rhs)[source]

Solves Ax = B, where A is a lower triangular matrix.

multiply(b)[source]

Returns self*b

See also

dot, cross, multiply_elementwise

norm(ord=None)[source]

Return the Norm of a Matrix or Vector. In the simplest case this is the geometric size of the vector Other norms can be specified by the ord parameter

ord

norm for matrices

norm for vectors

None

Frobenius norm

2-norm

‘fro’

Frobenius norm

  • does not exist

inf

max(abs(x))

-inf

min(abs(x))

1

as below

-1

as below

2

2-norm (largest sing. value)

as below

-2

smallest singular value

as below

other

  • does not exist

sum(abs(x)**ord)**(1./ord)

Examples

>>> from .. import Matrix, Symbol, trigsimp, cos, sin, oo
>>> x = Symbol('x', real=True)
>>> v = Matrix([cos(x), sin(x)])
>>> trigsimp( v.norm() )
1
>>> v.norm(10)
(sin(x)**10 + cos(x)**10)**(1/10)
>>> A = Matrix([[1, 1], [1, 1]])
>>> A.norm(2)# Spectral norm (max of |Ax|/|x| under 2-vector-norm)
2
>>> A.norm(-2) # Inverse spectral norm (smallest singular value)
0
>>> A.norm() # Frobenius Norm
2
>>> Matrix([1, -2]).norm(oo)
2
>>> Matrix([-1, 2]).norm(-oo)
1

See also

normalized

normalized()[source]

Return the normalized version of self.

See also

norm

pinv()[source]

Calculate the Moore-Penrose pseudoinverse of the matrix.

The Moore-Penrose pseudoinverse exists and is unique for any matrix. If the matrix is invertible, the pseudoinverse is the same as the inverse.

Examples

>>> from .. import Matrix
>>> Matrix([[1, 2, 3], [4, 5, 6]]).pinv()
Matrix([
[-17/18,  4/9],
[  -1/9,  1/9],
[ 13/18, -2/9]])

See also

inv, pinv_solve

References

pinv_solve(B, arbitrary_matrix=None)[source]

Solve Ax = B using the Moore-Penrose pseudoinverse.

There may be zero, one, or infinite solutions. If one solution exists, it will be returned. If infinite solutions exist, one will be returned based on the value of arbitrary_matrix. If no solutions exist, the least-squares solution is returned.

Parameters:
  • B (Matrix) – The right hand side of the equation to be solved for. Must have the same number of rows as matrix A.

  • arbitrary_matrix (Matrix) – If the system is underdetermined (e.g. A has more columns than rows), infinite solutions are possible, in terms of an arbitrary matrix. This parameter may be set to a specific matrix to use for that purpose; if so, it must be the same shape as x, with as many rows as matrix A has columns, and as many columns as matrix B. If left as None, an appropriate matrix containing dummy symbols in the form of wn_m will be used, with n and m being row and column position of each symbol.

Returns:

x – The matrix that will satisfy Ax = B. Will have as many rows as matrix A has columns, and as many columns as matrix B.

Return type:

Matrix

Examples

>>> from .. import Matrix
>>> A = Matrix([[1, 2, 3], [4, 5, 6]])
>>> B = Matrix([7, 8])
>>> A.pinv_solve(B)
Matrix([
[ _w0_0/6 - _w1_0/3 + _w2_0/6 - 55/18],
[-_w0_0/3 + 2*_w1_0/3 - _w2_0/3 + 1/9],
[ _w0_0/6 - _w1_0/3 + _w2_0/6 + 59/18]])
>>> A.pinv_solve(B, arbitrary_matrix=Matrix([0, 0, 0]))
Matrix([
[-55/18],
[   1/9],
[ 59/18]])

Notes

This may return either exact solutions or least squares solutions. To determine which, check A * A.pinv() * B == B. It will be True if exact solutions exist, and False if only a least-squares solution exists. Be aware that the left hand side of that equation may need to be simplified to correctly compare to the right hand side.

References

print_nonzero(symb='X')[source]

Shows location of non-zero entries for fast shape lookup.

Examples

>>> from ..matrices import Matrix, eye
>>> m = Matrix(2, 3, lambda i, j: i*3+j)
>>> m
Matrix([
[0, 1, 2],
[3, 4, 5]])
>>> m.print_nonzero()
[ XX]
[XXX]
>>> m = eye(4)
>>> m.print_nonzero("x")
[x   ]
[ x  ]
[  x ]
[   x]
project(v)[source]

Return the projection of self onto the line containing v.

Examples

>>> from .. import Matrix, S, sqrt
>>> V = Matrix([sqrt(3)/2, S.Half])
>>> x = Matrix([[1, 0]])
>>> V.project(x)
Matrix([[sqrt(3)/2, 0]])
>>> V.project(-x)
Matrix([[sqrt(3)/2, 0]])
solve(rhs, method='GE')[source]

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

For a list of possible inversion methods, see the .inv() docstring.

solve_least_squares(rhs, method='CH')[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. To find out which are available, see the docstring of the .inv() method.

Examples

>>> from ..matrices import Matrix, ones
>>> A = Matrix([1, 2, 3])
>>> B = Matrix([2, 3, 4])
>>> S = Matrix(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().n(2)
0.58

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

>>> xy += ones(2, 1)/10
>>> (S*xy - r).norm().n(2)
1.5
table(printer, rowstart='[', rowend=']', rowsep='\n', colsep=', ', align='right')[source]

String form of Matrix as a table.

printer is the printer to use for on the elements (generally something like StrPrinter())

rowstart is the string used to start each row (by default ‘[‘).

rowend is the string used to end each row (by default ‘]’).

rowsep is the string used to separate rows (by default a newline).

colsep is the string used to separate columns (by default ‘, ‘).

align defines how the elements are aligned. Must be one of ‘left’, ‘right’, or ‘center’. You can also use ‘<’, ‘>’, and ‘^’ to mean the same thing, respectively.

This is used by the string printer for Matrix.

Examples

>>> from .. import Matrix
>>> from ..printing.str import StrPrinter
>>> M = Matrix([[1, 2], [-33, 4]])
>>> printer = StrPrinter()
>>> M.table(printer)
'[  1, 2]\n[-33, 4]'
>>> print(M.table(printer))
[  1, 2]
[-33, 4]
>>> print(M.table(printer, rowsep=',\n'))
[  1, 2],
[-33, 4]
>>> print('[%s]' % M.table(printer, rowsep=',\n'))
[[  1, 2],
[-33, 4]]
>>> print(M.table(printer, colsep=' '))
[  1 2]
[-33 4]
>>> print(M.table(printer, align='center'))
[ 1 , 2]
[-33, 4]
>>> print(M.table(printer, rowstart='{', rowend='}'))
{  1, 2}
{-33, 4}
upper_triangular_solve(rhs)[source]

Solves Ax = B, where A is an upper triangular matrix.

vech(diagonal=True, check_symmetry=True)[source]

Return the unique elements of a symmetric Matrix as a one column matrix by stacking the elements in the lower triangle.

Arguments: diagonal – include the diagonal cells of self or not check_symmetry – checks symmetry of self but not completely reliably

Examples

>>> from .. import Matrix
>>> m=Matrix([[1, 2], [2, 3]])
>>> m
Matrix([
[1, 2],
[2, 3]])
>>> m.vech()
Matrix([
[1],
[2],
[3]])
>>> m.vech(diagonal=False)
Matrix([[2]])

See also

vec

class modelparameters.sympy.matrices.matrices.MatrixCalculus[source]

Bases: MatrixCommon

Provides calculus-related matrix operations.

diff(*args)[source]

Calculate the derivative of each element in the matrix. args will be passed to the integrate function.

Examples

>>> from ..matrices import Matrix
>>> from ..abc import x, y
>>> M = Matrix([[x, y], [1, 0]])
>>> M.diff(x)
Matrix([
[1, 0],
[0, 0]])

See also

integrate, limit

integrate(*args)[source]

Integrate each element of the matrix. args will be passed to the integrate function.

Examples

>>> from ..matrices import Matrix
>>> from ..abc import x, y
>>> M = Matrix([[x, y], [1, 0]])
>>> M.integrate((x, ))
Matrix([
[x**2/2, x*y],
[     x,   0]])
>>> M.integrate((x, 0, 2))
Matrix([
[2, 2*y],
[2,   0]])

See also

limit, diff

jacobian(X)[source]

Calculates the Jacobian matrix (derivative of a vector-valued function).

Parameters:
  • self (vector of expressions representing functions f_i(x_1, ..., x_n).) –

  • X (set of x_i's in order, it can be a list or a Matrix) –

  • order (Both self and X can be a row or a column matrix in any) –

  • (i.e.

  • work). (jacobian() should always) –

Examples

>>> from .. import sin, cos, Matrix
>>> from ..abc import rho, phi
>>> X = Matrix([rho*cos(phi), rho*sin(phi), rho**2])
>>> Y = Matrix([rho, phi])
>>> X.jacobian(Y)
Matrix([
[cos(phi), -rho*sin(phi)],
[sin(phi),  rho*cos(phi)],
[   2*rho,             0]])
>>> X = Matrix([rho*cos(phi), rho*sin(phi)])
>>> X.jacobian(Y)
Matrix([
[cos(phi), -rho*sin(phi)],
[sin(phi),  rho*cos(phi)]])

See also

hessian, wronskian

limit(*args)[source]

Calculate the limit of each element in the matrix. args will be passed to the limit function.

Examples

>>> from ..matrices import Matrix
>>> from ..abc import x, y
>>> M = Matrix([[x, y], [1, 0]])
>>> M.limit(x, 2)
Matrix([
[2, y],
[1, 0]])

See also

integrate, diff

class modelparameters.sympy.matrices.matrices.MatrixDeprecated[source]

Bases: MatrixCommon

A class to house deprecated matrix methods.

berkowitz()[source]
berkowitz_charpoly(x=_lambda, simplify=<function simplify>)[source]
berkowitz_det()[source]

Computes determinant using Berkowitz method.

See also

det, berkowitz

berkowitz_eigenvals(**flags)[source]

Computes eigenvalues of a Matrix using Berkowitz method.

See also

berkowitz

berkowitz_minors()[source]

Computes principal minors using Berkowitz method.

See also

berkowitz

cofactorMatrix(method='berkowitz')[source]
det_LU_decomposition()[source]

Compute matrix determinant using LU decomposition

Note that this method fails if the LU decomposition itself fails. In particular, if the matrix has no inverse this method will fail.

TODO: Implement algorithm for sparse matrices (SFF), http://www.eecis.udel.edu/~saunders/papers/sffge/it5.ps.

See also

det, det_bareiss, berkowitz_det

det_bareis()[source]
det_bareiss()[source]

Compute matrix determinant using Bareiss’ fraction-free algorithm which is an extension of the well known Gaussian elimination method. This approach is best suited for dense symbolic matrices and will result in a determinant with minimal number of fractions. It means that less term rewriting is needed on resulting formulae.

TODO: Implement algorithm for sparse matrices (SFF), http://www.eecis.udel.edu/~saunders/papers/sffge/it5.ps.

See also

det, berkowitz_det

jordan_cell(eigenval, n)[source]
jordan_cells(calc_transformation=True)[source]
minorEntry(i, j, method='berkowitz')[source]
minorMatrix(i, j)[source]
permuteBkwd(perm)[source]

Permute the rows of the matrix with the given permutation in reverse.

permuteFwd(perm)[source]

Permute the rows of the matrix with the given permutation.

class modelparameters.sympy.matrices.matrices.MatrixDeterminant[source]

Bases: MatrixCommon

Provides basic matrix determinant operations. Should not be instantiated directly.

adjugate(method='berkowitz')[source]

Returns the adjugate, or classical adjoint, of a matrix. That is, the transpose of the matrix of cofactors.

http://en.wikipedia.org/wiki/Adjugate

See also

cofactor_matrix, transpose

charpoly(x=_lambda, simplify=<function simplify>)[source]

Computes characteristic polynomial det(x*I - self) where I is the identity matrix.

A PurePoly is returned, so using different variables for x does not affect the comparison or the polynomials:

Examples

>>> from .. import Matrix
>>> from ..abc import x, y
>>> A = Matrix([[1, 3], [2, 0]])
>>> A.charpoly(x) == A.charpoly(y)
True

Specifying x is optional; a Dummy with name lambda is used by default (which looks good when pretty-printed in unicode):

>>> A.charpoly().as_expr()
_lambda**2 - _lambda - 6

No test is done to see that x doesn’t clash with an existing symbol, so using the default (lambda) or your own Dummy symbol is the safest option:

>>> A = Matrix([[1, 2], [x, 0]])
>>> A.charpoly().as_expr()
_lambda**2 - _lambda - 2*x
>>> A.charpoly(x).as_expr()
x**2 - 3*x

Notes

The Samuelson-Berkowitz algorithm is used to compute the characteristic polynomial efficiently and without any division operations. Thus the characteristic polynomial over any commutative ring without zero divisors can be computed.

See also

det

cofactor(i, j, method='berkowitz')[source]

Calculate the cofactor of an element.

cofactor_matrix(method='berkowitz')[source]

Return a matrix containing the cofactor of each element.

det(method='bareiss')[source]

Computes the determinant of a matrix. If the matrix is at most 3x3, a hard-coded formula is used. Otherwise, the determinant using the method method.

Possible values for “method”:

bareis berkowitz lu

minor(i, j, method='berkowitz')[source]

Return the (i,j) minor of self. That is, return the determinant of the matrix obtained by deleting the i`th row and `j`th column from `self.

minor_submatrix(i, j)[source]

Return the submatrix obtained by removing the i`th row and `j`th column from `self.

See also

minor, cofactor

class modelparameters.sympy.matrices.matrices.MatrixEigen[source]

Bases: MatrixSubspaces

Provides basic matrix eigenvalue/vector operations. Should not be instantiated directly.

diagonalize(reals_only=False, sort=False, normalize=False)[source]

Return (P, D), where D is diagonal and

D = P^-1 * M * P

where M is current matrix.

Parameters:
  • reals_only (bool. Whether to throw an error if complex numbers are need) – to diagonalize. (Default: False)

  • sort (bool. Sort the eigenvalues along the diagonal. (Default: False)) –

  • normalize (bool. If True, normalize the columns of P. (Default: False)) –

Examples

>>> from .. import Matrix
>>> m = Matrix(3, 3, [1, 2, 0, 0, 3, 0, 2, -4, 2])
>>> m
Matrix([
[1,  2, 0],
[0,  3, 0],
[2, -4, 2]])
>>> (P, D) = m.diagonalize()
>>> D
Matrix([
[1, 0, 0],
[0, 2, 0],
[0, 0, 3]])
>>> P
Matrix([
[-1, 0, -1],
[ 0, 0, -1],
[ 2, 1,  2]])
>>> P.inv() * m * P
Matrix([
[1, 0, 0],
[0, 2, 0],
[0, 0, 3]])

See also

is_diagonal, is_diagonalizable

eigenvals(error_when_incomplete=True, **flags)[source]

Return eigenvalues using the Berkowitz agorithm to compute the characteristic polynomial.

Parameters:
  • error_when_incomplete (bool) – Raise an error when not all eigenvalues are computed. This is caused by roots not returning a full list of eigenvalues.

  • Floats (Since the roots routine doesn't always work well with) –

:param : :param they will be replaced with Rationals before calling that: :param routine. If this is not desired: :param set flag rational to False.:

eigenvects(error_when_incomplete=True, **flags)[source]

Return list of triples (eigenval, multiplicity, basis).

The flag simplify has two effects:

1) if bool(simplify) is True, as_content_primitive() will be used to tidy up normalization artifacts; 2) if nullspace needs simplification to compute the basis, the simplify flag will be passed on to the nullspace routine which will interpret it there.

Parameters:
  • error_when_incomplete (bool) – Raise an error when not all eigenvalues are computed. This is caused by roots not returning a full list of eigenvalues.

  • Floats (If the matrix contains any) –

  • Rationals (they will be changed to) –

  • purposes (for computation) –

  • being (but the answers will be returned after) –

  • imaginary (evaluated with evalf. If it is desired to removed small) –

  • step (portions during the evalf) –

  • flag. (pass a value for the chop) –

is_diagonalizable(reals_only=False, **kwargs)[source]

Returns true if a matrix is diagonalizable.

Parameters:
  • reals_only (bool. If reals_only=True, determine whether the matrix can be) – diagonalized without complex numbers. (Default: False)

  • kwargs

  • ======

  • clear_cache (bool. If True, clear the result of any computations when finished.) – (Default: True)

Examples

>>> from .. import Matrix
>>> m = Matrix(3, 3, [1, 2, 0, 0, 3, 0, 2, -4, 2])
>>> m
Matrix([
[1,  2, 0],
[0,  3, 0],
[2, -4, 2]])
>>> m.is_diagonalizable()
True
>>> m = Matrix(2, 2, [0, 1, 0, 0])
>>> m
Matrix([
[0, 1],
[0, 0]])
>>> m.is_diagonalizable()
False
>>> m = Matrix(2, 2, [0, 1, -1, 0])
>>> m
Matrix([
[ 0, 1],
[-1, 0]])
>>> m.is_diagonalizable()
True
>>> m.is_diagonalizable(reals_only=True)
False

See also

is_diagonal, diagonalize

jordan_form(calc_transform=True, **kwargs)[source]

Return (P, J) where J is a Jordan block matrix and P is a matrix such that

self == P*J*P**-1

Parameters:
  • calc_transform (bool) – If False, then only J is returned.

  • chop (bool) – All matrices are convered to exact types when computing eigenvalues and eigenvectors. As a result, there may be approximation errors. If chop==True, these errors will be truncated.

Examples

>>> from .. import Matrix
>>> m = Matrix([[ 6,  5, -2, -3], [-3, -1,  3,  3], [ 2,  1, -2, -3], [-1,  1,  5,  5]])
>>> P, J = m.jordan_form()
>>> J
Matrix([
[2, 1, 0, 0],
[0, 2, 0, 0],
[0, 0, 2, 1],
[0, 0, 0, 2]])

See also

jordan_block

left_eigenvects(**flags)[source]

Returns left eigenvectors and eigenvalues.

This function returns the list of triples (eigenval, multiplicity, basis) for the left eigenvectors. Options are the same as for eigenvects(), i.e. the **flags arguments gets passed directly to eigenvects().

Examples

>>> from .. import Matrix
>>> M = Matrix([[0, 1, 1], [1, 0, 0], [1, 1, 1]])
>>> M.eigenvects()
[(-1, 1, [Matrix([
[-1],
[ 1],
[ 0]])]), (0, 1, [Matrix([
[ 0],
[-1],
[ 1]])]), (2, 1, [Matrix([
[2/3],
[1/3],
[  1]])])]
>>> M.left_eigenvects()
[(-1, 1, [Matrix([[-2, 1, 1]])]), (0, 1, [Matrix([[-1, -1, 1]])]), (2,
1, [Matrix([[1, 1, 1]])])]
singular_values()[source]

Compute the singular values of a Matrix

Examples

>>> from .. import Matrix, Symbol
>>> x = Symbol('x', real=True)
>>> A = Matrix([[0, 1, 0], [0, x, 0], [-1, 0, 0]])
>>> A.singular_values()
[sqrt(x**2 + 1), 1, 0]

See also

condition_number

class modelparameters.sympy.matrices.matrices.MatrixReductions[source]

Bases: MatrixDeterminant

Provides basic matrix row/column operations. Should not be instantiated directly.

echelon_form(iszerofunc=<function _iszero>, simplify=False, with_pivots=False)[source]

Returns a matrix row-equivalent to self that is in echelon form. Note that echelon form of a matrix is not unique, however, properties like the row space and the null space are preserved.

elementary_col_op(op='n->kn', col=None, k=None, col1=None, col2=None)[source]

Perfoms the elementary column operation op.

op may be one of

  • “n->kn” (column n goes to k*n)

  • “n<->m” (swap column n and column m)

  • “n->n+km” (column n goes to column n + k*column m)

Parameters:
  • op (string; the elementary row operation) –

  • col (the column to apply the column operation) –

  • k (the multiple to apply in the column operation) –

  • col1 (one column of a column swap) –

  • col2 (second column of a column swap or column "m" in the column operation) – “n->n+km”

elementary_row_op(op='n->kn', row=None, k=None, row1=None, row2=None)[source]

Perfoms the elementary row operation op.

op may be one of

  • “n->kn” (row n goes to k*n)

  • “n<->m” (swap row n and row m)

  • “n->n+km” (row n goes to row n + k*row m)

Parameters:
  • op (string; the elementary row operation) –

  • row (the row to apply the row operation) –

  • k (the multiple to apply in the row operation) –

  • row1 (one row of a row swap) –

  • row2 (second row of a row swap or row "m" in the row operation) – “n->n+km”

property is_echelon

Returns True if he matrix is in echelon form. That is, all rows of zeros are at the bottom, and below each leading non-zero in a row are exclusively zeros.

rank(iszerofunc=<function _iszero>, simplify=False)[source]

Returns the rank of a matrix

>>> from .. import Matrix
>>> from ..abc import x
>>> m = Matrix([[1, 2], [x, 1 - 1/x]])
>>> m.rank()
2
>>> n = Matrix(3, 3, range(1, 10))
>>> n.rank()
2
rref(iszerofunc=<function _iszero>, simplify=False, pivots=True, normalize_last=True)[source]

Return reduced row-echelon form of matrix and indices of pivot vars.

Parameters:
  • iszerofunc (Function) – A function used for detecting whether an element can act as a pivot. lambda x: x.is_zero is used by default.

  • simplify (Function) – A function used to simplify elements when looking for a pivot. By default SymPy’s `simplify`is used.

  • pivots (True or False) – If True, a tuple containing the row-reduced matrix and a tuple of pivot columns is returned. If False just the row-reduced matrix is returned.

  • normalize_last (True or False) – If True, no pivots are normalized to 1 until after all entries above and below each pivot are zeroed. This means the row reduction algorithm is fraction free until the very last step. If False, the naive row reduction procedure is used where each pivot is normalized to be 1 before row operations are used to zero above and below the pivot.

Notes

The default value of normalize_last=True can provide significant speedup to row reduction, especially on matrices with symbols. However, if you depend on the form row reduction algorithm leaves entries of the matrix, set noramlize_last=False

Examples

>>> from .. import Matrix
>>> from ..abc import x
>>> m = Matrix([[1, 2], [x, 1 - 1/x]])
>>> m.rref()
(Matrix([
[1, 0],
[0, 1]]), (0, 1))
>>> rref_matrix, rref_pivots = m.rref()
>>> rref_matrix
Matrix([
[1, 0],
[0, 1]])
>>> rref_pivots
(0, 1)
class modelparameters.sympy.matrices.matrices.MatrixSubspaces[source]

Bases: MatrixReductions

Provides methods relating to the fundamental subspaces of a matrix. Should not be instantiated directly.

columnspace(simplify=False)[source]

Returns a list of vectors (Matrix objects) that span columnspace of self

Examples

>>> from ..matrices import Matrix
>>> m = Matrix(3, 3, [1, 3, 0, -2, -6, 0, 3, 9, 6])
>>> m
Matrix([
[ 1,  3, 0],
[-2, -6, 0],
[ 3,  9, 6]])
>>> m.columnspace()
[Matrix([
[ 1],
[-2],
[ 3]]), Matrix([
[0],
[0],
[6]])]

See also

nullspace, rowspace

nullspace(simplify=False)[source]

Returns list of vectors (Matrix objects) that span nullspace of self

Examples

>>> from ..matrices import Matrix
>>> m = Matrix(3, 3, [1, 3, 0, -2, -6, 0, 3, 9, 6])
>>> m
Matrix([
[ 1,  3, 0],
[-2, -6, 0],
[ 3,  9, 6]])
>>> m.nullspace()
[Matrix([
[-3],
[ 1],
[ 0]])]

See also

columnspace, rowspace

classmethod orthogonalize(*vecs, **kwargs)[source]

Apply the Gram-Schmidt orthogonalization procedure to vectors supplied in vecs.

Parameters:
  • vecs (vectors to be made orthogonal) –

  • normalize (bool. Whether the returned vectors) – should be renormalized to be unit vectors.

rowspace(simplify=False)[source]

Returns a list of vectors that span the row space of self.

modelparameters.sympy.matrices.matrices.a2idx(j, n=None)[source]

Return integer after making positive and validating against n.

modelparameters.sympy.matrices.matrices.classof(A, B)[source]

Get the type of the result when combining matrices of different types.

Currently the strategy is that immutability is contagious.

Examples

>>> from .. import Matrix, ImmutableMatrix
>>> from .matrices import classof
>>> M = Matrix([[1, 2], [3, 4]]) # a Mutable Matrix
>>> IM = ImmutableMatrix([[1, 2], [3, 4]])
>>> classof(M, IM)
<class 'sympy.matrices.immutable.ImmutableDenseMatrix'>

modelparameters.sympy.matrices.normalforms module

modelparameters.sympy.matrices.normalforms.invariant_factors(m, domain=None)[source]

Return the tuple of abelian invariants for a matrix m (as in the Smith-Normal form)

References

[1] https://en.wikipedia.org/wiki/Smith_normal_form#Algorithm [2] http://sierra.nmsu.edu/morandi/notes/SmithNormalForm.pdf

modelparameters.sympy.matrices.normalforms.smith_normal_form(m, domain=None)[source]

Return the Smith Normal Form of a matrix m over the ring domain. This will only work if the ring is a principal ideal domain.

Examples

>>> from ..polys.solvers import RawMatrix as Matrix
>>> from ..polys.domains import ZZ
>>> from .normalforms import smith_normal_form
>>> m = Matrix([[12, 6, 4], [3, 9, 6], [2, 16, 14]])
>>> setattr(m, "ring", ZZ)
>>> print(smith_normal_form(m))
Matrix([[1, 0, 0], [0, 10, 0], [0, 0, -30]])

modelparameters.sympy.matrices.sparse module

class modelparameters.sympy.matrices.sparse.MutableSparseMatrix(*args, **kwargs)[source]

Bases: SparseMatrix, MatrixBase

as_mutable()[source]

Returns a mutable version of this matrix.

Examples

>>> from .. import ImmutableMatrix
>>> 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]])
col_del(k)[source]

Delete the given column of the matrix.

Examples

>>> from ..matrices import SparseMatrix
>>> M = SparseMatrix([[0, 0], [0, 1]])
>>> M
Matrix([
[0, 0],
[0, 1]])
>>> M.col_del(0)
>>> M
Matrix([
[0],
[1]])

See also

row_del

col_join(other)[source]

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

[A]
[B]

Examples

>>> from .. import SparseMatrix, Matrix, ones
>>> 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

>>> from ..matrices import SparseMatrix
>>> 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

>>> from ..matrices import SparseMatrix
>>> S = SparseMatrix.eye(3); S[2, 1] = 2
>>> S.col_swap(1, 0); S
Matrix([
[0, 1, 0],
[1, 0, 0],
[2, 0, 1]])
copyin_list(key, value)[source]
copyin_matrix(key, value)[source]
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

>>> from ..matrices import SparseMatrix
>>> 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_del(k)[source]

Delete the given row of the matrix.

Examples

>>> from ..matrices import SparseMatrix
>>> M = SparseMatrix([[0, 0], [0, 1]])
>>> M
Matrix([
[0, 0],
[0, 1]])
>>> M.row_del(0)
>>> M
Matrix([[0, 1]])

See also

col_del

row_join(other)[source]

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

[A B]

Examples

>>> from .. import SparseMatrix, Matrix
>>> 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

>>> from ..matrices import SparseMatrix
>>> 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]])

See also

row, zip_row_op, col_op

row_swap(i, j)[source]

Swap, in place, columns i and j.

Examples

>>> from ..matrices import SparseMatrix
>>> 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

>>> from ..matrices import SparseMatrix
>>> 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]])

See also

row, row_op, col_op

class modelparameters.sympy.matrices.sparse.SparseMatrix(*args, **kwargs)[source]

Bases: MatrixBase

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

Examples

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

See also

sympy.matrices.dense.Matrix

property 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

>>> from ..matrices import SparseMatrix
>>> 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
property RL

Alternate faster representation

applyfunc(f)[source]

Apply a function to each element of the matrix.

Examples

>>> from ..matrices import SparseMatrix
>>> 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

>>> from .. import ImmutableMatrix
>>> 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

>>> from ..matrices import SparseMatrix
>>> 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

>>> from ..matrices import SparseMatrix
>>> a=SparseMatrix(((1, 2), (3, 4)))
>>> a
Matrix([
[1, 2],
[3, 4]])
>>> a.CL
[(0, 0, 1), (1, 0, 3), (0, 1, 2), (1, 1, 4)]

See also

col_op, row_list

copy()[source]

Returns the copy of a matrix.

Examples

>>> from .. import Matrix
>>> A = Matrix(2, 2, [1, 2, 3, 4])
>>> A.copy()
Matrix([
[1, 2],
[3, 4]])
liupc()[source]

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

Examples

>>> from ..matrices import SparseMatrix
>>> 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) http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.39.7582

nnz()[source]

Returns the number of non-zero elements in Matrix.

row_list()[source]

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

Examples

>>> from ..matrices import SparseMatrix
>>> 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)]

See also

row_op, col_list

row_structure_symbolic_cholesky()[source]

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

Examples

>>> from ..matrices import SparseMatrix
>>> 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) http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.39.7582

scalar_multiply(scalar)[source]

Scalar element-wise multiplication

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

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

For a list of possible inversion methods, see the .inv() docstring.

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. To find out which are available, see the docstring of the .inv() method.

Examples

>>> from ..matrices import SparseMatrix, Matrix, ones
>>> 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().n(2)
0.58

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

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

modelparameters.sympy.matrices.sparsetools module

Module contents

A module that handles matrices.

Includes functions for fast creating matrices like zero, one/eye, random matrix, etc.