Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- ckpts/universal/global_step120/zero/12.mlp.dense_h_to_4h.weight/exp_avg.pt +3 -0
- ckpts/universal/global_step120/zero/12.mlp.dense_h_to_4h.weight/exp_avg_sq.pt +3 -0
- ckpts/universal/global_step120/zero/12.mlp.dense_h_to_4h.weight/fp32.pt +3 -0
- ckpts/universal/global_step120/zero/22.attention.dense.weight/exp_avg.pt +3 -0
- ckpts/universal/global_step120/zero/22.attention.dense.weight/fp32.pt +3 -0
- ckpts/universal/global_step120/zero/4.mlp.dense_h_to_4h_swiglu.weight/exp_avg_sq.pt +3 -0
- venv/lib/python3.10/site-packages/sympy/matrices/__init__.py +71 -0
- venv/lib/python3.10/site-packages/sympy/matrices/common.py +3227 -0
- venv/lib/python3.10/site-packages/sympy/matrices/decompositions.py +1629 -0
- venv/lib/python3.10/site-packages/sympy/matrices/dense.py +1090 -0
- venv/lib/python3.10/site-packages/sympy/matrices/determinant.py +898 -0
- venv/lib/python3.10/site-packages/sympy/matrices/eigen.py +1343 -0
- venv/lib/python3.10/site-packages/sympy/matrices/expressions/__init__.py +62 -0
- venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/__init__.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/_shape.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/adjoint.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/applyfunc.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/blockmatrix.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/companion.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/determinant.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/diagonal.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/dotproduct.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/factorizations.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/fourier.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/funcmatrix.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/hadamard.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/inverse.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/kronecker.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/matadd.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/matexpr.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/matmul.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/matpow.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/permutation.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/sets.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/slice.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/special.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/trace.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/transpose.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/matrices/expressions/_shape.py +102 -0
- venv/lib/python3.10/site-packages/sympy/matrices/expressions/adjoint.py +61 -0
- venv/lib/python3.10/site-packages/sympy/matrices/expressions/applyfunc.py +204 -0
- venv/lib/python3.10/site-packages/sympy/matrices/expressions/blockmatrix.py +979 -0
- venv/lib/python3.10/site-packages/sympy/matrices/expressions/companion.py +56 -0
- venv/lib/python3.10/site-packages/sympy/matrices/expressions/determinant.py +141 -0
- venv/lib/python3.10/site-packages/sympy/matrices/expressions/diagonal.py +220 -0
- venv/lib/python3.10/site-packages/sympy/matrices/expressions/dotproduct.py +55 -0
- venv/lib/python3.10/site-packages/sympy/matrices/expressions/factorizations.py +62 -0
- venv/lib/python3.10/site-packages/sympy/matrices/expressions/fourier.py +91 -0
- venv/lib/python3.10/site-packages/sympy/matrices/expressions/funcmatrix.py +118 -0
- venv/lib/python3.10/site-packages/sympy/matrices/expressions/hadamard.py +464 -0
ckpts/universal/global_step120/zero/12.mlp.dense_h_to_4h.weight/exp_avg.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:7db96ae90a2528bbdfb7bd14e1b594cb55cf63a2a5c9df1e4f72929c697ee400
|
| 3 |
+
size 33555612
|
ckpts/universal/global_step120/zero/12.mlp.dense_h_to_4h.weight/exp_avg_sq.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:7cceb5e1a070dc0299466bfc8bcaa50d5e9f0b43061562c102027ea5716c23d0
|
| 3 |
+
size 33555627
|
ckpts/universal/global_step120/zero/12.mlp.dense_h_to_4h.weight/fp32.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:6eeef10c55fb09d83fc18a1094e244bbc7a4dd1e80f98c59eb74711cf56ef533
|
| 3 |
+
size 33555533
|
ckpts/universal/global_step120/zero/22.attention.dense.weight/exp_avg.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:91cf52098e01840bde747b6ff66857526083b4ecdf818fd612852b2610a41a6d
|
| 3 |
+
size 16778396
|
ckpts/universal/global_step120/zero/22.attention.dense.weight/fp32.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:a38c570fa777460d7e69a636e398f55752a2170e0ce77bc4dbb1fdef9616e4cb
|
| 3 |
+
size 16778317
|
ckpts/universal/global_step120/zero/4.mlp.dense_h_to_4h_swiglu.weight/exp_avg_sq.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:b1b621cafb8fbdaa128a9f6bc02ae379ce059d05cc1b93351e3d980b24844134
|
| 3 |
+
size 33555627
|
venv/lib/python3.10/site-packages/sympy/matrices/__init__.py
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""A module that handles matrices.
|
| 2 |
+
|
| 3 |
+
Includes functions for fast creating matrices like zero, one/eye, random
|
| 4 |
+
matrix, etc.
|
| 5 |
+
"""
|
| 6 |
+
from .common import ShapeError, NonSquareMatrixError, MatrixKind
|
| 7 |
+
from .dense import (
|
| 8 |
+
GramSchmidt, casoratian, diag, eye, hessian, jordan_cell,
|
| 9 |
+
list2numpy, matrix2numpy, matrix_multiply_elementwise, ones,
|
| 10 |
+
randMatrix, rot_axis1, rot_axis2, rot_axis3, rot_ccw_axis1,
|
| 11 |
+
rot_ccw_axis2, rot_ccw_axis3, rot_givens,
|
| 12 |
+
symarray, wronskian, zeros)
|
| 13 |
+
from .dense import MutableDenseMatrix
|
| 14 |
+
from .matrices import DeferredVector, MatrixBase
|
| 15 |
+
|
| 16 |
+
MutableMatrix = MutableDenseMatrix
|
| 17 |
+
Matrix = MutableMatrix
|
| 18 |
+
|
| 19 |
+
from .sparse import MutableSparseMatrix
|
| 20 |
+
from .sparsetools import banded
|
| 21 |
+
from .immutable import ImmutableDenseMatrix, ImmutableSparseMatrix
|
| 22 |
+
|
| 23 |
+
ImmutableMatrix = ImmutableDenseMatrix
|
| 24 |
+
SparseMatrix = MutableSparseMatrix
|
| 25 |
+
|
| 26 |
+
from .expressions import (
|
| 27 |
+
MatrixSlice, BlockDiagMatrix, BlockMatrix, FunctionMatrix, Identity,
|
| 28 |
+
Inverse, MatAdd, MatMul, MatPow, MatrixExpr, MatrixSymbol, Trace,
|
| 29 |
+
Transpose, ZeroMatrix, OneMatrix, blockcut, block_collapse, matrix_symbols, Adjoint,
|
| 30 |
+
hadamard_product, HadamardProduct, HadamardPower, Determinant, det,
|
| 31 |
+
diagonalize_vector, DiagMatrix, DiagonalMatrix, DiagonalOf, trace,
|
| 32 |
+
DotProduct, kronecker_product, KroneckerProduct,
|
| 33 |
+
PermutationMatrix, MatrixPermute, MatrixSet, Permanent, per)
|
| 34 |
+
|
| 35 |
+
from .utilities import dotprodsimp
|
| 36 |
+
|
| 37 |
+
__all__ = [
|
| 38 |
+
'ShapeError', 'NonSquareMatrixError', 'MatrixKind',
|
| 39 |
+
|
| 40 |
+
'GramSchmidt', 'casoratian', 'diag', 'eye', 'hessian', 'jordan_cell',
|
| 41 |
+
'list2numpy', 'matrix2numpy', 'matrix_multiply_elementwise', 'ones',
|
| 42 |
+
'randMatrix', 'rot_axis1', 'rot_axis2', 'rot_axis3', 'symarray',
|
| 43 |
+
'wronskian', 'zeros', 'rot_ccw_axis1', 'rot_ccw_axis2', 'rot_ccw_axis3',
|
| 44 |
+
'rot_givens',
|
| 45 |
+
|
| 46 |
+
'MutableDenseMatrix',
|
| 47 |
+
|
| 48 |
+
'DeferredVector', 'MatrixBase',
|
| 49 |
+
|
| 50 |
+
'Matrix', 'MutableMatrix',
|
| 51 |
+
|
| 52 |
+
'MutableSparseMatrix',
|
| 53 |
+
|
| 54 |
+
'banded',
|
| 55 |
+
|
| 56 |
+
'ImmutableDenseMatrix', 'ImmutableSparseMatrix',
|
| 57 |
+
|
| 58 |
+
'ImmutableMatrix', 'SparseMatrix',
|
| 59 |
+
|
| 60 |
+
'MatrixSlice', 'BlockDiagMatrix', 'BlockMatrix', 'FunctionMatrix',
|
| 61 |
+
'Identity', 'Inverse', 'MatAdd', 'MatMul', 'MatPow', 'MatrixExpr',
|
| 62 |
+
'MatrixSymbol', 'Trace', 'Transpose', 'ZeroMatrix', 'OneMatrix',
|
| 63 |
+
'blockcut', 'block_collapse', 'matrix_symbols', 'Adjoint',
|
| 64 |
+
'hadamard_product', 'HadamardProduct', 'HadamardPower', 'Determinant',
|
| 65 |
+
'det', 'diagonalize_vector', 'DiagMatrix', 'DiagonalMatrix',
|
| 66 |
+
'DiagonalOf', 'trace', 'DotProduct', 'kronecker_product',
|
| 67 |
+
'KroneckerProduct', 'PermutationMatrix', 'MatrixPermute', 'MatrixSet',
|
| 68 |
+
'Permanent', 'per',
|
| 69 |
+
|
| 70 |
+
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
|
| 2 |
+
Basic methods common to all matrices to be used
|
| 3 |
+
when creating more advanced matrices (e.g., matrices over rings,
|
| 4 |
+
etc.).
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from collections import defaultdict
|
| 8 |
+
from collections.abc import Iterable
|
| 9 |
+
from inspect import isfunction
|
| 10 |
+
from functools import reduce
|
| 11 |
+
|
| 12 |
+
from sympy.assumptions.refine import refine
|
| 13 |
+
from sympy.core import SympifyError, Add
|
| 14 |
+
from sympy.core.basic import Atom
|
| 15 |
+
from sympy.core.decorators import call_highest_priority
|
| 16 |
+
from sympy.core.kind import Kind, NumberKind
|
| 17 |
+
from sympy.core.logic import fuzzy_and, FuzzyBool
|
| 18 |
+
from sympy.core.mod import Mod
|
| 19 |
+
from sympy.core.singleton import S
|
| 20 |
+
from sympy.core.symbol import Symbol
|
| 21 |
+
from sympy.core.sympify import sympify
|
| 22 |
+
from sympy.functions.elementary.complexes import Abs, re, im
|
| 23 |
+
from .utilities import _dotprodsimp, _simplify
|
| 24 |
+
from sympy.polys.polytools import Poly
|
| 25 |
+
from sympy.utilities.iterables import flatten, is_sequence
|
| 26 |
+
from sympy.utilities.misc import as_int, filldedent
|
| 27 |
+
from sympy.tensor.array import NDimArray
|
| 28 |
+
|
| 29 |
+
from .utilities import _get_intermediate_simp_bool
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
class MatrixError(Exception):
|
| 33 |
+
pass
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class ShapeError(ValueError, MatrixError):
|
| 37 |
+
"""Wrong matrix shape"""
|
| 38 |
+
pass
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class NonSquareMatrixError(ShapeError):
|
| 42 |
+
pass
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
class NonInvertibleMatrixError(ValueError, MatrixError):
|
| 46 |
+
"""The matrix in not invertible (division by multidimensional zero error)."""
|
| 47 |
+
pass
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
class NonPositiveDefiniteMatrixError(ValueError, MatrixError):
|
| 51 |
+
"""The matrix is not a positive-definite matrix."""
|
| 52 |
+
pass
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
class MatrixRequired:
|
| 56 |
+
"""All subclasses of matrix objects must implement the
|
| 57 |
+
required matrix properties listed here."""
|
| 58 |
+
rows = None # type: int
|
| 59 |
+
cols = None # type: int
|
| 60 |
+
_simplify = None
|
| 61 |
+
|
| 62 |
+
@classmethod
|
| 63 |
+
def _new(cls, *args, **kwargs):
|
| 64 |
+
"""`_new` must, at minimum, be callable as
|
| 65 |
+
`_new(rows, cols, mat) where mat is a flat list of the
|
| 66 |
+
elements of the matrix."""
|
| 67 |
+
raise NotImplementedError("Subclasses must implement this.")
|
| 68 |
+
|
| 69 |
+
def __eq__(self, other):
|
| 70 |
+
raise NotImplementedError("Subclasses must implement this.")
|
| 71 |
+
|
| 72 |
+
def __getitem__(self, key):
|
| 73 |
+
"""Implementations of __getitem__ should accept ints, in which
|
| 74 |
+
case the matrix is indexed as a flat list, tuples (i,j) in which
|
| 75 |
+
case the (i,j) entry is returned, slices, or mixed tuples (a,b)
|
| 76 |
+
where a and b are any combination of slices and integers."""
|
| 77 |
+
raise NotImplementedError("Subclasses must implement this.")
|
| 78 |
+
|
| 79 |
+
def __len__(self):
|
| 80 |
+
"""The total number of entries in the matrix."""
|
| 81 |
+
raise NotImplementedError("Subclasses must implement this.")
|
| 82 |
+
|
| 83 |
+
@property
|
| 84 |
+
def shape(self):
|
| 85 |
+
raise NotImplementedError("Subclasses must implement this.")
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
class MatrixShaping(MatrixRequired):
|
| 89 |
+
"""Provides basic matrix shaping and extracting of submatrices"""
|
| 90 |
+
|
| 91 |
+
def _eval_col_del(self, col):
|
| 92 |
+
def entry(i, j):
|
| 93 |
+
return self[i, j] if j < col else self[i, j + 1]
|
| 94 |
+
return self._new(self.rows, self.cols - 1, entry)
|
| 95 |
+
|
| 96 |
+
def _eval_col_insert(self, pos, other):
|
| 97 |
+
|
| 98 |
+
def entry(i, j):
|
| 99 |
+
if j < pos:
|
| 100 |
+
return self[i, j]
|
| 101 |
+
elif pos <= j < pos + other.cols:
|
| 102 |
+
return other[i, j - pos]
|
| 103 |
+
return self[i, j - other.cols]
|
| 104 |
+
|
| 105 |
+
return self._new(self.rows, self.cols + other.cols, entry)
|
| 106 |
+
|
| 107 |
+
def _eval_col_join(self, other):
|
| 108 |
+
rows = self.rows
|
| 109 |
+
|
| 110 |
+
def entry(i, j):
|
| 111 |
+
if i < rows:
|
| 112 |
+
return self[i, j]
|
| 113 |
+
return other[i - rows, j]
|
| 114 |
+
|
| 115 |
+
return classof(self, other)._new(self.rows + other.rows, self.cols,
|
| 116 |
+
entry)
|
| 117 |
+
|
| 118 |
+
def _eval_extract(self, rowsList, colsList):
|
| 119 |
+
mat = list(self)
|
| 120 |
+
cols = self.cols
|
| 121 |
+
indices = (i * cols + j for i in rowsList for j in colsList)
|
| 122 |
+
return self._new(len(rowsList), len(colsList),
|
| 123 |
+
[mat[i] for i in indices])
|
| 124 |
+
|
| 125 |
+
def _eval_get_diag_blocks(self):
|
| 126 |
+
sub_blocks = []
|
| 127 |
+
|
| 128 |
+
def recurse_sub_blocks(M):
|
| 129 |
+
i = 1
|
| 130 |
+
while i <= M.shape[0]:
|
| 131 |
+
if i == 1:
|
| 132 |
+
to_the_right = M[0, i:]
|
| 133 |
+
to_the_bottom = M[i:, 0]
|
| 134 |
+
else:
|
| 135 |
+
to_the_right = M[:i, i:]
|
| 136 |
+
to_the_bottom = M[i:, :i]
|
| 137 |
+
if any(to_the_right) or any(to_the_bottom):
|
| 138 |
+
i += 1
|
| 139 |
+
continue
|
| 140 |
+
else:
|
| 141 |
+
sub_blocks.append(M[:i, :i])
|
| 142 |
+
if M.shape == M[:i, :i].shape:
|
| 143 |
+
return
|
| 144 |
+
else:
|
| 145 |
+
recurse_sub_blocks(M[i:, i:])
|
| 146 |
+
return
|
| 147 |
+
|
| 148 |
+
recurse_sub_blocks(self)
|
| 149 |
+
return sub_blocks
|
| 150 |
+
|
| 151 |
+
def _eval_row_del(self, row):
|
| 152 |
+
def entry(i, j):
|
| 153 |
+
return self[i, j] if i < row else self[i + 1, j]
|
| 154 |
+
return self._new(self.rows - 1, self.cols, entry)
|
| 155 |
+
|
| 156 |
+
def _eval_row_insert(self, pos, other):
|
| 157 |
+
entries = list(self)
|
| 158 |
+
insert_pos = pos * self.cols
|
| 159 |
+
entries[insert_pos:insert_pos] = list(other)
|
| 160 |
+
return self._new(self.rows + other.rows, self.cols, entries)
|
| 161 |
+
|
| 162 |
+
def _eval_row_join(self, other):
|
| 163 |
+
cols = self.cols
|
| 164 |
+
|
| 165 |
+
def entry(i, j):
|
| 166 |
+
if j < cols:
|
| 167 |
+
return self[i, j]
|
| 168 |
+
return other[i, j - cols]
|
| 169 |
+
|
| 170 |
+
return classof(self, other)._new(self.rows, self.cols + other.cols,
|
| 171 |
+
entry)
|
| 172 |
+
|
| 173 |
+
def _eval_tolist(self):
|
| 174 |
+
return [list(self[i,:]) for i in range(self.rows)]
|
| 175 |
+
|
| 176 |
+
def _eval_todok(self):
|
| 177 |
+
dok = {}
|
| 178 |
+
rows, cols = self.shape
|
| 179 |
+
for i in range(rows):
|
| 180 |
+
for j in range(cols):
|
| 181 |
+
val = self[i, j]
|
| 182 |
+
if val != self.zero:
|
| 183 |
+
dok[i, j] = val
|
| 184 |
+
return dok
|
| 185 |
+
|
| 186 |
+
def _eval_vec(self):
|
| 187 |
+
rows = self.rows
|
| 188 |
+
|
| 189 |
+
def entry(n, _):
|
| 190 |
+
# we want to read off the columns first
|
| 191 |
+
j = n // rows
|
| 192 |
+
i = n - j * rows
|
| 193 |
+
return self[i, j]
|
| 194 |
+
|
| 195 |
+
return self._new(len(self), 1, entry)
|
| 196 |
+
|
| 197 |
+
def _eval_vech(self, diagonal):
|
| 198 |
+
c = self.cols
|
| 199 |
+
v = []
|
| 200 |
+
if diagonal:
|
| 201 |
+
for j in range(c):
|
| 202 |
+
for i in range(j, c):
|
| 203 |
+
v.append(self[i, j])
|
| 204 |
+
else:
|
| 205 |
+
for j in range(c):
|
| 206 |
+
for i in range(j + 1, c):
|
| 207 |
+
v.append(self[i, j])
|
| 208 |
+
return self._new(len(v), 1, v)
|
| 209 |
+
|
| 210 |
+
def col_del(self, col):
|
| 211 |
+
"""Delete the specified column."""
|
| 212 |
+
if col < 0:
|
| 213 |
+
col += self.cols
|
| 214 |
+
if not 0 <= col < self.cols:
|
| 215 |
+
raise IndexError("Column {} is out of range.".format(col))
|
| 216 |
+
return self._eval_col_del(col)
|
| 217 |
+
|
| 218 |
+
def col_insert(self, pos, other):
|
| 219 |
+
"""Insert one or more columns at the given column position.
|
| 220 |
+
|
| 221 |
+
Examples
|
| 222 |
+
========
|
| 223 |
+
|
| 224 |
+
>>> from sympy import zeros, ones
|
| 225 |
+
>>> M = zeros(3)
|
| 226 |
+
>>> V = ones(3, 1)
|
| 227 |
+
>>> M.col_insert(1, V)
|
| 228 |
+
Matrix([
|
| 229 |
+
[0, 1, 0, 0],
|
| 230 |
+
[0, 1, 0, 0],
|
| 231 |
+
[0, 1, 0, 0]])
|
| 232 |
+
|
| 233 |
+
See Also
|
| 234 |
+
========
|
| 235 |
+
|
| 236 |
+
col
|
| 237 |
+
row_insert
|
| 238 |
+
"""
|
| 239 |
+
# Allows you to build a matrix even if it is null matrix
|
| 240 |
+
if not self:
|
| 241 |
+
return type(self)(other)
|
| 242 |
+
|
| 243 |
+
pos = as_int(pos)
|
| 244 |
+
|
| 245 |
+
if pos < 0:
|
| 246 |
+
pos = self.cols + pos
|
| 247 |
+
if pos < 0:
|
| 248 |
+
pos = 0
|
| 249 |
+
elif pos > self.cols:
|
| 250 |
+
pos = self.cols
|
| 251 |
+
|
| 252 |
+
if self.rows != other.rows:
|
| 253 |
+
raise ShapeError(
|
| 254 |
+
"The matrices have incompatible number of rows ({} and {})"
|
| 255 |
+
.format(self.rows, other.rows))
|
| 256 |
+
|
| 257 |
+
return self._eval_col_insert(pos, other)
|
| 258 |
+
|
| 259 |
+
def col_join(self, other):
|
| 260 |
+
"""Concatenates two matrices along self's last and other's first row.
|
| 261 |
+
|
| 262 |
+
Examples
|
| 263 |
+
========
|
| 264 |
+
|
| 265 |
+
>>> from sympy import zeros, ones
|
| 266 |
+
>>> M = zeros(3)
|
| 267 |
+
>>> V = ones(1, 3)
|
| 268 |
+
>>> M.col_join(V)
|
| 269 |
+
Matrix([
|
| 270 |
+
[0, 0, 0],
|
| 271 |
+
[0, 0, 0],
|
| 272 |
+
[0, 0, 0],
|
| 273 |
+
[1, 1, 1]])
|
| 274 |
+
|
| 275 |
+
See Also
|
| 276 |
+
========
|
| 277 |
+
|
| 278 |
+
col
|
| 279 |
+
row_join
|
| 280 |
+
"""
|
| 281 |
+
# A null matrix can always be stacked (see #10770)
|
| 282 |
+
if self.rows == 0 and self.cols != other.cols:
|
| 283 |
+
return self._new(0, other.cols, []).col_join(other)
|
| 284 |
+
|
| 285 |
+
if self.cols != other.cols:
|
| 286 |
+
raise ShapeError(
|
| 287 |
+
"The matrices have incompatible number of columns ({} and {})"
|
| 288 |
+
.format(self.cols, other.cols))
|
| 289 |
+
return self._eval_col_join(other)
|
| 290 |
+
|
| 291 |
+
def col(self, j):
|
| 292 |
+
"""Elementary column selector.
|
| 293 |
+
|
| 294 |
+
Examples
|
| 295 |
+
========
|
| 296 |
+
|
| 297 |
+
>>> from sympy import eye
|
| 298 |
+
>>> eye(2).col(0)
|
| 299 |
+
Matrix([
|
| 300 |
+
[1],
|
| 301 |
+
[0]])
|
| 302 |
+
|
| 303 |
+
See Also
|
| 304 |
+
========
|
| 305 |
+
|
| 306 |
+
row
|
| 307 |
+
col_del
|
| 308 |
+
col_join
|
| 309 |
+
col_insert
|
| 310 |
+
"""
|
| 311 |
+
return self[:, j]
|
| 312 |
+
|
| 313 |
+
def extract(self, rowsList, colsList):
|
| 314 |
+
r"""Return a submatrix by specifying a list of rows and columns.
|
| 315 |
+
Negative indices can be given. All indices must be in the range
|
| 316 |
+
$-n \le i < n$ where $n$ is the number of rows or columns.
|
| 317 |
+
|
| 318 |
+
Examples
|
| 319 |
+
========
|
| 320 |
+
|
| 321 |
+
>>> from sympy import Matrix
|
| 322 |
+
>>> m = Matrix(4, 3, range(12))
|
| 323 |
+
>>> m
|
| 324 |
+
Matrix([
|
| 325 |
+
[0, 1, 2],
|
| 326 |
+
[3, 4, 5],
|
| 327 |
+
[6, 7, 8],
|
| 328 |
+
[9, 10, 11]])
|
| 329 |
+
>>> m.extract([0, 1, 3], [0, 1])
|
| 330 |
+
Matrix([
|
| 331 |
+
[0, 1],
|
| 332 |
+
[3, 4],
|
| 333 |
+
[9, 10]])
|
| 334 |
+
|
| 335 |
+
Rows or columns can be repeated:
|
| 336 |
+
|
| 337 |
+
>>> m.extract([0, 0, 1], [-1])
|
| 338 |
+
Matrix([
|
| 339 |
+
[2],
|
| 340 |
+
[2],
|
| 341 |
+
[5]])
|
| 342 |
+
|
| 343 |
+
Every other row can be taken by using range to provide the indices:
|
| 344 |
+
|
| 345 |
+
>>> m.extract(range(0, m.rows, 2), [-1])
|
| 346 |
+
Matrix([
|
| 347 |
+
[2],
|
| 348 |
+
[8]])
|
| 349 |
+
|
| 350 |
+
RowsList or colsList can also be a list of booleans, in which case
|
| 351 |
+
the rows or columns corresponding to the True values will be selected:
|
| 352 |
+
|
| 353 |
+
>>> m.extract([0, 1, 2, 3], [True, False, True])
|
| 354 |
+
Matrix([
|
| 355 |
+
[0, 2],
|
| 356 |
+
[3, 5],
|
| 357 |
+
[6, 8],
|
| 358 |
+
[9, 11]])
|
| 359 |
+
"""
|
| 360 |
+
|
| 361 |
+
if not is_sequence(rowsList) or not is_sequence(colsList):
|
| 362 |
+
raise TypeError("rowsList and colsList must be iterable")
|
| 363 |
+
# ensure rowsList and colsList are lists of integers
|
| 364 |
+
if rowsList and all(isinstance(i, bool) for i in rowsList):
|
| 365 |
+
rowsList = [index for index, item in enumerate(rowsList) if item]
|
| 366 |
+
if colsList and all(isinstance(i, bool) for i in colsList):
|
| 367 |
+
colsList = [index for index, item in enumerate(colsList) if item]
|
| 368 |
+
|
| 369 |
+
# ensure everything is in range
|
| 370 |
+
rowsList = [a2idx(k, self.rows) for k in rowsList]
|
| 371 |
+
colsList = [a2idx(k, self.cols) for k in colsList]
|
| 372 |
+
|
| 373 |
+
return self._eval_extract(rowsList, colsList)
|
| 374 |
+
|
| 375 |
+
def get_diag_blocks(self):
|
| 376 |
+
"""Obtains the square sub-matrices on the main diagonal of a square matrix.
|
| 377 |
+
|
| 378 |
+
Useful for inverting symbolic matrices or solving systems of
|
| 379 |
+
linear equations which may be decoupled by having a block diagonal
|
| 380 |
+
structure.
|
| 381 |
+
|
| 382 |
+
Examples
|
| 383 |
+
========
|
| 384 |
+
|
| 385 |
+
>>> from sympy import Matrix
|
| 386 |
+
>>> from sympy.abc import x, y, z
|
| 387 |
+
>>> A = Matrix([[1, 3, 0, 0], [y, z*z, 0, 0], [0, 0, x, 0], [0, 0, 0, 0]])
|
| 388 |
+
>>> a1, a2, a3 = A.get_diag_blocks()
|
| 389 |
+
>>> a1
|
| 390 |
+
Matrix([
|
| 391 |
+
[1, 3],
|
| 392 |
+
[y, z**2]])
|
| 393 |
+
>>> a2
|
| 394 |
+
Matrix([[x]])
|
| 395 |
+
>>> a3
|
| 396 |
+
Matrix([[0]])
|
| 397 |
+
|
| 398 |
+
"""
|
| 399 |
+
return self._eval_get_diag_blocks()
|
| 400 |
+
|
| 401 |
+
@classmethod
|
| 402 |
+
def hstack(cls, *args):
|
| 403 |
+
"""Return a matrix formed by joining args horizontally (i.e.
|
| 404 |
+
by repeated application of row_join).
|
| 405 |
+
|
| 406 |
+
Examples
|
| 407 |
+
========
|
| 408 |
+
|
| 409 |
+
>>> from sympy import Matrix, eye
|
| 410 |
+
>>> Matrix.hstack(eye(2), 2*eye(2))
|
| 411 |
+
Matrix([
|
| 412 |
+
[1, 0, 2, 0],
|
| 413 |
+
[0, 1, 0, 2]])
|
| 414 |
+
"""
|
| 415 |
+
if len(args) == 0:
|
| 416 |
+
return cls._new()
|
| 417 |
+
|
| 418 |
+
kls = type(args[0])
|
| 419 |
+
return reduce(kls.row_join, args)
|
| 420 |
+
|
| 421 |
+
def reshape(self, rows, cols):
|
| 422 |
+
"""Reshape the matrix. Total number of elements must remain the same.
|
| 423 |
+
|
| 424 |
+
Examples
|
| 425 |
+
========
|
| 426 |
+
|
| 427 |
+
>>> from sympy import Matrix
|
| 428 |
+
>>> m = Matrix(2, 3, lambda i, j: 1)
|
| 429 |
+
>>> m
|
| 430 |
+
Matrix([
|
| 431 |
+
[1, 1, 1],
|
| 432 |
+
[1, 1, 1]])
|
| 433 |
+
>>> m.reshape(1, 6)
|
| 434 |
+
Matrix([[1, 1, 1, 1, 1, 1]])
|
| 435 |
+
>>> m.reshape(3, 2)
|
| 436 |
+
Matrix([
|
| 437 |
+
[1, 1],
|
| 438 |
+
[1, 1],
|
| 439 |
+
[1, 1]])
|
| 440 |
+
|
| 441 |
+
"""
|
| 442 |
+
if self.rows * self.cols != rows * cols:
|
| 443 |
+
raise ValueError("Invalid reshape parameters %d %d" % (rows, cols))
|
| 444 |
+
return self._new(rows, cols, lambda i, j: self[i * cols + j])
|
| 445 |
+
|
| 446 |
+
def row_del(self, row):
|
| 447 |
+
"""Delete the specified row."""
|
| 448 |
+
if row < 0:
|
| 449 |
+
row += self.rows
|
| 450 |
+
if not 0 <= row < self.rows:
|
| 451 |
+
raise IndexError("Row {} is out of range.".format(row))
|
| 452 |
+
|
| 453 |
+
return self._eval_row_del(row)
|
| 454 |
+
|
| 455 |
+
def row_insert(self, pos, other):
|
| 456 |
+
"""Insert one or more rows at the given row position.
|
| 457 |
+
|
| 458 |
+
Examples
|
| 459 |
+
========
|
| 460 |
+
|
| 461 |
+
>>> from sympy import zeros, ones
|
| 462 |
+
>>> M = zeros(3)
|
| 463 |
+
>>> V = ones(1, 3)
|
| 464 |
+
>>> M.row_insert(1, V)
|
| 465 |
+
Matrix([
|
| 466 |
+
[0, 0, 0],
|
| 467 |
+
[1, 1, 1],
|
| 468 |
+
[0, 0, 0],
|
| 469 |
+
[0, 0, 0]])
|
| 470 |
+
|
| 471 |
+
See Also
|
| 472 |
+
========
|
| 473 |
+
|
| 474 |
+
row
|
| 475 |
+
col_insert
|
| 476 |
+
"""
|
| 477 |
+
# Allows you to build a matrix even if it is null matrix
|
| 478 |
+
if not self:
|
| 479 |
+
return self._new(other)
|
| 480 |
+
|
| 481 |
+
pos = as_int(pos)
|
| 482 |
+
|
| 483 |
+
if pos < 0:
|
| 484 |
+
pos = self.rows + pos
|
| 485 |
+
if pos < 0:
|
| 486 |
+
pos = 0
|
| 487 |
+
elif pos > self.rows:
|
| 488 |
+
pos = self.rows
|
| 489 |
+
|
| 490 |
+
if self.cols != other.cols:
|
| 491 |
+
raise ShapeError(
|
| 492 |
+
"The matrices have incompatible number of columns ({} and {})"
|
| 493 |
+
.format(self.cols, other.cols))
|
| 494 |
+
|
| 495 |
+
return self._eval_row_insert(pos, other)
|
| 496 |
+
|
| 497 |
+
def row_join(self, other):
|
| 498 |
+
"""Concatenates two matrices along self's last and rhs's first column
|
| 499 |
+
|
| 500 |
+
Examples
|
| 501 |
+
========
|
| 502 |
+
|
| 503 |
+
>>> from sympy import zeros, ones
|
| 504 |
+
>>> M = zeros(3)
|
| 505 |
+
>>> V = ones(3, 1)
|
| 506 |
+
>>> M.row_join(V)
|
| 507 |
+
Matrix([
|
| 508 |
+
[0, 0, 0, 1],
|
| 509 |
+
[0, 0, 0, 1],
|
| 510 |
+
[0, 0, 0, 1]])
|
| 511 |
+
|
| 512 |
+
See Also
|
| 513 |
+
========
|
| 514 |
+
|
| 515 |
+
row
|
| 516 |
+
col_join
|
| 517 |
+
"""
|
| 518 |
+
# A null matrix can always be stacked (see #10770)
|
| 519 |
+
if self.cols == 0 and self.rows != other.rows:
|
| 520 |
+
return self._new(other.rows, 0, []).row_join(other)
|
| 521 |
+
|
| 522 |
+
if self.rows != other.rows:
|
| 523 |
+
raise ShapeError(
|
| 524 |
+
"The matrices have incompatible number of rows ({} and {})"
|
| 525 |
+
.format(self.rows, other.rows))
|
| 526 |
+
return self._eval_row_join(other)
|
| 527 |
+
|
| 528 |
+
def diagonal(self, k=0):
|
| 529 |
+
"""Returns the kth diagonal of self. The main diagonal
|
| 530 |
+
corresponds to `k=0`; diagonals above and below correspond to
|
| 531 |
+
`k > 0` and `k < 0`, respectively. The values of `self[i, j]`
|
| 532 |
+
for which `j - i = k`, are returned in order of increasing
|
| 533 |
+
`i + j`, starting with `i + j = |k|`.
|
| 534 |
+
|
| 535 |
+
Examples
|
| 536 |
+
========
|
| 537 |
+
|
| 538 |
+
>>> from sympy import Matrix
|
| 539 |
+
>>> m = Matrix(3, 3, lambda i, j: j - i); m
|
| 540 |
+
Matrix([
|
| 541 |
+
[ 0, 1, 2],
|
| 542 |
+
[-1, 0, 1],
|
| 543 |
+
[-2, -1, 0]])
|
| 544 |
+
>>> _.diagonal()
|
| 545 |
+
Matrix([[0, 0, 0]])
|
| 546 |
+
>>> m.diagonal(1)
|
| 547 |
+
Matrix([[1, 1]])
|
| 548 |
+
>>> m.diagonal(-2)
|
| 549 |
+
Matrix([[-2]])
|
| 550 |
+
|
| 551 |
+
Even though the diagonal is returned as a Matrix, the element
|
| 552 |
+
retrieval can be done with a single index:
|
| 553 |
+
|
| 554 |
+
>>> Matrix.diag(1, 2, 3).diagonal()[1] # instead of [0, 1]
|
| 555 |
+
2
|
| 556 |
+
|
| 557 |
+
See Also
|
| 558 |
+
========
|
| 559 |
+
|
| 560 |
+
diag
|
| 561 |
+
"""
|
| 562 |
+
rv = []
|
| 563 |
+
k = as_int(k)
|
| 564 |
+
r = 0 if k > 0 else -k
|
| 565 |
+
c = 0 if r else k
|
| 566 |
+
while True:
|
| 567 |
+
if r == self.rows or c == self.cols:
|
| 568 |
+
break
|
| 569 |
+
rv.append(self[r, c])
|
| 570 |
+
r += 1
|
| 571 |
+
c += 1
|
| 572 |
+
if not rv:
|
| 573 |
+
raise ValueError(filldedent('''
|
| 574 |
+
The %s diagonal is out of range [%s, %s]''' % (
|
| 575 |
+
k, 1 - self.rows, self.cols - 1)))
|
| 576 |
+
return self._new(1, len(rv), rv)
|
| 577 |
+
|
| 578 |
+
def row(self, i):
|
| 579 |
+
"""Elementary row selector.
|
| 580 |
+
|
| 581 |
+
Examples
|
| 582 |
+
========
|
| 583 |
+
|
| 584 |
+
>>> from sympy import eye
|
| 585 |
+
>>> eye(2).row(0)
|
| 586 |
+
Matrix([[1, 0]])
|
| 587 |
+
|
| 588 |
+
See Also
|
| 589 |
+
========
|
| 590 |
+
|
| 591 |
+
col
|
| 592 |
+
row_del
|
| 593 |
+
row_join
|
| 594 |
+
row_insert
|
| 595 |
+
"""
|
| 596 |
+
return self[i, :]
|
| 597 |
+
|
| 598 |
+
@property
|
| 599 |
+
def shape(self):
|
| 600 |
+
"""The shape (dimensions) of the matrix as the 2-tuple (rows, cols).
|
| 601 |
+
|
| 602 |
+
Examples
|
| 603 |
+
========
|
| 604 |
+
|
| 605 |
+
>>> from sympy import zeros
|
| 606 |
+
>>> M = zeros(2, 3)
|
| 607 |
+
>>> M.shape
|
| 608 |
+
(2, 3)
|
| 609 |
+
>>> M.rows
|
| 610 |
+
2
|
| 611 |
+
>>> M.cols
|
| 612 |
+
3
|
| 613 |
+
"""
|
| 614 |
+
return (self.rows, self.cols)
|
| 615 |
+
|
| 616 |
+
def todok(self):
|
| 617 |
+
"""Return the matrix as dictionary of keys.
|
| 618 |
+
|
| 619 |
+
Examples
|
| 620 |
+
========
|
| 621 |
+
|
| 622 |
+
>>> from sympy import Matrix
|
| 623 |
+
>>> M = Matrix.eye(3)
|
| 624 |
+
>>> M.todok()
|
| 625 |
+
{(0, 0): 1, (1, 1): 1, (2, 2): 1}
|
| 626 |
+
"""
|
| 627 |
+
return self._eval_todok()
|
| 628 |
+
|
| 629 |
+
def tolist(self):
|
| 630 |
+
"""Return the Matrix as a nested Python list.
|
| 631 |
+
|
| 632 |
+
Examples
|
| 633 |
+
========
|
| 634 |
+
|
| 635 |
+
>>> from sympy import Matrix, ones
|
| 636 |
+
>>> m = Matrix(3, 3, range(9))
|
| 637 |
+
>>> m
|
| 638 |
+
Matrix([
|
| 639 |
+
[0, 1, 2],
|
| 640 |
+
[3, 4, 5],
|
| 641 |
+
[6, 7, 8]])
|
| 642 |
+
>>> m.tolist()
|
| 643 |
+
[[0, 1, 2], [3, 4, 5], [6, 7, 8]]
|
| 644 |
+
>>> ones(3, 0).tolist()
|
| 645 |
+
[[], [], []]
|
| 646 |
+
|
| 647 |
+
When there are no rows then it will not be possible to tell how
|
| 648 |
+
many columns were in the original matrix:
|
| 649 |
+
|
| 650 |
+
>>> ones(0, 3).tolist()
|
| 651 |
+
[]
|
| 652 |
+
|
| 653 |
+
"""
|
| 654 |
+
if not self.rows:
|
| 655 |
+
return []
|
| 656 |
+
if not self.cols:
|
| 657 |
+
return [[] for i in range(self.rows)]
|
| 658 |
+
return self._eval_tolist()
|
| 659 |
+
|
| 660 |
+
def todod(M):
|
| 661 |
+
"""Returns matrix as dict of dicts containing non-zero elements of the Matrix
|
| 662 |
+
|
| 663 |
+
Examples
|
| 664 |
+
========
|
| 665 |
+
|
| 666 |
+
>>> from sympy import Matrix
|
| 667 |
+
>>> A = Matrix([[0, 1],[0, 3]])
|
| 668 |
+
>>> A
|
| 669 |
+
Matrix([
|
| 670 |
+
[0, 1],
|
| 671 |
+
[0, 3]])
|
| 672 |
+
>>> A.todod()
|
| 673 |
+
{0: {1: 1}, 1: {1: 3}}
|
| 674 |
+
|
| 675 |
+
|
| 676 |
+
"""
|
| 677 |
+
rowsdict = {}
|
| 678 |
+
Mlol = M.tolist()
|
| 679 |
+
for i, Mi in enumerate(Mlol):
|
| 680 |
+
row = {j: Mij for j, Mij in enumerate(Mi) if Mij}
|
| 681 |
+
if row:
|
| 682 |
+
rowsdict[i] = row
|
| 683 |
+
return rowsdict
|
| 684 |
+
|
| 685 |
+
def vec(self):
|
| 686 |
+
"""Return the Matrix converted into a one column matrix by stacking columns
|
| 687 |
+
|
| 688 |
+
Examples
|
| 689 |
+
========
|
| 690 |
+
|
| 691 |
+
>>> from sympy import Matrix
|
| 692 |
+
>>> m=Matrix([[1, 3], [2, 4]])
|
| 693 |
+
>>> m
|
| 694 |
+
Matrix([
|
| 695 |
+
[1, 3],
|
| 696 |
+
[2, 4]])
|
| 697 |
+
>>> m.vec()
|
| 698 |
+
Matrix([
|
| 699 |
+
[1],
|
| 700 |
+
[2],
|
| 701 |
+
[3],
|
| 702 |
+
[4]])
|
| 703 |
+
|
| 704 |
+
See Also
|
| 705 |
+
========
|
| 706 |
+
|
| 707 |
+
vech
|
| 708 |
+
"""
|
| 709 |
+
return self._eval_vec()
|
| 710 |
+
|
| 711 |
+
def vech(self, diagonal=True, check_symmetry=True):
|
| 712 |
+
"""Reshapes the matrix into a column vector by stacking the
|
| 713 |
+
elements in the lower triangle.
|
| 714 |
+
|
| 715 |
+
Parameters
|
| 716 |
+
==========
|
| 717 |
+
|
| 718 |
+
diagonal : bool, optional
|
| 719 |
+
If ``True``, it includes the diagonal elements.
|
| 720 |
+
|
| 721 |
+
check_symmetry : bool, optional
|
| 722 |
+
If ``True``, it checks whether the matrix is symmetric.
|
| 723 |
+
|
| 724 |
+
Examples
|
| 725 |
+
========
|
| 726 |
+
|
| 727 |
+
>>> from sympy import Matrix
|
| 728 |
+
>>> m=Matrix([[1, 2], [2, 3]])
|
| 729 |
+
>>> m
|
| 730 |
+
Matrix([
|
| 731 |
+
[1, 2],
|
| 732 |
+
[2, 3]])
|
| 733 |
+
>>> m.vech()
|
| 734 |
+
Matrix([
|
| 735 |
+
[1],
|
| 736 |
+
[2],
|
| 737 |
+
[3]])
|
| 738 |
+
>>> m.vech(diagonal=False)
|
| 739 |
+
Matrix([[2]])
|
| 740 |
+
|
| 741 |
+
Notes
|
| 742 |
+
=====
|
| 743 |
+
|
| 744 |
+
This should work for symmetric matrices and ``vech`` can
|
| 745 |
+
represent symmetric matrices in vector form with less size than
|
| 746 |
+
``vec``.
|
| 747 |
+
|
| 748 |
+
See Also
|
| 749 |
+
========
|
| 750 |
+
|
| 751 |
+
vec
|
| 752 |
+
"""
|
| 753 |
+
if not self.is_square:
|
| 754 |
+
raise NonSquareMatrixError
|
| 755 |
+
|
| 756 |
+
if check_symmetry and not self.is_symmetric():
|
| 757 |
+
raise ValueError("The matrix is not symmetric.")
|
| 758 |
+
|
| 759 |
+
return self._eval_vech(diagonal)
|
| 760 |
+
|
| 761 |
+
@classmethod
|
| 762 |
+
def vstack(cls, *args):
|
| 763 |
+
"""Return a matrix formed by joining args vertically (i.e.
|
| 764 |
+
by repeated application of col_join).
|
| 765 |
+
|
| 766 |
+
Examples
|
| 767 |
+
========
|
| 768 |
+
|
| 769 |
+
>>> from sympy import Matrix, eye
|
| 770 |
+
>>> Matrix.vstack(eye(2), 2*eye(2))
|
| 771 |
+
Matrix([
|
| 772 |
+
[1, 0],
|
| 773 |
+
[0, 1],
|
| 774 |
+
[2, 0],
|
| 775 |
+
[0, 2]])
|
| 776 |
+
"""
|
| 777 |
+
if len(args) == 0:
|
| 778 |
+
return cls._new()
|
| 779 |
+
|
| 780 |
+
kls = type(args[0])
|
| 781 |
+
return reduce(kls.col_join, args)
|
| 782 |
+
|
| 783 |
+
|
| 784 |
+
class MatrixSpecial(MatrixRequired):
|
| 785 |
+
"""Construction of special matrices"""
|
| 786 |
+
|
| 787 |
+
@classmethod
|
| 788 |
+
def _eval_diag(cls, rows, cols, diag_dict):
|
| 789 |
+
"""diag_dict is a defaultdict containing
|
| 790 |
+
all the entries of the diagonal matrix."""
|
| 791 |
+
def entry(i, j):
|
| 792 |
+
return diag_dict[(i, j)]
|
| 793 |
+
return cls._new(rows, cols, entry)
|
| 794 |
+
|
| 795 |
+
@classmethod
|
| 796 |
+
def _eval_eye(cls, rows, cols):
|
| 797 |
+
vals = [cls.zero]*(rows*cols)
|
| 798 |
+
vals[::cols+1] = [cls.one]*min(rows, cols)
|
| 799 |
+
return cls._new(rows, cols, vals, copy=False)
|
| 800 |
+
|
| 801 |
+
@classmethod
|
| 802 |
+
def _eval_jordan_block(cls, size: int, eigenvalue, band='upper'):
|
| 803 |
+
if band == 'lower':
|
| 804 |
+
def entry(i, j):
|
| 805 |
+
if i == j:
|
| 806 |
+
return eigenvalue
|
| 807 |
+
elif j + 1 == i:
|
| 808 |
+
return cls.one
|
| 809 |
+
return cls.zero
|
| 810 |
+
else:
|
| 811 |
+
def entry(i, j):
|
| 812 |
+
if i == j:
|
| 813 |
+
return eigenvalue
|
| 814 |
+
elif i + 1 == j:
|
| 815 |
+
return cls.one
|
| 816 |
+
return cls.zero
|
| 817 |
+
return cls._new(size, size, entry)
|
| 818 |
+
|
| 819 |
+
@classmethod
|
| 820 |
+
def _eval_ones(cls, rows, cols):
|
| 821 |
+
def entry(i, j):
|
| 822 |
+
return cls.one
|
| 823 |
+
return cls._new(rows, cols, entry)
|
| 824 |
+
|
| 825 |
+
@classmethod
|
| 826 |
+
def _eval_zeros(cls, rows, cols):
|
| 827 |
+
return cls._new(rows, cols, [cls.zero]*(rows*cols), copy=False)
|
| 828 |
+
|
| 829 |
+
@classmethod
|
| 830 |
+
def _eval_wilkinson(cls, n):
|
| 831 |
+
def entry(i, j):
|
| 832 |
+
return cls.one if i + 1 == j else cls.zero
|
| 833 |
+
|
| 834 |
+
D = cls._new(2*n + 1, 2*n + 1, entry)
|
| 835 |
+
|
| 836 |
+
wminus = cls.diag(list(range(-n, n + 1)), unpack=True) + D + D.T
|
| 837 |
+
wplus = abs(cls.diag(list(range(-n, n + 1)), unpack=True)) + D + D.T
|
| 838 |
+
|
| 839 |
+
return wminus, wplus
|
| 840 |
+
|
| 841 |
+
@classmethod
|
| 842 |
+
def diag(kls, *args, strict=False, unpack=True, rows=None, cols=None, **kwargs):
|
| 843 |
+
"""Returns a matrix with the specified diagonal.
|
| 844 |
+
If matrices are passed, a block-diagonal matrix
|
| 845 |
+
is created (i.e. the "direct sum" of the matrices).
|
| 846 |
+
|
| 847 |
+
kwargs
|
| 848 |
+
======
|
| 849 |
+
|
| 850 |
+
rows : rows of the resulting matrix; computed if
|
| 851 |
+
not given.
|
| 852 |
+
|
| 853 |
+
cols : columns of the resulting matrix; computed if
|
| 854 |
+
not given.
|
| 855 |
+
|
| 856 |
+
cls : class for the resulting matrix
|
| 857 |
+
|
| 858 |
+
unpack : bool which, when True (default), unpacks a single
|
| 859 |
+
sequence rather than interpreting it as a Matrix.
|
| 860 |
+
|
| 861 |
+
strict : bool which, when False (default), allows Matrices to
|
| 862 |
+
have variable-length rows.
|
| 863 |
+
|
| 864 |
+
Examples
|
| 865 |
+
========
|
| 866 |
+
|
| 867 |
+
>>> from sympy import Matrix
|
| 868 |
+
>>> Matrix.diag(1, 2, 3)
|
| 869 |
+
Matrix([
|
| 870 |
+
[1, 0, 0],
|
| 871 |
+
[0, 2, 0],
|
| 872 |
+
[0, 0, 3]])
|
| 873 |
+
|
| 874 |
+
The current default is to unpack a single sequence. If this is
|
| 875 |
+
not desired, set `unpack=False` and it will be interpreted as
|
| 876 |
+
a matrix.
|
| 877 |
+
|
| 878 |
+
>>> Matrix.diag([1, 2, 3]) == Matrix.diag(1, 2, 3)
|
| 879 |
+
True
|
| 880 |
+
|
| 881 |
+
When more than one element is passed, each is interpreted as
|
| 882 |
+
something to put on the diagonal. Lists are converted to
|
| 883 |
+
matrices. Filling of the diagonal always continues from
|
| 884 |
+
the bottom right hand corner of the previous item: this
|
| 885 |
+
will create a block-diagonal matrix whether the matrices
|
| 886 |
+
are square or not.
|
| 887 |
+
|
| 888 |
+
>>> col = [1, 2, 3]
|
| 889 |
+
>>> row = [[4, 5]]
|
| 890 |
+
>>> Matrix.diag(col, row)
|
| 891 |
+
Matrix([
|
| 892 |
+
[1, 0, 0],
|
| 893 |
+
[2, 0, 0],
|
| 894 |
+
[3, 0, 0],
|
| 895 |
+
[0, 4, 5]])
|
| 896 |
+
|
| 897 |
+
When `unpack` is False, elements within a list need not all be
|
| 898 |
+
of the same length. Setting `strict` to True would raise a
|
| 899 |
+
ValueError for the following:
|
| 900 |
+
|
| 901 |
+
>>> Matrix.diag([[1, 2, 3], [4, 5], [6]], unpack=False)
|
| 902 |
+
Matrix([
|
| 903 |
+
[1, 2, 3],
|
| 904 |
+
[4, 5, 0],
|
| 905 |
+
[6, 0, 0]])
|
| 906 |
+
|
| 907 |
+
The type of the returned matrix can be set with the ``cls``
|
| 908 |
+
keyword.
|
| 909 |
+
|
| 910 |
+
>>> from sympy import ImmutableMatrix
|
| 911 |
+
>>> from sympy.utilities.misc import func_name
|
| 912 |
+
>>> func_name(Matrix.diag(1, cls=ImmutableMatrix))
|
| 913 |
+
'ImmutableDenseMatrix'
|
| 914 |
+
|
| 915 |
+
A zero dimension matrix can be used to position the start of
|
| 916 |
+
the filling at the start of an arbitrary row or column:
|
| 917 |
+
|
| 918 |
+
>>> from sympy import ones
|
| 919 |
+
>>> r2 = ones(0, 2)
|
| 920 |
+
>>> Matrix.diag(r2, 1, 2)
|
| 921 |
+
Matrix([
|
| 922 |
+
[0, 0, 1, 0],
|
| 923 |
+
[0, 0, 0, 2]])
|
| 924 |
+
|
| 925 |
+
See Also
|
| 926 |
+
========
|
| 927 |
+
eye
|
| 928 |
+
diagonal
|
| 929 |
+
.dense.diag
|
| 930 |
+
.expressions.blockmatrix.BlockMatrix
|
| 931 |
+
.sparsetools.banded
|
| 932 |
+
"""
|
| 933 |
+
from sympy.matrices.matrices import MatrixBase
|
| 934 |
+
from sympy.matrices.dense import Matrix
|
| 935 |
+
from sympy.matrices import SparseMatrix
|
| 936 |
+
klass = kwargs.get('cls', kls)
|
| 937 |
+
if unpack and len(args) == 1 and is_sequence(args[0]) and \
|
| 938 |
+
not isinstance(args[0], MatrixBase):
|
| 939 |
+
args = args[0]
|
| 940 |
+
|
| 941 |
+
# fill a default dict with the diagonal entries
|
| 942 |
+
diag_entries = defaultdict(int)
|
| 943 |
+
rmax = cmax = 0 # keep track of the biggest index seen
|
| 944 |
+
for m in args:
|
| 945 |
+
if isinstance(m, list):
|
| 946 |
+
if strict:
|
| 947 |
+
# if malformed, Matrix will raise an error
|
| 948 |
+
_ = Matrix(m)
|
| 949 |
+
r, c = _.shape
|
| 950 |
+
m = _.tolist()
|
| 951 |
+
else:
|
| 952 |
+
r, c, smat = SparseMatrix._handle_creation_inputs(m)
|
| 953 |
+
for (i, j), _ in smat.items():
|
| 954 |
+
diag_entries[(i + rmax, j + cmax)] = _
|
| 955 |
+
m = [] # to skip process below
|
| 956 |
+
elif hasattr(m, 'shape'): # a Matrix
|
| 957 |
+
# convert to list of lists
|
| 958 |
+
r, c = m.shape
|
| 959 |
+
m = m.tolist()
|
| 960 |
+
else: # in this case, we're a single value
|
| 961 |
+
diag_entries[(rmax, cmax)] = m
|
| 962 |
+
rmax += 1
|
| 963 |
+
cmax += 1
|
| 964 |
+
continue
|
| 965 |
+
# process list of lists
|
| 966 |
+
for i, mi in enumerate(m):
|
| 967 |
+
for j, _ in enumerate(mi):
|
| 968 |
+
diag_entries[(i + rmax, j + cmax)] = _
|
| 969 |
+
rmax += r
|
| 970 |
+
cmax += c
|
| 971 |
+
if rows is None:
|
| 972 |
+
rows, cols = cols, rows
|
| 973 |
+
if rows is None:
|
| 974 |
+
rows, cols = rmax, cmax
|
| 975 |
+
else:
|
| 976 |
+
cols = rows if cols is None else cols
|
| 977 |
+
if rows < rmax or cols < cmax:
|
| 978 |
+
raise ValueError(filldedent('''
|
| 979 |
+
The constructed matrix is {} x {} but a size of {} x {}
|
| 980 |
+
was specified.'''.format(rmax, cmax, rows, cols)))
|
| 981 |
+
return klass._eval_diag(rows, cols, diag_entries)
|
| 982 |
+
|
| 983 |
+
@classmethod
|
| 984 |
+
def eye(kls, rows, cols=None, **kwargs):
|
| 985 |
+
"""Returns an identity matrix.
|
| 986 |
+
|
| 987 |
+
Parameters
|
| 988 |
+
==========
|
| 989 |
+
|
| 990 |
+
rows : rows of the matrix
|
| 991 |
+
cols : cols of the matrix (if None, cols=rows)
|
| 992 |
+
|
| 993 |
+
kwargs
|
| 994 |
+
======
|
| 995 |
+
cls : class of the returned matrix
|
| 996 |
+
"""
|
| 997 |
+
if cols is None:
|
| 998 |
+
cols = rows
|
| 999 |
+
if rows < 0 or cols < 0:
|
| 1000 |
+
raise ValueError("Cannot create a {} x {} matrix. "
|
| 1001 |
+
"Both dimensions must be positive".format(rows, cols))
|
| 1002 |
+
klass = kwargs.get('cls', kls)
|
| 1003 |
+
rows, cols = as_int(rows), as_int(cols)
|
| 1004 |
+
|
| 1005 |
+
return klass._eval_eye(rows, cols)
|
| 1006 |
+
|
| 1007 |
+
@classmethod
|
| 1008 |
+
def jordan_block(kls, size=None, eigenvalue=None, *, band='upper', **kwargs):
|
| 1009 |
+
"""Returns a Jordan block
|
| 1010 |
+
|
| 1011 |
+
Parameters
|
| 1012 |
+
==========
|
| 1013 |
+
|
| 1014 |
+
size : Integer, optional
|
| 1015 |
+
Specifies the shape of the Jordan block matrix.
|
| 1016 |
+
|
| 1017 |
+
eigenvalue : Number or Symbol
|
| 1018 |
+
Specifies the value for the main diagonal of the matrix.
|
| 1019 |
+
|
| 1020 |
+
.. note::
|
| 1021 |
+
The keyword ``eigenval`` is also specified as an alias
|
| 1022 |
+
of this keyword, but it is not recommended to use.
|
| 1023 |
+
|
| 1024 |
+
We may deprecate the alias in later release.
|
| 1025 |
+
|
| 1026 |
+
band : 'upper' or 'lower', optional
|
| 1027 |
+
Specifies the position of the off-diagonal to put `1` s on.
|
| 1028 |
+
|
| 1029 |
+
cls : Matrix, optional
|
| 1030 |
+
Specifies the matrix class of the output form.
|
| 1031 |
+
|
| 1032 |
+
If it is not specified, the class type where the method is
|
| 1033 |
+
being executed on will be returned.
|
| 1034 |
+
|
| 1035 |
+
Returns
|
| 1036 |
+
=======
|
| 1037 |
+
|
| 1038 |
+
Matrix
|
| 1039 |
+
A Jordan block matrix.
|
| 1040 |
+
|
| 1041 |
+
Raises
|
| 1042 |
+
======
|
| 1043 |
+
|
| 1044 |
+
ValueError
|
| 1045 |
+
If insufficient arguments are given for matrix size
|
| 1046 |
+
specification, or no eigenvalue is given.
|
| 1047 |
+
|
| 1048 |
+
Examples
|
| 1049 |
+
========
|
| 1050 |
+
|
| 1051 |
+
Creating a default Jordan block:
|
| 1052 |
+
|
| 1053 |
+
>>> from sympy import Matrix
|
| 1054 |
+
>>> from sympy.abc import x
|
| 1055 |
+
>>> Matrix.jordan_block(4, x)
|
| 1056 |
+
Matrix([
|
| 1057 |
+
[x, 1, 0, 0],
|
| 1058 |
+
[0, x, 1, 0],
|
| 1059 |
+
[0, 0, x, 1],
|
| 1060 |
+
[0, 0, 0, x]])
|
| 1061 |
+
|
| 1062 |
+
Creating an alternative Jordan block matrix where `1` is on
|
| 1063 |
+
lower off-diagonal:
|
| 1064 |
+
|
| 1065 |
+
>>> Matrix.jordan_block(4, x, band='lower')
|
| 1066 |
+
Matrix([
|
| 1067 |
+
[x, 0, 0, 0],
|
| 1068 |
+
[1, x, 0, 0],
|
| 1069 |
+
[0, 1, x, 0],
|
| 1070 |
+
[0, 0, 1, x]])
|
| 1071 |
+
|
| 1072 |
+
Creating a Jordan block with keyword arguments
|
| 1073 |
+
|
| 1074 |
+
>>> Matrix.jordan_block(size=4, eigenvalue=x)
|
| 1075 |
+
Matrix([
|
| 1076 |
+
[x, 1, 0, 0],
|
| 1077 |
+
[0, x, 1, 0],
|
| 1078 |
+
[0, 0, x, 1],
|
| 1079 |
+
[0, 0, 0, x]])
|
| 1080 |
+
|
| 1081 |
+
References
|
| 1082 |
+
==========
|
| 1083 |
+
|
| 1084 |
+
.. [1] https://en.wikipedia.org/wiki/Jordan_matrix
|
| 1085 |
+
"""
|
| 1086 |
+
klass = kwargs.pop('cls', kls)
|
| 1087 |
+
|
| 1088 |
+
eigenval = kwargs.get('eigenval', None)
|
| 1089 |
+
if eigenvalue is None and eigenval is None:
|
| 1090 |
+
raise ValueError("Must supply an eigenvalue")
|
| 1091 |
+
elif eigenvalue != eigenval and None not in (eigenval, eigenvalue):
|
| 1092 |
+
raise ValueError(
|
| 1093 |
+
"Inconsistent values are given: 'eigenval'={}, "
|
| 1094 |
+
"'eigenvalue'={}".format(eigenval, eigenvalue))
|
| 1095 |
+
else:
|
| 1096 |
+
if eigenval is not None:
|
| 1097 |
+
eigenvalue = eigenval
|
| 1098 |
+
|
| 1099 |
+
if size is None:
|
| 1100 |
+
raise ValueError("Must supply a matrix size")
|
| 1101 |
+
|
| 1102 |
+
size = as_int(size)
|
| 1103 |
+
return klass._eval_jordan_block(size, eigenvalue, band)
|
| 1104 |
+
|
| 1105 |
+
@classmethod
|
| 1106 |
+
def ones(kls, rows, cols=None, **kwargs):
|
| 1107 |
+
"""Returns a matrix of ones.
|
| 1108 |
+
|
| 1109 |
+
Parameters
|
| 1110 |
+
==========
|
| 1111 |
+
|
| 1112 |
+
rows : rows of the matrix
|
| 1113 |
+
cols : cols of the matrix (if None, cols=rows)
|
| 1114 |
+
|
| 1115 |
+
kwargs
|
| 1116 |
+
======
|
| 1117 |
+
cls : class of the returned matrix
|
| 1118 |
+
"""
|
| 1119 |
+
if cols is None:
|
| 1120 |
+
cols = rows
|
| 1121 |
+
klass = kwargs.get('cls', kls)
|
| 1122 |
+
rows, cols = as_int(rows), as_int(cols)
|
| 1123 |
+
|
| 1124 |
+
return klass._eval_ones(rows, cols)
|
| 1125 |
+
|
| 1126 |
+
@classmethod
|
| 1127 |
+
def zeros(kls, rows, cols=None, **kwargs):
|
| 1128 |
+
"""Returns a matrix of zeros.
|
| 1129 |
+
|
| 1130 |
+
Parameters
|
| 1131 |
+
==========
|
| 1132 |
+
|
| 1133 |
+
rows : rows of the matrix
|
| 1134 |
+
cols : cols of the matrix (if None, cols=rows)
|
| 1135 |
+
|
| 1136 |
+
kwargs
|
| 1137 |
+
======
|
| 1138 |
+
cls : class of the returned matrix
|
| 1139 |
+
"""
|
| 1140 |
+
if cols is None:
|
| 1141 |
+
cols = rows
|
| 1142 |
+
if rows < 0 or cols < 0:
|
| 1143 |
+
raise ValueError("Cannot create a {} x {} matrix. "
|
| 1144 |
+
"Both dimensions must be positive".format(rows, cols))
|
| 1145 |
+
klass = kwargs.get('cls', kls)
|
| 1146 |
+
rows, cols = as_int(rows), as_int(cols)
|
| 1147 |
+
|
| 1148 |
+
return klass._eval_zeros(rows, cols)
|
| 1149 |
+
|
| 1150 |
+
@classmethod
|
| 1151 |
+
def companion(kls, poly):
|
| 1152 |
+
"""Returns a companion matrix of a polynomial.
|
| 1153 |
+
|
| 1154 |
+
Examples
|
| 1155 |
+
========
|
| 1156 |
+
|
| 1157 |
+
>>> from sympy import Matrix, Poly, Symbol, symbols
|
| 1158 |
+
>>> x = Symbol('x')
|
| 1159 |
+
>>> c0, c1, c2, c3, c4 = symbols('c0:5')
|
| 1160 |
+
>>> p = Poly(c0 + c1*x + c2*x**2 + c3*x**3 + c4*x**4 + x**5, x)
|
| 1161 |
+
>>> Matrix.companion(p)
|
| 1162 |
+
Matrix([
|
| 1163 |
+
[0, 0, 0, 0, -c0],
|
| 1164 |
+
[1, 0, 0, 0, -c1],
|
| 1165 |
+
[0, 1, 0, 0, -c2],
|
| 1166 |
+
[0, 0, 1, 0, -c3],
|
| 1167 |
+
[0, 0, 0, 1, -c4]])
|
| 1168 |
+
"""
|
| 1169 |
+
poly = kls._sympify(poly)
|
| 1170 |
+
if not isinstance(poly, Poly):
|
| 1171 |
+
raise ValueError("{} must be a Poly instance.".format(poly))
|
| 1172 |
+
if not poly.is_monic:
|
| 1173 |
+
raise ValueError("{} must be a monic polynomial.".format(poly))
|
| 1174 |
+
if not poly.is_univariate:
|
| 1175 |
+
raise ValueError(
|
| 1176 |
+
"{} must be a univariate polynomial.".format(poly))
|
| 1177 |
+
|
| 1178 |
+
size = poly.degree()
|
| 1179 |
+
if not size >= 1:
|
| 1180 |
+
raise ValueError(
|
| 1181 |
+
"{} must have degree not less than 1.".format(poly))
|
| 1182 |
+
|
| 1183 |
+
coeffs = poly.all_coeffs()
|
| 1184 |
+
def entry(i, j):
|
| 1185 |
+
if j == size - 1:
|
| 1186 |
+
return -coeffs[-1 - i]
|
| 1187 |
+
elif i == j + 1:
|
| 1188 |
+
return kls.one
|
| 1189 |
+
return kls.zero
|
| 1190 |
+
return kls._new(size, size, entry)
|
| 1191 |
+
|
| 1192 |
+
|
| 1193 |
+
@classmethod
|
| 1194 |
+
def wilkinson(kls, n, **kwargs):
|
| 1195 |
+
"""Returns two square Wilkinson Matrix of size 2*n + 1
|
| 1196 |
+
$W_{2n + 1}^-, W_{2n + 1}^+ =$ Wilkinson(n)
|
| 1197 |
+
|
| 1198 |
+
Examples
|
| 1199 |
+
========
|
| 1200 |
+
|
| 1201 |
+
>>> from sympy import Matrix
|
| 1202 |
+
>>> wminus, wplus = Matrix.wilkinson(3)
|
| 1203 |
+
>>> wminus
|
| 1204 |
+
Matrix([
|
| 1205 |
+
[-3, 1, 0, 0, 0, 0, 0],
|
| 1206 |
+
[ 1, -2, 1, 0, 0, 0, 0],
|
| 1207 |
+
[ 0, 1, -1, 1, 0, 0, 0],
|
| 1208 |
+
[ 0, 0, 1, 0, 1, 0, 0],
|
| 1209 |
+
[ 0, 0, 0, 1, 1, 1, 0],
|
| 1210 |
+
[ 0, 0, 0, 0, 1, 2, 1],
|
| 1211 |
+
[ 0, 0, 0, 0, 0, 1, 3]])
|
| 1212 |
+
>>> wplus
|
| 1213 |
+
Matrix([
|
| 1214 |
+
[3, 1, 0, 0, 0, 0, 0],
|
| 1215 |
+
[1, 2, 1, 0, 0, 0, 0],
|
| 1216 |
+
[0, 1, 1, 1, 0, 0, 0],
|
| 1217 |
+
[0, 0, 1, 0, 1, 0, 0],
|
| 1218 |
+
[0, 0, 0, 1, 1, 1, 0],
|
| 1219 |
+
[0, 0, 0, 0, 1, 2, 1],
|
| 1220 |
+
[0, 0, 0, 0, 0, 1, 3]])
|
| 1221 |
+
|
| 1222 |
+
References
|
| 1223 |
+
==========
|
| 1224 |
+
|
| 1225 |
+
.. [1] https://blogs.mathworks.com/cleve/2013/04/15/wilkinsons-matrices-2/
|
| 1226 |
+
.. [2] J. H. Wilkinson, The Algebraic Eigenvalue Problem, Claredon Press, Oxford, 1965, 662 pp.
|
| 1227 |
+
|
| 1228 |
+
"""
|
| 1229 |
+
klass = kwargs.get('cls', kls)
|
| 1230 |
+
n = as_int(n)
|
| 1231 |
+
return klass._eval_wilkinson(n)
|
| 1232 |
+
|
| 1233 |
+
class MatrixProperties(MatrixRequired):
|
| 1234 |
+
"""Provides basic properties of a matrix."""
|
| 1235 |
+
|
| 1236 |
+
def _eval_atoms(self, *types):
|
| 1237 |
+
result = set()
|
| 1238 |
+
for i in self:
|
| 1239 |
+
result.update(i.atoms(*types))
|
| 1240 |
+
return result
|
| 1241 |
+
|
| 1242 |
+
def _eval_free_symbols(self):
|
| 1243 |
+
return set().union(*(i.free_symbols for i in self if i))
|
| 1244 |
+
|
| 1245 |
+
def _eval_has(self, *patterns):
|
| 1246 |
+
return any(a.has(*patterns) for a in self)
|
| 1247 |
+
|
| 1248 |
+
def _eval_is_anti_symmetric(self, simpfunc):
|
| 1249 |
+
if not all(simpfunc(self[i, j] + self[j, i]).is_zero for i in range(self.rows) for j in range(self.cols)):
|
| 1250 |
+
return False
|
| 1251 |
+
return True
|
| 1252 |
+
|
| 1253 |
+
def _eval_is_diagonal(self):
|
| 1254 |
+
for i in range(self.rows):
|
| 1255 |
+
for j in range(self.cols):
|
| 1256 |
+
if i != j and self[i, j]:
|
| 1257 |
+
return False
|
| 1258 |
+
return True
|
| 1259 |
+
|
| 1260 |
+
# _eval_is_hermitian is called by some general SymPy
|
| 1261 |
+
# routines and has a different *args signature. Make
|
| 1262 |
+
# sure the names don't clash by adding `_matrix_` in name.
|
| 1263 |
+
def _eval_is_matrix_hermitian(self, simpfunc):
|
| 1264 |
+
mat = self._new(self.rows, self.cols, lambda i, j: simpfunc(self[i, j] - self[j, i].conjugate()))
|
| 1265 |
+
return mat.is_zero_matrix
|
| 1266 |
+
|
| 1267 |
+
def _eval_is_Identity(self) -> FuzzyBool:
|
| 1268 |
+
def dirac(i, j):
|
| 1269 |
+
if i == j:
|
| 1270 |
+
return 1
|
| 1271 |
+
return 0
|
| 1272 |
+
|
| 1273 |
+
return all(self[i, j] == dirac(i, j)
|
| 1274 |
+
for i in range(self.rows)
|
| 1275 |
+
for j in range(self.cols))
|
| 1276 |
+
|
| 1277 |
+
def _eval_is_lower_hessenberg(self):
|
| 1278 |
+
return all(self[i, j].is_zero
|
| 1279 |
+
for i in range(self.rows)
|
| 1280 |
+
for j in range(i + 2, self.cols))
|
| 1281 |
+
|
| 1282 |
+
def _eval_is_lower(self):
|
| 1283 |
+
return all(self[i, j].is_zero
|
| 1284 |
+
for i in range(self.rows)
|
| 1285 |
+
for j in range(i + 1, self.cols))
|
| 1286 |
+
|
| 1287 |
+
def _eval_is_symbolic(self):
|
| 1288 |
+
return self.has(Symbol)
|
| 1289 |
+
|
| 1290 |
+
def _eval_is_symmetric(self, simpfunc):
|
| 1291 |
+
mat = self._new(self.rows, self.cols, lambda i, j: simpfunc(self[i, j] - self[j, i]))
|
| 1292 |
+
return mat.is_zero_matrix
|
| 1293 |
+
|
| 1294 |
+
def _eval_is_zero_matrix(self):
|
| 1295 |
+
if any(i.is_zero == False for i in self):
|
| 1296 |
+
return False
|
| 1297 |
+
if any(i.is_zero is None for i in self):
|
| 1298 |
+
return None
|
| 1299 |
+
return True
|
| 1300 |
+
|
| 1301 |
+
def _eval_is_upper_hessenberg(self):
|
| 1302 |
+
return all(self[i, j].is_zero
|
| 1303 |
+
for i in range(2, self.rows)
|
| 1304 |
+
for j in range(min(self.cols, (i - 1))))
|
| 1305 |
+
|
| 1306 |
+
def _eval_values(self):
|
| 1307 |
+
return [i for i in self if not i.is_zero]
|
| 1308 |
+
|
| 1309 |
+
def _has_positive_diagonals(self):
|
| 1310 |
+
diagonal_entries = (self[i, i] for i in range(self.rows))
|
| 1311 |
+
return fuzzy_and(x.is_positive for x in diagonal_entries)
|
| 1312 |
+
|
| 1313 |
+
def _has_nonnegative_diagonals(self):
|
| 1314 |
+
diagonal_entries = (self[i, i] for i in range(self.rows))
|
| 1315 |
+
return fuzzy_and(x.is_nonnegative for x in diagonal_entries)
|
| 1316 |
+
|
| 1317 |
+
def atoms(self, *types):
|
| 1318 |
+
"""Returns the atoms that form the current object.
|
| 1319 |
+
|
| 1320 |
+
Examples
|
| 1321 |
+
========
|
| 1322 |
+
|
| 1323 |
+
>>> from sympy.abc import x, y
|
| 1324 |
+
>>> from sympy import Matrix
|
| 1325 |
+
>>> Matrix([[x]])
|
| 1326 |
+
Matrix([[x]])
|
| 1327 |
+
>>> _.atoms()
|
| 1328 |
+
{x}
|
| 1329 |
+
>>> Matrix([[x, y], [y, x]])
|
| 1330 |
+
Matrix([
|
| 1331 |
+
[x, y],
|
| 1332 |
+
[y, x]])
|
| 1333 |
+
>>> _.atoms()
|
| 1334 |
+
{x, y}
|
| 1335 |
+
"""
|
| 1336 |
+
|
| 1337 |
+
types = tuple(t if isinstance(t, type) else type(t) for t in types)
|
| 1338 |
+
if not types:
|
| 1339 |
+
types = (Atom,)
|
| 1340 |
+
return self._eval_atoms(*types)
|
| 1341 |
+
|
| 1342 |
+
@property
|
| 1343 |
+
def free_symbols(self):
|
| 1344 |
+
"""Returns the free symbols within the matrix.
|
| 1345 |
+
|
| 1346 |
+
Examples
|
| 1347 |
+
========
|
| 1348 |
+
|
| 1349 |
+
>>> from sympy.abc import x
|
| 1350 |
+
>>> from sympy import Matrix
|
| 1351 |
+
>>> Matrix([[x], [1]]).free_symbols
|
| 1352 |
+
{x}
|
| 1353 |
+
"""
|
| 1354 |
+
return self._eval_free_symbols()
|
| 1355 |
+
|
| 1356 |
+
def has(self, *patterns):
|
| 1357 |
+
"""Test whether any subexpression matches any of the patterns.
|
| 1358 |
+
|
| 1359 |
+
Examples
|
| 1360 |
+
========
|
| 1361 |
+
|
| 1362 |
+
>>> from sympy import Matrix, SparseMatrix, Float
|
| 1363 |
+
>>> from sympy.abc import x, y
|
| 1364 |
+
>>> A = Matrix(((1, x), (0.2, 3)))
|
| 1365 |
+
>>> B = SparseMatrix(((1, x), (0.2, 3)))
|
| 1366 |
+
>>> A.has(x)
|
| 1367 |
+
True
|
| 1368 |
+
>>> A.has(y)
|
| 1369 |
+
False
|
| 1370 |
+
>>> A.has(Float)
|
| 1371 |
+
True
|
| 1372 |
+
>>> B.has(x)
|
| 1373 |
+
True
|
| 1374 |
+
>>> B.has(y)
|
| 1375 |
+
False
|
| 1376 |
+
>>> B.has(Float)
|
| 1377 |
+
True
|
| 1378 |
+
"""
|
| 1379 |
+
return self._eval_has(*patterns)
|
| 1380 |
+
|
| 1381 |
+
def is_anti_symmetric(self, simplify=True):
|
| 1382 |
+
"""Check if matrix M is an antisymmetric matrix,
|
| 1383 |
+
that is, M is a square matrix with all M[i, j] == -M[j, i].
|
| 1384 |
+
|
| 1385 |
+
When ``simplify=True`` (default), the sum M[i, j] + M[j, i] is
|
| 1386 |
+
simplified before testing to see if it is zero. By default,
|
| 1387 |
+
the SymPy simplify function is used. To use a custom function
|
| 1388 |
+
set simplify to a function that accepts a single argument which
|
| 1389 |
+
returns a simplified expression. To skip simplification, set
|
| 1390 |
+
simplify to False but note that although this will be faster,
|
| 1391 |
+
it may induce false negatives.
|
| 1392 |
+
|
| 1393 |
+
Examples
|
| 1394 |
+
========
|
| 1395 |
+
|
| 1396 |
+
>>> from sympy import Matrix, symbols
|
| 1397 |
+
>>> m = Matrix(2, 2, [0, 1, -1, 0])
|
| 1398 |
+
>>> m
|
| 1399 |
+
Matrix([
|
| 1400 |
+
[ 0, 1],
|
| 1401 |
+
[-1, 0]])
|
| 1402 |
+
>>> m.is_anti_symmetric()
|
| 1403 |
+
True
|
| 1404 |
+
>>> x, y = symbols('x y')
|
| 1405 |
+
>>> m = Matrix(2, 3, [0, 0, x, -y, 0, 0])
|
| 1406 |
+
>>> m
|
| 1407 |
+
Matrix([
|
| 1408 |
+
[ 0, 0, x],
|
| 1409 |
+
[-y, 0, 0]])
|
| 1410 |
+
>>> m.is_anti_symmetric()
|
| 1411 |
+
False
|
| 1412 |
+
|
| 1413 |
+
>>> from sympy.abc import x, y
|
| 1414 |
+
>>> m = Matrix(3, 3, [0, x**2 + 2*x + 1, y,
|
| 1415 |
+
... -(x + 1)**2, 0, x*y,
|
| 1416 |
+
... -y, -x*y, 0])
|
| 1417 |
+
|
| 1418 |
+
Simplification of matrix elements is done by default so even
|
| 1419 |
+
though two elements which should be equal and opposite would not
|
| 1420 |
+
pass an equality test, the matrix is still reported as
|
| 1421 |
+
anti-symmetric:
|
| 1422 |
+
|
| 1423 |
+
>>> m[0, 1] == -m[1, 0]
|
| 1424 |
+
False
|
| 1425 |
+
>>> m.is_anti_symmetric()
|
| 1426 |
+
True
|
| 1427 |
+
|
| 1428 |
+
If ``simplify=False`` is used for the case when a Matrix is already
|
| 1429 |
+
simplified, this will speed things up. Here, we see that without
|
| 1430 |
+
simplification the matrix does not appear anti-symmetric:
|
| 1431 |
+
|
| 1432 |
+
>>> m.is_anti_symmetric(simplify=False)
|
| 1433 |
+
False
|
| 1434 |
+
|
| 1435 |
+
But if the matrix were already expanded, then it would appear
|
| 1436 |
+
anti-symmetric and simplification in the is_anti_symmetric routine
|
| 1437 |
+
is not needed:
|
| 1438 |
+
|
| 1439 |
+
>>> m = m.expand()
|
| 1440 |
+
>>> m.is_anti_symmetric(simplify=False)
|
| 1441 |
+
True
|
| 1442 |
+
"""
|
| 1443 |
+
# accept custom simplification
|
| 1444 |
+
simpfunc = simplify
|
| 1445 |
+
if not isfunction(simplify):
|
| 1446 |
+
simpfunc = _simplify if simplify else lambda x: x
|
| 1447 |
+
|
| 1448 |
+
if not self.is_square:
|
| 1449 |
+
return False
|
| 1450 |
+
return self._eval_is_anti_symmetric(simpfunc)
|
| 1451 |
+
|
| 1452 |
+
def is_diagonal(self):
|
| 1453 |
+
"""Check if matrix is diagonal,
|
| 1454 |
+
that is matrix in which the entries outside the main diagonal are all zero.
|
| 1455 |
+
|
| 1456 |
+
Examples
|
| 1457 |
+
========
|
| 1458 |
+
|
| 1459 |
+
>>> from sympy import Matrix, diag
|
| 1460 |
+
>>> m = Matrix(2, 2, [1, 0, 0, 2])
|
| 1461 |
+
>>> m
|
| 1462 |
+
Matrix([
|
| 1463 |
+
[1, 0],
|
| 1464 |
+
[0, 2]])
|
| 1465 |
+
>>> m.is_diagonal()
|
| 1466 |
+
True
|
| 1467 |
+
|
| 1468 |
+
>>> m = Matrix(2, 2, [1, 1, 0, 2])
|
| 1469 |
+
>>> m
|
| 1470 |
+
Matrix([
|
| 1471 |
+
[1, 1],
|
| 1472 |
+
[0, 2]])
|
| 1473 |
+
>>> m.is_diagonal()
|
| 1474 |
+
False
|
| 1475 |
+
|
| 1476 |
+
>>> m = diag(1, 2, 3)
|
| 1477 |
+
>>> m
|
| 1478 |
+
Matrix([
|
| 1479 |
+
[1, 0, 0],
|
| 1480 |
+
[0, 2, 0],
|
| 1481 |
+
[0, 0, 3]])
|
| 1482 |
+
>>> m.is_diagonal()
|
| 1483 |
+
True
|
| 1484 |
+
|
| 1485 |
+
See Also
|
| 1486 |
+
========
|
| 1487 |
+
|
| 1488 |
+
is_lower
|
| 1489 |
+
is_upper
|
| 1490 |
+
sympy.matrices.matrices.MatrixEigen.is_diagonalizable
|
| 1491 |
+
diagonalize
|
| 1492 |
+
"""
|
| 1493 |
+
return self._eval_is_diagonal()
|
| 1494 |
+
|
| 1495 |
+
@property
|
| 1496 |
+
def is_weakly_diagonally_dominant(self):
|
| 1497 |
+
r"""Tests if the matrix is row weakly diagonally dominant.
|
| 1498 |
+
|
| 1499 |
+
Explanation
|
| 1500 |
+
===========
|
| 1501 |
+
|
| 1502 |
+
A $n, n$ matrix $A$ is row weakly diagonally dominant if
|
| 1503 |
+
|
| 1504 |
+
.. math::
|
| 1505 |
+
\left|A_{i, i}\right| \ge \sum_{j = 0, j \neq i}^{n-1}
|
| 1506 |
+
\left|A_{i, j}\right| \quad {\text{for all }}
|
| 1507 |
+
i \in \{ 0, ..., n-1 \}
|
| 1508 |
+
|
| 1509 |
+
Examples
|
| 1510 |
+
========
|
| 1511 |
+
|
| 1512 |
+
>>> from sympy import Matrix
|
| 1513 |
+
>>> A = Matrix([[3, -2, 1], [1, -3, 2], [-1, 2, 4]])
|
| 1514 |
+
>>> A.is_weakly_diagonally_dominant
|
| 1515 |
+
True
|
| 1516 |
+
|
| 1517 |
+
>>> A = Matrix([[-2, 2, 1], [1, 3, 2], [1, -2, 0]])
|
| 1518 |
+
>>> A.is_weakly_diagonally_dominant
|
| 1519 |
+
False
|
| 1520 |
+
|
| 1521 |
+
>>> A = Matrix([[-4, 2, 1], [1, 6, 2], [1, -2, 5]])
|
| 1522 |
+
>>> A.is_weakly_diagonally_dominant
|
| 1523 |
+
True
|
| 1524 |
+
|
| 1525 |
+
Notes
|
| 1526 |
+
=====
|
| 1527 |
+
|
| 1528 |
+
If you want to test whether a matrix is column diagonally
|
| 1529 |
+
dominant, you can apply the test after transposing the matrix.
|
| 1530 |
+
"""
|
| 1531 |
+
if not self.is_square:
|
| 1532 |
+
return False
|
| 1533 |
+
|
| 1534 |
+
rows, cols = self.shape
|
| 1535 |
+
|
| 1536 |
+
def test_row(i):
|
| 1537 |
+
summation = self.zero
|
| 1538 |
+
for j in range(cols):
|
| 1539 |
+
if i != j:
|
| 1540 |
+
summation += Abs(self[i, j])
|
| 1541 |
+
return (Abs(self[i, i]) - summation).is_nonnegative
|
| 1542 |
+
|
| 1543 |
+
return fuzzy_and(test_row(i) for i in range(rows))
|
| 1544 |
+
|
| 1545 |
+
@property
|
| 1546 |
+
def is_strongly_diagonally_dominant(self):
|
| 1547 |
+
r"""Tests if the matrix is row strongly diagonally dominant.
|
| 1548 |
+
|
| 1549 |
+
Explanation
|
| 1550 |
+
===========
|
| 1551 |
+
|
| 1552 |
+
A $n, n$ matrix $A$ is row strongly diagonally dominant if
|
| 1553 |
+
|
| 1554 |
+
.. math::
|
| 1555 |
+
\left|A_{i, i}\right| > \sum_{j = 0, j \neq i}^{n-1}
|
| 1556 |
+
\left|A_{i, j}\right| \quad {\text{for all }}
|
| 1557 |
+
i \in \{ 0, ..., n-1 \}
|
| 1558 |
+
|
| 1559 |
+
Examples
|
| 1560 |
+
========
|
| 1561 |
+
|
| 1562 |
+
>>> from sympy import Matrix
|
| 1563 |
+
>>> A = Matrix([[3, -2, 1], [1, -3, 2], [-1, 2, 4]])
|
| 1564 |
+
>>> A.is_strongly_diagonally_dominant
|
| 1565 |
+
False
|
| 1566 |
+
|
| 1567 |
+
>>> A = Matrix([[-2, 2, 1], [1, 3, 2], [1, -2, 0]])
|
| 1568 |
+
>>> A.is_strongly_diagonally_dominant
|
| 1569 |
+
False
|
| 1570 |
+
|
| 1571 |
+
>>> A = Matrix([[-4, 2, 1], [1, 6, 2], [1, -2, 5]])
|
| 1572 |
+
>>> A.is_strongly_diagonally_dominant
|
| 1573 |
+
True
|
| 1574 |
+
|
| 1575 |
+
Notes
|
| 1576 |
+
=====
|
| 1577 |
+
|
| 1578 |
+
If you want to test whether a matrix is column diagonally
|
| 1579 |
+
dominant, you can apply the test after transposing the matrix.
|
| 1580 |
+
"""
|
| 1581 |
+
if not self.is_square:
|
| 1582 |
+
return False
|
| 1583 |
+
|
| 1584 |
+
rows, cols = self.shape
|
| 1585 |
+
|
| 1586 |
+
def test_row(i):
|
| 1587 |
+
summation = self.zero
|
| 1588 |
+
for j in range(cols):
|
| 1589 |
+
if i != j:
|
| 1590 |
+
summation += Abs(self[i, j])
|
| 1591 |
+
return (Abs(self[i, i]) - summation).is_positive
|
| 1592 |
+
|
| 1593 |
+
return fuzzy_and(test_row(i) for i in range(rows))
|
| 1594 |
+
|
| 1595 |
+
@property
|
| 1596 |
+
def is_hermitian(self):
|
| 1597 |
+
"""Checks if the matrix is Hermitian.
|
| 1598 |
+
|
| 1599 |
+
In a Hermitian matrix element i,j is the complex conjugate of
|
| 1600 |
+
element j,i.
|
| 1601 |
+
|
| 1602 |
+
Examples
|
| 1603 |
+
========
|
| 1604 |
+
|
| 1605 |
+
>>> from sympy import Matrix
|
| 1606 |
+
>>> from sympy import I
|
| 1607 |
+
>>> from sympy.abc import x
|
| 1608 |
+
>>> a = Matrix([[1, I], [-I, 1]])
|
| 1609 |
+
>>> a
|
| 1610 |
+
Matrix([
|
| 1611 |
+
[ 1, I],
|
| 1612 |
+
[-I, 1]])
|
| 1613 |
+
>>> a.is_hermitian
|
| 1614 |
+
True
|
| 1615 |
+
>>> a[0, 0] = 2*I
|
| 1616 |
+
>>> a.is_hermitian
|
| 1617 |
+
False
|
| 1618 |
+
>>> a[0, 0] = x
|
| 1619 |
+
>>> a.is_hermitian
|
| 1620 |
+
>>> a[0, 1] = a[1, 0]*I
|
| 1621 |
+
>>> a.is_hermitian
|
| 1622 |
+
False
|
| 1623 |
+
"""
|
| 1624 |
+
if not self.is_square:
|
| 1625 |
+
return False
|
| 1626 |
+
|
| 1627 |
+
return self._eval_is_matrix_hermitian(_simplify)
|
| 1628 |
+
|
| 1629 |
+
@property
|
| 1630 |
+
def is_Identity(self) -> FuzzyBool:
|
| 1631 |
+
if not self.is_square:
|
| 1632 |
+
return False
|
| 1633 |
+
return self._eval_is_Identity()
|
| 1634 |
+
|
| 1635 |
+
@property
|
| 1636 |
+
def is_lower_hessenberg(self):
|
| 1637 |
+
r"""Checks if the matrix is in the lower-Hessenberg form.
|
| 1638 |
+
|
| 1639 |
+
The lower hessenberg matrix has zero entries
|
| 1640 |
+
above the first superdiagonal.
|
| 1641 |
+
|
| 1642 |
+
Examples
|
| 1643 |
+
========
|
| 1644 |
+
|
| 1645 |
+
>>> from sympy import Matrix
|
| 1646 |
+
>>> a = Matrix([[1, 2, 0, 0], [5, 2, 3, 0], [3, 4, 3, 7], [5, 6, 1, 1]])
|
| 1647 |
+
>>> a
|
| 1648 |
+
Matrix([
|
| 1649 |
+
[1, 2, 0, 0],
|
| 1650 |
+
[5, 2, 3, 0],
|
| 1651 |
+
[3, 4, 3, 7],
|
| 1652 |
+
[5, 6, 1, 1]])
|
| 1653 |
+
>>> a.is_lower_hessenberg
|
| 1654 |
+
True
|
| 1655 |
+
|
| 1656 |
+
See Also
|
| 1657 |
+
========
|
| 1658 |
+
|
| 1659 |
+
is_upper_hessenberg
|
| 1660 |
+
is_lower
|
| 1661 |
+
"""
|
| 1662 |
+
return self._eval_is_lower_hessenberg()
|
| 1663 |
+
|
| 1664 |
+
@property
|
| 1665 |
+
def is_lower(self):
|
| 1666 |
+
"""Check if matrix is a lower triangular matrix. True can be returned
|
| 1667 |
+
even if the matrix is not square.
|
| 1668 |
+
|
| 1669 |
+
Examples
|
| 1670 |
+
========
|
| 1671 |
+
|
| 1672 |
+
>>> from sympy import Matrix
|
| 1673 |
+
>>> m = Matrix(2, 2, [1, 0, 0, 1])
|
| 1674 |
+
>>> m
|
| 1675 |
+
Matrix([
|
| 1676 |
+
[1, 0],
|
| 1677 |
+
[0, 1]])
|
| 1678 |
+
>>> m.is_lower
|
| 1679 |
+
True
|
| 1680 |
+
|
| 1681 |
+
>>> m = Matrix(4, 3, [0, 0, 0, 2, 0, 0, 1, 4, 0, 6, 6, 5])
|
| 1682 |
+
>>> m
|
| 1683 |
+
Matrix([
|
| 1684 |
+
[0, 0, 0],
|
| 1685 |
+
[2, 0, 0],
|
| 1686 |
+
[1, 4, 0],
|
| 1687 |
+
[6, 6, 5]])
|
| 1688 |
+
>>> m.is_lower
|
| 1689 |
+
True
|
| 1690 |
+
|
| 1691 |
+
>>> from sympy.abc import x, y
|
| 1692 |
+
>>> m = Matrix(2, 2, [x**2 + y, y**2 + x, 0, x + y])
|
| 1693 |
+
>>> m
|
| 1694 |
+
Matrix([
|
| 1695 |
+
[x**2 + y, x + y**2],
|
| 1696 |
+
[ 0, x + y]])
|
| 1697 |
+
>>> m.is_lower
|
| 1698 |
+
False
|
| 1699 |
+
|
| 1700 |
+
See Also
|
| 1701 |
+
========
|
| 1702 |
+
|
| 1703 |
+
is_upper
|
| 1704 |
+
is_diagonal
|
| 1705 |
+
is_lower_hessenberg
|
| 1706 |
+
"""
|
| 1707 |
+
return self._eval_is_lower()
|
| 1708 |
+
|
| 1709 |
+
@property
|
| 1710 |
+
def is_square(self):
|
| 1711 |
+
"""Checks if a matrix is square.
|
| 1712 |
+
|
| 1713 |
+
A matrix is square if the number of rows equals the number of columns.
|
| 1714 |
+
The empty matrix is square by definition, since the number of rows and
|
| 1715 |
+
the number of columns are both zero.
|
| 1716 |
+
|
| 1717 |
+
Examples
|
| 1718 |
+
========
|
| 1719 |
+
|
| 1720 |
+
>>> from sympy import Matrix
|
| 1721 |
+
>>> a = Matrix([[1, 2, 3], [4, 5, 6]])
|
| 1722 |
+
>>> b = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
|
| 1723 |
+
>>> c = Matrix([])
|
| 1724 |
+
>>> a.is_square
|
| 1725 |
+
False
|
| 1726 |
+
>>> b.is_square
|
| 1727 |
+
True
|
| 1728 |
+
>>> c.is_square
|
| 1729 |
+
True
|
| 1730 |
+
"""
|
| 1731 |
+
return self.rows == self.cols
|
| 1732 |
+
|
| 1733 |
+
def is_symbolic(self):
|
| 1734 |
+
"""Checks if any elements contain Symbols.
|
| 1735 |
+
|
| 1736 |
+
Examples
|
| 1737 |
+
========
|
| 1738 |
+
|
| 1739 |
+
>>> from sympy import Matrix
|
| 1740 |
+
>>> from sympy.abc import x, y
|
| 1741 |
+
>>> M = Matrix([[x, y], [1, 0]])
|
| 1742 |
+
>>> M.is_symbolic()
|
| 1743 |
+
True
|
| 1744 |
+
|
| 1745 |
+
"""
|
| 1746 |
+
return self._eval_is_symbolic()
|
| 1747 |
+
|
| 1748 |
+
def is_symmetric(self, simplify=True):
|
| 1749 |
+
"""Check if matrix is symmetric matrix,
|
| 1750 |
+
that is square matrix and is equal to its transpose.
|
| 1751 |
+
|
| 1752 |
+
By default, simplifications occur before testing symmetry.
|
| 1753 |
+
They can be skipped using 'simplify=False'; while speeding things a bit,
|
| 1754 |
+
this may however induce false negatives.
|
| 1755 |
+
|
| 1756 |
+
Examples
|
| 1757 |
+
========
|
| 1758 |
+
|
| 1759 |
+
>>> from sympy import Matrix
|
| 1760 |
+
>>> m = Matrix(2, 2, [0, 1, 1, 2])
|
| 1761 |
+
>>> m
|
| 1762 |
+
Matrix([
|
| 1763 |
+
[0, 1],
|
| 1764 |
+
[1, 2]])
|
| 1765 |
+
>>> m.is_symmetric()
|
| 1766 |
+
True
|
| 1767 |
+
|
| 1768 |
+
>>> m = Matrix(2, 2, [0, 1, 2, 0])
|
| 1769 |
+
>>> m
|
| 1770 |
+
Matrix([
|
| 1771 |
+
[0, 1],
|
| 1772 |
+
[2, 0]])
|
| 1773 |
+
>>> m.is_symmetric()
|
| 1774 |
+
False
|
| 1775 |
+
|
| 1776 |
+
>>> m = Matrix(2, 3, [0, 0, 0, 0, 0, 0])
|
| 1777 |
+
>>> m
|
| 1778 |
+
Matrix([
|
| 1779 |
+
[0, 0, 0],
|
| 1780 |
+
[0, 0, 0]])
|
| 1781 |
+
>>> m.is_symmetric()
|
| 1782 |
+
False
|
| 1783 |
+
|
| 1784 |
+
>>> from sympy.abc import x, y
|
| 1785 |
+
>>> m = Matrix(3, 3, [1, x**2 + 2*x + 1, y, (x + 1)**2, 2, 0, y, 0, 3])
|
| 1786 |
+
>>> m
|
| 1787 |
+
Matrix([
|
| 1788 |
+
[ 1, x**2 + 2*x + 1, y],
|
| 1789 |
+
[(x + 1)**2, 2, 0],
|
| 1790 |
+
[ y, 0, 3]])
|
| 1791 |
+
>>> m.is_symmetric()
|
| 1792 |
+
True
|
| 1793 |
+
|
| 1794 |
+
If the matrix is already simplified, you may speed-up is_symmetric()
|
| 1795 |
+
test by using 'simplify=False'.
|
| 1796 |
+
|
| 1797 |
+
>>> bool(m.is_symmetric(simplify=False))
|
| 1798 |
+
False
|
| 1799 |
+
>>> m1 = m.expand()
|
| 1800 |
+
>>> m1.is_symmetric(simplify=False)
|
| 1801 |
+
True
|
| 1802 |
+
"""
|
| 1803 |
+
simpfunc = simplify
|
| 1804 |
+
if not isfunction(simplify):
|
| 1805 |
+
simpfunc = _simplify if simplify else lambda x: x
|
| 1806 |
+
|
| 1807 |
+
if not self.is_square:
|
| 1808 |
+
return False
|
| 1809 |
+
|
| 1810 |
+
return self._eval_is_symmetric(simpfunc)
|
| 1811 |
+
|
| 1812 |
+
@property
|
| 1813 |
+
def is_upper_hessenberg(self):
|
| 1814 |
+
"""Checks if the matrix is the upper-Hessenberg form.
|
| 1815 |
+
|
| 1816 |
+
The upper hessenberg matrix has zero entries
|
| 1817 |
+
below the first subdiagonal.
|
| 1818 |
+
|
| 1819 |
+
Examples
|
| 1820 |
+
========
|
| 1821 |
+
|
| 1822 |
+
>>> from sympy import Matrix
|
| 1823 |
+
>>> a = Matrix([[1, 4, 2, 3], [3, 4, 1, 7], [0, 2, 3, 4], [0, 0, 1, 3]])
|
| 1824 |
+
>>> a
|
| 1825 |
+
Matrix([
|
| 1826 |
+
[1, 4, 2, 3],
|
| 1827 |
+
[3, 4, 1, 7],
|
| 1828 |
+
[0, 2, 3, 4],
|
| 1829 |
+
[0, 0, 1, 3]])
|
| 1830 |
+
>>> a.is_upper_hessenberg
|
| 1831 |
+
True
|
| 1832 |
+
|
| 1833 |
+
See Also
|
| 1834 |
+
========
|
| 1835 |
+
|
| 1836 |
+
is_lower_hessenberg
|
| 1837 |
+
is_upper
|
| 1838 |
+
"""
|
| 1839 |
+
return self._eval_is_upper_hessenberg()
|
| 1840 |
+
|
| 1841 |
+
@property
|
| 1842 |
+
def is_upper(self):
|
| 1843 |
+
"""Check if matrix is an upper triangular matrix. True can be returned
|
| 1844 |
+
even if the matrix is not square.
|
| 1845 |
+
|
| 1846 |
+
Examples
|
| 1847 |
+
========
|
| 1848 |
+
|
| 1849 |
+
>>> from sympy import Matrix
|
| 1850 |
+
>>> m = Matrix(2, 2, [1, 0, 0, 1])
|
| 1851 |
+
>>> m
|
| 1852 |
+
Matrix([
|
| 1853 |
+
[1, 0],
|
| 1854 |
+
[0, 1]])
|
| 1855 |
+
>>> m.is_upper
|
| 1856 |
+
True
|
| 1857 |
+
|
| 1858 |
+
>>> m = Matrix(4, 3, [5, 1, 9, 0, 4, 6, 0, 0, 5, 0, 0, 0])
|
| 1859 |
+
>>> m
|
| 1860 |
+
Matrix([
|
| 1861 |
+
[5, 1, 9],
|
| 1862 |
+
[0, 4, 6],
|
| 1863 |
+
[0, 0, 5],
|
| 1864 |
+
[0, 0, 0]])
|
| 1865 |
+
>>> m.is_upper
|
| 1866 |
+
True
|
| 1867 |
+
|
| 1868 |
+
>>> m = Matrix(2, 3, [4, 2, 5, 6, 1, 1])
|
| 1869 |
+
>>> m
|
| 1870 |
+
Matrix([
|
| 1871 |
+
[4, 2, 5],
|
| 1872 |
+
[6, 1, 1]])
|
| 1873 |
+
>>> m.is_upper
|
| 1874 |
+
False
|
| 1875 |
+
|
| 1876 |
+
See Also
|
| 1877 |
+
========
|
| 1878 |
+
|
| 1879 |
+
is_lower
|
| 1880 |
+
is_diagonal
|
| 1881 |
+
is_upper_hessenberg
|
| 1882 |
+
"""
|
| 1883 |
+
return all(self[i, j].is_zero
|
| 1884 |
+
for i in range(1, self.rows)
|
| 1885 |
+
for j in range(min(i, self.cols)))
|
| 1886 |
+
|
| 1887 |
+
@property
|
| 1888 |
+
def is_zero_matrix(self):
|
| 1889 |
+
"""Checks if a matrix is a zero matrix.
|
| 1890 |
+
|
| 1891 |
+
A matrix is zero if every element is zero. A matrix need not be square
|
| 1892 |
+
to be considered zero. The empty matrix is zero by the principle of
|
| 1893 |
+
vacuous truth. For a matrix that may or may not be zero (e.g.
|
| 1894 |
+
contains a symbol), this will be None
|
| 1895 |
+
|
| 1896 |
+
Examples
|
| 1897 |
+
========
|
| 1898 |
+
|
| 1899 |
+
>>> from sympy import Matrix, zeros
|
| 1900 |
+
>>> from sympy.abc import x
|
| 1901 |
+
>>> a = Matrix([[0, 0], [0, 0]])
|
| 1902 |
+
>>> b = zeros(3, 4)
|
| 1903 |
+
>>> c = Matrix([[0, 1], [0, 0]])
|
| 1904 |
+
>>> d = Matrix([])
|
| 1905 |
+
>>> e = Matrix([[x, 0], [0, 0]])
|
| 1906 |
+
>>> a.is_zero_matrix
|
| 1907 |
+
True
|
| 1908 |
+
>>> b.is_zero_matrix
|
| 1909 |
+
True
|
| 1910 |
+
>>> c.is_zero_matrix
|
| 1911 |
+
False
|
| 1912 |
+
>>> d.is_zero_matrix
|
| 1913 |
+
True
|
| 1914 |
+
>>> e.is_zero_matrix
|
| 1915 |
+
"""
|
| 1916 |
+
return self._eval_is_zero_matrix()
|
| 1917 |
+
|
| 1918 |
+
def values(self):
|
| 1919 |
+
"""Return non-zero values of self."""
|
| 1920 |
+
return self._eval_values()
|
| 1921 |
+
|
| 1922 |
+
|
| 1923 |
+
class MatrixOperations(MatrixRequired):
|
| 1924 |
+
"""Provides basic matrix shape and elementwise
|
| 1925 |
+
operations. Should not be instantiated directly."""
|
| 1926 |
+
|
| 1927 |
+
def _eval_adjoint(self):
|
| 1928 |
+
return self.transpose().conjugate()
|
| 1929 |
+
|
| 1930 |
+
def _eval_applyfunc(self, f):
|
| 1931 |
+
out = self._new(self.rows, self.cols, [f(x) for x in self])
|
| 1932 |
+
return out
|
| 1933 |
+
|
| 1934 |
+
def _eval_as_real_imag(self): # type: ignore
|
| 1935 |
+
return (self.applyfunc(re), self.applyfunc(im))
|
| 1936 |
+
|
| 1937 |
+
def _eval_conjugate(self):
|
| 1938 |
+
return self.applyfunc(lambda x: x.conjugate())
|
| 1939 |
+
|
| 1940 |
+
def _eval_permute_cols(self, perm):
|
| 1941 |
+
# apply the permutation to a list
|
| 1942 |
+
mapping = list(perm)
|
| 1943 |
+
|
| 1944 |
+
def entry(i, j):
|
| 1945 |
+
return self[i, mapping[j]]
|
| 1946 |
+
|
| 1947 |
+
return self._new(self.rows, self.cols, entry)
|
| 1948 |
+
|
| 1949 |
+
def _eval_permute_rows(self, perm):
|
| 1950 |
+
# apply the permutation to a list
|
| 1951 |
+
mapping = list(perm)
|
| 1952 |
+
|
| 1953 |
+
def entry(i, j):
|
| 1954 |
+
return self[mapping[i], j]
|
| 1955 |
+
|
| 1956 |
+
return self._new(self.rows, self.cols, entry)
|
| 1957 |
+
|
| 1958 |
+
def _eval_trace(self):
|
| 1959 |
+
return sum(self[i, i] for i in range(self.rows))
|
| 1960 |
+
|
| 1961 |
+
def _eval_transpose(self):
|
| 1962 |
+
return self._new(self.cols, self.rows, lambda i, j: self[j, i])
|
| 1963 |
+
|
| 1964 |
+
def adjoint(self):
|
| 1965 |
+
"""Conjugate transpose or Hermitian conjugation."""
|
| 1966 |
+
return self._eval_adjoint()
|
| 1967 |
+
|
| 1968 |
+
def applyfunc(self, f):
|
| 1969 |
+
"""Apply a function to each element of the matrix.
|
| 1970 |
+
|
| 1971 |
+
Examples
|
| 1972 |
+
========
|
| 1973 |
+
|
| 1974 |
+
>>> from sympy import Matrix
|
| 1975 |
+
>>> m = Matrix(2, 2, lambda i, j: i*2+j)
|
| 1976 |
+
>>> m
|
| 1977 |
+
Matrix([
|
| 1978 |
+
[0, 1],
|
| 1979 |
+
[2, 3]])
|
| 1980 |
+
>>> m.applyfunc(lambda i: 2*i)
|
| 1981 |
+
Matrix([
|
| 1982 |
+
[0, 2],
|
| 1983 |
+
[4, 6]])
|
| 1984 |
+
|
| 1985 |
+
"""
|
| 1986 |
+
if not callable(f):
|
| 1987 |
+
raise TypeError("`f` must be callable.")
|
| 1988 |
+
|
| 1989 |
+
return self._eval_applyfunc(f)
|
| 1990 |
+
|
| 1991 |
+
def as_real_imag(self, deep=True, **hints):
|
| 1992 |
+
"""Returns a tuple containing the (real, imaginary) part of matrix."""
|
| 1993 |
+
# XXX: Ignoring deep and hints...
|
| 1994 |
+
return self._eval_as_real_imag()
|
| 1995 |
+
|
| 1996 |
+
def conjugate(self):
|
| 1997 |
+
"""Return the by-element conjugation.
|
| 1998 |
+
|
| 1999 |
+
Examples
|
| 2000 |
+
========
|
| 2001 |
+
|
| 2002 |
+
>>> from sympy import SparseMatrix, I
|
| 2003 |
+
>>> a = SparseMatrix(((1, 2 + I), (3, 4), (I, -I)))
|
| 2004 |
+
>>> a
|
| 2005 |
+
Matrix([
|
| 2006 |
+
[1, 2 + I],
|
| 2007 |
+
[3, 4],
|
| 2008 |
+
[I, -I]])
|
| 2009 |
+
>>> a.C
|
| 2010 |
+
Matrix([
|
| 2011 |
+
[ 1, 2 - I],
|
| 2012 |
+
[ 3, 4],
|
| 2013 |
+
[-I, I]])
|
| 2014 |
+
|
| 2015 |
+
See Also
|
| 2016 |
+
========
|
| 2017 |
+
|
| 2018 |
+
transpose: Matrix transposition
|
| 2019 |
+
H: Hermite conjugation
|
| 2020 |
+
sympy.matrices.matrices.MatrixBase.D: Dirac conjugation
|
| 2021 |
+
"""
|
| 2022 |
+
return self._eval_conjugate()
|
| 2023 |
+
|
| 2024 |
+
def doit(self, **hints):
|
| 2025 |
+
return self.applyfunc(lambda x: x.doit(**hints))
|
| 2026 |
+
|
| 2027 |
+
def evalf(self, n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False):
|
| 2028 |
+
"""Apply evalf() to each element of self."""
|
| 2029 |
+
options = {'subs':subs, 'maxn':maxn, 'chop':chop, 'strict':strict,
|
| 2030 |
+
'quad':quad, 'verbose':verbose}
|
| 2031 |
+
return self.applyfunc(lambda i: i.evalf(n, **options))
|
| 2032 |
+
|
| 2033 |
+
def expand(self, deep=True, modulus=None, power_base=True, power_exp=True,
|
| 2034 |
+
mul=True, log=True, multinomial=True, basic=True, **hints):
|
| 2035 |
+
"""Apply core.function.expand to each entry of the matrix.
|
| 2036 |
+
|
| 2037 |
+
Examples
|
| 2038 |
+
========
|
| 2039 |
+
|
| 2040 |
+
>>> from sympy.abc import x
|
| 2041 |
+
>>> from sympy import Matrix
|
| 2042 |
+
>>> Matrix(1, 1, [x*(x+1)])
|
| 2043 |
+
Matrix([[x*(x + 1)]])
|
| 2044 |
+
>>> _.expand()
|
| 2045 |
+
Matrix([[x**2 + x]])
|
| 2046 |
+
|
| 2047 |
+
"""
|
| 2048 |
+
return self.applyfunc(lambda x: x.expand(
|
| 2049 |
+
deep, modulus, power_base, power_exp, mul, log, multinomial, basic,
|
| 2050 |
+
**hints))
|
| 2051 |
+
|
| 2052 |
+
@property
|
| 2053 |
+
def H(self):
|
| 2054 |
+
"""Return Hermite conjugate.
|
| 2055 |
+
|
| 2056 |
+
Examples
|
| 2057 |
+
========
|
| 2058 |
+
|
| 2059 |
+
>>> from sympy import Matrix, I
|
| 2060 |
+
>>> m = Matrix((0, 1 + I, 2, 3))
|
| 2061 |
+
>>> m
|
| 2062 |
+
Matrix([
|
| 2063 |
+
[ 0],
|
| 2064 |
+
[1 + I],
|
| 2065 |
+
[ 2],
|
| 2066 |
+
[ 3]])
|
| 2067 |
+
>>> m.H
|
| 2068 |
+
Matrix([[0, 1 - I, 2, 3]])
|
| 2069 |
+
|
| 2070 |
+
See Also
|
| 2071 |
+
========
|
| 2072 |
+
|
| 2073 |
+
conjugate: By-element conjugation
|
| 2074 |
+
sympy.matrices.matrices.MatrixBase.D: Dirac conjugation
|
| 2075 |
+
"""
|
| 2076 |
+
return self.T.C
|
| 2077 |
+
|
| 2078 |
+
def permute(self, perm, orientation='rows', direction='forward'):
|
| 2079 |
+
r"""Permute the rows or columns of a matrix by the given list of
|
| 2080 |
+
swaps.
|
| 2081 |
+
|
| 2082 |
+
Parameters
|
| 2083 |
+
==========
|
| 2084 |
+
|
| 2085 |
+
perm : Permutation, list, or list of lists
|
| 2086 |
+
A representation for the permutation.
|
| 2087 |
+
|
| 2088 |
+
If it is ``Permutation``, it is used directly with some
|
| 2089 |
+
resizing with respect to the matrix size.
|
| 2090 |
+
|
| 2091 |
+
If it is specified as list of lists,
|
| 2092 |
+
(e.g., ``[[0, 1], [0, 2]]``), then the permutation is formed
|
| 2093 |
+
from applying the product of cycles. The direction how the
|
| 2094 |
+
cyclic product is applied is described in below.
|
| 2095 |
+
|
| 2096 |
+
If it is specified as a list, the list should represent
|
| 2097 |
+
an array form of a permutation. (e.g., ``[1, 2, 0]``) which
|
| 2098 |
+
would would form the swapping function
|
| 2099 |
+
`0 \mapsto 1, 1 \mapsto 2, 2\mapsto 0`.
|
| 2100 |
+
|
| 2101 |
+
orientation : 'rows', 'cols'
|
| 2102 |
+
A flag to control whether to permute the rows or the columns
|
| 2103 |
+
|
| 2104 |
+
direction : 'forward', 'backward'
|
| 2105 |
+
A flag to control whether to apply the permutations from
|
| 2106 |
+
the start of the list first, or from the back of the list
|
| 2107 |
+
first.
|
| 2108 |
+
|
| 2109 |
+
For example, if the permutation specification is
|
| 2110 |
+
``[[0, 1], [0, 2]]``,
|
| 2111 |
+
|
| 2112 |
+
If the flag is set to ``'forward'``, the cycle would be
|
| 2113 |
+
formed as `0 \mapsto 2, 2 \mapsto 1, 1 \mapsto 0`.
|
| 2114 |
+
|
| 2115 |
+
If the flag is set to ``'backward'``, the cycle would be
|
| 2116 |
+
formed as `0 \mapsto 1, 1 \mapsto 2, 2 \mapsto 0`.
|
| 2117 |
+
|
| 2118 |
+
If the argument ``perm`` is not in a form of list of lists,
|
| 2119 |
+
this flag takes no effect.
|
| 2120 |
+
|
| 2121 |
+
Examples
|
| 2122 |
+
========
|
| 2123 |
+
|
| 2124 |
+
>>> from sympy import eye
|
| 2125 |
+
>>> M = eye(3)
|
| 2126 |
+
>>> M.permute([[0, 1], [0, 2]], orientation='rows', direction='forward')
|
| 2127 |
+
Matrix([
|
| 2128 |
+
[0, 0, 1],
|
| 2129 |
+
[1, 0, 0],
|
| 2130 |
+
[0, 1, 0]])
|
| 2131 |
+
|
| 2132 |
+
>>> from sympy import eye
|
| 2133 |
+
>>> M = eye(3)
|
| 2134 |
+
>>> M.permute([[0, 1], [0, 2]], orientation='rows', direction='backward')
|
| 2135 |
+
Matrix([
|
| 2136 |
+
[0, 1, 0],
|
| 2137 |
+
[0, 0, 1],
|
| 2138 |
+
[1, 0, 0]])
|
| 2139 |
+
|
| 2140 |
+
Notes
|
| 2141 |
+
=====
|
| 2142 |
+
|
| 2143 |
+
If a bijective function
|
| 2144 |
+
`\sigma : \mathbb{N}_0 \rightarrow \mathbb{N}_0` denotes the
|
| 2145 |
+
permutation.
|
| 2146 |
+
|
| 2147 |
+
If the matrix `A` is the matrix to permute, represented as
|
| 2148 |
+
a horizontal or a vertical stack of vectors:
|
| 2149 |
+
|
| 2150 |
+
.. math::
|
| 2151 |
+
A =
|
| 2152 |
+
\begin{bmatrix}
|
| 2153 |
+
a_0 \\ a_1 \\ \vdots \\ a_{n-1}
|
| 2154 |
+
\end{bmatrix} =
|
| 2155 |
+
\begin{bmatrix}
|
| 2156 |
+
\alpha_0 & \alpha_1 & \cdots & \alpha_{n-1}
|
| 2157 |
+
\end{bmatrix}
|
| 2158 |
+
|
| 2159 |
+
If the matrix `B` is the result, the permutation of matrix rows
|
| 2160 |
+
is defined as:
|
| 2161 |
+
|
| 2162 |
+
.. math::
|
| 2163 |
+
B := \begin{bmatrix}
|
| 2164 |
+
a_{\sigma(0)} \\ a_{\sigma(1)} \\ \vdots \\ a_{\sigma(n-1)}
|
| 2165 |
+
\end{bmatrix}
|
| 2166 |
+
|
| 2167 |
+
And the permutation of matrix columns is defined as:
|
| 2168 |
+
|
| 2169 |
+
.. math::
|
| 2170 |
+
B := \begin{bmatrix}
|
| 2171 |
+
\alpha_{\sigma(0)} & \alpha_{\sigma(1)} &
|
| 2172 |
+
\cdots & \alpha_{\sigma(n-1)}
|
| 2173 |
+
\end{bmatrix}
|
| 2174 |
+
"""
|
| 2175 |
+
from sympy.combinatorics import Permutation
|
| 2176 |
+
|
| 2177 |
+
# allow british variants and `columns`
|
| 2178 |
+
if direction == 'forwards':
|
| 2179 |
+
direction = 'forward'
|
| 2180 |
+
if direction == 'backwards':
|
| 2181 |
+
direction = 'backward'
|
| 2182 |
+
if orientation == 'columns':
|
| 2183 |
+
orientation = 'cols'
|
| 2184 |
+
|
| 2185 |
+
if direction not in ('forward', 'backward'):
|
| 2186 |
+
raise TypeError("direction='{}' is an invalid kwarg. "
|
| 2187 |
+
"Try 'forward' or 'backward'".format(direction))
|
| 2188 |
+
if orientation not in ('rows', 'cols'):
|
| 2189 |
+
raise TypeError("orientation='{}' is an invalid kwarg. "
|
| 2190 |
+
"Try 'rows' or 'cols'".format(orientation))
|
| 2191 |
+
|
| 2192 |
+
if not isinstance(perm, (Permutation, Iterable)):
|
| 2193 |
+
raise ValueError(
|
| 2194 |
+
"{} must be a list, a list of lists, "
|
| 2195 |
+
"or a SymPy permutation object.".format(perm))
|
| 2196 |
+
|
| 2197 |
+
# ensure all swaps are in range
|
| 2198 |
+
max_index = self.rows if orientation == 'rows' else self.cols
|
| 2199 |
+
if not all(0 <= t <= max_index for t in flatten(list(perm))):
|
| 2200 |
+
raise IndexError("`swap` indices out of range.")
|
| 2201 |
+
|
| 2202 |
+
if perm and not isinstance(perm, Permutation) and \
|
| 2203 |
+
isinstance(perm[0], Iterable):
|
| 2204 |
+
if direction == 'forward':
|
| 2205 |
+
perm = list(reversed(perm))
|
| 2206 |
+
perm = Permutation(perm, size=max_index+1)
|
| 2207 |
+
else:
|
| 2208 |
+
perm = Permutation(perm, size=max_index+1)
|
| 2209 |
+
|
| 2210 |
+
if orientation == 'rows':
|
| 2211 |
+
return self._eval_permute_rows(perm)
|
| 2212 |
+
if orientation == 'cols':
|
| 2213 |
+
return self._eval_permute_cols(perm)
|
| 2214 |
+
|
| 2215 |
+
def permute_cols(self, swaps, direction='forward'):
|
| 2216 |
+
"""Alias for
|
| 2217 |
+
``self.permute(swaps, orientation='cols', direction=direction)``
|
| 2218 |
+
|
| 2219 |
+
See Also
|
| 2220 |
+
========
|
| 2221 |
+
|
| 2222 |
+
permute
|
| 2223 |
+
"""
|
| 2224 |
+
return self.permute(swaps, orientation='cols', direction=direction)
|
| 2225 |
+
|
| 2226 |
+
def permute_rows(self, swaps, direction='forward'):
|
| 2227 |
+
"""Alias for
|
| 2228 |
+
``self.permute(swaps, orientation='rows', direction=direction)``
|
| 2229 |
+
|
| 2230 |
+
See Also
|
| 2231 |
+
========
|
| 2232 |
+
|
| 2233 |
+
permute
|
| 2234 |
+
"""
|
| 2235 |
+
return self.permute(swaps, orientation='rows', direction=direction)
|
| 2236 |
+
|
| 2237 |
+
def refine(self, assumptions=True):
|
| 2238 |
+
"""Apply refine to each element of the matrix.
|
| 2239 |
+
|
| 2240 |
+
Examples
|
| 2241 |
+
========
|
| 2242 |
+
|
| 2243 |
+
>>> from sympy import Symbol, Matrix, Abs, sqrt, Q
|
| 2244 |
+
>>> x = Symbol('x')
|
| 2245 |
+
>>> Matrix([[Abs(x)**2, sqrt(x**2)],[sqrt(x**2), Abs(x)**2]])
|
| 2246 |
+
Matrix([
|
| 2247 |
+
[ Abs(x)**2, sqrt(x**2)],
|
| 2248 |
+
[sqrt(x**2), Abs(x)**2]])
|
| 2249 |
+
>>> _.refine(Q.real(x))
|
| 2250 |
+
Matrix([
|
| 2251 |
+
[ x**2, Abs(x)],
|
| 2252 |
+
[Abs(x), x**2]])
|
| 2253 |
+
|
| 2254 |
+
"""
|
| 2255 |
+
return self.applyfunc(lambda x: refine(x, assumptions))
|
| 2256 |
+
|
| 2257 |
+
def replace(self, F, G, map=False, simultaneous=True, exact=None):
|
| 2258 |
+
"""Replaces Function F in Matrix entries with Function G.
|
| 2259 |
+
|
| 2260 |
+
Examples
|
| 2261 |
+
========
|
| 2262 |
+
|
| 2263 |
+
>>> from sympy import symbols, Function, Matrix
|
| 2264 |
+
>>> F, G = symbols('F, G', cls=Function)
|
| 2265 |
+
>>> M = Matrix(2, 2, lambda i, j: F(i+j)) ; M
|
| 2266 |
+
Matrix([
|
| 2267 |
+
[F(0), F(1)],
|
| 2268 |
+
[F(1), F(2)]])
|
| 2269 |
+
>>> N = M.replace(F,G)
|
| 2270 |
+
>>> N
|
| 2271 |
+
Matrix([
|
| 2272 |
+
[G(0), G(1)],
|
| 2273 |
+
[G(1), G(2)]])
|
| 2274 |
+
"""
|
| 2275 |
+
return self.applyfunc(
|
| 2276 |
+
lambda x: x.replace(F, G, map=map, simultaneous=simultaneous, exact=exact))
|
| 2277 |
+
|
| 2278 |
+
def rot90(self, k=1):
|
| 2279 |
+
"""Rotates Matrix by 90 degrees
|
| 2280 |
+
|
| 2281 |
+
Parameters
|
| 2282 |
+
==========
|
| 2283 |
+
|
| 2284 |
+
k : int
|
| 2285 |
+
Specifies how many times the matrix is rotated by 90 degrees
|
| 2286 |
+
(clockwise when positive, counter-clockwise when negative).
|
| 2287 |
+
|
| 2288 |
+
Examples
|
| 2289 |
+
========
|
| 2290 |
+
|
| 2291 |
+
>>> from sympy import Matrix, symbols
|
| 2292 |
+
>>> A = Matrix(2, 2, symbols('a:d'))
|
| 2293 |
+
>>> A
|
| 2294 |
+
Matrix([
|
| 2295 |
+
[a, b],
|
| 2296 |
+
[c, d]])
|
| 2297 |
+
|
| 2298 |
+
Rotating the matrix clockwise one time:
|
| 2299 |
+
|
| 2300 |
+
>>> A.rot90(1)
|
| 2301 |
+
Matrix([
|
| 2302 |
+
[c, a],
|
| 2303 |
+
[d, b]])
|
| 2304 |
+
|
| 2305 |
+
Rotating the matrix anticlockwise two times:
|
| 2306 |
+
|
| 2307 |
+
>>> A.rot90(-2)
|
| 2308 |
+
Matrix([
|
| 2309 |
+
[d, c],
|
| 2310 |
+
[b, a]])
|
| 2311 |
+
"""
|
| 2312 |
+
|
| 2313 |
+
mod = k%4
|
| 2314 |
+
if mod == 0:
|
| 2315 |
+
return self
|
| 2316 |
+
if mod == 1:
|
| 2317 |
+
return self[::-1, ::].T
|
| 2318 |
+
if mod == 2:
|
| 2319 |
+
return self[::-1, ::-1]
|
| 2320 |
+
if mod == 3:
|
| 2321 |
+
return self[::, ::-1].T
|
| 2322 |
+
|
| 2323 |
+
def simplify(self, **kwargs):
|
| 2324 |
+
"""Apply simplify to each element of the matrix.
|
| 2325 |
+
|
| 2326 |
+
Examples
|
| 2327 |
+
========
|
| 2328 |
+
|
| 2329 |
+
>>> from sympy.abc import x, y
|
| 2330 |
+
>>> from sympy import SparseMatrix, sin, cos
|
| 2331 |
+
>>> SparseMatrix(1, 1, [x*sin(y)**2 + x*cos(y)**2])
|
| 2332 |
+
Matrix([[x*sin(y)**2 + x*cos(y)**2]])
|
| 2333 |
+
>>> _.simplify()
|
| 2334 |
+
Matrix([[x]])
|
| 2335 |
+
"""
|
| 2336 |
+
return self.applyfunc(lambda x: x.simplify(**kwargs))
|
| 2337 |
+
|
| 2338 |
+
def subs(self, *args, **kwargs): # should mirror core.basic.subs
|
| 2339 |
+
"""Return a new matrix with subs applied to each entry.
|
| 2340 |
+
|
| 2341 |
+
Examples
|
| 2342 |
+
========
|
| 2343 |
+
|
| 2344 |
+
>>> from sympy.abc import x, y
|
| 2345 |
+
>>> from sympy import SparseMatrix, Matrix
|
| 2346 |
+
>>> SparseMatrix(1, 1, [x])
|
| 2347 |
+
Matrix([[x]])
|
| 2348 |
+
>>> _.subs(x, y)
|
| 2349 |
+
Matrix([[y]])
|
| 2350 |
+
>>> Matrix(_).subs(y, x)
|
| 2351 |
+
Matrix([[x]])
|
| 2352 |
+
"""
|
| 2353 |
+
|
| 2354 |
+
if len(args) == 1 and not isinstance(args[0], (dict, set)) and iter(args[0]) and not is_sequence(args[0]):
|
| 2355 |
+
args = (list(args[0]),)
|
| 2356 |
+
|
| 2357 |
+
return self.applyfunc(lambda x: x.subs(*args, **kwargs))
|
| 2358 |
+
|
| 2359 |
+
def trace(self):
|
| 2360 |
+
"""
|
| 2361 |
+
Returns the trace of a square matrix i.e. the sum of the
|
| 2362 |
+
diagonal elements.
|
| 2363 |
+
|
| 2364 |
+
Examples
|
| 2365 |
+
========
|
| 2366 |
+
|
| 2367 |
+
>>> from sympy import Matrix
|
| 2368 |
+
>>> A = Matrix(2, 2, [1, 2, 3, 4])
|
| 2369 |
+
>>> A.trace()
|
| 2370 |
+
5
|
| 2371 |
+
|
| 2372 |
+
"""
|
| 2373 |
+
if self.rows != self.cols:
|
| 2374 |
+
raise NonSquareMatrixError()
|
| 2375 |
+
return self._eval_trace()
|
| 2376 |
+
|
| 2377 |
+
def transpose(self):
|
| 2378 |
+
"""
|
| 2379 |
+
Returns the transpose of the matrix.
|
| 2380 |
+
|
| 2381 |
+
Examples
|
| 2382 |
+
========
|
| 2383 |
+
|
| 2384 |
+
>>> from sympy import Matrix
|
| 2385 |
+
>>> A = Matrix(2, 2, [1, 2, 3, 4])
|
| 2386 |
+
>>> A.transpose()
|
| 2387 |
+
Matrix([
|
| 2388 |
+
[1, 3],
|
| 2389 |
+
[2, 4]])
|
| 2390 |
+
|
| 2391 |
+
>>> from sympy import Matrix, I
|
| 2392 |
+
>>> m=Matrix(((1, 2+I), (3, 4)))
|
| 2393 |
+
>>> m
|
| 2394 |
+
Matrix([
|
| 2395 |
+
[1, 2 + I],
|
| 2396 |
+
[3, 4]])
|
| 2397 |
+
>>> m.transpose()
|
| 2398 |
+
Matrix([
|
| 2399 |
+
[ 1, 3],
|
| 2400 |
+
[2 + I, 4]])
|
| 2401 |
+
>>> m.T == m.transpose()
|
| 2402 |
+
True
|
| 2403 |
+
|
| 2404 |
+
See Also
|
| 2405 |
+
========
|
| 2406 |
+
|
| 2407 |
+
conjugate: By-element conjugation
|
| 2408 |
+
|
| 2409 |
+
"""
|
| 2410 |
+
return self._eval_transpose()
|
| 2411 |
+
|
| 2412 |
+
@property
|
| 2413 |
+
def T(self):
|
| 2414 |
+
'''Matrix transposition'''
|
| 2415 |
+
return self.transpose()
|
| 2416 |
+
|
| 2417 |
+
@property
|
| 2418 |
+
def C(self):
|
| 2419 |
+
'''By-element conjugation'''
|
| 2420 |
+
return self.conjugate()
|
| 2421 |
+
|
| 2422 |
+
def n(self, *args, **kwargs):
|
| 2423 |
+
"""Apply evalf() to each element of self."""
|
| 2424 |
+
return self.evalf(*args, **kwargs)
|
| 2425 |
+
|
| 2426 |
+
def xreplace(self, rule): # should mirror core.basic.xreplace
|
| 2427 |
+
"""Return a new matrix with xreplace applied to each entry.
|
| 2428 |
+
|
| 2429 |
+
Examples
|
| 2430 |
+
========
|
| 2431 |
+
|
| 2432 |
+
>>> from sympy.abc import x, y
|
| 2433 |
+
>>> from sympy import SparseMatrix, Matrix
|
| 2434 |
+
>>> SparseMatrix(1, 1, [x])
|
| 2435 |
+
Matrix([[x]])
|
| 2436 |
+
>>> _.xreplace({x: y})
|
| 2437 |
+
Matrix([[y]])
|
| 2438 |
+
>>> Matrix(_).xreplace({y: x})
|
| 2439 |
+
Matrix([[x]])
|
| 2440 |
+
"""
|
| 2441 |
+
return self.applyfunc(lambda x: x.xreplace(rule))
|
| 2442 |
+
|
| 2443 |
+
def _eval_simplify(self, **kwargs):
|
| 2444 |
+
# XXX: We can't use self.simplify here as mutable subclasses will
|
| 2445 |
+
# override simplify and have it return None
|
| 2446 |
+
return MatrixOperations.simplify(self, **kwargs)
|
| 2447 |
+
|
| 2448 |
+
def _eval_trigsimp(self, **opts):
|
| 2449 |
+
from sympy.simplify.trigsimp import trigsimp
|
| 2450 |
+
return self.applyfunc(lambda x: trigsimp(x, **opts))
|
| 2451 |
+
|
| 2452 |
+
def upper_triangular(self, k=0):
|
| 2453 |
+
"""Return the elements on and above the kth diagonal of a matrix.
|
| 2454 |
+
If k is not specified then simply returns upper-triangular portion
|
| 2455 |
+
of a matrix
|
| 2456 |
+
|
| 2457 |
+
Examples
|
| 2458 |
+
========
|
| 2459 |
+
|
| 2460 |
+
>>> from sympy import ones
|
| 2461 |
+
>>> A = ones(4)
|
| 2462 |
+
>>> A.upper_triangular()
|
| 2463 |
+
Matrix([
|
| 2464 |
+
[1, 1, 1, 1],
|
| 2465 |
+
[0, 1, 1, 1],
|
| 2466 |
+
[0, 0, 1, 1],
|
| 2467 |
+
[0, 0, 0, 1]])
|
| 2468 |
+
|
| 2469 |
+
>>> A.upper_triangular(2)
|
| 2470 |
+
Matrix([
|
| 2471 |
+
[0, 0, 1, 1],
|
| 2472 |
+
[0, 0, 0, 1],
|
| 2473 |
+
[0, 0, 0, 0],
|
| 2474 |
+
[0, 0, 0, 0]])
|
| 2475 |
+
|
| 2476 |
+
>>> A.upper_triangular(-1)
|
| 2477 |
+
Matrix([
|
| 2478 |
+
[1, 1, 1, 1],
|
| 2479 |
+
[1, 1, 1, 1],
|
| 2480 |
+
[0, 1, 1, 1],
|
| 2481 |
+
[0, 0, 1, 1]])
|
| 2482 |
+
|
| 2483 |
+
"""
|
| 2484 |
+
|
| 2485 |
+
def entry(i, j):
|
| 2486 |
+
return self[i, j] if i + k <= j else self.zero
|
| 2487 |
+
|
| 2488 |
+
return self._new(self.rows, self.cols, entry)
|
| 2489 |
+
|
| 2490 |
+
|
| 2491 |
+
def lower_triangular(self, k=0):
|
| 2492 |
+
"""Return the elements on and below the kth diagonal of a matrix.
|
| 2493 |
+
If k is not specified then simply returns lower-triangular portion
|
| 2494 |
+
of a matrix
|
| 2495 |
+
|
| 2496 |
+
Examples
|
| 2497 |
+
========
|
| 2498 |
+
|
| 2499 |
+
>>> from sympy import ones
|
| 2500 |
+
>>> A = ones(4)
|
| 2501 |
+
>>> A.lower_triangular()
|
| 2502 |
+
Matrix([
|
| 2503 |
+
[1, 0, 0, 0],
|
| 2504 |
+
[1, 1, 0, 0],
|
| 2505 |
+
[1, 1, 1, 0],
|
| 2506 |
+
[1, 1, 1, 1]])
|
| 2507 |
+
|
| 2508 |
+
>>> A.lower_triangular(-2)
|
| 2509 |
+
Matrix([
|
| 2510 |
+
[0, 0, 0, 0],
|
| 2511 |
+
[0, 0, 0, 0],
|
| 2512 |
+
[1, 0, 0, 0],
|
| 2513 |
+
[1, 1, 0, 0]])
|
| 2514 |
+
|
| 2515 |
+
>>> A.lower_triangular(1)
|
| 2516 |
+
Matrix([
|
| 2517 |
+
[1, 1, 0, 0],
|
| 2518 |
+
[1, 1, 1, 0],
|
| 2519 |
+
[1, 1, 1, 1],
|
| 2520 |
+
[1, 1, 1, 1]])
|
| 2521 |
+
|
| 2522 |
+
"""
|
| 2523 |
+
|
| 2524 |
+
def entry(i, j):
|
| 2525 |
+
return self[i, j] if i + k >= j else self.zero
|
| 2526 |
+
|
| 2527 |
+
return self._new(self.rows, self.cols, entry)
|
| 2528 |
+
|
| 2529 |
+
|
| 2530 |
+
|
| 2531 |
+
class MatrixArithmetic(MatrixRequired):
|
| 2532 |
+
"""Provides basic matrix arithmetic operations.
|
| 2533 |
+
Should not be instantiated directly."""
|
| 2534 |
+
|
| 2535 |
+
_op_priority = 10.01
|
| 2536 |
+
|
| 2537 |
+
def _eval_Abs(self):
|
| 2538 |
+
return self._new(self.rows, self.cols, lambda i, j: Abs(self[i, j]))
|
| 2539 |
+
|
| 2540 |
+
def _eval_add(self, other):
|
| 2541 |
+
return self._new(self.rows, self.cols,
|
| 2542 |
+
lambda i, j: self[i, j] + other[i, j])
|
| 2543 |
+
|
| 2544 |
+
def _eval_matrix_mul(self, other):
|
| 2545 |
+
def entry(i, j):
|
| 2546 |
+
vec = [self[i,k]*other[k,j] for k in range(self.cols)]
|
| 2547 |
+
try:
|
| 2548 |
+
return Add(*vec)
|
| 2549 |
+
except (TypeError, SympifyError):
|
| 2550 |
+
# Some matrices don't work with `sum` or `Add`
|
| 2551 |
+
# They don't work with `sum` because `sum` tries to add `0`
|
| 2552 |
+
# Fall back to a safe way to multiply if the `Add` fails.
|
| 2553 |
+
return reduce(lambda a, b: a + b, vec)
|
| 2554 |
+
|
| 2555 |
+
return self._new(self.rows, other.cols, entry)
|
| 2556 |
+
|
| 2557 |
+
def _eval_matrix_mul_elementwise(self, other):
|
| 2558 |
+
return self._new(self.rows, self.cols, lambda i, j: self[i,j]*other[i,j])
|
| 2559 |
+
|
| 2560 |
+
def _eval_matrix_rmul(self, other):
|
| 2561 |
+
def entry(i, j):
|
| 2562 |
+
return sum(other[i,k]*self[k,j] for k in range(other.cols))
|
| 2563 |
+
return self._new(other.rows, self.cols, entry)
|
| 2564 |
+
|
| 2565 |
+
def _eval_pow_by_recursion(self, num):
|
| 2566 |
+
if num == 1:
|
| 2567 |
+
return self
|
| 2568 |
+
|
| 2569 |
+
if num % 2 == 1:
|
| 2570 |
+
a, b = self, self._eval_pow_by_recursion(num - 1)
|
| 2571 |
+
else:
|
| 2572 |
+
a = b = self._eval_pow_by_recursion(num // 2)
|
| 2573 |
+
|
| 2574 |
+
return a.multiply(b)
|
| 2575 |
+
|
| 2576 |
+
def _eval_pow_by_cayley(self, exp):
|
| 2577 |
+
from sympy.discrete.recurrences import linrec_coeffs
|
| 2578 |
+
row = self.shape[0]
|
| 2579 |
+
p = self.charpoly()
|
| 2580 |
+
|
| 2581 |
+
coeffs = (-p).all_coeffs()[1:]
|
| 2582 |
+
coeffs = linrec_coeffs(coeffs, exp)
|
| 2583 |
+
new_mat = self.eye(row)
|
| 2584 |
+
ans = self.zeros(row)
|
| 2585 |
+
|
| 2586 |
+
for i in range(row):
|
| 2587 |
+
ans += coeffs[i]*new_mat
|
| 2588 |
+
new_mat *= self
|
| 2589 |
+
|
| 2590 |
+
return ans
|
| 2591 |
+
|
| 2592 |
+
def _eval_pow_by_recursion_dotprodsimp(self, num, prevsimp=None):
|
| 2593 |
+
if prevsimp is None:
|
| 2594 |
+
prevsimp = [True]*len(self)
|
| 2595 |
+
|
| 2596 |
+
if num == 1:
|
| 2597 |
+
return self
|
| 2598 |
+
|
| 2599 |
+
if num % 2 == 1:
|
| 2600 |
+
a, b = self, self._eval_pow_by_recursion_dotprodsimp(num - 1,
|
| 2601 |
+
prevsimp=prevsimp)
|
| 2602 |
+
else:
|
| 2603 |
+
a = b = self._eval_pow_by_recursion_dotprodsimp(num // 2,
|
| 2604 |
+
prevsimp=prevsimp)
|
| 2605 |
+
|
| 2606 |
+
m = a.multiply(b, dotprodsimp=False)
|
| 2607 |
+
lenm = len(m)
|
| 2608 |
+
elems = [None]*lenm
|
| 2609 |
+
|
| 2610 |
+
for i in range(lenm):
|
| 2611 |
+
if prevsimp[i]:
|
| 2612 |
+
elems[i], prevsimp[i] = _dotprodsimp(m[i], withsimp=True)
|
| 2613 |
+
else:
|
| 2614 |
+
elems[i] = m[i]
|
| 2615 |
+
|
| 2616 |
+
return m._new(m.rows, m.cols, elems)
|
| 2617 |
+
|
| 2618 |
+
def _eval_scalar_mul(self, other):
|
| 2619 |
+
return self._new(self.rows, self.cols, lambda i, j: self[i,j]*other)
|
| 2620 |
+
|
| 2621 |
+
def _eval_scalar_rmul(self, other):
|
| 2622 |
+
return self._new(self.rows, self.cols, lambda i, j: other*self[i,j])
|
| 2623 |
+
|
| 2624 |
+
def _eval_Mod(self, other):
|
| 2625 |
+
return self._new(self.rows, self.cols, lambda i, j: Mod(self[i, j], other))
|
| 2626 |
+
|
| 2627 |
+
# Python arithmetic functions
|
| 2628 |
+
def __abs__(self):
|
| 2629 |
+
"""Returns a new matrix with entry-wise absolute values."""
|
| 2630 |
+
return self._eval_Abs()
|
| 2631 |
+
|
| 2632 |
+
@call_highest_priority('__radd__')
|
| 2633 |
+
def __add__(self, other):
|
| 2634 |
+
"""Return self + other, raising ShapeError if shapes do not match."""
|
| 2635 |
+
if isinstance(other, NDimArray): # Matrix and array addition is currently not implemented
|
| 2636 |
+
return NotImplemented
|
| 2637 |
+
other = _matrixify(other)
|
| 2638 |
+
# matrix-like objects can have shapes. This is
|
| 2639 |
+
# our first sanity check.
|
| 2640 |
+
if hasattr(other, 'shape'):
|
| 2641 |
+
if self.shape != other.shape:
|
| 2642 |
+
raise ShapeError("Matrix size mismatch: %s + %s" % (
|
| 2643 |
+
self.shape, other.shape))
|
| 2644 |
+
|
| 2645 |
+
# honest SymPy matrices defer to their class's routine
|
| 2646 |
+
if getattr(other, 'is_Matrix', False):
|
| 2647 |
+
# call the highest-priority class's _eval_add
|
| 2648 |
+
a, b = self, other
|
| 2649 |
+
if a.__class__ != classof(a, b):
|
| 2650 |
+
b, a = a, b
|
| 2651 |
+
return a._eval_add(b)
|
| 2652 |
+
# Matrix-like objects can be passed to CommonMatrix routines directly.
|
| 2653 |
+
if getattr(other, 'is_MatrixLike', False):
|
| 2654 |
+
return MatrixArithmetic._eval_add(self, other)
|
| 2655 |
+
|
| 2656 |
+
raise TypeError('cannot add %s and %s' % (type(self), type(other)))
|
| 2657 |
+
|
| 2658 |
+
@call_highest_priority('__rtruediv__')
|
| 2659 |
+
def __truediv__(self, other):
|
| 2660 |
+
return self * (self.one / other)
|
| 2661 |
+
|
| 2662 |
+
@call_highest_priority('__rmatmul__')
|
| 2663 |
+
def __matmul__(self, other):
|
| 2664 |
+
other = _matrixify(other)
|
| 2665 |
+
if not getattr(other, 'is_Matrix', False) and not getattr(other, 'is_MatrixLike', False):
|
| 2666 |
+
return NotImplemented
|
| 2667 |
+
|
| 2668 |
+
return self.__mul__(other)
|
| 2669 |
+
|
| 2670 |
+
def __mod__(self, other):
|
| 2671 |
+
return self.applyfunc(lambda x: x % other)
|
| 2672 |
+
|
| 2673 |
+
@call_highest_priority('__rmul__')
|
| 2674 |
+
def __mul__(self, other):
|
| 2675 |
+
"""Return self*other where other is either a scalar or a matrix
|
| 2676 |
+
of compatible dimensions.
|
| 2677 |
+
|
| 2678 |
+
Examples
|
| 2679 |
+
========
|
| 2680 |
+
|
| 2681 |
+
>>> from sympy import Matrix
|
| 2682 |
+
>>> A = Matrix([[1, 2, 3], [4, 5, 6]])
|
| 2683 |
+
>>> 2*A == A*2 == Matrix([[2, 4, 6], [8, 10, 12]])
|
| 2684 |
+
True
|
| 2685 |
+
>>> B = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
|
| 2686 |
+
>>> A*B
|
| 2687 |
+
Matrix([
|
| 2688 |
+
[30, 36, 42],
|
| 2689 |
+
[66, 81, 96]])
|
| 2690 |
+
>>> B*A
|
| 2691 |
+
Traceback (most recent call last):
|
| 2692 |
+
...
|
| 2693 |
+
ShapeError: Matrices size mismatch.
|
| 2694 |
+
>>>
|
| 2695 |
+
|
| 2696 |
+
See Also
|
| 2697 |
+
========
|
| 2698 |
+
|
| 2699 |
+
matrix_multiply_elementwise
|
| 2700 |
+
"""
|
| 2701 |
+
|
| 2702 |
+
return self.multiply(other)
|
| 2703 |
+
|
| 2704 |
+
def multiply(self, other, dotprodsimp=None):
|
| 2705 |
+
"""Same as __mul__() but with optional simplification.
|
| 2706 |
+
|
| 2707 |
+
Parameters
|
| 2708 |
+
==========
|
| 2709 |
+
|
| 2710 |
+
dotprodsimp : bool, optional
|
| 2711 |
+
Specifies whether intermediate term algebraic simplification is used
|
| 2712 |
+
during matrix multiplications to control expression blowup and thus
|
| 2713 |
+
speed up calculation. Default is off.
|
| 2714 |
+
"""
|
| 2715 |
+
|
| 2716 |
+
isimpbool = _get_intermediate_simp_bool(False, dotprodsimp)
|
| 2717 |
+
other = _matrixify(other)
|
| 2718 |
+
# matrix-like objects can have shapes. This is
|
| 2719 |
+
# our first sanity check. Double check other is not explicitly not a Matrix.
|
| 2720 |
+
if (hasattr(other, 'shape') and len(other.shape) == 2 and
|
| 2721 |
+
(getattr(other, 'is_Matrix', True) or
|
| 2722 |
+
getattr(other, 'is_MatrixLike', True))):
|
| 2723 |
+
if self.shape[1] != other.shape[0]:
|
| 2724 |
+
raise ShapeError("Matrix size mismatch: %s * %s." % (
|
| 2725 |
+
self.shape, other.shape))
|
| 2726 |
+
|
| 2727 |
+
# honest SymPy matrices defer to their class's routine
|
| 2728 |
+
if getattr(other, 'is_Matrix', False):
|
| 2729 |
+
m = self._eval_matrix_mul(other)
|
| 2730 |
+
if isimpbool:
|
| 2731 |
+
return m._new(m.rows, m.cols, [_dotprodsimp(e) for e in m])
|
| 2732 |
+
return m
|
| 2733 |
+
|
| 2734 |
+
# Matrix-like objects can be passed to CommonMatrix routines directly.
|
| 2735 |
+
if getattr(other, 'is_MatrixLike', False):
|
| 2736 |
+
return MatrixArithmetic._eval_matrix_mul(self, other)
|
| 2737 |
+
|
| 2738 |
+
# if 'other' is not iterable then scalar multiplication.
|
| 2739 |
+
if not isinstance(other, Iterable):
|
| 2740 |
+
try:
|
| 2741 |
+
return self._eval_scalar_mul(other)
|
| 2742 |
+
except TypeError:
|
| 2743 |
+
pass
|
| 2744 |
+
|
| 2745 |
+
return NotImplemented
|
| 2746 |
+
|
| 2747 |
+
def multiply_elementwise(self, other):
|
| 2748 |
+
"""Return the Hadamard product (elementwise product) of A and B
|
| 2749 |
+
|
| 2750 |
+
Examples
|
| 2751 |
+
========
|
| 2752 |
+
|
| 2753 |
+
>>> from sympy import Matrix
|
| 2754 |
+
>>> A = Matrix([[0, 1, 2], [3, 4, 5]])
|
| 2755 |
+
>>> B = Matrix([[1, 10, 100], [100, 10, 1]])
|
| 2756 |
+
>>> A.multiply_elementwise(B)
|
| 2757 |
+
Matrix([
|
| 2758 |
+
[ 0, 10, 200],
|
| 2759 |
+
[300, 40, 5]])
|
| 2760 |
+
|
| 2761 |
+
See Also
|
| 2762 |
+
========
|
| 2763 |
+
|
| 2764 |
+
sympy.matrices.matrices.MatrixBase.cross
|
| 2765 |
+
sympy.matrices.matrices.MatrixBase.dot
|
| 2766 |
+
multiply
|
| 2767 |
+
"""
|
| 2768 |
+
if self.shape != other.shape:
|
| 2769 |
+
raise ShapeError("Matrix shapes must agree {} != {}".format(self.shape, other.shape))
|
| 2770 |
+
|
| 2771 |
+
return self._eval_matrix_mul_elementwise(other)
|
| 2772 |
+
|
| 2773 |
+
def __neg__(self):
|
| 2774 |
+
return self._eval_scalar_mul(-1)
|
| 2775 |
+
|
| 2776 |
+
@call_highest_priority('__rpow__')
|
| 2777 |
+
def __pow__(self, exp):
|
| 2778 |
+
"""Return self**exp a scalar or symbol."""
|
| 2779 |
+
|
| 2780 |
+
return self.pow(exp)
|
| 2781 |
+
|
| 2782 |
+
|
| 2783 |
+
def pow(self, exp, method=None):
|
| 2784 |
+
r"""Return self**exp a scalar or symbol.
|
| 2785 |
+
|
| 2786 |
+
Parameters
|
| 2787 |
+
==========
|
| 2788 |
+
|
| 2789 |
+
method : multiply, mulsimp, jordan, cayley
|
| 2790 |
+
If multiply then it returns exponentiation using recursion.
|
| 2791 |
+
If jordan then Jordan form exponentiation will be used.
|
| 2792 |
+
If cayley then the exponentiation is done using Cayley-Hamilton
|
| 2793 |
+
theorem.
|
| 2794 |
+
If mulsimp then the exponentiation is done using recursion
|
| 2795 |
+
with dotprodsimp. This specifies whether intermediate term
|
| 2796 |
+
algebraic simplification is used during naive matrix power to
|
| 2797 |
+
control expression blowup and thus speed up calculation.
|
| 2798 |
+
If None, then it heuristically decides which method to use.
|
| 2799 |
+
|
| 2800 |
+
"""
|
| 2801 |
+
|
| 2802 |
+
if method is not None and method not in ['multiply', 'mulsimp', 'jordan', 'cayley']:
|
| 2803 |
+
raise TypeError('No such method')
|
| 2804 |
+
if self.rows != self.cols:
|
| 2805 |
+
raise NonSquareMatrixError()
|
| 2806 |
+
a = self
|
| 2807 |
+
jordan_pow = getattr(a, '_matrix_pow_by_jordan_blocks', None)
|
| 2808 |
+
exp = sympify(exp)
|
| 2809 |
+
|
| 2810 |
+
if exp.is_zero:
|
| 2811 |
+
return a._new(a.rows, a.cols, lambda i, j: int(i == j))
|
| 2812 |
+
if exp == 1:
|
| 2813 |
+
return a
|
| 2814 |
+
|
| 2815 |
+
diagonal = getattr(a, 'is_diagonal', None)
|
| 2816 |
+
if diagonal is not None and diagonal():
|
| 2817 |
+
return a._new(a.rows, a.cols, lambda i, j: a[i,j]**exp if i == j else 0)
|
| 2818 |
+
|
| 2819 |
+
if exp.is_Number and exp % 1 == 0:
|
| 2820 |
+
if a.rows == 1:
|
| 2821 |
+
return a._new([[a[0]**exp]])
|
| 2822 |
+
if exp < 0:
|
| 2823 |
+
exp = -exp
|
| 2824 |
+
a = a.inv()
|
| 2825 |
+
# When certain conditions are met,
|
| 2826 |
+
# Jordan block algorithm is faster than
|
| 2827 |
+
# computation by recursion.
|
| 2828 |
+
if method == 'jordan':
|
| 2829 |
+
try:
|
| 2830 |
+
return jordan_pow(exp)
|
| 2831 |
+
except MatrixError:
|
| 2832 |
+
if method == 'jordan':
|
| 2833 |
+
raise
|
| 2834 |
+
|
| 2835 |
+
elif method == 'cayley':
|
| 2836 |
+
if not exp.is_Number or exp % 1 != 0:
|
| 2837 |
+
raise ValueError("cayley method is only valid for integer powers")
|
| 2838 |
+
return a._eval_pow_by_cayley(exp)
|
| 2839 |
+
|
| 2840 |
+
elif method == "mulsimp":
|
| 2841 |
+
if not exp.is_Number or exp % 1 != 0:
|
| 2842 |
+
raise ValueError("mulsimp method is only valid for integer powers")
|
| 2843 |
+
return a._eval_pow_by_recursion_dotprodsimp(exp)
|
| 2844 |
+
|
| 2845 |
+
elif method == "multiply":
|
| 2846 |
+
if not exp.is_Number or exp % 1 != 0:
|
| 2847 |
+
raise ValueError("multiply method is only valid for integer powers")
|
| 2848 |
+
return a._eval_pow_by_recursion(exp)
|
| 2849 |
+
|
| 2850 |
+
elif method is None and exp.is_Number and exp % 1 == 0:
|
| 2851 |
+
# Decide heuristically which method to apply
|
| 2852 |
+
if a.rows == 2 and exp > 100000:
|
| 2853 |
+
return jordan_pow(exp)
|
| 2854 |
+
elif _get_intermediate_simp_bool(True, None):
|
| 2855 |
+
return a._eval_pow_by_recursion_dotprodsimp(exp)
|
| 2856 |
+
elif exp > 10000:
|
| 2857 |
+
return a._eval_pow_by_cayley(exp)
|
| 2858 |
+
else:
|
| 2859 |
+
return a._eval_pow_by_recursion(exp)
|
| 2860 |
+
|
| 2861 |
+
if jordan_pow:
|
| 2862 |
+
try:
|
| 2863 |
+
return jordan_pow(exp)
|
| 2864 |
+
except NonInvertibleMatrixError:
|
| 2865 |
+
# Raised by jordan_pow on zero determinant matrix unless exp is
|
| 2866 |
+
# definitely known to be a non-negative integer.
|
| 2867 |
+
# Here we raise if n is definitely not a non-negative integer
|
| 2868 |
+
# but otherwise we can leave this as an unevaluated MatPow.
|
| 2869 |
+
if exp.is_integer is False or exp.is_nonnegative is False:
|
| 2870 |
+
raise
|
| 2871 |
+
|
| 2872 |
+
from sympy.matrices.expressions import MatPow
|
| 2873 |
+
return MatPow(a, exp)
|
| 2874 |
+
|
| 2875 |
+
@call_highest_priority('__add__')
|
| 2876 |
+
def __radd__(self, other):
|
| 2877 |
+
return self + other
|
| 2878 |
+
|
| 2879 |
+
@call_highest_priority('__matmul__')
|
| 2880 |
+
def __rmatmul__(self, other):
|
| 2881 |
+
other = _matrixify(other)
|
| 2882 |
+
if not getattr(other, 'is_Matrix', False) and not getattr(other, 'is_MatrixLike', False):
|
| 2883 |
+
return NotImplemented
|
| 2884 |
+
|
| 2885 |
+
return self.__rmul__(other)
|
| 2886 |
+
|
| 2887 |
+
@call_highest_priority('__mul__')
|
| 2888 |
+
def __rmul__(self, other):
|
| 2889 |
+
return self.rmultiply(other)
|
| 2890 |
+
|
| 2891 |
+
def rmultiply(self, other, dotprodsimp=None):
|
| 2892 |
+
"""Same as __rmul__() but with optional simplification.
|
| 2893 |
+
|
| 2894 |
+
Parameters
|
| 2895 |
+
==========
|
| 2896 |
+
|
| 2897 |
+
dotprodsimp : bool, optional
|
| 2898 |
+
Specifies whether intermediate term algebraic simplification is used
|
| 2899 |
+
during matrix multiplications to control expression blowup and thus
|
| 2900 |
+
speed up calculation. Default is off.
|
| 2901 |
+
"""
|
| 2902 |
+
isimpbool = _get_intermediate_simp_bool(False, dotprodsimp)
|
| 2903 |
+
other = _matrixify(other)
|
| 2904 |
+
# matrix-like objects can have shapes. This is
|
| 2905 |
+
# our first sanity check. Double check other is not explicitly not a Matrix.
|
| 2906 |
+
if (hasattr(other, 'shape') and len(other.shape) == 2 and
|
| 2907 |
+
(getattr(other, 'is_Matrix', True) or
|
| 2908 |
+
getattr(other, 'is_MatrixLike', True))):
|
| 2909 |
+
if self.shape[0] != other.shape[1]:
|
| 2910 |
+
raise ShapeError("Matrix size mismatch.")
|
| 2911 |
+
|
| 2912 |
+
# honest SymPy matrices defer to their class's routine
|
| 2913 |
+
if getattr(other, 'is_Matrix', False):
|
| 2914 |
+
m = self._eval_matrix_rmul(other)
|
| 2915 |
+
if isimpbool:
|
| 2916 |
+
return m._new(m.rows, m.cols, [_dotprodsimp(e) for e in m])
|
| 2917 |
+
return m
|
| 2918 |
+
# Matrix-like objects can be passed to CommonMatrix routines directly.
|
| 2919 |
+
if getattr(other, 'is_MatrixLike', False):
|
| 2920 |
+
return MatrixArithmetic._eval_matrix_rmul(self, other)
|
| 2921 |
+
|
| 2922 |
+
# if 'other' is not iterable then scalar multiplication.
|
| 2923 |
+
if not isinstance(other, Iterable):
|
| 2924 |
+
try:
|
| 2925 |
+
return self._eval_scalar_rmul(other)
|
| 2926 |
+
except TypeError:
|
| 2927 |
+
pass
|
| 2928 |
+
|
| 2929 |
+
return NotImplemented
|
| 2930 |
+
|
| 2931 |
+
@call_highest_priority('__sub__')
|
| 2932 |
+
def __rsub__(self, a):
|
| 2933 |
+
return (-self) + a
|
| 2934 |
+
|
| 2935 |
+
@call_highest_priority('__rsub__')
|
| 2936 |
+
def __sub__(self, a):
|
| 2937 |
+
return self + (-a)
|
| 2938 |
+
|
| 2939 |
+
class MatrixCommon(MatrixArithmetic, MatrixOperations, MatrixProperties,
|
| 2940 |
+
MatrixSpecial, MatrixShaping):
|
| 2941 |
+
"""All common matrix operations including basic arithmetic, shaping,
|
| 2942 |
+
and special matrices like `zeros`, and `eye`."""
|
| 2943 |
+
_diff_wrt = True # type: bool
|
| 2944 |
+
|
| 2945 |
+
|
| 2946 |
+
class _MinimalMatrix:
|
| 2947 |
+
"""Class providing the minimum functionality
|
| 2948 |
+
for a matrix-like object and implementing every method
|
| 2949 |
+
required for a `MatrixRequired`. This class does not have everything
|
| 2950 |
+
needed to become a full-fledged SymPy object, but it will satisfy the
|
| 2951 |
+
requirements of anything inheriting from `MatrixRequired`. If you wish
|
| 2952 |
+
to make a specialized matrix type, make sure to implement these
|
| 2953 |
+
methods and properties with the exception of `__init__` and `__repr__`
|
| 2954 |
+
which are included for convenience."""
|
| 2955 |
+
|
| 2956 |
+
is_MatrixLike = True
|
| 2957 |
+
_sympify = staticmethod(sympify)
|
| 2958 |
+
_class_priority = 3
|
| 2959 |
+
zero = S.Zero
|
| 2960 |
+
one = S.One
|
| 2961 |
+
|
| 2962 |
+
is_Matrix = True
|
| 2963 |
+
is_MatrixExpr = False
|
| 2964 |
+
|
| 2965 |
+
@classmethod
|
| 2966 |
+
def _new(cls, *args, **kwargs):
|
| 2967 |
+
return cls(*args, **kwargs)
|
| 2968 |
+
|
| 2969 |
+
def __init__(self, rows, cols=None, mat=None, copy=False):
|
| 2970 |
+
if isfunction(mat):
|
| 2971 |
+
# if we passed in a function, use that to populate the indices
|
| 2972 |
+
mat = [mat(i, j) for i in range(rows) for j in range(cols)]
|
| 2973 |
+
if cols is None and mat is None:
|
| 2974 |
+
mat = rows
|
| 2975 |
+
rows, cols = getattr(mat, 'shape', (rows, cols))
|
| 2976 |
+
try:
|
| 2977 |
+
# if we passed in a list of lists, flatten it and set the size
|
| 2978 |
+
if cols is None and mat is None:
|
| 2979 |
+
mat = rows
|
| 2980 |
+
cols = len(mat[0])
|
| 2981 |
+
rows = len(mat)
|
| 2982 |
+
mat = [x for l in mat for x in l]
|
| 2983 |
+
except (IndexError, TypeError):
|
| 2984 |
+
pass
|
| 2985 |
+
self.mat = tuple(self._sympify(x) for x in mat)
|
| 2986 |
+
self.rows, self.cols = rows, cols
|
| 2987 |
+
if self.rows is None or self.cols is None:
|
| 2988 |
+
raise NotImplementedError("Cannot initialize matrix with given parameters")
|
| 2989 |
+
|
| 2990 |
+
def __getitem__(self, key):
|
| 2991 |
+
def _normalize_slices(row_slice, col_slice):
|
| 2992 |
+
"""Ensure that row_slice and col_slice do not have
|
| 2993 |
+
`None` in their arguments. Any integers are converted
|
| 2994 |
+
to slices of length 1"""
|
| 2995 |
+
if not isinstance(row_slice, slice):
|
| 2996 |
+
row_slice = slice(row_slice, row_slice + 1, None)
|
| 2997 |
+
row_slice = slice(*row_slice.indices(self.rows))
|
| 2998 |
+
|
| 2999 |
+
if not isinstance(col_slice, slice):
|
| 3000 |
+
col_slice = slice(col_slice, col_slice + 1, None)
|
| 3001 |
+
col_slice = slice(*col_slice.indices(self.cols))
|
| 3002 |
+
|
| 3003 |
+
return (row_slice, col_slice)
|
| 3004 |
+
|
| 3005 |
+
def _coord_to_index(i, j):
|
| 3006 |
+
"""Return the index in _mat corresponding
|
| 3007 |
+
to the (i,j) position in the matrix. """
|
| 3008 |
+
return i * self.cols + j
|
| 3009 |
+
|
| 3010 |
+
if isinstance(key, tuple):
|
| 3011 |
+
i, j = key
|
| 3012 |
+
if isinstance(i, slice) or isinstance(j, slice):
|
| 3013 |
+
# if the coordinates are not slices, make them so
|
| 3014 |
+
# and expand the slices so they don't contain `None`
|
| 3015 |
+
i, j = _normalize_slices(i, j)
|
| 3016 |
+
|
| 3017 |
+
rowsList, colsList = list(range(self.rows))[i], \
|
| 3018 |
+
list(range(self.cols))[j]
|
| 3019 |
+
indices = (i * self.cols + j for i in rowsList for j in
|
| 3020 |
+
colsList)
|
| 3021 |
+
return self._new(len(rowsList), len(colsList),
|
| 3022 |
+
[self.mat[i] for i in indices])
|
| 3023 |
+
|
| 3024 |
+
# if the key is a tuple of ints, change
|
| 3025 |
+
# it to an array index
|
| 3026 |
+
key = _coord_to_index(i, j)
|
| 3027 |
+
return self.mat[key]
|
| 3028 |
+
|
| 3029 |
+
def __eq__(self, other):
|
| 3030 |
+
try:
|
| 3031 |
+
classof(self, other)
|
| 3032 |
+
except TypeError:
|
| 3033 |
+
return False
|
| 3034 |
+
return (
|
| 3035 |
+
self.shape == other.shape and list(self) == list(other))
|
| 3036 |
+
|
| 3037 |
+
def __len__(self):
|
| 3038 |
+
return self.rows*self.cols
|
| 3039 |
+
|
| 3040 |
+
def __repr__(self):
|
| 3041 |
+
return "_MinimalMatrix({}, {}, {})".format(self.rows, self.cols,
|
| 3042 |
+
self.mat)
|
| 3043 |
+
|
| 3044 |
+
@property
|
| 3045 |
+
def shape(self):
|
| 3046 |
+
return (self.rows, self.cols)
|
| 3047 |
+
|
| 3048 |
+
|
| 3049 |
+
class _CastableMatrix: # this is needed here ONLY FOR TESTS.
|
| 3050 |
+
def as_mutable(self):
|
| 3051 |
+
return self
|
| 3052 |
+
|
| 3053 |
+
def as_immutable(self):
|
| 3054 |
+
return self
|
| 3055 |
+
|
| 3056 |
+
|
| 3057 |
+
class _MatrixWrapper:
|
| 3058 |
+
"""Wrapper class providing the minimum functionality for a matrix-like
|
| 3059 |
+
object: .rows, .cols, .shape, indexability, and iterability. CommonMatrix
|
| 3060 |
+
math operations should work on matrix-like objects. This one is intended for
|
| 3061 |
+
matrix-like objects which use the same indexing format as SymPy with respect
|
| 3062 |
+
to returning matrix elements instead of rows for non-tuple indexes.
|
| 3063 |
+
"""
|
| 3064 |
+
|
| 3065 |
+
is_Matrix = False # needs to be here because of __getattr__
|
| 3066 |
+
is_MatrixLike = True
|
| 3067 |
+
|
| 3068 |
+
def __init__(self, mat, shape):
|
| 3069 |
+
self.mat = mat
|
| 3070 |
+
self.shape = shape
|
| 3071 |
+
self.rows, self.cols = shape
|
| 3072 |
+
|
| 3073 |
+
def __getitem__(self, key):
|
| 3074 |
+
if isinstance(key, tuple):
|
| 3075 |
+
return sympify(self.mat.__getitem__(key))
|
| 3076 |
+
|
| 3077 |
+
return sympify(self.mat.__getitem__((key // self.rows, key % self.cols)))
|
| 3078 |
+
|
| 3079 |
+
def __iter__(self): # supports numpy.matrix and numpy.array
|
| 3080 |
+
mat = self.mat
|
| 3081 |
+
cols = self.cols
|
| 3082 |
+
|
| 3083 |
+
return iter(sympify(mat[r, c]) for r in range(self.rows) for c in range(cols))
|
| 3084 |
+
|
| 3085 |
+
|
| 3086 |
+
class MatrixKind(Kind):
|
| 3087 |
+
"""
|
| 3088 |
+
Kind for all matrices in SymPy.
|
| 3089 |
+
|
| 3090 |
+
Basic class for this kind is ``MatrixBase`` and ``MatrixExpr``,
|
| 3091 |
+
but any expression representing the matrix can have this.
|
| 3092 |
+
|
| 3093 |
+
Parameters
|
| 3094 |
+
==========
|
| 3095 |
+
|
| 3096 |
+
element_kind : Kind
|
| 3097 |
+
Kind of the element. Default is
|
| 3098 |
+
:class:`sympy.core.kind.NumberKind`,
|
| 3099 |
+
which means that the matrix contains only numbers.
|
| 3100 |
+
|
| 3101 |
+
Examples
|
| 3102 |
+
========
|
| 3103 |
+
|
| 3104 |
+
Any instance of matrix class has ``MatrixKind``:
|
| 3105 |
+
|
| 3106 |
+
>>> from sympy import MatrixSymbol
|
| 3107 |
+
>>> A = MatrixSymbol('A', 2,2)
|
| 3108 |
+
>>> A.kind
|
| 3109 |
+
MatrixKind(NumberKind)
|
| 3110 |
+
|
| 3111 |
+
Although expression representing a matrix may be not instance of
|
| 3112 |
+
matrix class, it will have ``MatrixKind`` as well:
|
| 3113 |
+
|
| 3114 |
+
>>> from sympy import MatrixExpr, Integral
|
| 3115 |
+
>>> from sympy.abc import x
|
| 3116 |
+
>>> intM = Integral(A, x)
|
| 3117 |
+
>>> isinstance(intM, MatrixExpr)
|
| 3118 |
+
False
|
| 3119 |
+
>>> intM.kind
|
| 3120 |
+
MatrixKind(NumberKind)
|
| 3121 |
+
|
| 3122 |
+
Use ``isinstance()`` to check for ``MatrixKind`` without specifying
|
| 3123 |
+
the element kind. Use ``is`` with specifying the element kind:
|
| 3124 |
+
|
| 3125 |
+
>>> from sympy import Matrix
|
| 3126 |
+
>>> from sympy.core import NumberKind
|
| 3127 |
+
>>> from sympy.matrices import MatrixKind
|
| 3128 |
+
>>> M = Matrix([1, 2])
|
| 3129 |
+
>>> isinstance(M.kind, MatrixKind)
|
| 3130 |
+
True
|
| 3131 |
+
>>> M.kind is MatrixKind(NumberKind)
|
| 3132 |
+
True
|
| 3133 |
+
|
| 3134 |
+
See Also
|
| 3135 |
+
========
|
| 3136 |
+
|
| 3137 |
+
sympy.core.kind.NumberKind
|
| 3138 |
+
sympy.core.kind.UndefinedKind
|
| 3139 |
+
sympy.core.containers.TupleKind
|
| 3140 |
+
sympy.sets.sets.SetKind
|
| 3141 |
+
|
| 3142 |
+
"""
|
| 3143 |
+
def __new__(cls, element_kind=NumberKind):
|
| 3144 |
+
obj = super().__new__(cls, element_kind)
|
| 3145 |
+
obj.element_kind = element_kind
|
| 3146 |
+
return obj
|
| 3147 |
+
|
| 3148 |
+
def __repr__(self):
|
| 3149 |
+
return "MatrixKind(%s)" % self.element_kind
|
| 3150 |
+
|
| 3151 |
+
|
| 3152 |
+
def _matrixify(mat):
|
| 3153 |
+
"""If `mat` is a Matrix or is matrix-like,
|
| 3154 |
+
return a Matrix or MatrixWrapper object. Otherwise
|
| 3155 |
+
`mat` is passed through without modification."""
|
| 3156 |
+
|
| 3157 |
+
if getattr(mat, 'is_Matrix', False) or getattr(mat, 'is_MatrixLike', False):
|
| 3158 |
+
return mat
|
| 3159 |
+
|
| 3160 |
+
if not(getattr(mat, 'is_Matrix', True) or getattr(mat, 'is_MatrixLike', True)):
|
| 3161 |
+
return mat
|
| 3162 |
+
|
| 3163 |
+
shape = None
|
| 3164 |
+
|
| 3165 |
+
if hasattr(mat, 'shape'): # numpy, scipy.sparse
|
| 3166 |
+
if len(mat.shape) == 2:
|
| 3167 |
+
shape = mat.shape
|
| 3168 |
+
elif hasattr(mat, 'rows') and hasattr(mat, 'cols'): # mpmath
|
| 3169 |
+
shape = (mat.rows, mat.cols)
|
| 3170 |
+
|
| 3171 |
+
if shape:
|
| 3172 |
+
return _MatrixWrapper(mat, shape)
|
| 3173 |
+
|
| 3174 |
+
return mat
|
| 3175 |
+
|
| 3176 |
+
|
| 3177 |
+
def a2idx(j, n=None):
|
| 3178 |
+
"""Return integer after making positive and validating against n."""
|
| 3179 |
+
if not isinstance(j, int):
|
| 3180 |
+
jindex = getattr(j, '__index__', None)
|
| 3181 |
+
if jindex is not None:
|
| 3182 |
+
j = jindex()
|
| 3183 |
+
else:
|
| 3184 |
+
raise IndexError("Invalid index a[%r]" % (j,))
|
| 3185 |
+
if n is not None:
|
| 3186 |
+
if j < 0:
|
| 3187 |
+
j += n
|
| 3188 |
+
if not (j >= 0 and j < n):
|
| 3189 |
+
raise IndexError("Index out of range: a[%s]" % (j,))
|
| 3190 |
+
return int(j)
|
| 3191 |
+
|
| 3192 |
+
|
| 3193 |
+
def classof(A, B):
|
| 3194 |
+
"""
|
| 3195 |
+
Get the type of the result when combining matrices of different types.
|
| 3196 |
+
|
| 3197 |
+
Currently the strategy is that immutability is contagious.
|
| 3198 |
+
|
| 3199 |
+
Examples
|
| 3200 |
+
========
|
| 3201 |
+
|
| 3202 |
+
>>> from sympy import Matrix, ImmutableMatrix
|
| 3203 |
+
>>> from sympy.matrices.common import classof
|
| 3204 |
+
>>> M = Matrix([[1, 2], [3, 4]]) # a Mutable Matrix
|
| 3205 |
+
>>> IM = ImmutableMatrix([[1, 2], [3, 4]])
|
| 3206 |
+
>>> classof(M, IM)
|
| 3207 |
+
<class 'sympy.matrices.immutable.ImmutableDenseMatrix'>
|
| 3208 |
+
"""
|
| 3209 |
+
priority_A = getattr(A, '_class_priority', None)
|
| 3210 |
+
priority_B = getattr(B, '_class_priority', None)
|
| 3211 |
+
if None not in (priority_A, priority_B):
|
| 3212 |
+
if A._class_priority > B._class_priority:
|
| 3213 |
+
return A.__class__
|
| 3214 |
+
else:
|
| 3215 |
+
return B.__class__
|
| 3216 |
+
|
| 3217 |
+
try:
|
| 3218 |
+
import numpy
|
| 3219 |
+
except ImportError:
|
| 3220 |
+
pass
|
| 3221 |
+
else:
|
| 3222 |
+
if isinstance(A, numpy.ndarray):
|
| 3223 |
+
return B.__class__
|
| 3224 |
+
if isinstance(B, numpy.ndarray):
|
| 3225 |
+
return A.__class__
|
| 3226 |
+
|
| 3227 |
+
raise TypeError("Incompatible classes %s, %s" % (A.__class__, B.__class__))
|
venv/lib/python3.10/site-packages/sympy/matrices/decompositions.py
ADDED
|
@@ -0,0 +1,1629 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import copy
|
| 2 |
+
|
| 3 |
+
from sympy.core import S
|
| 4 |
+
from sympy.core.function import expand_mul
|
| 5 |
+
from sympy.functions.elementary.miscellaneous import Min, sqrt
|
| 6 |
+
from sympy.functions.elementary.complexes import sign
|
| 7 |
+
|
| 8 |
+
from .common import NonSquareMatrixError, NonPositiveDefiniteMatrixError
|
| 9 |
+
from .utilities import _get_intermediate_simp, _iszero
|
| 10 |
+
from .determinant import _find_reasonable_pivot_naive
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def _rank_decomposition(M, iszerofunc=_iszero, simplify=False):
|
| 14 |
+
r"""Returns a pair of matrices (`C`, `F`) with matching rank
|
| 15 |
+
such that `A = C F`.
|
| 16 |
+
|
| 17 |
+
Parameters
|
| 18 |
+
==========
|
| 19 |
+
|
| 20 |
+
iszerofunc : Function, optional
|
| 21 |
+
A function used for detecting whether an element can
|
| 22 |
+
act as a pivot. ``lambda x: x.is_zero`` is used by default.
|
| 23 |
+
|
| 24 |
+
simplify : Bool or Function, optional
|
| 25 |
+
A function used to simplify elements when looking for a
|
| 26 |
+
pivot. By default SymPy's ``simplify`` is used.
|
| 27 |
+
|
| 28 |
+
Returns
|
| 29 |
+
=======
|
| 30 |
+
|
| 31 |
+
(C, F) : Matrices
|
| 32 |
+
`C` and `F` are full-rank matrices with rank as same as `A`,
|
| 33 |
+
whose product gives `A`.
|
| 34 |
+
|
| 35 |
+
See Notes for additional mathematical details.
|
| 36 |
+
|
| 37 |
+
Examples
|
| 38 |
+
========
|
| 39 |
+
|
| 40 |
+
>>> from sympy import Matrix
|
| 41 |
+
>>> A = Matrix([
|
| 42 |
+
... [1, 3, 1, 4],
|
| 43 |
+
... [2, 7, 3, 9],
|
| 44 |
+
... [1, 5, 3, 1],
|
| 45 |
+
... [1, 2, 0, 8]
|
| 46 |
+
... ])
|
| 47 |
+
>>> C, F = A.rank_decomposition()
|
| 48 |
+
>>> C
|
| 49 |
+
Matrix([
|
| 50 |
+
[1, 3, 4],
|
| 51 |
+
[2, 7, 9],
|
| 52 |
+
[1, 5, 1],
|
| 53 |
+
[1, 2, 8]])
|
| 54 |
+
>>> F
|
| 55 |
+
Matrix([
|
| 56 |
+
[1, 0, -2, 0],
|
| 57 |
+
[0, 1, 1, 0],
|
| 58 |
+
[0, 0, 0, 1]])
|
| 59 |
+
>>> C * F == A
|
| 60 |
+
True
|
| 61 |
+
|
| 62 |
+
Notes
|
| 63 |
+
=====
|
| 64 |
+
|
| 65 |
+
Obtaining `F`, an RREF of `A`, is equivalent to creating a
|
| 66 |
+
product
|
| 67 |
+
|
| 68 |
+
.. math::
|
| 69 |
+
E_n E_{n-1} ... E_1 A = F
|
| 70 |
+
|
| 71 |
+
where `E_n, E_{n-1}, \dots, E_1` are the elimination matrices or
|
| 72 |
+
permutation matrices equivalent to each row-reduction step.
|
| 73 |
+
|
| 74 |
+
The inverse of the same product of elimination matrices gives
|
| 75 |
+
`C`:
|
| 76 |
+
|
| 77 |
+
.. math::
|
| 78 |
+
C = \left(E_n E_{n-1} \dots E_1\right)^{-1}
|
| 79 |
+
|
| 80 |
+
It is not necessary, however, to actually compute the inverse:
|
| 81 |
+
the columns of `C` are those from the original matrix with the
|
| 82 |
+
same column indices as the indices of the pivot columns of `F`.
|
| 83 |
+
|
| 84 |
+
References
|
| 85 |
+
==========
|
| 86 |
+
|
| 87 |
+
.. [1] https://en.wikipedia.org/wiki/Rank_factorization
|
| 88 |
+
|
| 89 |
+
.. [2] Piziak, R.; Odell, P. L. (1 June 1999).
|
| 90 |
+
"Full Rank Factorization of Matrices".
|
| 91 |
+
Mathematics Magazine. 72 (3): 193. doi:10.2307/2690882
|
| 92 |
+
|
| 93 |
+
See Also
|
| 94 |
+
========
|
| 95 |
+
|
| 96 |
+
sympy.matrices.matrices.MatrixReductions.rref
|
| 97 |
+
"""
|
| 98 |
+
|
| 99 |
+
F, pivot_cols = M.rref(simplify=simplify, iszerofunc=iszerofunc,
|
| 100 |
+
pivots=True)
|
| 101 |
+
rank = len(pivot_cols)
|
| 102 |
+
|
| 103 |
+
C = M.extract(range(M.rows), pivot_cols)
|
| 104 |
+
F = F[:rank, :]
|
| 105 |
+
|
| 106 |
+
return C, F
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def _liupc(M):
|
| 110 |
+
"""Liu's algorithm, for pre-determination of the Elimination Tree of
|
| 111 |
+
the given matrix, used in row-based symbolic Cholesky factorization.
|
| 112 |
+
|
| 113 |
+
Examples
|
| 114 |
+
========
|
| 115 |
+
|
| 116 |
+
>>> from sympy import SparseMatrix
|
| 117 |
+
>>> S = SparseMatrix([
|
| 118 |
+
... [1, 0, 3, 2],
|
| 119 |
+
... [0, 0, 1, 0],
|
| 120 |
+
... [4, 0, 0, 5],
|
| 121 |
+
... [0, 6, 7, 0]])
|
| 122 |
+
>>> S.liupc()
|
| 123 |
+
([[0], [], [0], [1, 2]], [4, 3, 4, 4])
|
| 124 |
+
|
| 125 |
+
References
|
| 126 |
+
==========
|
| 127 |
+
|
| 128 |
+
.. [1] Symbolic Sparse Cholesky Factorization using Elimination Trees,
|
| 129 |
+
Jeroen Van Grondelle (1999)
|
| 130 |
+
https://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.39.7582
|
| 131 |
+
"""
|
| 132 |
+
# Algorithm 2.4, p 17 of reference
|
| 133 |
+
|
| 134 |
+
# get the indices of the elements that are non-zero on or below diag
|
| 135 |
+
R = [[] for r in range(M.rows)]
|
| 136 |
+
|
| 137 |
+
for r, c, _ in M.row_list():
|
| 138 |
+
if c <= r:
|
| 139 |
+
R[r].append(c)
|
| 140 |
+
|
| 141 |
+
inf = len(R) # nothing will be this large
|
| 142 |
+
parent = [inf]*M.rows
|
| 143 |
+
virtual = [inf]*M.rows
|
| 144 |
+
|
| 145 |
+
for r in range(M.rows):
|
| 146 |
+
for c in R[r][:-1]:
|
| 147 |
+
while virtual[c] < r:
|
| 148 |
+
t = virtual[c]
|
| 149 |
+
virtual[c] = r
|
| 150 |
+
c = t
|
| 151 |
+
|
| 152 |
+
if virtual[c] == inf:
|
| 153 |
+
parent[c] = virtual[c] = r
|
| 154 |
+
|
| 155 |
+
return R, parent
|
| 156 |
+
|
| 157 |
+
def _row_structure_symbolic_cholesky(M):
|
| 158 |
+
"""Symbolic cholesky factorization, for pre-determination of the
|
| 159 |
+
non-zero structure of the Cholesky factororization.
|
| 160 |
+
|
| 161 |
+
Examples
|
| 162 |
+
========
|
| 163 |
+
|
| 164 |
+
>>> from sympy import SparseMatrix
|
| 165 |
+
>>> S = SparseMatrix([
|
| 166 |
+
... [1, 0, 3, 2],
|
| 167 |
+
... [0, 0, 1, 0],
|
| 168 |
+
... [4, 0, 0, 5],
|
| 169 |
+
... [0, 6, 7, 0]])
|
| 170 |
+
>>> S.row_structure_symbolic_cholesky()
|
| 171 |
+
[[0], [], [0], [1, 2]]
|
| 172 |
+
|
| 173 |
+
References
|
| 174 |
+
==========
|
| 175 |
+
|
| 176 |
+
.. [1] Symbolic Sparse Cholesky Factorization using Elimination Trees,
|
| 177 |
+
Jeroen Van Grondelle (1999)
|
| 178 |
+
https://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.39.7582
|
| 179 |
+
"""
|
| 180 |
+
|
| 181 |
+
R, parent = M.liupc()
|
| 182 |
+
inf = len(R) # this acts as infinity
|
| 183 |
+
Lrow = copy.deepcopy(R)
|
| 184 |
+
|
| 185 |
+
for k in range(M.rows):
|
| 186 |
+
for j in R[k]:
|
| 187 |
+
while j != inf and j != k:
|
| 188 |
+
Lrow[k].append(j)
|
| 189 |
+
j = parent[j]
|
| 190 |
+
|
| 191 |
+
Lrow[k] = sorted(set(Lrow[k]))
|
| 192 |
+
|
| 193 |
+
return Lrow
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
def _cholesky(M, hermitian=True):
|
| 197 |
+
"""Returns the Cholesky-type decomposition L of a matrix A
|
| 198 |
+
such that L * L.H == A if hermitian flag is True,
|
| 199 |
+
or L * L.T == A if hermitian is False.
|
| 200 |
+
|
| 201 |
+
A must be a Hermitian positive-definite matrix if hermitian is True,
|
| 202 |
+
or a symmetric matrix if it is False.
|
| 203 |
+
|
| 204 |
+
Examples
|
| 205 |
+
========
|
| 206 |
+
|
| 207 |
+
>>> from sympy import Matrix
|
| 208 |
+
>>> A = Matrix(((25, 15, -5), (15, 18, 0), (-5, 0, 11)))
|
| 209 |
+
>>> A.cholesky()
|
| 210 |
+
Matrix([
|
| 211 |
+
[ 5, 0, 0],
|
| 212 |
+
[ 3, 3, 0],
|
| 213 |
+
[-1, 1, 3]])
|
| 214 |
+
>>> A.cholesky() * A.cholesky().T
|
| 215 |
+
Matrix([
|
| 216 |
+
[25, 15, -5],
|
| 217 |
+
[15, 18, 0],
|
| 218 |
+
[-5, 0, 11]])
|
| 219 |
+
|
| 220 |
+
The matrix can have complex entries:
|
| 221 |
+
|
| 222 |
+
>>> from sympy import I
|
| 223 |
+
>>> A = Matrix(((9, 3*I), (-3*I, 5)))
|
| 224 |
+
>>> A.cholesky()
|
| 225 |
+
Matrix([
|
| 226 |
+
[ 3, 0],
|
| 227 |
+
[-I, 2]])
|
| 228 |
+
>>> A.cholesky() * A.cholesky().H
|
| 229 |
+
Matrix([
|
| 230 |
+
[ 9, 3*I],
|
| 231 |
+
[-3*I, 5]])
|
| 232 |
+
|
| 233 |
+
Non-hermitian Cholesky-type decomposition may be useful when the
|
| 234 |
+
matrix is not positive-definite.
|
| 235 |
+
|
| 236 |
+
>>> A = Matrix([[1, 2], [2, 1]])
|
| 237 |
+
>>> L = A.cholesky(hermitian=False)
|
| 238 |
+
>>> L
|
| 239 |
+
Matrix([
|
| 240 |
+
[1, 0],
|
| 241 |
+
[2, sqrt(3)*I]])
|
| 242 |
+
>>> L*L.T == A
|
| 243 |
+
True
|
| 244 |
+
|
| 245 |
+
See Also
|
| 246 |
+
========
|
| 247 |
+
|
| 248 |
+
sympy.matrices.dense.DenseMatrix.LDLdecomposition
|
| 249 |
+
sympy.matrices.matrices.MatrixBase.LUdecomposition
|
| 250 |
+
QRdecomposition
|
| 251 |
+
"""
|
| 252 |
+
|
| 253 |
+
from .dense import MutableDenseMatrix
|
| 254 |
+
|
| 255 |
+
if not M.is_square:
|
| 256 |
+
raise NonSquareMatrixError("Matrix must be square.")
|
| 257 |
+
if hermitian and not M.is_hermitian:
|
| 258 |
+
raise ValueError("Matrix must be Hermitian.")
|
| 259 |
+
if not hermitian and not M.is_symmetric():
|
| 260 |
+
raise ValueError("Matrix must be symmetric.")
|
| 261 |
+
|
| 262 |
+
L = MutableDenseMatrix.zeros(M.rows, M.rows)
|
| 263 |
+
|
| 264 |
+
if hermitian:
|
| 265 |
+
for i in range(M.rows):
|
| 266 |
+
for j in range(i):
|
| 267 |
+
L[i, j] = ((1 / L[j, j])*(M[i, j] -
|
| 268 |
+
sum(L[i, k]*L[j, k].conjugate() for k in range(j))))
|
| 269 |
+
|
| 270 |
+
Lii2 = (M[i, i] -
|
| 271 |
+
sum(L[i, k]*L[i, k].conjugate() for k in range(i)))
|
| 272 |
+
|
| 273 |
+
if Lii2.is_positive is False:
|
| 274 |
+
raise NonPositiveDefiniteMatrixError(
|
| 275 |
+
"Matrix must be positive-definite")
|
| 276 |
+
|
| 277 |
+
L[i, i] = sqrt(Lii2)
|
| 278 |
+
|
| 279 |
+
else:
|
| 280 |
+
for i in range(M.rows):
|
| 281 |
+
for j in range(i):
|
| 282 |
+
L[i, j] = ((1 / L[j, j])*(M[i, j] -
|
| 283 |
+
sum(L[i, k]*L[j, k] for k in range(j))))
|
| 284 |
+
|
| 285 |
+
L[i, i] = sqrt(M[i, i] -
|
| 286 |
+
sum(L[i, k]**2 for k in range(i)))
|
| 287 |
+
|
| 288 |
+
return M._new(L)
|
| 289 |
+
|
| 290 |
+
def _cholesky_sparse(M, hermitian=True):
|
| 291 |
+
"""
|
| 292 |
+
Returns the Cholesky decomposition L of a matrix A
|
| 293 |
+
such that L * L.T = A
|
| 294 |
+
|
| 295 |
+
A must be a square, symmetric, positive-definite
|
| 296 |
+
and non-singular matrix
|
| 297 |
+
|
| 298 |
+
Examples
|
| 299 |
+
========
|
| 300 |
+
|
| 301 |
+
>>> from sympy import SparseMatrix
|
| 302 |
+
>>> A = SparseMatrix(((25,15,-5),(15,18,0),(-5,0,11)))
|
| 303 |
+
>>> A.cholesky()
|
| 304 |
+
Matrix([
|
| 305 |
+
[ 5, 0, 0],
|
| 306 |
+
[ 3, 3, 0],
|
| 307 |
+
[-1, 1, 3]])
|
| 308 |
+
>>> A.cholesky() * A.cholesky().T == A
|
| 309 |
+
True
|
| 310 |
+
|
| 311 |
+
The matrix can have complex entries:
|
| 312 |
+
|
| 313 |
+
>>> from sympy import I
|
| 314 |
+
>>> A = SparseMatrix(((9, 3*I), (-3*I, 5)))
|
| 315 |
+
>>> A.cholesky()
|
| 316 |
+
Matrix([
|
| 317 |
+
[ 3, 0],
|
| 318 |
+
[-I, 2]])
|
| 319 |
+
>>> A.cholesky() * A.cholesky().H
|
| 320 |
+
Matrix([
|
| 321 |
+
[ 9, 3*I],
|
| 322 |
+
[-3*I, 5]])
|
| 323 |
+
|
| 324 |
+
Non-hermitian Cholesky-type decomposition may be useful when the
|
| 325 |
+
matrix is not positive-definite.
|
| 326 |
+
|
| 327 |
+
>>> A = SparseMatrix([[1, 2], [2, 1]])
|
| 328 |
+
>>> L = A.cholesky(hermitian=False)
|
| 329 |
+
>>> L
|
| 330 |
+
Matrix([
|
| 331 |
+
[1, 0],
|
| 332 |
+
[2, sqrt(3)*I]])
|
| 333 |
+
>>> L*L.T == A
|
| 334 |
+
True
|
| 335 |
+
|
| 336 |
+
See Also
|
| 337 |
+
========
|
| 338 |
+
|
| 339 |
+
sympy.matrices.sparse.SparseMatrix.LDLdecomposition
|
| 340 |
+
sympy.matrices.matrices.MatrixBase.LUdecomposition
|
| 341 |
+
QRdecomposition
|
| 342 |
+
"""
|
| 343 |
+
|
| 344 |
+
from .dense import MutableDenseMatrix
|
| 345 |
+
|
| 346 |
+
if not M.is_square:
|
| 347 |
+
raise NonSquareMatrixError("Matrix must be square.")
|
| 348 |
+
if hermitian and not M.is_hermitian:
|
| 349 |
+
raise ValueError("Matrix must be Hermitian.")
|
| 350 |
+
if not hermitian and not M.is_symmetric():
|
| 351 |
+
raise ValueError("Matrix must be symmetric.")
|
| 352 |
+
|
| 353 |
+
dps = _get_intermediate_simp(expand_mul, expand_mul)
|
| 354 |
+
Crowstruc = M.row_structure_symbolic_cholesky()
|
| 355 |
+
C = MutableDenseMatrix.zeros(M.rows)
|
| 356 |
+
|
| 357 |
+
for i in range(len(Crowstruc)):
|
| 358 |
+
for j in Crowstruc[i]:
|
| 359 |
+
if i != j:
|
| 360 |
+
C[i, j] = M[i, j]
|
| 361 |
+
summ = 0
|
| 362 |
+
|
| 363 |
+
for p1 in Crowstruc[i]:
|
| 364 |
+
if p1 < j:
|
| 365 |
+
for p2 in Crowstruc[j]:
|
| 366 |
+
if p2 < j:
|
| 367 |
+
if p1 == p2:
|
| 368 |
+
if hermitian:
|
| 369 |
+
summ += C[i, p1]*C[j, p1].conjugate()
|
| 370 |
+
else:
|
| 371 |
+
summ += C[i, p1]*C[j, p1]
|
| 372 |
+
else:
|
| 373 |
+
break
|
| 374 |
+
else:
|
| 375 |
+
break
|
| 376 |
+
|
| 377 |
+
C[i, j] = dps((C[i, j] - summ) / C[j, j])
|
| 378 |
+
|
| 379 |
+
else: # i == j
|
| 380 |
+
C[j, j] = M[j, j]
|
| 381 |
+
summ = 0
|
| 382 |
+
|
| 383 |
+
for k in Crowstruc[j]:
|
| 384 |
+
if k < j:
|
| 385 |
+
if hermitian:
|
| 386 |
+
summ += C[j, k]*C[j, k].conjugate()
|
| 387 |
+
else:
|
| 388 |
+
summ += C[j, k]**2
|
| 389 |
+
else:
|
| 390 |
+
break
|
| 391 |
+
|
| 392 |
+
Cjj2 = dps(C[j, j] - summ)
|
| 393 |
+
|
| 394 |
+
if hermitian and Cjj2.is_positive is False:
|
| 395 |
+
raise NonPositiveDefiniteMatrixError(
|
| 396 |
+
"Matrix must be positive-definite")
|
| 397 |
+
|
| 398 |
+
C[j, j] = sqrt(Cjj2)
|
| 399 |
+
|
| 400 |
+
return M._new(C)
|
| 401 |
+
|
| 402 |
+
|
| 403 |
+
def _LDLdecomposition(M, hermitian=True):
|
| 404 |
+
"""Returns the LDL Decomposition (L, D) of matrix A,
|
| 405 |
+
such that L * D * L.H == A if hermitian flag is True, or
|
| 406 |
+
L * D * L.T == A if hermitian is False.
|
| 407 |
+
This method eliminates the use of square root.
|
| 408 |
+
Further this ensures that all the diagonal entries of L are 1.
|
| 409 |
+
A must be a Hermitian positive-definite matrix if hermitian is True,
|
| 410 |
+
or a symmetric matrix otherwise.
|
| 411 |
+
|
| 412 |
+
Examples
|
| 413 |
+
========
|
| 414 |
+
|
| 415 |
+
>>> from sympy import Matrix, eye
|
| 416 |
+
>>> A = Matrix(((25, 15, -5), (15, 18, 0), (-5, 0, 11)))
|
| 417 |
+
>>> L, D = A.LDLdecomposition()
|
| 418 |
+
>>> L
|
| 419 |
+
Matrix([
|
| 420 |
+
[ 1, 0, 0],
|
| 421 |
+
[ 3/5, 1, 0],
|
| 422 |
+
[-1/5, 1/3, 1]])
|
| 423 |
+
>>> D
|
| 424 |
+
Matrix([
|
| 425 |
+
[25, 0, 0],
|
| 426 |
+
[ 0, 9, 0],
|
| 427 |
+
[ 0, 0, 9]])
|
| 428 |
+
>>> L * D * L.T * A.inv() == eye(A.rows)
|
| 429 |
+
True
|
| 430 |
+
|
| 431 |
+
The matrix can have complex entries:
|
| 432 |
+
|
| 433 |
+
>>> from sympy import I
|
| 434 |
+
>>> A = Matrix(((9, 3*I), (-3*I, 5)))
|
| 435 |
+
>>> L, D = A.LDLdecomposition()
|
| 436 |
+
>>> L
|
| 437 |
+
Matrix([
|
| 438 |
+
[ 1, 0],
|
| 439 |
+
[-I/3, 1]])
|
| 440 |
+
>>> D
|
| 441 |
+
Matrix([
|
| 442 |
+
[9, 0],
|
| 443 |
+
[0, 4]])
|
| 444 |
+
>>> L*D*L.H == A
|
| 445 |
+
True
|
| 446 |
+
|
| 447 |
+
See Also
|
| 448 |
+
========
|
| 449 |
+
|
| 450 |
+
sympy.matrices.dense.DenseMatrix.cholesky
|
| 451 |
+
sympy.matrices.matrices.MatrixBase.LUdecomposition
|
| 452 |
+
QRdecomposition
|
| 453 |
+
"""
|
| 454 |
+
|
| 455 |
+
from .dense import MutableDenseMatrix
|
| 456 |
+
|
| 457 |
+
if not M.is_square:
|
| 458 |
+
raise NonSquareMatrixError("Matrix must be square.")
|
| 459 |
+
if hermitian and not M.is_hermitian:
|
| 460 |
+
raise ValueError("Matrix must be Hermitian.")
|
| 461 |
+
if not hermitian and not M.is_symmetric():
|
| 462 |
+
raise ValueError("Matrix must be symmetric.")
|
| 463 |
+
|
| 464 |
+
D = MutableDenseMatrix.zeros(M.rows, M.rows)
|
| 465 |
+
L = MutableDenseMatrix.eye(M.rows)
|
| 466 |
+
|
| 467 |
+
if hermitian:
|
| 468 |
+
for i in range(M.rows):
|
| 469 |
+
for j in range(i):
|
| 470 |
+
L[i, j] = (1 / D[j, j])*(M[i, j] - sum(
|
| 471 |
+
L[i, k]*L[j, k].conjugate()*D[k, k] for k in range(j)))
|
| 472 |
+
|
| 473 |
+
D[i, i] = (M[i, i] -
|
| 474 |
+
sum(L[i, k]*L[i, k].conjugate()*D[k, k] for k in range(i)))
|
| 475 |
+
|
| 476 |
+
if D[i, i].is_positive is False:
|
| 477 |
+
raise NonPositiveDefiniteMatrixError(
|
| 478 |
+
"Matrix must be positive-definite")
|
| 479 |
+
|
| 480 |
+
else:
|
| 481 |
+
for i in range(M.rows):
|
| 482 |
+
for j in range(i):
|
| 483 |
+
L[i, j] = (1 / D[j, j])*(M[i, j] - sum(
|
| 484 |
+
L[i, k]*L[j, k]*D[k, k] for k in range(j)))
|
| 485 |
+
|
| 486 |
+
D[i, i] = M[i, i] - sum(L[i, k]**2*D[k, k] for k in range(i))
|
| 487 |
+
|
| 488 |
+
return M._new(L), M._new(D)
|
| 489 |
+
|
| 490 |
+
def _LDLdecomposition_sparse(M, hermitian=True):
|
| 491 |
+
"""
|
| 492 |
+
Returns the LDL Decomposition (matrices ``L`` and ``D``) of matrix
|
| 493 |
+
``A``, such that ``L * D * L.T == A``. ``A`` must be a square,
|
| 494 |
+
symmetric, positive-definite and non-singular.
|
| 495 |
+
|
| 496 |
+
This method eliminates the use of square root and ensures that all
|
| 497 |
+
the diagonal entries of L are 1.
|
| 498 |
+
|
| 499 |
+
Examples
|
| 500 |
+
========
|
| 501 |
+
|
| 502 |
+
>>> from sympy import SparseMatrix
|
| 503 |
+
>>> A = SparseMatrix(((25, 15, -5), (15, 18, 0), (-5, 0, 11)))
|
| 504 |
+
>>> L, D = A.LDLdecomposition()
|
| 505 |
+
>>> L
|
| 506 |
+
Matrix([
|
| 507 |
+
[ 1, 0, 0],
|
| 508 |
+
[ 3/5, 1, 0],
|
| 509 |
+
[-1/5, 1/3, 1]])
|
| 510 |
+
>>> D
|
| 511 |
+
Matrix([
|
| 512 |
+
[25, 0, 0],
|
| 513 |
+
[ 0, 9, 0],
|
| 514 |
+
[ 0, 0, 9]])
|
| 515 |
+
>>> L * D * L.T == A
|
| 516 |
+
True
|
| 517 |
+
|
| 518 |
+
"""
|
| 519 |
+
|
| 520 |
+
from .dense import MutableDenseMatrix
|
| 521 |
+
|
| 522 |
+
if not M.is_square:
|
| 523 |
+
raise NonSquareMatrixError("Matrix must be square.")
|
| 524 |
+
if hermitian and not M.is_hermitian:
|
| 525 |
+
raise ValueError("Matrix must be Hermitian.")
|
| 526 |
+
if not hermitian and not M.is_symmetric():
|
| 527 |
+
raise ValueError("Matrix must be symmetric.")
|
| 528 |
+
|
| 529 |
+
dps = _get_intermediate_simp(expand_mul, expand_mul)
|
| 530 |
+
Lrowstruc = M.row_structure_symbolic_cholesky()
|
| 531 |
+
L = MutableDenseMatrix.eye(M.rows)
|
| 532 |
+
D = MutableDenseMatrix.zeros(M.rows, M.cols)
|
| 533 |
+
|
| 534 |
+
for i in range(len(Lrowstruc)):
|
| 535 |
+
for j in Lrowstruc[i]:
|
| 536 |
+
if i != j:
|
| 537 |
+
L[i, j] = M[i, j]
|
| 538 |
+
summ = 0
|
| 539 |
+
|
| 540 |
+
for p1 in Lrowstruc[i]:
|
| 541 |
+
if p1 < j:
|
| 542 |
+
for p2 in Lrowstruc[j]:
|
| 543 |
+
if p2 < j:
|
| 544 |
+
if p1 == p2:
|
| 545 |
+
if hermitian:
|
| 546 |
+
summ += L[i, p1]*L[j, p1].conjugate()*D[p1, p1]
|
| 547 |
+
else:
|
| 548 |
+
summ += L[i, p1]*L[j, p1]*D[p1, p1]
|
| 549 |
+
else:
|
| 550 |
+
break
|
| 551 |
+
else:
|
| 552 |
+
break
|
| 553 |
+
|
| 554 |
+
L[i, j] = dps((L[i, j] - summ) / D[j, j])
|
| 555 |
+
|
| 556 |
+
else: # i == j
|
| 557 |
+
D[i, i] = M[i, i]
|
| 558 |
+
summ = 0
|
| 559 |
+
|
| 560 |
+
for k in Lrowstruc[i]:
|
| 561 |
+
if k < i:
|
| 562 |
+
if hermitian:
|
| 563 |
+
summ += L[i, k]*L[i, k].conjugate()*D[k, k]
|
| 564 |
+
else:
|
| 565 |
+
summ += L[i, k]**2*D[k, k]
|
| 566 |
+
else:
|
| 567 |
+
break
|
| 568 |
+
|
| 569 |
+
D[i, i] = dps(D[i, i] - summ)
|
| 570 |
+
|
| 571 |
+
if hermitian and D[i, i].is_positive is False:
|
| 572 |
+
raise NonPositiveDefiniteMatrixError(
|
| 573 |
+
"Matrix must be positive-definite")
|
| 574 |
+
|
| 575 |
+
return M._new(L), M._new(D)
|
| 576 |
+
|
| 577 |
+
|
| 578 |
+
def _LUdecomposition(M, iszerofunc=_iszero, simpfunc=None, rankcheck=False):
|
| 579 |
+
"""Returns (L, U, perm) where L is a lower triangular matrix with unit
|
| 580 |
+
diagonal, U is an upper triangular matrix, and perm is a list of row
|
| 581 |
+
swap index pairs. If A is the original matrix, then
|
| 582 |
+
``A = (L*U).permuteBkwd(perm)``, and the row permutation matrix P such
|
| 583 |
+
that $P A = L U$ can be computed by ``P = eye(A.rows).permuteFwd(perm)``.
|
| 584 |
+
|
| 585 |
+
See documentation for LUCombined for details about the keyword argument
|
| 586 |
+
rankcheck, iszerofunc, and simpfunc.
|
| 587 |
+
|
| 588 |
+
Parameters
|
| 589 |
+
==========
|
| 590 |
+
|
| 591 |
+
rankcheck : bool, optional
|
| 592 |
+
Determines if this function should detect the rank
|
| 593 |
+
deficiency of the matrixis and should raise a
|
| 594 |
+
``ValueError``.
|
| 595 |
+
|
| 596 |
+
iszerofunc : function, optional
|
| 597 |
+
A function which determines if a given expression is zero.
|
| 598 |
+
|
| 599 |
+
The function should be a callable that takes a single
|
| 600 |
+
SymPy expression and returns a 3-valued boolean value
|
| 601 |
+
``True``, ``False``, or ``None``.
|
| 602 |
+
|
| 603 |
+
It is internally used by the pivot searching algorithm.
|
| 604 |
+
See the notes section for a more information about the
|
| 605 |
+
pivot searching algorithm.
|
| 606 |
+
|
| 607 |
+
simpfunc : function or None, optional
|
| 608 |
+
A function that simplifies the input.
|
| 609 |
+
|
| 610 |
+
If this is specified as a function, this function should be
|
| 611 |
+
a callable that takes a single SymPy expression and returns
|
| 612 |
+
an another SymPy expression that is algebraically
|
| 613 |
+
equivalent.
|
| 614 |
+
|
| 615 |
+
If ``None``, it indicates that the pivot search algorithm
|
| 616 |
+
should not attempt to simplify any candidate pivots.
|
| 617 |
+
|
| 618 |
+
It is internally used by the pivot searching algorithm.
|
| 619 |
+
See the notes section for a more information about the
|
| 620 |
+
pivot searching algorithm.
|
| 621 |
+
|
| 622 |
+
Examples
|
| 623 |
+
========
|
| 624 |
+
|
| 625 |
+
>>> from sympy import Matrix
|
| 626 |
+
>>> a = Matrix([[4, 3], [6, 3]])
|
| 627 |
+
>>> L, U, _ = a.LUdecomposition()
|
| 628 |
+
>>> L
|
| 629 |
+
Matrix([
|
| 630 |
+
[ 1, 0],
|
| 631 |
+
[3/2, 1]])
|
| 632 |
+
>>> U
|
| 633 |
+
Matrix([
|
| 634 |
+
[4, 3],
|
| 635 |
+
[0, -3/2]])
|
| 636 |
+
|
| 637 |
+
See Also
|
| 638 |
+
========
|
| 639 |
+
|
| 640 |
+
sympy.matrices.dense.DenseMatrix.cholesky
|
| 641 |
+
sympy.matrices.dense.DenseMatrix.LDLdecomposition
|
| 642 |
+
QRdecomposition
|
| 643 |
+
LUdecomposition_Simple
|
| 644 |
+
LUdecompositionFF
|
| 645 |
+
LUsolve
|
| 646 |
+
"""
|
| 647 |
+
|
| 648 |
+
combined, p = M.LUdecomposition_Simple(iszerofunc=iszerofunc,
|
| 649 |
+
simpfunc=simpfunc, rankcheck=rankcheck)
|
| 650 |
+
|
| 651 |
+
# L is lower triangular ``M.rows x M.rows``
|
| 652 |
+
# U is upper triangular ``M.rows x M.cols``
|
| 653 |
+
# L has unit diagonal. For each column in combined, the subcolumn
|
| 654 |
+
# below the diagonal of combined is shared by L.
|
| 655 |
+
# If L has more columns than combined, then the remaining subcolumns
|
| 656 |
+
# below the diagonal of L are zero.
|
| 657 |
+
# The upper triangular portion of L and combined are equal.
|
| 658 |
+
def entry_L(i, j):
|
| 659 |
+
if i < j:
|
| 660 |
+
# Super diagonal entry
|
| 661 |
+
return M.zero
|
| 662 |
+
elif i == j:
|
| 663 |
+
return M.one
|
| 664 |
+
elif j < combined.cols:
|
| 665 |
+
return combined[i, j]
|
| 666 |
+
|
| 667 |
+
# Subdiagonal entry of L with no corresponding
|
| 668 |
+
# entry in combined
|
| 669 |
+
return M.zero
|
| 670 |
+
|
| 671 |
+
def entry_U(i, j):
|
| 672 |
+
return M.zero if i > j else combined[i, j]
|
| 673 |
+
|
| 674 |
+
L = M._new(combined.rows, combined.rows, entry_L)
|
| 675 |
+
U = M._new(combined.rows, combined.cols, entry_U)
|
| 676 |
+
|
| 677 |
+
return L, U, p
|
| 678 |
+
|
| 679 |
+
def _LUdecomposition_Simple(M, iszerofunc=_iszero, simpfunc=None,
|
| 680 |
+
rankcheck=False):
|
| 681 |
+
r"""Compute the PLU decomposition of the matrix.
|
| 682 |
+
|
| 683 |
+
Parameters
|
| 684 |
+
==========
|
| 685 |
+
|
| 686 |
+
rankcheck : bool, optional
|
| 687 |
+
Determines if this function should detect the rank
|
| 688 |
+
deficiency of the matrixis and should raise a
|
| 689 |
+
``ValueError``.
|
| 690 |
+
|
| 691 |
+
iszerofunc : function, optional
|
| 692 |
+
A function which determines if a given expression is zero.
|
| 693 |
+
|
| 694 |
+
The function should be a callable that takes a single
|
| 695 |
+
SymPy expression and returns a 3-valued boolean value
|
| 696 |
+
``True``, ``False``, or ``None``.
|
| 697 |
+
|
| 698 |
+
It is internally used by the pivot searching algorithm.
|
| 699 |
+
See the notes section for a more information about the
|
| 700 |
+
pivot searching algorithm.
|
| 701 |
+
|
| 702 |
+
simpfunc : function or None, optional
|
| 703 |
+
A function that simplifies the input.
|
| 704 |
+
|
| 705 |
+
If this is specified as a function, this function should be
|
| 706 |
+
a callable that takes a single SymPy expression and returns
|
| 707 |
+
an another SymPy expression that is algebraically
|
| 708 |
+
equivalent.
|
| 709 |
+
|
| 710 |
+
If ``None``, it indicates that the pivot search algorithm
|
| 711 |
+
should not attempt to simplify any candidate pivots.
|
| 712 |
+
|
| 713 |
+
It is internally used by the pivot searching algorithm.
|
| 714 |
+
See the notes section for a more information about the
|
| 715 |
+
pivot searching algorithm.
|
| 716 |
+
|
| 717 |
+
Returns
|
| 718 |
+
=======
|
| 719 |
+
|
| 720 |
+
(lu, row_swaps) : (Matrix, list)
|
| 721 |
+
If the original matrix is a $m, n$ matrix:
|
| 722 |
+
|
| 723 |
+
*lu* is a $m, n$ matrix, which contains result of the
|
| 724 |
+
decomposition in a compressed form. See the notes section
|
| 725 |
+
to see how the matrix is compressed.
|
| 726 |
+
|
| 727 |
+
*row_swaps* is a $m$-element list where each element is a
|
| 728 |
+
pair of row exchange indices.
|
| 729 |
+
|
| 730 |
+
``A = (L*U).permute_backward(perm)``, and the row
|
| 731 |
+
permutation matrix $P$ from the formula $P A = L U$ can be
|
| 732 |
+
computed by ``P=eye(A.row).permute_forward(perm)``.
|
| 733 |
+
|
| 734 |
+
Raises
|
| 735 |
+
======
|
| 736 |
+
|
| 737 |
+
ValueError
|
| 738 |
+
Raised if ``rankcheck=True`` and the matrix is found to
|
| 739 |
+
be rank deficient during the computation.
|
| 740 |
+
|
| 741 |
+
Notes
|
| 742 |
+
=====
|
| 743 |
+
|
| 744 |
+
About the PLU decomposition:
|
| 745 |
+
|
| 746 |
+
PLU decomposition is a generalization of a LU decomposition
|
| 747 |
+
which can be extended for rank-deficient matrices.
|
| 748 |
+
|
| 749 |
+
It can further be generalized for non-square matrices, and this
|
| 750 |
+
is the notation that SymPy is using.
|
| 751 |
+
|
| 752 |
+
PLU decomposition is a decomposition of a $m, n$ matrix $A$ in
|
| 753 |
+
the form of $P A = L U$ where
|
| 754 |
+
|
| 755 |
+
* $L$ is a $m, m$ lower triangular matrix with unit diagonal
|
| 756 |
+
entries.
|
| 757 |
+
* $U$ is a $m, n$ upper triangular matrix.
|
| 758 |
+
* $P$ is a $m, m$ permutation matrix.
|
| 759 |
+
|
| 760 |
+
So, for a square matrix, the decomposition would look like:
|
| 761 |
+
|
| 762 |
+
.. math::
|
| 763 |
+
L = \begin{bmatrix}
|
| 764 |
+
1 & 0 & 0 & \cdots & 0 \\
|
| 765 |
+
L_{1, 0} & 1 & 0 & \cdots & 0 \\
|
| 766 |
+
L_{2, 0} & L_{2, 1} & 1 & \cdots & 0 \\
|
| 767 |
+
\vdots & \vdots & \vdots & \ddots & \vdots \\
|
| 768 |
+
L_{n-1, 0} & L_{n-1, 1} & L_{n-1, 2} & \cdots & 1
|
| 769 |
+
\end{bmatrix}
|
| 770 |
+
|
| 771 |
+
.. math::
|
| 772 |
+
U = \begin{bmatrix}
|
| 773 |
+
U_{0, 0} & U_{0, 1} & U_{0, 2} & \cdots & U_{0, n-1} \\
|
| 774 |
+
0 & U_{1, 1} & U_{1, 2} & \cdots & U_{1, n-1} \\
|
| 775 |
+
0 & 0 & U_{2, 2} & \cdots & U_{2, n-1} \\
|
| 776 |
+
\vdots & \vdots & \vdots & \ddots & \vdots \\
|
| 777 |
+
0 & 0 & 0 & \cdots & U_{n-1, n-1}
|
| 778 |
+
\end{bmatrix}
|
| 779 |
+
|
| 780 |
+
And for a matrix with more rows than the columns,
|
| 781 |
+
the decomposition would look like:
|
| 782 |
+
|
| 783 |
+
.. math::
|
| 784 |
+
L = \begin{bmatrix}
|
| 785 |
+
1 & 0 & 0 & \cdots & 0 & 0 & \cdots & 0 \\
|
| 786 |
+
L_{1, 0} & 1 & 0 & \cdots & 0 & 0 & \cdots & 0 \\
|
| 787 |
+
L_{2, 0} & L_{2, 1} & 1 & \cdots & 0 & 0 & \cdots & 0 \\
|
| 788 |
+
\vdots & \vdots & \vdots & \ddots & \vdots & \vdots & \ddots
|
| 789 |
+
& \vdots \\
|
| 790 |
+
L_{n-1, 0} & L_{n-1, 1} & L_{n-1, 2} & \cdots & 1 & 0
|
| 791 |
+
& \cdots & 0 \\
|
| 792 |
+
L_{n, 0} & L_{n, 1} & L_{n, 2} & \cdots & L_{n, n-1} & 1
|
| 793 |
+
& \cdots & 0 \\
|
| 794 |
+
\vdots & \vdots & \vdots & \ddots & \vdots & \vdots
|
| 795 |
+
& \ddots & \vdots \\
|
| 796 |
+
L_{m-1, 0} & L_{m-1, 1} & L_{m-1, 2} & \cdots & L_{m-1, n-1}
|
| 797 |
+
& 0 & \cdots & 1 \\
|
| 798 |
+
\end{bmatrix}
|
| 799 |
+
|
| 800 |
+
.. math::
|
| 801 |
+
U = \begin{bmatrix}
|
| 802 |
+
U_{0, 0} & U_{0, 1} & U_{0, 2} & \cdots & U_{0, n-1} \\
|
| 803 |
+
0 & U_{1, 1} & U_{1, 2} & \cdots & U_{1, n-1} \\
|
| 804 |
+
0 & 0 & U_{2, 2} & \cdots & U_{2, n-1} \\
|
| 805 |
+
\vdots & \vdots & \vdots & \ddots & \vdots \\
|
| 806 |
+
0 & 0 & 0 & \cdots & U_{n-1, n-1} \\
|
| 807 |
+
0 & 0 & 0 & \cdots & 0 \\
|
| 808 |
+
\vdots & \vdots & \vdots & \ddots & \vdots \\
|
| 809 |
+
0 & 0 & 0 & \cdots & 0
|
| 810 |
+
\end{bmatrix}
|
| 811 |
+
|
| 812 |
+
Finally, for a matrix with more columns than the rows, the
|
| 813 |
+
decomposition would look like:
|
| 814 |
+
|
| 815 |
+
.. math::
|
| 816 |
+
L = \begin{bmatrix}
|
| 817 |
+
1 & 0 & 0 & \cdots & 0 \\
|
| 818 |
+
L_{1, 0} & 1 & 0 & \cdots & 0 \\
|
| 819 |
+
L_{2, 0} & L_{2, 1} & 1 & \cdots & 0 \\
|
| 820 |
+
\vdots & \vdots & \vdots & \ddots & \vdots \\
|
| 821 |
+
L_{m-1, 0} & L_{m-1, 1} & L_{m-1, 2} & \cdots & 1
|
| 822 |
+
\end{bmatrix}
|
| 823 |
+
|
| 824 |
+
.. math::
|
| 825 |
+
U = \begin{bmatrix}
|
| 826 |
+
U_{0, 0} & U_{0, 1} & U_{0, 2} & \cdots & U_{0, m-1}
|
| 827 |
+
& \cdots & U_{0, n-1} \\
|
| 828 |
+
0 & U_{1, 1} & U_{1, 2} & \cdots & U_{1, m-1}
|
| 829 |
+
& \cdots & U_{1, n-1} \\
|
| 830 |
+
0 & 0 & U_{2, 2} & \cdots & U_{2, m-1}
|
| 831 |
+
& \cdots & U_{2, n-1} \\
|
| 832 |
+
\vdots & \vdots & \vdots & \ddots & \vdots
|
| 833 |
+
& \cdots & \vdots \\
|
| 834 |
+
0 & 0 & 0 & \cdots & U_{m-1, m-1}
|
| 835 |
+
& \cdots & U_{m-1, n-1} \\
|
| 836 |
+
\end{bmatrix}
|
| 837 |
+
|
| 838 |
+
About the compressed LU storage:
|
| 839 |
+
|
| 840 |
+
The results of the decomposition are often stored in compressed
|
| 841 |
+
forms rather than returning $L$ and $U$ matrices individually.
|
| 842 |
+
|
| 843 |
+
It may be less intiuitive, but it is commonly used for a lot of
|
| 844 |
+
numeric libraries because of the efficiency.
|
| 845 |
+
|
| 846 |
+
The storage matrix is defined as following for this specific
|
| 847 |
+
method:
|
| 848 |
+
|
| 849 |
+
* The subdiagonal elements of $L$ are stored in the subdiagonal
|
| 850 |
+
portion of $LU$, that is $LU_{i, j} = L_{i, j}$ whenever
|
| 851 |
+
$i > j$.
|
| 852 |
+
* The elements on the diagonal of $L$ are all 1, and are not
|
| 853 |
+
explicitly stored.
|
| 854 |
+
* $U$ is stored in the upper triangular portion of $LU$, that is
|
| 855 |
+
$LU_{i, j} = U_{i, j}$ whenever $i <= j$.
|
| 856 |
+
* For a case of $m > n$, the right side of the $L$ matrix is
|
| 857 |
+
trivial to store.
|
| 858 |
+
* For a case of $m < n$, the below side of the $U$ matrix is
|
| 859 |
+
trivial to store.
|
| 860 |
+
|
| 861 |
+
So, for a square matrix, the compressed output matrix would be:
|
| 862 |
+
|
| 863 |
+
.. math::
|
| 864 |
+
LU = \begin{bmatrix}
|
| 865 |
+
U_{0, 0} & U_{0, 1} & U_{0, 2} & \cdots & U_{0, n-1} \\
|
| 866 |
+
L_{1, 0} & U_{1, 1} & U_{1, 2} & \cdots & U_{1, n-1} \\
|
| 867 |
+
L_{2, 0} & L_{2, 1} & U_{2, 2} & \cdots & U_{2, n-1} \\
|
| 868 |
+
\vdots & \vdots & \vdots & \ddots & \vdots \\
|
| 869 |
+
L_{n-1, 0} & L_{n-1, 1} & L_{n-1, 2} & \cdots & U_{n-1, n-1}
|
| 870 |
+
\end{bmatrix}
|
| 871 |
+
|
| 872 |
+
For a matrix with more rows than the columns, the compressed
|
| 873 |
+
output matrix would be:
|
| 874 |
+
|
| 875 |
+
.. math::
|
| 876 |
+
LU = \begin{bmatrix}
|
| 877 |
+
U_{0, 0} & U_{0, 1} & U_{0, 2} & \cdots & U_{0, n-1} \\
|
| 878 |
+
L_{1, 0} & U_{1, 1} & U_{1, 2} & \cdots & U_{1, n-1} \\
|
| 879 |
+
L_{2, 0} & L_{2, 1} & U_{2, 2} & \cdots & U_{2, n-1} \\
|
| 880 |
+
\vdots & \vdots & \vdots & \ddots & \vdots \\
|
| 881 |
+
L_{n-1, 0} & L_{n-1, 1} & L_{n-1, 2} & \cdots
|
| 882 |
+
& U_{n-1, n-1} \\
|
| 883 |
+
\vdots & \vdots & \vdots & \ddots & \vdots \\
|
| 884 |
+
L_{m-1, 0} & L_{m-1, 1} & L_{m-1, 2} & \cdots
|
| 885 |
+
& L_{m-1, n-1} \\
|
| 886 |
+
\end{bmatrix}
|
| 887 |
+
|
| 888 |
+
For a matrix with more columns than the rows, the compressed
|
| 889 |
+
output matrix would be:
|
| 890 |
+
|
| 891 |
+
.. math::
|
| 892 |
+
LU = \begin{bmatrix}
|
| 893 |
+
U_{0, 0} & U_{0, 1} & U_{0, 2} & \cdots & U_{0, m-1}
|
| 894 |
+
& \cdots & U_{0, n-1} \\
|
| 895 |
+
L_{1, 0} & U_{1, 1} & U_{1, 2} & \cdots & U_{1, m-1}
|
| 896 |
+
& \cdots & U_{1, n-1} \\
|
| 897 |
+
L_{2, 0} & L_{2, 1} & U_{2, 2} & \cdots & U_{2, m-1}
|
| 898 |
+
& \cdots & U_{2, n-1} \\
|
| 899 |
+
\vdots & \vdots & \vdots & \ddots & \vdots
|
| 900 |
+
& \cdots & \vdots \\
|
| 901 |
+
L_{m-1, 0} & L_{m-1, 1} & L_{m-1, 2} & \cdots & U_{m-1, m-1}
|
| 902 |
+
& \cdots & U_{m-1, n-1} \\
|
| 903 |
+
\end{bmatrix}
|
| 904 |
+
|
| 905 |
+
About the pivot searching algorithm:
|
| 906 |
+
|
| 907 |
+
When a matrix contains symbolic entries, the pivot search algorithm
|
| 908 |
+
differs from the case where every entry can be categorized as zero or
|
| 909 |
+
nonzero.
|
| 910 |
+
The algorithm searches column by column through the submatrix whose
|
| 911 |
+
top left entry coincides with the pivot position.
|
| 912 |
+
If it exists, the pivot is the first entry in the current search
|
| 913 |
+
column that iszerofunc guarantees is nonzero.
|
| 914 |
+
If no such candidate exists, then each candidate pivot is simplified
|
| 915 |
+
if simpfunc is not None.
|
| 916 |
+
The search is repeated, with the difference that a candidate may be
|
| 917 |
+
the pivot if ``iszerofunc()`` cannot guarantee that it is nonzero.
|
| 918 |
+
In the second search the pivot is the first candidate that
|
| 919 |
+
iszerofunc can guarantee is nonzero.
|
| 920 |
+
If no such candidate exists, then the pivot is the first candidate
|
| 921 |
+
for which iszerofunc returns None.
|
| 922 |
+
If no such candidate exists, then the search is repeated in the next
|
| 923 |
+
column to the right.
|
| 924 |
+
The pivot search algorithm differs from the one in ``rref()``, which
|
| 925 |
+
relies on ``_find_reasonable_pivot()``.
|
| 926 |
+
Future versions of ``LUdecomposition_simple()`` may use
|
| 927 |
+
``_find_reasonable_pivot()``.
|
| 928 |
+
|
| 929 |
+
See Also
|
| 930 |
+
========
|
| 931 |
+
|
| 932 |
+
sympy.matrices.matrices.MatrixBase.LUdecomposition
|
| 933 |
+
LUdecompositionFF
|
| 934 |
+
LUsolve
|
| 935 |
+
"""
|
| 936 |
+
|
| 937 |
+
if rankcheck:
|
| 938 |
+
# https://github.com/sympy/sympy/issues/9796
|
| 939 |
+
pass
|
| 940 |
+
|
| 941 |
+
if S.Zero in M.shape:
|
| 942 |
+
# Define LU decomposition of a matrix with no entries as a matrix
|
| 943 |
+
# of the same dimensions with all zero entries.
|
| 944 |
+
return M.zeros(M.rows, M.cols), []
|
| 945 |
+
|
| 946 |
+
dps = _get_intermediate_simp()
|
| 947 |
+
lu = M.as_mutable()
|
| 948 |
+
row_swaps = []
|
| 949 |
+
|
| 950 |
+
pivot_col = 0
|
| 951 |
+
|
| 952 |
+
for pivot_row in range(0, lu.rows - 1):
|
| 953 |
+
# Search for pivot. Prefer entry that iszeropivot determines
|
| 954 |
+
# is nonzero, over entry that iszeropivot cannot guarantee
|
| 955 |
+
# is zero.
|
| 956 |
+
# XXX ``_find_reasonable_pivot`` uses slow zero testing. Blocked by bug #10279
|
| 957 |
+
# Future versions of LUdecomposition_simple can pass iszerofunc and simpfunc
|
| 958 |
+
# to _find_reasonable_pivot().
|
| 959 |
+
# In pass 3 of _find_reasonable_pivot(), the predicate in ``if x.equals(S.Zero):``
|
| 960 |
+
# calls sympy.simplify(), and not the simplification function passed in via
|
| 961 |
+
# the keyword argument simpfunc.
|
| 962 |
+
iszeropivot = True
|
| 963 |
+
|
| 964 |
+
while pivot_col != M.cols and iszeropivot:
|
| 965 |
+
sub_col = (lu[r, pivot_col] for r in range(pivot_row, M.rows))
|
| 966 |
+
|
| 967 |
+
pivot_row_offset, pivot_value, is_assumed_non_zero, ind_simplified_pairs =\
|
| 968 |
+
_find_reasonable_pivot_naive(sub_col, iszerofunc, simpfunc)
|
| 969 |
+
|
| 970 |
+
iszeropivot = pivot_value is None
|
| 971 |
+
|
| 972 |
+
if iszeropivot:
|
| 973 |
+
# All candidate pivots in this column are zero.
|
| 974 |
+
# Proceed to next column.
|
| 975 |
+
pivot_col += 1
|
| 976 |
+
|
| 977 |
+
if rankcheck and pivot_col != pivot_row:
|
| 978 |
+
# All entries including and below the pivot position are
|
| 979 |
+
# zero, which indicates that the rank of the matrix is
|
| 980 |
+
# strictly less than min(num rows, num cols)
|
| 981 |
+
# Mimic behavior of previous implementation, by throwing a
|
| 982 |
+
# ValueError.
|
| 983 |
+
raise ValueError("Rank of matrix is strictly less than"
|
| 984 |
+
" number of rows or columns."
|
| 985 |
+
" Pass keyword argument"
|
| 986 |
+
" rankcheck=False to compute"
|
| 987 |
+
" the LU decomposition of this matrix.")
|
| 988 |
+
|
| 989 |
+
candidate_pivot_row = None if pivot_row_offset is None else pivot_row + pivot_row_offset
|
| 990 |
+
|
| 991 |
+
if candidate_pivot_row is None and iszeropivot:
|
| 992 |
+
# If candidate_pivot_row is None and iszeropivot is True
|
| 993 |
+
# after pivot search has completed, then the submatrix
|
| 994 |
+
# below and to the right of (pivot_row, pivot_col) is
|
| 995 |
+
# all zeros, indicating that Gaussian elimination is
|
| 996 |
+
# complete.
|
| 997 |
+
return lu, row_swaps
|
| 998 |
+
|
| 999 |
+
# Update entries simplified during pivot search.
|
| 1000 |
+
for offset, val in ind_simplified_pairs:
|
| 1001 |
+
lu[pivot_row + offset, pivot_col] = val
|
| 1002 |
+
|
| 1003 |
+
if pivot_row != candidate_pivot_row:
|
| 1004 |
+
# Row swap book keeping:
|
| 1005 |
+
# Record which rows were swapped.
|
| 1006 |
+
# Update stored portion of L factor by multiplying L on the
|
| 1007 |
+
# left and right with the current permutation.
|
| 1008 |
+
# Swap rows of U.
|
| 1009 |
+
row_swaps.append([pivot_row, candidate_pivot_row])
|
| 1010 |
+
|
| 1011 |
+
# Update L.
|
| 1012 |
+
lu[pivot_row, 0:pivot_row], lu[candidate_pivot_row, 0:pivot_row] = \
|
| 1013 |
+
lu[candidate_pivot_row, 0:pivot_row], lu[pivot_row, 0:pivot_row]
|
| 1014 |
+
|
| 1015 |
+
# Swap pivot row of U with candidate pivot row.
|
| 1016 |
+
lu[pivot_row, pivot_col:lu.cols], lu[candidate_pivot_row, pivot_col:lu.cols] = \
|
| 1017 |
+
lu[candidate_pivot_row, pivot_col:lu.cols], lu[pivot_row, pivot_col:lu.cols]
|
| 1018 |
+
|
| 1019 |
+
# Introduce zeros below the pivot by adding a multiple of the
|
| 1020 |
+
# pivot row to a row under it, and store the result in the
|
| 1021 |
+
# row under it.
|
| 1022 |
+
# Only entries in the target row whose index is greater than
|
| 1023 |
+
# start_col may be nonzero.
|
| 1024 |
+
start_col = pivot_col + 1
|
| 1025 |
+
|
| 1026 |
+
for row in range(pivot_row + 1, lu.rows):
|
| 1027 |
+
# Store factors of L in the subcolumn below
|
| 1028 |
+
# (pivot_row, pivot_row).
|
| 1029 |
+
lu[row, pivot_row] = \
|
| 1030 |
+
dps(lu[row, pivot_col]/lu[pivot_row, pivot_col])
|
| 1031 |
+
|
| 1032 |
+
# Form the linear combination of the pivot row and the current
|
| 1033 |
+
# row below the pivot row that zeros the entries below the pivot.
|
| 1034 |
+
# Employing slicing instead of a loop here raises
|
| 1035 |
+
# NotImplementedError: Cannot add Zero to MutableSparseMatrix
|
| 1036 |
+
# in sympy/matrices/tests/test_sparse.py.
|
| 1037 |
+
# c = pivot_row + 1 if pivot_row == pivot_col else pivot_col
|
| 1038 |
+
for c in range(start_col, lu.cols):
|
| 1039 |
+
lu[row, c] = dps(lu[row, c] - lu[row, pivot_row]*lu[pivot_row, c])
|
| 1040 |
+
|
| 1041 |
+
if pivot_row != pivot_col:
|
| 1042 |
+
# matrix rank < min(num rows, num cols),
|
| 1043 |
+
# so factors of L are not stored directly below the pivot.
|
| 1044 |
+
# These entries are zero by construction, so don't bother
|
| 1045 |
+
# computing them.
|
| 1046 |
+
for row in range(pivot_row + 1, lu.rows):
|
| 1047 |
+
lu[row, pivot_col] = M.zero
|
| 1048 |
+
|
| 1049 |
+
pivot_col += 1
|
| 1050 |
+
|
| 1051 |
+
if pivot_col == lu.cols:
|
| 1052 |
+
# All candidate pivots are zero implies that Gaussian
|
| 1053 |
+
# elimination is complete.
|
| 1054 |
+
return lu, row_swaps
|
| 1055 |
+
|
| 1056 |
+
if rankcheck:
|
| 1057 |
+
if iszerofunc(
|
| 1058 |
+
lu[Min(lu.rows, lu.cols) - 1, Min(lu.rows, lu.cols) - 1]):
|
| 1059 |
+
raise ValueError("Rank of matrix is strictly less than"
|
| 1060 |
+
" number of rows or columns."
|
| 1061 |
+
" Pass keyword argument"
|
| 1062 |
+
" rankcheck=False to compute"
|
| 1063 |
+
" the LU decomposition of this matrix.")
|
| 1064 |
+
|
| 1065 |
+
return lu, row_swaps
|
| 1066 |
+
|
| 1067 |
+
def _LUdecompositionFF(M):
|
| 1068 |
+
"""Compute a fraction-free LU decomposition.
|
| 1069 |
+
|
| 1070 |
+
Returns 4 matrices P, L, D, U such that PA = L D**-1 U.
|
| 1071 |
+
If the elements of the matrix belong to some integral domain I, then all
|
| 1072 |
+
elements of L, D and U are guaranteed to belong to I.
|
| 1073 |
+
|
| 1074 |
+
See Also
|
| 1075 |
+
========
|
| 1076 |
+
|
| 1077 |
+
sympy.matrices.matrices.MatrixBase.LUdecomposition
|
| 1078 |
+
LUdecomposition_Simple
|
| 1079 |
+
LUsolve
|
| 1080 |
+
|
| 1081 |
+
References
|
| 1082 |
+
==========
|
| 1083 |
+
|
| 1084 |
+
.. [1] W. Zhou & D.J. Jeffrey, "Fraction-free matrix factors: new forms
|
| 1085 |
+
for LU and QR factors". Frontiers in Computer Science in China,
|
| 1086 |
+
Vol 2, no. 1, pp. 67-80, 2008.
|
| 1087 |
+
"""
|
| 1088 |
+
|
| 1089 |
+
from sympy.matrices import SparseMatrix
|
| 1090 |
+
|
| 1091 |
+
zeros = SparseMatrix.zeros
|
| 1092 |
+
eye = SparseMatrix.eye
|
| 1093 |
+
n, m = M.rows, M.cols
|
| 1094 |
+
U, L, P = M.as_mutable(), eye(n), eye(n)
|
| 1095 |
+
DD = zeros(n, n)
|
| 1096 |
+
oldpivot = 1
|
| 1097 |
+
|
| 1098 |
+
for k in range(n - 1):
|
| 1099 |
+
if U[k, k] == 0:
|
| 1100 |
+
for kpivot in range(k + 1, n):
|
| 1101 |
+
if U[kpivot, k]:
|
| 1102 |
+
break
|
| 1103 |
+
else:
|
| 1104 |
+
raise ValueError("Matrix is not full rank")
|
| 1105 |
+
|
| 1106 |
+
U[k, k:], U[kpivot, k:] = U[kpivot, k:], U[k, k:]
|
| 1107 |
+
L[k, :k], L[kpivot, :k] = L[kpivot, :k], L[k, :k]
|
| 1108 |
+
P[k, :], P[kpivot, :] = P[kpivot, :], P[k, :]
|
| 1109 |
+
|
| 1110 |
+
L [k, k] = Ukk = U[k, k]
|
| 1111 |
+
DD[k, k] = oldpivot * Ukk
|
| 1112 |
+
|
| 1113 |
+
for i in range(k + 1, n):
|
| 1114 |
+
L[i, k] = Uik = U[i, k]
|
| 1115 |
+
|
| 1116 |
+
for j in range(k + 1, m):
|
| 1117 |
+
U[i, j] = (Ukk * U[i, j] - U[k, j] * Uik) / oldpivot
|
| 1118 |
+
|
| 1119 |
+
U[i, k] = 0
|
| 1120 |
+
|
| 1121 |
+
oldpivot = Ukk
|
| 1122 |
+
|
| 1123 |
+
DD[n - 1, n - 1] = oldpivot
|
| 1124 |
+
|
| 1125 |
+
return P, L, DD, U
|
| 1126 |
+
|
| 1127 |
+
def _singular_value_decomposition(A):
|
| 1128 |
+
r"""Returns a Condensed Singular Value decomposition.
|
| 1129 |
+
|
| 1130 |
+
Explanation
|
| 1131 |
+
===========
|
| 1132 |
+
|
| 1133 |
+
A Singular Value decomposition is a decomposition in the form $A = U \Sigma V$
|
| 1134 |
+
where
|
| 1135 |
+
|
| 1136 |
+
- $U, V$ are column orthogonal matrix.
|
| 1137 |
+
- $\Sigma$ is a diagonal matrix, where the main diagonal contains singular
|
| 1138 |
+
values of matrix A.
|
| 1139 |
+
|
| 1140 |
+
A column orthogonal matrix satisfies
|
| 1141 |
+
$\mathbb{I} = U^H U$ while a full orthogonal matrix satisfies
|
| 1142 |
+
relation $\mathbb{I} = U U^H = U^H U$ where $\mathbb{I}$ is an identity
|
| 1143 |
+
matrix with matching dimensions.
|
| 1144 |
+
|
| 1145 |
+
For matrices which are not square or are rank-deficient, it is
|
| 1146 |
+
sufficient to return a column orthogonal matrix because augmenting
|
| 1147 |
+
them may introduce redundant computations.
|
| 1148 |
+
In condensed Singular Value Decomposition we only return column orthogonal
|
| 1149 |
+
matrices because of this reason
|
| 1150 |
+
|
| 1151 |
+
If you want to augment the results to return a full orthogonal
|
| 1152 |
+
decomposition, you should use the following procedures.
|
| 1153 |
+
|
| 1154 |
+
- Augment the $U, V$ matrices with columns that are orthogonal to every
|
| 1155 |
+
other columns and make it square.
|
| 1156 |
+
- Augment the $\Sigma$ matrix with zero rows to make it have the same
|
| 1157 |
+
shape as the original matrix.
|
| 1158 |
+
|
| 1159 |
+
The procedure will be illustrated in the examples section.
|
| 1160 |
+
|
| 1161 |
+
Examples
|
| 1162 |
+
========
|
| 1163 |
+
|
| 1164 |
+
we take a full rank matrix first:
|
| 1165 |
+
|
| 1166 |
+
>>> from sympy import Matrix
|
| 1167 |
+
>>> A = Matrix([[1, 2],[2,1]])
|
| 1168 |
+
>>> U, S, V = A.singular_value_decomposition()
|
| 1169 |
+
>>> U
|
| 1170 |
+
Matrix([
|
| 1171 |
+
[ sqrt(2)/2, sqrt(2)/2],
|
| 1172 |
+
[-sqrt(2)/2, sqrt(2)/2]])
|
| 1173 |
+
>>> S
|
| 1174 |
+
Matrix([
|
| 1175 |
+
[1, 0],
|
| 1176 |
+
[0, 3]])
|
| 1177 |
+
>>> V
|
| 1178 |
+
Matrix([
|
| 1179 |
+
[-sqrt(2)/2, sqrt(2)/2],
|
| 1180 |
+
[ sqrt(2)/2, sqrt(2)/2]])
|
| 1181 |
+
|
| 1182 |
+
If a matrix if square and full rank both U, V
|
| 1183 |
+
are orthogonal in both directions
|
| 1184 |
+
|
| 1185 |
+
>>> U * U.H
|
| 1186 |
+
Matrix([
|
| 1187 |
+
[1, 0],
|
| 1188 |
+
[0, 1]])
|
| 1189 |
+
>>> U.H * U
|
| 1190 |
+
Matrix([
|
| 1191 |
+
[1, 0],
|
| 1192 |
+
[0, 1]])
|
| 1193 |
+
|
| 1194 |
+
>>> V * V.H
|
| 1195 |
+
Matrix([
|
| 1196 |
+
[1, 0],
|
| 1197 |
+
[0, 1]])
|
| 1198 |
+
>>> V.H * V
|
| 1199 |
+
Matrix([
|
| 1200 |
+
[1, 0],
|
| 1201 |
+
[0, 1]])
|
| 1202 |
+
>>> A == U * S * V.H
|
| 1203 |
+
True
|
| 1204 |
+
|
| 1205 |
+
>>> C = Matrix([
|
| 1206 |
+
... [1, 0, 0, 0, 2],
|
| 1207 |
+
... [0, 0, 3, 0, 0],
|
| 1208 |
+
... [0, 0, 0, 0, 0],
|
| 1209 |
+
... [0, 2, 0, 0, 0],
|
| 1210 |
+
... ])
|
| 1211 |
+
>>> U, S, V = C.singular_value_decomposition()
|
| 1212 |
+
|
| 1213 |
+
>>> V.H * V
|
| 1214 |
+
Matrix([
|
| 1215 |
+
[1, 0, 0],
|
| 1216 |
+
[0, 1, 0],
|
| 1217 |
+
[0, 0, 1]])
|
| 1218 |
+
>>> V * V.H
|
| 1219 |
+
Matrix([
|
| 1220 |
+
[1/5, 0, 0, 0, 2/5],
|
| 1221 |
+
[ 0, 1, 0, 0, 0],
|
| 1222 |
+
[ 0, 0, 1, 0, 0],
|
| 1223 |
+
[ 0, 0, 0, 0, 0],
|
| 1224 |
+
[2/5, 0, 0, 0, 4/5]])
|
| 1225 |
+
|
| 1226 |
+
If you want to augment the results to be a full orthogonal
|
| 1227 |
+
decomposition, you should augment $V$ with an another orthogonal
|
| 1228 |
+
column.
|
| 1229 |
+
|
| 1230 |
+
You are able to append an arbitrary standard basis that are linearly
|
| 1231 |
+
independent to every other columns and you can run the Gram-Schmidt
|
| 1232 |
+
process to make them augmented as orthogonal basis.
|
| 1233 |
+
|
| 1234 |
+
>>> V_aug = V.row_join(Matrix([[0,0,0,0,1],
|
| 1235 |
+
... [0,0,0,1,0]]).H)
|
| 1236 |
+
>>> V_aug = V_aug.QRdecomposition()[0]
|
| 1237 |
+
>>> V_aug
|
| 1238 |
+
Matrix([
|
| 1239 |
+
[0, sqrt(5)/5, 0, -2*sqrt(5)/5, 0],
|
| 1240 |
+
[1, 0, 0, 0, 0],
|
| 1241 |
+
[0, 0, 1, 0, 0],
|
| 1242 |
+
[0, 0, 0, 0, 1],
|
| 1243 |
+
[0, 2*sqrt(5)/5, 0, sqrt(5)/5, 0]])
|
| 1244 |
+
>>> V_aug.H * V_aug
|
| 1245 |
+
Matrix([
|
| 1246 |
+
[1, 0, 0, 0, 0],
|
| 1247 |
+
[0, 1, 0, 0, 0],
|
| 1248 |
+
[0, 0, 1, 0, 0],
|
| 1249 |
+
[0, 0, 0, 1, 0],
|
| 1250 |
+
[0, 0, 0, 0, 1]])
|
| 1251 |
+
>>> V_aug * V_aug.H
|
| 1252 |
+
Matrix([
|
| 1253 |
+
[1, 0, 0, 0, 0],
|
| 1254 |
+
[0, 1, 0, 0, 0],
|
| 1255 |
+
[0, 0, 1, 0, 0],
|
| 1256 |
+
[0, 0, 0, 1, 0],
|
| 1257 |
+
[0, 0, 0, 0, 1]])
|
| 1258 |
+
|
| 1259 |
+
Similarly we augment U
|
| 1260 |
+
|
| 1261 |
+
>>> U_aug = U.row_join(Matrix([0,0,1,0]))
|
| 1262 |
+
>>> U_aug = U_aug.QRdecomposition()[0]
|
| 1263 |
+
>>> U_aug
|
| 1264 |
+
Matrix([
|
| 1265 |
+
[0, 1, 0, 0],
|
| 1266 |
+
[0, 0, 1, 0],
|
| 1267 |
+
[0, 0, 0, 1],
|
| 1268 |
+
[1, 0, 0, 0]])
|
| 1269 |
+
|
| 1270 |
+
>>> U_aug.H * U_aug
|
| 1271 |
+
Matrix([
|
| 1272 |
+
[1, 0, 0, 0],
|
| 1273 |
+
[0, 1, 0, 0],
|
| 1274 |
+
[0, 0, 1, 0],
|
| 1275 |
+
[0, 0, 0, 1]])
|
| 1276 |
+
>>> U_aug * U_aug.H
|
| 1277 |
+
Matrix([
|
| 1278 |
+
[1, 0, 0, 0],
|
| 1279 |
+
[0, 1, 0, 0],
|
| 1280 |
+
[0, 0, 1, 0],
|
| 1281 |
+
[0, 0, 0, 1]])
|
| 1282 |
+
|
| 1283 |
+
We add 2 zero columns and one row to S
|
| 1284 |
+
|
| 1285 |
+
>>> S_aug = S.col_join(Matrix([[0,0,0]]))
|
| 1286 |
+
>>> S_aug = S_aug.row_join(Matrix([[0,0,0,0],
|
| 1287 |
+
... [0,0,0,0]]).H)
|
| 1288 |
+
>>> S_aug
|
| 1289 |
+
Matrix([
|
| 1290 |
+
[2, 0, 0, 0, 0],
|
| 1291 |
+
[0, sqrt(5), 0, 0, 0],
|
| 1292 |
+
[0, 0, 3, 0, 0],
|
| 1293 |
+
[0, 0, 0, 0, 0]])
|
| 1294 |
+
|
| 1295 |
+
|
| 1296 |
+
|
| 1297 |
+
>>> U_aug * S_aug * V_aug.H == C
|
| 1298 |
+
True
|
| 1299 |
+
|
| 1300 |
+
"""
|
| 1301 |
+
|
| 1302 |
+
AH = A.H
|
| 1303 |
+
m, n = A.shape
|
| 1304 |
+
if m >= n:
|
| 1305 |
+
V, S = (AH * A).diagonalize()
|
| 1306 |
+
|
| 1307 |
+
ranked = []
|
| 1308 |
+
for i, x in enumerate(S.diagonal()):
|
| 1309 |
+
if not x.is_zero:
|
| 1310 |
+
ranked.append(i)
|
| 1311 |
+
|
| 1312 |
+
V = V[:, ranked]
|
| 1313 |
+
|
| 1314 |
+
Singular_vals = [sqrt(S[i, i]) for i in range(S.rows) if i in ranked]
|
| 1315 |
+
|
| 1316 |
+
S = S.zeros(len(Singular_vals))
|
| 1317 |
+
|
| 1318 |
+
for i, sv in enumerate(Singular_vals):
|
| 1319 |
+
S[i, i] = sv
|
| 1320 |
+
|
| 1321 |
+
V, _ = V.QRdecomposition()
|
| 1322 |
+
U = A * V * S.inv()
|
| 1323 |
+
else:
|
| 1324 |
+
U, S = (A * AH).diagonalize()
|
| 1325 |
+
|
| 1326 |
+
ranked = []
|
| 1327 |
+
for i, x in enumerate(S.diagonal()):
|
| 1328 |
+
if not x.is_zero:
|
| 1329 |
+
ranked.append(i)
|
| 1330 |
+
|
| 1331 |
+
U = U[:, ranked]
|
| 1332 |
+
Singular_vals = [sqrt(S[i, i]) for i in range(S.rows) if i in ranked]
|
| 1333 |
+
|
| 1334 |
+
S = S.zeros(len(Singular_vals))
|
| 1335 |
+
|
| 1336 |
+
for i, sv in enumerate(Singular_vals):
|
| 1337 |
+
S[i, i] = sv
|
| 1338 |
+
|
| 1339 |
+
U, _ = U.QRdecomposition()
|
| 1340 |
+
V = AH * U * S.inv()
|
| 1341 |
+
|
| 1342 |
+
return U, S, V
|
| 1343 |
+
|
| 1344 |
+
def _QRdecomposition_optional(M, normalize=True):
|
| 1345 |
+
def dot(u, v):
|
| 1346 |
+
return u.dot(v, hermitian=True)
|
| 1347 |
+
|
| 1348 |
+
dps = _get_intermediate_simp(expand_mul, expand_mul)
|
| 1349 |
+
|
| 1350 |
+
A = M.as_mutable()
|
| 1351 |
+
ranked = []
|
| 1352 |
+
|
| 1353 |
+
Q = A
|
| 1354 |
+
R = A.zeros(A.cols)
|
| 1355 |
+
|
| 1356 |
+
for j in range(A.cols):
|
| 1357 |
+
for i in range(j):
|
| 1358 |
+
if Q[:, i].is_zero_matrix:
|
| 1359 |
+
continue
|
| 1360 |
+
|
| 1361 |
+
R[i, j] = dot(Q[:, i], Q[:, j]) / dot(Q[:, i], Q[:, i])
|
| 1362 |
+
R[i, j] = dps(R[i, j])
|
| 1363 |
+
Q[:, j] -= Q[:, i] * R[i, j]
|
| 1364 |
+
|
| 1365 |
+
Q[:, j] = dps(Q[:, j])
|
| 1366 |
+
if Q[:, j].is_zero_matrix is not True:
|
| 1367 |
+
ranked.append(j)
|
| 1368 |
+
R[j, j] = M.one
|
| 1369 |
+
|
| 1370 |
+
Q = Q.extract(range(Q.rows), ranked)
|
| 1371 |
+
R = R.extract(ranked, range(R.cols))
|
| 1372 |
+
|
| 1373 |
+
if normalize:
|
| 1374 |
+
# Normalization
|
| 1375 |
+
for i in range(Q.cols):
|
| 1376 |
+
norm = Q[:, i].norm()
|
| 1377 |
+
Q[:, i] /= norm
|
| 1378 |
+
R[i, :] *= norm
|
| 1379 |
+
|
| 1380 |
+
return M.__class__(Q), M.__class__(R)
|
| 1381 |
+
|
| 1382 |
+
|
| 1383 |
+
def _QRdecomposition(M):
|
| 1384 |
+
r"""Returns a QR decomposition.
|
| 1385 |
+
|
| 1386 |
+
Explanation
|
| 1387 |
+
===========
|
| 1388 |
+
|
| 1389 |
+
A QR decomposition is a decomposition in the form $A = Q R$
|
| 1390 |
+
where
|
| 1391 |
+
|
| 1392 |
+
- $Q$ is a column orthogonal matrix.
|
| 1393 |
+
- $R$ is a upper triangular (trapezoidal) matrix.
|
| 1394 |
+
|
| 1395 |
+
A column orthogonal matrix satisfies
|
| 1396 |
+
$\mathbb{I} = Q^H Q$ while a full orthogonal matrix satisfies
|
| 1397 |
+
relation $\mathbb{I} = Q Q^H = Q^H Q$ where $I$ is an identity
|
| 1398 |
+
matrix with matching dimensions.
|
| 1399 |
+
|
| 1400 |
+
For matrices which are not square or are rank-deficient, it is
|
| 1401 |
+
sufficient to return a column orthogonal matrix because augmenting
|
| 1402 |
+
them may introduce redundant computations.
|
| 1403 |
+
And an another advantage of this is that you can easily inspect the
|
| 1404 |
+
matrix rank by counting the number of columns of $Q$.
|
| 1405 |
+
|
| 1406 |
+
If you want to augment the results to return a full orthogonal
|
| 1407 |
+
decomposition, you should use the following procedures.
|
| 1408 |
+
|
| 1409 |
+
- Augment the $Q$ matrix with columns that are orthogonal to every
|
| 1410 |
+
other columns and make it square.
|
| 1411 |
+
- Augment the $R$ matrix with zero rows to make it have the same
|
| 1412 |
+
shape as the original matrix.
|
| 1413 |
+
|
| 1414 |
+
The procedure will be illustrated in the examples section.
|
| 1415 |
+
|
| 1416 |
+
Examples
|
| 1417 |
+
========
|
| 1418 |
+
|
| 1419 |
+
A full rank matrix example:
|
| 1420 |
+
|
| 1421 |
+
>>> from sympy import Matrix
|
| 1422 |
+
>>> A = Matrix([[12, -51, 4], [6, 167, -68], [-4, 24, -41]])
|
| 1423 |
+
>>> Q, R = A.QRdecomposition()
|
| 1424 |
+
>>> Q
|
| 1425 |
+
Matrix([
|
| 1426 |
+
[ 6/7, -69/175, -58/175],
|
| 1427 |
+
[ 3/7, 158/175, 6/175],
|
| 1428 |
+
[-2/7, 6/35, -33/35]])
|
| 1429 |
+
>>> R
|
| 1430 |
+
Matrix([
|
| 1431 |
+
[14, 21, -14],
|
| 1432 |
+
[ 0, 175, -70],
|
| 1433 |
+
[ 0, 0, 35]])
|
| 1434 |
+
|
| 1435 |
+
If the matrix is square and full rank, the $Q$ matrix becomes
|
| 1436 |
+
orthogonal in both directions, and needs no augmentation.
|
| 1437 |
+
|
| 1438 |
+
>>> Q * Q.H
|
| 1439 |
+
Matrix([
|
| 1440 |
+
[1, 0, 0],
|
| 1441 |
+
[0, 1, 0],
|
| 1442 |
+
[0, 0, 1]])
|
| 1443 |
+
>>> Q.H * Q
|
| 1444 |
+
Matrix([
|
| 1445 |
+
[1, 0, 0],
|
| 1446 |
+
[0, 1, 0],
|
| 1447 |
+
[0, 0, 1]])
|
| 1448 |
+
|
| 1449 |
+
>>> A == Q*R
|
| 1450 |
+
True
|
| 1451 |
+
|
| 1452 |
+
A rank deficient matrix example:
|
| 1453 |
+
|
| 1454 |
+
>>> A = Matrix([[12, -51, 0], [6, 167, 0], [-4, 24, 0]])
|
| 1455 |
+
>>> Q, R = A.QRdecomposition()
|
| 1456 |
+
>>> Q
|
| 1457 |
+
Matrix([
|
| 1458 |
+
[ 6/7, -69/175],
|
| 1459 |
+
[ 3/7, 158/175],
|
| 1460 |
+
[-2/7, 6/35]])
|
| 1461 |
+
>>> R
|
| 1462 |
+
Matrix([
|
| 1463 |
+
[14, 21, 0],
|
| 1464 |
+
[ 0, 175, 0]])
|
| 1465 |
+
|
| 1466 |
+
QRdecomposition might return a matrix Q that is rectangular.
|
| 1467 |
+
In this case the orthogonality condition might be satisfied as
|
| 1468 |
+
$\mathbb{I} = Q.H*Q$ but not in the reversed product
|
| 1469 |
+
$\mathbb{I} = Q * Q.H$.
|
| 1470 |
+
|
| 1471 |
+
>>> Q.H * Q
|
| 1472 |
+
Matrix([
|
| 1473 |
+
[1, 0],
|
| 1474 |
+
[0, 1]])
|
| 1475 |
+
>>> Q * Q.H
|
| 1476 |
+
Matrix([
|
| 1477 |
+
[27261/30625, 348/30625, -1914/6125],
|
| 1478 |
+
[ 348/30625, 30589/30625, 198/6125],
|
| 1479 |
+
[ -1914/6125, 198/6125, 136/1225]])
|
| 1480 |
+
|
| 1481 |
+
If you want to augment the results to be a full orthogonal
|
| 1482 |
+
decomposition, you should augment $Q$ with an another orthogonal
|
| 1483 |
+
column.
|
| 1484 |
+
|
| 1485 |
+
You are able to append an arbitrary standard basis that are linearly
|
| 1486 |
+
independent to every other columns and you can run the Gram-Schmidt
|
| 1487 |
+
process to make them augmented as orthogonal basis.
|
| 1488 |
+
|
| 1489 |
+
>>> Q_aug = Q.row_join(Matrix([0, 0, 1]))
|
| 1490 |
+
>>> Q_aug = Q_aug.QRdecomposition()[0]
|
| 1491 |
+
>>> Q_aug
|
| 1492 |
+
Matrix([
|
| 1493 |
+
[ 6/7, -69/175, 58/175],
|
| 1494 |
+
[ 3/7, 158/175, -6/175],
|
| 1495 |
+
[-2/7, 6/35, 33/35]])
|
| 1496 |
+
>>> Q_aug.H * Q_aug
|
| 1497 |
+
Matrix([
|
| 1498 |
+
[1, 0, 0],
|
| 1499 |
+
[0, 1, 0],
|
| 1500 |
+
[0, 0, 1]])
|
| 1501 |
+
>>> Q_aug * Q_aug.H
|
| 1502 |
+
Matrix([
|
| 1503 |
+
[1, 0, 0],
|
| 1504 |
+
[0, 1, 0],
|
| 1505 |
+
[0, 0, 1]])
|
| 1506 |
+
|
| 1507 |
+
Augmenting the $R$ matrix with zero row is straightforward.
|
| 1508 |
+
|
| 1509 |
+
>>> R_aug = R.col_join(Matrix([[0, 0, 0]]))
|
| 1510 |
+
>>> R_aug
|
| 1511 |
+
Matrix([
|
| 1512 |
+
[14, 21, 0],
|
| 1513 |
+
[ 0, 175, 0],
|
| 1514 |
+
[ 0, 0, 0]])
|
| 1515 |
+
>>> Q_aug * R_aug == A
|
| 1516 |
+
True
|
| 1517 |
+
|
| 1518 |
+
A zero matrix example:
|
| 1519 |
+
|
| 1520 |
+
>>> from sympy import Matrix
|
| 1521 |
+
>>> A = Matrix.zeros(3, 4)
|
| 1522 |
+
>>> Q, R = A.QRdecomposition()
|
| 1523 |
+
|
| 1524 |
+
They may return matrices with zero rows and columns.
|
| 1525 |
+
|
| 1526 |
+
>>> Q
|
| 1527 |
+
Matrix(3, 0, [])
|
| 1528 |
+
>>> R
|
| 1529 |
+
Matrix(0, 4, [])
|
| 1530 |
+
>>> Q*R
|
| 1531 |
+
Matrix([
|
| 1532 |
+
[0, 0, 0, 0],
|
| 1533 |
+
[0, 0, 0, 0],
|
| 1534 |
+
[0, 0, 0, 0]])
|
| 1535 |
+
|
| 1536 |
+
As the same augmentation rule described above, $Q$ can be augmented
|
| 1537 |
+
with columns of an identity matrix and $R$ can be augmented with
|
| 1538 |
+
rows of a zero matrix.
|
| 1539 |
+
|
| 1540 |
+
>>> Q_aug = Q.row_join(Matrix.eye(3))
|
| 1541 |
+
>>> R_aug = R.col_join(Matrix.zeros(3, 4))
|
| 1542 |
+
>>> Q_aug * Q_aug.T
|
| 1543 |
+
Matrix([
|
| 1544 |
+
[1, 0, 0],
|
| 1545 |
+
[0, 1, 0],
|
| 1546 |
+
[0, 0, 1]])
|
| 1547 |
+
>>> R_aug
|
| 1548 |
+
Matrix([
|
| 1549 |
+
[0, 0, 0, 0],
|
| 1550 |
+
[0, 0, 0, 0],
|
| 1551 |
+
[0, 0, 0, 0]])
|
| 1552 |
+
>>> Q_aug * R_aug == A
|
| 1553 |
+
True
|
| 1554 |
+
|
| 1555 |
+
See Also
|
| 1556 |
+
========
|
| 1557 |
+
|
| 1558 |
+
sympy.matrices.dense.DenseMatrix.cholesky
|
| 1559 |
+
sympy.matrices.dense.DenseMatrix.LDLdecomposition
|
| 1560 |
+
sympy.matrices.matrices.MatrixBase.LUdecomposition
|
| 1561 |
+
QRsolve
|
| 1562 |
+
"""
|
| 1563 |
+
return _QRdecomposition_optional(M, normalize=True)
|
| 1564 |
+
|
| 1565 |
+
def _upper_hessenberg_decomposition(A):
|
| 1566 |
+
"""Converts a matrix into Hessenberg matrix H.
|
| 1567 |
+
|
| 1568 |
+
Returns 2 matrices H, P s.t.
|
| 1569 |
+
$P H P^{T} = A$, where H is an upper hessenberg matrix
|
| 1570 |
+
and P is an orthogonal matrix
|
| 1571 |
+
|
| 1572 |
+
Examples
|
| 1573 |
+
========
|
| 1574 |
+
|
| 1575 |
+
>>> from sympy import Matrix
|
| 1576 |
+
>>> A = Matrix([
|
| 1577 |
+
... [1,2,3],
|
| 1578 |
+
... [-3,5,6],
|
| 1579 |
+
... [4,-8,9],
|
| 1580 |
+
... ])
|
| 1581 |
+
>>> H, P = A.upper_hessenberg_decomposition()
|
| 1582 |
+
>>> H
|
| 1583 |
+
Matrix([
|
| 1584 |
+
[1, 6/5, 17/5],
|
| 1585 |
+
[5, 213/25, -134/25],
|
| 1586 |
+
[0, 216/25, 137/25]])
|
| 1587 |
+
>>> P
|
| 1588 |
+
Matrix([
|
| 1589 |
+
[1, 0, 0],
|
| 1590 |
+
[0, -3/5, 4/5],
|
| 1591 |
+
[0, 4/5, 3/5]])
|
| 1592 |
+
>>> P * H * P.H == A
|
| 1593 |
+
True
|
| 1594 |
+
|
| 1595 |
+
|
| 1596 |
+
References
|
| 1597 |
+
==========
|
| 1598 |
+
|
| 1599 |
+
.. [#] https://mathworld.wolfram.com/HessenbergDecomposition.html
|
| 1600 |
+
"""
|
| 1601 |
+
|
| 1602 |
+
M = A.as_mutable()
|
| 1603 |
+
|
| 1604 |
+
if not M.is_square:
|
| 1605 |
+
raise NonSquareMatrixError("Matrix must be square.")
|
| 1606 |
+
|
| 1607 |
+
n = M.cols
|
| 1608 |
+
P = M.eye(n)
|
| 1609 |
+
H = M
|
| 1610 |
+
|
| 1611 |
+
for j in range(n - 2):
|
| 1612 |
+
|
| 1613 |
+
u = H[j + 1:, j]
|
| 1614 |
+
|
| 1615 |
+
if u[1:, :].is_zero_matrix:
|
| 1616 |
+
continue
|
| 1617 |
+
|
| 1618 |
+
if sign(u[0]) != 0:
|
| 1619 |
+
u[0] = u[0] + sign(u[0]) * u.norm()
|
| 1620 |
+
else:
|
| 1621 |
+
u[0] = u[0] + u.norm()
|
| 1622 |
+
|
| 1623 |
+
v = u / u.norm()
|
| 1624 |
+
|
| 1625 |
+
H[j + 1:, :] = H[j + 1:, :] - 2 * v * (v.H * H[j + 1:, :])
|
| 1626 |
+
H[:, j + 1:] = H[:, j + 1:] - (H[:, j + 1:] * (2 * v)) * v.H
|
| 1627 |
+
P[:, j + 1:] = P[:, j + 1:] - (P[:, j + 1:] * (2 * v)) * v.H
|
| 1628 |
+
|
| 1629 |
+
return H, P
|
venv/lib/python3.10/site-packages/sympy/matrices/dense.py
ADDED
|
@@ -0,0 +1,1090 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
| 6 |
+
from sympy.core.sympify import sympify
|
| 7 |
+
from sympy.functions.elementary.trigonometric import cos, sin
|
| 8 |
+
from sympy.utilities.decorator import doctest_depends_on
|
| 9 |
+
from sympy.utilities.exceptions import sympy_deprecation_warning
|
| 10 |
+
from sympy.utilities.iterables import is_sequence
|
| 11 |
+
|
| 12 |
+
from .common import ShapeError
|
| 13 |
+
from .decompositions import _cholesky, _LDLdecomposition
|
| 14 |
+
from .matrices import MatrixBase
|
| 15 |
+
from .repmatrix import MutableRepMatrix, RepMatrix
|
| 16 |
+
from .solvers import _lower_triangular_solve, _upper_triangular_solve
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def _iszero(x):
|
| 20 |
+
"""Returns True if x is zero."""
|
| 21 |
+
return x.is_zero
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class DenseMatrix(RepMatrix):
|
| 25 |
+
"""Matrix implementation based on DomainMatrix as the internal representation"""
|
| 26 |
+
|
| 27 |
+
#
|
| 28 |
+
# DenseMatrix is a superclass for both MutableDenseMatrix and
|
| 29 |
+
# ImmutableDenseMatrix. Methods shared by both classes but not for the
|
| 30 |
+
# Sparse classes should be implemented here.
|
| 31 |
+
#
|
| 32 |
+
|
| 33 |
+
is_MatrixExpr = False # type: bool
|
| 34 |
+
|
| 35 |
+
_op_priority = 10.01
|
| 36 |
+
_class_priority = 4
|
| 37 |
+
|
| 38 |
+
@property
|
| 39 |
+
def _mat(self):
|
| 40 |
+
sympy_deprecation_warning(
|
| 41 |
+
"""
|
| 42 |
+
The private _mat attribute of Matrix is deprecated. Use the
|
| 43 |
+
.flat() method instead.
|
| 44 |
+
""",
|
| 45 |
+
deprecated_since_version="1.9",
|
| 46 |
+
active_deprecations_target="deprecated-private-matrix-attributes"
|
| 47 |
+
)
|
| 48 |
+
|
| 49 |
+
return self.flat()
|
| 50 |
+
|
| 51 |
+
def _eval_inverse(self, **kwargs):
|
| 52 |
+
return self.inv(method=kwargs.get('method', 'GE'),
|
| 53 |
+
iszerofunc=kwargs.get('iszerofunc', _iszero),
|
| 54 |
+
try_block_diag=kwargs.get('try_block_diag', False))
|
| 55 |
+
|
| 56 |
+
def as_immutable(self):
|
| 57 |
+
"""Returns an Immutable version of this Matrix
|
| 58 |
+
"""
|
| 59 |
+
from .immutable import ImmutableDenseMatrix as cls
|
| 60 |
+
return cls._fromrep(self._rep.copy())
|
| 61 |
+
|
| 62 |
+
def as_mutable(self):
|
| 63 |
+
"""Returns a mutable version of this matrix
|
| 64 |
+
|
| 65 |
+
Examples
|
| 66 |
+
========
|
| 67 |
+
|
| 68 |
+
>>> from sympy import ImmutableMatrix
|
| 69 |
+
>>> X = ImmutableMatrix([[1, 2], [3, 4]])
|
| 70 |
+
>>> Y = X.as_mutable()
|
| 71 |
+
>>> Y[1, 1] = 5 # Can set values in Y
|
| 72 |
+
>>> Y
|
| 73 |
+
Matrix([
|
| 74 |
+
[1, 2],
|
| 75 |
+
[3, 5]])
|
| 76 |
+
"""
|
| 77 |
+
return Matrix(self)
|
| 78 |
+
|
| 79 |
+
def cholesky(self, hermitian=True):
|
| 80 |
+
return _cholesky(self, hermitian=hermitian)
|
| 81 |
+
|
| 82 |
+
def LDLdecomposition(self, hermitian=True):
|
| 83 |
+
return _LDLdecomposition(self, hermitian=hermitian)
|
| 84 |
+
|
| 85 |
+
def lower_triangular_solve(self, rhs):
|
| 86 |
+
return _lower_triangular_solve(self, rhs)
|
| 87 |
+
|
| 88 |
+
def upper_triangular_solve(self, rhs):
|
| 89 |
+
return _upper_triangular_solve(self, rhs)
|
| 90 |
+
|
| 91 |
+
cholesky.__doc__ = _cholesky.__doc__
|
| 92 |
+
LDLdecomposition.__doc__ = _LDLdecomposition.__doc__
|
| 93 |
+
lower_triangular_solve.__doc__ = _lower_triangular_solve.__doc__
|
| 94 |
+
upper_triangular_solve.__doc__ = _upper_triangular_solve.__doc__
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def _force_mutable(x):
|
| 98 |
+
"""Return a matrix as a Matrix, otherwise return x."""
|
| 99 |
+
if getattr(x, 'is_Matrix', False):
|
| 100 |
+
return x.as_mutable()
|
| 101 |
+
elif isinstance(x, Basic):
|
| 102 |
+
return x
|
| 103 |
+
elif hasattr(x, '__array__'):
|
| 104 |
+
a = x.__array__()
|
| 105 |
+
if len(a.shape) == 0:
|
| 106 |
+
return sympify(a)
|
| 107 |
+
return Matrix(x)
|
| 108 |
+
return x
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
class MutableDenseMatrix(DenseMatrix, MutableRepMatrix):
|
| 112 |
+
|
| 113 |
+
def simplify(self, **kwargs):
|
| 114 |
+
"""Applies simplify to the elements of a matrix in place.
|
| 115 |
+
|
| 116 |
+
This is a shortcut for M.applyfunc(lambda x: simplify(x, ratio, measure))
|
| 117 |
+
|
| 118 |
+
See Also
|
| 119 |
+
========
|
| 120 |
+
|
| 121 |
+
sympy.simplify.simplify.simplify
|
| 122 |
+
"""
|
| 123 |
+
from sympy.simplify.simplify import simplify as _simplify
|
| 124 |
+
for (i, j), element in self.todok().items():
|
| 125 |
+
self[i, j] = _simplify(element, **kwargs)
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
MutableMatrix = Matrix = MutableDenseMatrix
|
| 129 |
+
|
| 130 |
+
###########
|
| 131 |
+
# Numpy Utility Functions:
|
| 132 |
+
# list2numpy, matrix2numpy, symmarray
|
| 133 |
+
###########
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def list2numpy(l, dtype=object): # pragma: no cover
|
| 137 |
+
"""Converts Python list of SymPy expressions to a NumPy array.
|
| 138 |
+
|
| 139 |
+
See Also
|
| 140 |
+
========
|
| 141 |
+
|
| 142 |
+
matrix2numpy
|
| 143 |
+
"""
|
| 144 |
+
from numpy import empty
|
| 145 |
+
a = empty(len(l), dtype)
|
| 146 |
+
for i, s in enumerate(l):
|
| 147 |
+
a[i] = s
|
| 148 |
+
return a
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def matrix2numpy(m, dtype=object): # pragma: no cover
|
| 152 |
+
"""Converts SymPy's matrix to a NumPy array.
|
| 153 |
+
|
| 154 |
+
See Also
|
| 155 |
+
========
|
| 156 |
+
|
| 157 |
+
list2numpy
|
| 158 |
+
"""
|
| 159 |
+
from numpy import empty
|
| 160 |
+
a = empty(m.shape, dtype)
|
| 161 |
+
for i in range(m.rows):
|
| 162 |
+
for j in range(m.cols):
|
| 163 |
+
a[i, j] = m[i, j]
|
| 164 |
+
return a
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
###########
|
| 168 |
+
# Rotation matrices:
|
| 169 |
+
# rot_givens, rot_axis[123], rot_ccw_axis[123]
|
| 170 |
+
###########
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
def rot_givens(i, j, theta, dim=3):
|
| 174 |
+
r"""Returns a a Givens rotation matrix, a a rotation in the
|
| 175 |
+
plane spanned by two coordinates axes.
|
| 176 |
+
|
| 177 |
+
Explanation
|
| 178 |
+
===========
|
| 179 |
+
|
| 180 |
+
The Givens rotation corresponds to a generalization of rotation
|
| 181 |
+
matrices to any number of dimensions, given by:
|
| 182 |
+
|
| 183 |
+
.. math::
|
| 184 |
+
G(i, j, \theta) =
|
| 185 |
+
\begin{bmatrix}
|
| 186 |
+
1 & \cdots & 0 & \cdots & 0 & \cdots & 0 \\
|
| 187 |
+
\vdots & \ddots & \vdots & & \vdots & & \vdots \\
|
| 188 |
+
0 & \cdots & c & \cdots & -s & \cdots & 0 \\
|
| 189 |
+
\vdots & & \vdots & \ddots & \vdots & & \vdots \\
|
| 190 |
+
0 & \cdots & s & \cdots & c & \cdots & 0 \\
|
| 191 |
+
\vdots & & \vdots & & \vdots & \ddots & \vdots \\
|
| 192 |
+
0 & \cdots & 0 & \cdots & 0 & \cdots & 1
|
| 193 |
+
\end{bmatrix}
|
| 194 |
+
|
| 195 |
+
Where $c = \cos(\theta)$ and $s = \sin(\theta)$ appear at the intersections
|
| 196 |
+
``i``\th and ``j``\th rows and columns.
|
| 197 |
+
|
| 198 |
+
For fixed ``i > j``\, the non-zero elements of a Givens matrix are
|
| 199 |
+
given by:
|
| 200 |
+
|
| 201 |
+
- $g_{kk} = 1$ for $k \ne i,\,j$
|
| 202 |
+
- $g_{kk} = c$ for $k = i,\,j$
|
| 203 |
+
- $g_{ji} = -g_{ij} = -s$
|
| 204 |
+
|
| 205 |
+
Parameters
|
| 206 |
+
==========
|
| 207 |
+
|
| 208 |
+
i : int between ``0`` and ``dim - 1``
|
| 209 |
+
Represents first axis
|
| 210 |
+
j : int between ``0`` and ``dim - 1``
|
| 211 |
+
Represents second axis
|
| 212 |
+
dim : int bigger than 1
|
| 213 |
+
Number of dimentions. Defaults to 3.
|
| 214 |
+
|
| 215 |
+
Examples
|
| 216 |
+
========
|
| 217 |
+
|
| 218 |
+
>>> from sympy import pi, rot_givens
|
| 219 |
+
|
| 220 |
+
A counterclockwise rotation of pi/3 (60 degrees) around
|
| 221 |
+
the third axis (z-axis):
|
| 222 |
+
|
| 223 |
+
>>> rot_givens(1, 0, pi/3)
|
| 224 |
+
Matrix([
|
| 225 |
+
[ 1/2, -sqrt(3)/2, 0],
|
| 226 |
+
[sqrt(3)/2, 1/2, 0],
|
| 227 |
+
[ 0, 0, 1]])
|
| 228 |
+
|
| 229 |
+
If we rotate by pi/2 (90 degrees):
|
| 230 |
+
|
| 231 |
+
>>> rot_givens(1, 0, pi/2)
|
| 232 |
+
Matrix([
|
| 233 |
+
[0, -1, 0],
|
| 234 |
+
[1, 0, 0],
|
| 235 |
+
[0, 0, 1]])
|
| 236 |
+
|
| 237 |
+
This can be generalized to any number
|
| 238 |
+
of dimensions:
|
| 239 |
+
|
| 240 |
+
>>> rot_givens(1, 0, pi/2, dim=4)
|
| 241 |
+
Matrix([
|
| 242 |
+
[0, -1, 0, 0],
|
| 243 |
+
[1, 0, 0, 0],
|
| 244 |
+
[0, 0, 1, 0],
|
| 245 |
+
[0, 0, 0, 1]])
|
| 246 |
+
|
| 247 |
+
References
|
| 248 |
+
==========
|
| 249 |
+
|
| 250 |
+
.. [1] https://en.wikipedia.org/wiki/Givens_rotation
|
| 251 |
+
|
| 252 |
+
See Also
|
| 253 |
+
========
|
| 254 |
+
|
| 255 |
+
rot_axis1: Returns a rotation matrix for a rotation of theta (in radians)
|
| 256 |
+
about the 1-axis (clockwise around the x axis)
|
| 257 |
+
rot_axis2: Returns a rotation matrix for a rotation of theta (in radians)
|
| 258 |
+
about the 2-axis (clockwise around the y axis)
|
| 259 |
+
rot_axis3: Returns a rotation matrix for a rotation of theta (in radians)
|
| 260 |
+
about the 3-axis (clockwise around the z axis)
|
| 261 |
+
rot_ccw_axis1: Returns a rotation matrix for a rotation of theta (in radians)
|
| 262 |
+
about the 1-axis (counterclockwise around the x axis)
|
| 263 |
+
rot_ccw_axis2: Returns a rotation matrix for a rotation of theta (in radians)
|
| 264 |
+
about the 2-axis (counterclockwise around the y axis)
|
| 265 |
+
rot_ccw_axis3: Returns a rotation matrix for a rotation of theta (in radians)
|
| 266 |
+
about the 3-axis (counterclockwise around the z axis)
|
| 267 |
+
"""
|
| 268 |
+
if not isinstance(dim, int) or dim < 2:
|
| 269 |
+
raise ValueError('dim must be an integer biggen than one, '
|
| 270 |
+
'got {}.'.format(dim))
|
| 271 |
+
|
| 272 |
+
if i == j:
|
| 273 |
+
raise ValueError('i and j must be different, '
|
| 274 |
+
'got ({}, {})'.format(i, j))
|
| 275 |
+
|
| 276 |
+
for ij in [i, j]:
|
| 277 |
+
if not isinstance(ij, int) or ij < 0 or ij > dim - 1:
|
| 278 |
+
raise ValueError('i and j must be integers between 0 and '
|
| 279 |
+
'{}, got i={} and j={}.'.format(dim-1, i, j))
|
| 280 |
+
|
| 281 |
+
theta = sympify(theta)
|
| 282 |
+
c = cos(theta)
|
| 283 |
+
s = sin(theta)
|
| 284 |
+
M = eye(dim)
|
| 285 |
+
M[i, i] = c
|
| 286 |
+
M[j, j] = c
|
| 287 |
+
M[i, j] = s
|
| 288 |
+
M[j, i] = -s
|
| 289 |
+
return M
|
| 290 |
+
|
| 291 |
+
|
| 292 |
+
def rot_axis3(theta):
|
| 293 |
+
r"""Returns a rotation matrix for a rotation of theta (in radians)
|
| 294 |
+
about the 3-axis.
|
| 295 |
+
|
| 296 |
+
Explanation
|
| 297 |
+
===========
|
| 298 |
+
|
| 299 |
+
For a right-handed coordinate system, this corresponds to a
|
| 300 |
+
clockwise rotation around the `z`-axis, given by:
|
| 301 |
+
|
| 302 |
+
.. math::
|
| 303 |
+
|
| 304 |
+
R = \begin{bmatrix}
|
| 305 |
+
\cos(\theta) & \sin(\theta) & 0 \\
|
| 306 |
+
-\sin(\theta) & \cos(\theta) & 0 \\
|
| 307 |
+
0 & 0 & 1
|
| 308 |
+
\end{bmatrix}
|
| 309 |
+
|
| 310 |
+
Examples
|
| 311 |
+
========
|
| 312 |
+
|
| 313 |
+
>>> from sympy import pi, rot_axis3
|
| 314 |
+
|
| 315 |
+
A rotation of pi/3 (60 degrees):
|
| 316 |
+
|
| 317 |
+
>>> theta = pi/3
|
| 318 |
+
>>> rot_axis3(theta)
|
| 319 |
+
Matrix([
|
| 320 |
+
[ 1/2, sqrt(3)/2, 0],
|
| 321 |
+
[-sqrt(3)/2, 1/2, 0],
|
| 322 |
+
[ 0, 0, 1]])
|
| 323 |
+
|
| 324 |
+
If we rotate by pi/2 (90 degrees):
|
| 325 |
+
|
| 326 |
+
>>> rot_axis3(pi/2)
|
| 327 |
+
Matrix([
|
| 328 |
+
[ 0, 1, 0],
|
| 329 |
+
[-1, 0, 0],
|
| 330 |
+
[ 0, 0, 1]])
|
| 331 |
+
|
| 332 |
+
See Also
|
| 333 |
+
========
|
| 334 |
+
|
| 335 |
+
rot_givens: Returns a Givens rotation matrix (generalized rotation for
|
| 336 |
+
any number of dimensions)
|
| 337 |
+
rot_ccw_axis3: Returns a rotation matrix for a rotation of theta (in radians)
|
| 338 |
+
about the 3-axis (counterclockwise around the z axis)
|
| 339 |
+
rot_axis1: Returns a rotation matrix for a rotation of theta (in radians)
|
| 340 |
+
about the 1-axis (clockwise around the x axis)
|
| 341 |
+
rot_axis2: Returns a rotation matrix for a rotation of theta (in radians)
|
| 342 |
+
about the 2-axis (clockwise around the y axis)
|
| 343 |
+
"""
|
| 344 |
+
return rot_givens(0, 1, theta, dim=3)
|
| 345 |
+
|
| 346 |
+
|
| 347 |
+
def rot_axis2(theta):
|
| 348 |
+
r"""Returns a rotation matrix for a rotation of theta (in radians)
|
| 349 |
+
about the 2-axis.
|
| 350 |
+
|
| 351 |
+
Explanation
|
| 352 |
+
===========
|
| 353 |
+
|
| 354 |
+
For a right-handed coordinate system, this corresponds to a
|
| 355 |
+
clockwise rotation around the `y`-axis, given by:
|
| 356 |
+
|
| 357 |
+
.. math::
|
| 358 |
+
|
| 359 |
+
R = \begin{bmatrix}
|
| 360 |
+
\cos(\theta) & 0 & -\sin(\theta) \\
|
| 361 |
+
0 & 1 & 0 \\
|
| 362 |
+
\sin(\theta) & 0 & \cos(\theta)
|
| 363 |
+
\end{bmatrix}
|
| 364 |
+
|
| 365 |
+
Examples
|
| 366 |
+
========
|
| 367 |
+
|
| 368 |
+
>>> from sympy import pi, rot_axis2
|
| 369 |
+
|
| 370 |
+
A rotation of pi/3 (60 degrees):
|
| 371 |
+
|
| 372 |
+
>>> theta = pi/3
|
| 373 |
+
>>> rot_axis2(theta)
|
| 374 |
+
Matrix([
|
| 375 |
+
[ 1/2, 0, -sqrt(3)/2],
|
| 376 |
+
[ 0, 1, 0],
|
| 377 |
+
[sqrt(3)/2, 0, 1/2]])
|
| 378 |
+
|
| 379 |
+
If we rotate by pi/2 (90 degrees):
|
| 380 |
+
|
| 381 |
+
>>> rot_axis2(pi/2)
|
| 382 |
+
Matrix([
|
| 383 |
+
[0, 0, -1],
|
| 384 |
+
[0, 1, 0],
|
| 385 |
+
[1, 0, 0]])
|
| 386 |
+
|
| 387 |
+
See Also
|
| 388 |
+
========
|
| 389 |
+
|
| 390 |
+
rot_givens: Returns a Givens rotation matrix (generalized rotation for
|
| 391 |
+
any number of dimensions)
|
| 392 |
+
rot_ccw_axis2: Returns a rotation matrix for a rotation of theta (in radians)
|
| 393 |
+
about the 2-axis (clockwise around the y axis)
|
| 394 |
+
rot_axis1: Returns a rotation matrix for a rotation of theta (in radians)
|
| 395 |
+
about the 1-axis (counterclockwise around the x axis)
|
| 396 |
+
rot_axis3: Returns a rotation matrix for a rotation of theta (in radians)
|
| 397 |
+
about the 3-axis (counterclockwise around the z axis)
|
| 398 |
+
"""
|
| 399 |
+
return rot_givens(2, 0, theta, dim=3)
|
| 400 |
+
|
| 401 |
+
|
| 402 |
+
def rot_axis1(theta):
|
| 403 |
+
r"""Returns a rotation matrix for a rotation of theta (in radians)
|
| 404 |
+
about the 1-axis.
|
| 405 |
+
|
| 406 |
+
Explanation
|
| 407 |
+
===========
|
| 408 |
+
|
| 409 |
+
For a right-handed coordinate system, this corresponds to a
|
| 410 |
+
clockwise rotation around the `x`-axis, given by:
|
| 411 |
+
|
| 412 |
+
.. math::
|
| 413 |
+
|
| 414 |
+
R = \begin{bmatrix}
|
| 415 |
+
1 & 0 & 0 \\
|
| 416 |
+
0 & \cos(\theta) & \sin(\theta) \\
|
| 417 |
+
0 & -\sin(\theta) & \cos(\theta)
|
| 418 |
+
\end{bmatrix}
|
| 419 |
+
|
| 420 |
+
Examples
|
| 421 |
+
========
|
| 422 |
+
|
| 423 |
+
>>> from sympy import pi, rot_axis1
|
| 424 |
+
|
| 425 |
+
A rotation of pi/3 (60 degrees):
|
| 426 |
+
|
| 427 |
+
>>> theta = pi/3
|
| 428 |
+
>>> rot_axis1(theta)
|
| 429 |
+
Matrix([
|
| 430 |
+
[1, 0, 0],
|
| 431 |
+
[0, 1/2, sqrt(3)/2],
|
| 432 |
+
[0, -sqrt(3)/2, 1/2]])
|
| 433 |
+
|
| 434 |
+
If we rotate by pi/2 (90 degrees):
|
| 435 |
+
|
| 436 |
+
>>> rot_axis1(pi/2)
|
| 437 |
+
Matrix([
|
| 438 |
+
[1, 0, 0],
|
| 439 |
+
[0, 0, 1],
|
| 440 |
+
[0, -1, 0]])
|
| 441 |
+
|
| 442 |
+
See Also
|
| 443 |
+
========
|
| 444 |
+
|
| 445 |
+
rot_givens: Returns a Givens rotation matrix (generalized rotation for
|
| 446 |
+
any number of dimensions)
|
| 447 |
+
rot_ccw_axis1: Returns a rotation matrix for a rotation of theta (in radians)
|
| 448 |
+
about the 1-axis (counterclockwise around the x axis)
|
| 449 |
+
rot_axis2: Returns a rotation matrix for a rotation of theta (in radians)
|
| 450 |
+
about the 2-axis (clockwise around the y axis)
|
| 451 |
+
rot_axis3: Returns a rotation matrix for a rotation of theta (in radians)
|
| 452 |
+
about the 3-axis (clockwise around the z axis)
|
| 453 |
+
"""
|
| 454 |
+
return rot_givens(1, 2, theta, dim=3)
|
| 455 |
+
|
| 456 |
+
|
| 457 |
+
def rot_ccw_axis3(theta):
|
| 458 |
+
r"""Returns a rotation matrix for a rotation of theta (in radians)
|
| 459 |
+
about the 3-axis.
|
| 460 |
+
|
| 461 |
+
Explanation
|
| 462 |
+
===========
|
| 463 |
+
|
| 464 |
+
For a right-handed coordinate system, this corresponds to a
|
| 465 |
+
counterclockwise rotation around the `z`-axis, given by:
|
| 466 |
+
|
| 467 |
+
.. math::
|
| 468 |
+
|
| 469 |
+
R = \begin{bmatrix}
|
| 470 |
+
\cos(\theta) & -\sin(\theta) & 0 \\
|
| 471 |
+
\sin(\theta) & \cos(\theta) & 0 \\
|
| 472 |
+
0 & 0 & 1
|
| 473 |
+
\end{bmatrix}
|
| 474 |
+
|
| 475 |
+
Examples
|
| 476 |
+
========
|
| 477 |
+
|
| 478 |
+
>>> from sympy import pi, rot_ccw_axis3
|
| 479 |
+
|
| 480 |
+
A rotation of pi/3 (60 degrees):
|
| 481 |
+
|
| 482 |
+
>>> theta = pi/3
|
| 483 |
+
>>> rot_ccw_axis3(theta)
|
| 484 |
+
Matrix([
|
| 485 |
+
[ 1/2, -sqrt(3)/2, 0],
|
| 486 |
+
[sqrt(3)/2, 1/2, 0],
|
| 487 |
+
[ 0, 0, 1]])
|
| 488 |
+
|
| 489 |
+
If we rotate by pi/2 (90 degrees):
|
| 490 |
+
|
| 491 |
+
>>> rot_ccw_axis3(pi/2)
|
| 492 |
+
Matrix([
|
| 493 |
+
[0, -1, 0],
|
| 494 |
+
[1, 0, 0],
|
| 495 |
+
[0, 0, 1]])
|
| 496 |
+
|
| 497 |
+
See Also
|
| 498 |
+
========
|
| 499 |
+
|
| 500 |
+
rot_givens: Returns a Givens rotation matrix (generalized rotation for
|
| 501 |
+
any number of dimensions)
|
| 502 |
+
rot_axis3: Returns a rotation matrix for a rotation of theta (in radians)
|
| 503 |
+
about the 3-axis (clockwise around the z axis)
|
| 504 |
+
rot_ccw_axis1: Returns a rotation matrix for a rotation of theta (in radians)
|
| 505 |
+
about the 1-axis (counterclockwise around the x axis)
|
| 506 |
+
rot_ccw_axis2: Returns a rotation matrix for a rotation of theta (in radians)
|
| 507 |
+
about the 2-axis (counterclockwise around the y axis)
|
| 508 |
+
"""
|
| 509 |
+
return rot_givens(1, 0, theta, dim=3)
|
| 510 |
+
|
| 511 |
+
|
| 512 |
+
def rot_ccw_axis2(theta):
|
| 513 |
+
r"""Returns a rotation matrix for a rotation of theta (in radians)
|
| 514 |
+
about the 2-axis.
|
| 515 |
+
|
| 516 |
+
Explanation
|
| 517 |
+
===========
|
| 518 |
+
|
| 519 |
+
For a right-handed coordinate system, this corresponds to a
|
| 520 |
+
counterclockwise rotation around the `y`-axis, given by:
|
| 521 |
+
|
| 522 |
+
.. math::
|
| 523 |
+
|
| 524 |
+
R = \begin{bmatrix}
|
| 525 |
+
\cos(\theta) & 0 & \sin(\theta) \\
|
| 526 |
+
0 & 1 & 0 \\
|
| 527 |
+
-\sin(\theta) & 0 & \cos(\theta)
|
| 528 |
+
\end{bmatrix}
|
| 529 |
+
|
| 530 |
+
Examples
|
| 531 |
+
========
|
| 532 |
+
|
| 533 |
+
>>> from sympy import pi, rot_ccw_axis2
|
| 534 |
+
|
| 535 |
+
A rotation of pi/3 (60 degrees):
|
| 536 |
+
|
| 537 |
+
>>> theta = pi/3
|
| 538 |
+
>>> rot_ccw_axis2(theta)
|
| 539 |
+
Matrix([
|
| 540 |
+
[ 1/2, 0, sqrt(3)/2],
|
| 541 |
+
[ 0, 1, 0],
|
| 542 |
+
[-sqrt(3)/2, 0, 1/2]])
|
| 543 |
+
|
| 544 |
+
If we rotate by pi/2 (90 degrees):
|
| 545 |
+
|
| 546 |
+
>>> rot_ccw_axis2(pi/2)
|
| 547 |
+
Matrix([
|
| 548 |
+
[ 0, 0, 1],
|
| 549 |
+
[ 0, 1, 0],
|
| 550 |
+
[-1, 0, 0]])
|
| 551 |
+
|
| 552 |
+
See Also
|
| 553 |
+
========
|
| 554 |
+
|
| 555 |
+
rot_givens: Returns a Givens rotation matrix (generalized rotation for
|
| 556 |
+
any number of dimensions)
|
| 557 |
+
rot_axis2: Returns a rotation matrix for a rotation of theta (in radians)
|
| 558 |
+
about the 2-axis (clockwise around the y axis)
|
| 559 |
+
rot_ccw_axis1: Returns a rotation matrix for a rotation of theta (in radians)
|
| 560 |
+
about the 1-axis (counterclockwise around the x axis)
|
| 561 |
+
rot_ccw_axis3: Returns a rotation matrix for a rotation of theta (in radians)
|
| 562 |
+
about the 3-axis (counterclockwise around the z axis)
|
| 563 |
+
"""
|
| 564 |
+
return rot_givens(0, 2, theta, dim=3)
|
| 565 |
+
|
| 566 |
+
|
| 567 |
+
def rot_ccw_axis1(theta):
|
| 568 |
+
r"""Returns a rotation matrix for a rotation of theta (in radians)
|
| 569 |
+
about the 1-axis.
|
| 570 |
+
|
| 571 |
+
Explanation
|
| 572 |
+
===========
|
| 573 |
+
|
| 574 |
+
For a right-handed coordinate system, this corresponds to a
|
| 575 |
+
counterclockwise rotation around the `x`-axis, given by:
|
| 576 |
+
|
| 577 |
+
.. math::
|
| 578 |
+
|
| 579 |
+
R = \begin{bmatrix}
|
| 580 |
+
1 & 0 & 0 \\
|
| 581 |
+
0 & \cos(\theta) & -\sin(\theta) \\
|
| 582 |
+
0 & \sin(\theta) & \cos(\theta)
|
| 583 |
+
\end{bmatrix}
|
| 584 |
+
|
| 585 |
+
Examples
|
| 586 |
+
========
|
| 587 |
+
|
| 588 |
+
>>> from sympy import pi, rot_ccw_axis1
|
| 589 |
+
|
| 590 |
+
A rotation of pi/3 (60 degrees):
|
| 591 |
+
|
| 592 |
+
>>> theta = pi/3
|
| 593 |
+
>>> rot_ccw_axis1(theta)
|
| 594 |
+
Matrix([
|
| 595 |
+
[1, 0, 0],
|
| 596 |
+
[0, 1/2, -sqrt(3)/2],
|
| 597 |
+
[0, sqrt(3)/2, 1/2]])
|
| 598 |
+
|
| 599 |
+
If we rotate by pi/2 (90 degrees):
|
| 600 |
+
|
| 601 |
+
>>> rot_ccw_axis1(pi/2)
|
| 602 |
+
Matrix([
|
| 603 |
+
[1, 0, 0],
|
| 604 |
+
[0, 0, -1],
|
| 605 |
+
[0, 1, 0]])
|
| 606 |
+
|
| 607 |
+
See Also
|
| 608 |
+
========
|
| 609 |
+
|
| 610 |
+
rot_givens: Returns a Givens rotation matrix (generalized rotation for
|
| 611 |
+
any number of dimensions)
|
| 612 |
+
rot_axis1: Returns a rotation matrix for a rotation of theta (in radians)
|
| 613 |
+
about the 1-axis (clockwise around the x axis)
|
| 614 |
+
rot_ccw_axis2: Returns a rotation matrix for a rotation of theta (in radians)
|
| 615 |
+
about the 2-axis (counterclockwise around the y axis)
|
| 616 |
+
rot_ccw_axis3: Returns a rotation matrix for a rotation of theta (in radians)
|
| 617 |
+
about the 3-axis (counterclockwise around the z axis)
|
| 618 |
+
"""
|
| 619 |
+
return rot_givens(2, 1, theta, dim=3)
|
| 620 |
+
|
| 621 |
+
|
| 622 |
+
@doctest_depends_on(modules=('numpy',))
|
| 623 |
+
def symarray(prefix, shape, **kwargs): # pragma: no cover
|
| 624 |
+
r"""Create a numpy ndarray of symbols (as an object array).
|
| 625 |
+
|
| 626 |
+
The created symbols are named ``prefix_i1_i2_``... You should thus provide a
|
| 627 |
+
non-empty prefix if you want your symbols to be unique for different output
|
| 628 |
+
arrays, as SymPy symbols with identical names are the same object.
|
| 629 |
+
|
| 630 |
+
Parameters
|
| 631 |
+
----------
|
| 632 |
+
|
| 633 |
+
prefix : string
|
| 634 |
+
A prefix prepended to the name of every symbol.
|
| 635 |
+
|
| 636 |
+
shape : int or tuple
|
| 637 |
+
Shape of the created array. If an int, the array is one-dimensional; for
|
| 638 |
+
more than one dimension the shape must be a tuple.
|
| 639 |
+
|
| 640 |
+
\*\*kwargs : dict
|
| 641 |
+
keyword arguments passed on to Symbol
|
| 642 |
+
|
| 643 |
+
Examples
|
| 644 |
+
========
|
| 645 |
+
These doctests require numpy.
|
| 646 |
+
|
| 647 |
+
>>> from sympy import symarray
|
| 648 |
+
>>> symarray('', 3)
|
| 649 |
+
[_0 _1 _2]
|
| 650 |
+
|
| 651 |
+
If you want multiple symarrays to contain distinct symbols, you *must*
|
| 652 |
+
provide unique prefixes:
|
| 653 |
+
|
| 654 |
+
>>> a = symarray('', 3)
|
| 655 |
+
>>> b = symarray('', 3)
|
| 656 |
+
>>> a[0] == b[0]
|
| 657 |
+
True
|
| 658 |
+
>>> a = symarray('a', 3)
|
| 659 |
+
>>> b = symarray('b', 3)
|
| 660 |
+
>>> a[0] == b[0]
|
| 661 |
+
False
|
| 662 |
+
|
| 663 |
+
Creating symarrays with a prefix:
|
| 664 |
+
|
| 665 |
+
>>> symarray('a', 3)
|
| 666 |
+
[a_0 a_1 a_2]
|
| 667 |
+
|
| 668 |
+
For more than one dimension, the shape must be given as a tuple:
|
| 669 |
+
|
| 670 |
+
>>> symarray('a', (2, 3))
|
| 671 |
+
[[a_0_0 a_0_1 a_0_2]
|
| 672 |
+
[a_1_0 a_1_1 a_1_2]]
|
| 673 |
+
>>> symarray('a', (2, 3, 2))
|
| 674 |
+
[[[a_0_0_0 a_0_0_1]
|
| 675 |
+
[a_0_1_0 a_0_1_1]
|
| 676 |
+
[a_0_2_0 a_0_2_1]]
|
| 677 |
+
<BLANKLINE>
|
| 678 |
+
[[a_1_0_0 a_1_0_1]
|
| 679 |
+
[a_1_1_0 a_1_1_1]
|
| 680 |
+
[a_1_2_0 a_1_2_1]]]
|
| 681 |
+
|
| 682 |
+
For setting assumptions of the underlying Symbols:
|
| 683 |
+
|
| 684 |
+
>>> [s.is_real for s in symarray('a', 2, real=True)]
|
| 685 |
+
[True, True]
|
| 686 |
+
"""
|
| 687 |
+
from numpy import empty, ndindex
|
| 688 |
+
arr = empty(shape, dtype=object)
|
| 689 |
+
for index in ndindex(shape):
|
| 690 |
+
arr[index] = Symbol('%s_%s' % (prefix, '_'.join(map(str, index))),
|
| 691 |
+
**kwargs)
|
| 692 |
+
return arr
|
| 693 |
+
|
| 694 |
+
|
| 695 |
+
###############
|
| 696 |
+
# Functions
|
| 697 |
+
###############
|
| 698 |
+
|
| 699 |
+
def casoratian(seqs, n, zero=True):
|
| 700 |
+
"""Given linear difference operator L of order 'k' and homogeneous
|
| 701 |
+
equation Ly = 0 we want to compute kernel of L, which is a set
|
| 702 |
+
of 'k' sequences: a(n), b(n), ... z(n).
|
| 703 |
+
|
| 704 |
+
Solutions of L are linearly independent iff their Casoratian,
|
| 705 |
+
denoted as C(a, b, ..., z), do not vanish for n = 0.
|
| 706 |
+
|
| 707 |
+
Casoratian is defined by k x k determinant::
|
| 708 |
+
|
| 709 |
+
+ a(n) b(n) . . . z(n) +
|
| 710 |
+
| a(n+1) b(n+1) . . . z(n+1) |
|
| 711 |
+
| . . . . |
|
| 712 |
+
| . . . . |
|
| 713 |
+
| . . . . |
|
| 714 |
+
+ a(n+k-1) b(n+k-1) . . . z(n+k-1) +
|
| 715 |
+
|
| 716 |
+
It proves very useful in rsolve_hyper() where it is applied
|
| 717 |
+
to a generating set of a recurrence to factor out linearly
|
| 718 |
+
dependent solutions and return a basis:
|
| 719 |
+
|
| 720 |
+
>>> from sympy import Symbol, casoratian, factorial
|
| 721 |
+
>>> n = Symbol('n', integer=True)
|
| 722 |
+
|
| 723 |
+
Exponential and factorial are linearly independent:
|
| 724 |
+
|
| 725 |
+
>>> casoratian([2**n, factorial(n)], n) != 0
|
| 726 |
+
True
|
| 727 |
+
|
| 728 |
+
"""
|
| 729 |
+
|
| 730 |
+
seqs = list(map(sympify, seqs))
|
| 731 |
+
|
| 732 |
+
if not zero:
|
| 733 |
+
f = lambda i, j: seqs[j].subs(n, n + i)
|
| 734 |
+
else:
|
| 735 |
+
f = lambda i, j: seqs[j].subs(n, i)
|
| 736 |
+
|
| 737 |
+
k = len(seqs)
|
| 738 |
+
|
| 739 |
+
return Matrix(k, k, f).det()
|
| 740 |
+
|
| 741 |
+
|
| 742 |
+
def eye(*args, **kwargs):
|
| 743 |
+
"""Create square identity matrix n x n
|
| 744 |
+
|
| 745 |
+
See Also
|
| 746 |
+
========
|
| 747 |
+
|
| 748 |
+
diag
|
| 749 |
+
zeros
|
| 750 |
+
ones
|
| 751 |
+
"""
|
| 752 |
+
|
| 753 |
+
return Matrix.eye(*args, **kwargs)
|
| 754 |
+
|
| 755 |
+
|
| 756 |
+
def diag(*values, strict=True, unpack=False, **kwargs):
|
| 757 |
+
"""Returns a matrix with the provided values placed on the
|
| 758 |
+
diagonal. If non-square matrices are included, they will
|
| 759 |
+
produce a block-diagonal matrix.
|
| 760 |
+
|
| 761 |
+
Examples
|
| 762 |
+
========
|
| 763 |
+
|
| 764 |
+
This version of diag is a thin wrapper to Matrix.diag that differs
|
| 765 |
+
in that it treats all lists like matrices -- even when a single list
|
| 766 |
+
is given. If this is not desired, either put a `*` before the list or
|
| 767 |
+
set `unpack=True`.
|
| 768 |
+
|
| 769 |
+
>>> from sympy import diag
|
| 770 |
+
|
| 771 |
+
>>> diag([1, 2, 3], unpack=True) # = diag(1,2,3) or diag(*[1,2,3])
|
| 772 |
+
Matrix([
|
| 773 |
+
[1, 0, 0],
|
| 774 |
+
[0, 2, 0],
|
| 775 |
+
[0, 0, 3]])
|
| 776 |
+
|
| 777 |
+
>>> diag([1, 2, 3]) # a column vector
|
| 778 |
+
Matrix([
|
| 779 |
+
[1],
|
| 780 |
+
[2],
|
| 781 |
+
[3]])
|
| 782 |
+
|
| 783 |
+
See Also
|
| 784 |
+
========
|
| 785 |
+
.common.MatrixCommon.eye
|
| 786 |
+
.common.MatrixCommon.diagonal
|
| 787 |
+
.common.MatrixCommon.diag
|
| 788 |
+
.expressions.blockmatrix.BlockMatrix
|
| 789 |
+
"""
|
| 790 |
+
return Matrix.diag(*values, strict=strict, unpack=unpack, **kwargs)
|
| 791 |
+
|
| 792 |
+
|
| 793 |
+
def GramSchmidt(vlist, orthonormal=False):
|
| 794 |
+
"""Apply the Gram-Schmidt process to a set of vectors.
|
| 795 |
+
|
| 796 |
+
Parameters
|
| 797 |
+
==========
|
| 798 |
+
|
| 799 |
+
vlist : List of Matrix
|
| 800 |
+
Vectors to be orthogonalized for.
|
| 801 |
+
|
| 802 |
+
orthonormal : Bool, optional
|
| 803 |
+
If true, return an orthonormal basis.
|
| 804 |
+
|
| 805 |
+
Returns
|
| 806 |
+
=======
|
| 807 |
+
|
| 808 |
+
vlist : List of Matrix
|
| 809 |
+
Orthogonalized vectors
|
| 810 |
+
|
| 811 |
+
Notes
|
| 812 |
+
=====
|
| 813 |
+
|
| 814 |
+
This routine is mostly duplicate from ``Matrix.orthogonalize``,
|
| 815 |
+
except for some difference that this always raises error when
|
| 816 |
+
linearly dependent vectors are found, and the keyword ``normalize``
|
| 817 |
+
has been named as ``orthonormal`` in this function.
|
| 818 |
+
|
| 819 |
+
See Also
|
| 820 |
+
========
|
| 821 |
+
|
| 822 |
+
.matrices.MatrixSubspaces.orthogonalize
|
| 823 |
+
|
| 824 |
+
References
|
| 825 |
+
==========
|
| 826 |
+
|
| 827 |
+
.. [1] https://en.wikipedia.org/wiki/Gram%E2%80%93Schmidt_process
|
| 828 |
+
"""
|
| 829 |
+
return MutableDenseMatrix.orthogonalize(
|
| 830 |
+
*vlist, normalize=orthonormal, rankcheck=True
|
| 831 |
+
)
|
| 832 |
+
|
| 833 |
+
|
| 834 |
+
def hessian(f, varlist, constraints=()):
|
| 835 |
+
"""Compute Hessian matrix for a function f wrt parameters in varlist
|
| 836 |
+
which may be given as a sequence or a row/column vector. A list of
|
| 837 |
+
constraints may optionally be given.
|
| 838 |
+
|
| 839 |
+
Examples
|
| 840 |
+
========
|
| 841 |
+
|
| 842 |
+
>>> from sympy import Function, hessian, pprint
|
| 843 |
+
>>> from sympy.abc import x, y
|
| 844 |
+
>>> f = Function('f')(x, y)
|
| 845 |
+
>>> g1 = Function('g')(x, y)
|
| 846 |
+
>>> g2 = x**2 + 3*y
|
| 847 |
+
>>> pprint(hessian(f, (x, y), [g1, g2]))
|
| 848 |
+
[ d d ]
|
| 849 |
+
[ 0 0 --(g(x, y)) --(g(x, y)) ]
|
| 850 |
+
[ dx dy ]
|
| 851 |
+
[ ]
|
| 852 |
+
[ 0 0 2*x 3 ]
|
| 853 |
+
[ ]
|
| 854 |
+
[ 2 2 ]
|
| 855 |
+
[d d d ]
|
| 856 |
+
[--(g(x, y)) 2*x ---(f(x, y)) -----(f(x, y))]
|
| 857 |
+
[dx 2 dy dx ]
|
| 858 |
+
[ dx ]
|
| 859 |
+
[ ]
|
| 860 |
+
[ 2 2 ]
|
| 861 |
+
[d d d ]
|
| 862 |
+
[--(g(x, y)) 3 -----(f(x, y)) ---(f(x, y)) ]
|
| 863 |
+
[dy dy dx 2 ]
|
| 864 |
+
[ dy ]
|
| 865 |
+
|
| 866 |
+
References
|
| 867 |
+
==========
|
| 868 |
+
|
| 869 |
+
.. [1] https://en.wikipedia.org/wiki/Hessian_matrix
|
| 870 |
+
|
| 871 |
+
See Also
|
| 872 |
+
========
|
| 873 |
+
|
| 874 |
+
sympy.matrices.matrices.MatrixCalculus.jacobian
|
| 875 |
+
wronskian
|
| 876 |
+
"""
|
| 877 |
+
# f is the expression representing a function f, return regular matrix
|
| 878 |
+
if isinstance(varlist, MatrixBase):
|
| 879 |
+
if 1 not in varlist.shape:
|
| 880 |
+
raise ShapeError("`varlist` must be a column or row vector.")
|
| 881 |
+
if varlist.cols == 1:
|
| 882 |
+
varlist = varlist.T
|
| 883 |
+
varlist = varlist.tolist()[0]
|
| 884 |
+
if is_sequence(varlist):
|
| 885 |
+
n = len(varlist)
|
| 886 |
+
if not n:
|
| 887 |
+
raise ShapeError("`len(varlist)` must not be zero.")
|
| 888 |
+
else:
|
| 889 |
+
raise ValueError("Improper variable list in hessian function")
|
| 890 |
+
if not getattr(f, 'diff'):
|
| 891 |
+
# check differentiability
|
| 892 |
+
raise ValueError("Function `f` (%s) is not differentiable" % f)
|
| 893 |
+
m = len(constraints)
|
| 894 |
+
N = m + n
|
| 895 |
+
out = zeros(N)
|
| 896 |
+
for k, g in enumerate(constraints):
|
| 897 |
+
if not getattr(g, 'diff'):
|
| 898 |
+
# check differentiability
|
| 899 |
+
raise ValueError("Function `f` (%s) is not differentiable" % f)
|
| 900 |
+
for i in range(n):
|
| 901 |
+
out[k, i + m] = g.diff(varlist[i])
|
| 902 |
+
for i in range(n):
|
| 903 |
+
for j in range(i, n):
|
| 904 |
+
out[i + m, j + m] = f.diff(varlist[i]).diff(varlist[j])
|
| 905 |
+
for i in range(N):
|
| 906 |
+
for j in range(i + 1, N):
|
| 907 |
+
out[j, i] = out[i, j]
|
| 908 |
+
return out
|
| 909 |
+
|
| 910 |
+
|
| 911 |
+
def jordan_cell(eigenval, n):
|
| 912 |
+
"""
|
| 913 |
+
Create a Jordan block:
|
| 914 |
+
|
| 915 |
+
Examples
|
| 916 |
+
========
|
| 917 |
+
|
| 918 |
+
>>> from sympy import jordan_cell
|
| 919 |
+
>>> from sympy.abc import x
|
| 920 |
+
>>> jordan_cell(x, 4)
|
| 921 |
+
Matrix([
|
| 922 |
+
[x, 1, 0, 0],
|
| 923 |
+
[0, x, 1, 0],
|
| 924 |
+
[0, 0, x, 1],
|
| 925 |
+
[0, 0, 0, x]])
|
| 926 |
+
"""
|
| 927 |
+
|
| 928 |
+
return Matrix.jordan_block(size=n, eigenvalue=eigenval)
|
| 929 |
+
|
| 930 |
+
|
| 931 |
+
def matrix_multiply_elementwise(A, B):
|
| 932 |
+
"""Return the Hadamard product (elementwise product) of A and B
|
| 933 |
+
|
| 934 |
+
>>> from sympy import Matrix, matrix_multiply_elementwise
|
| 935 |
+
>>> A = Matrix([[0, 1, 2], [3, 4, 5]])
|
| 936 |
+
>>> B = Matrix([[1, 10, 100], [100, 10, 1]])
|
| 937 |
+
>>> matrix_multiply_elementwise(A, B)
|
| 938 |
+
Matrix([
|
| 939 |
+
[ 0, 10, 200],
|
| 940 |
+
[300, 40, 5]])
|
| 941 |
+
|
| 942 |
+
See Also
|
| 943 |
+
========
|
| 944 |
+
|
| 945 |
+
sympy.matrices.common.MatrixCommon.__mul__
|
| 946 |
+
"""
|
| 947 |
+
return A.multiply_elementwise(B)
|
| 948 |
+
|
| 949 |
+
|
| 950 |
+
def ones(*args, **kwargs):
|
| 951 |
+
"""Returns a matrix of ones with ``rows`` rows and ``cols`` columns;
|
| 952 |
+
if ``cols`` is omitted a square matrix will be returned.
|
| 953 |
+
|
| 954 |
+
See Also
|
| 955 |
+
========
|
| 956 |
+
|
| 957 |
+
zeros
|
| 958 |
+
eye
|
| 959 |
+
diag
|
| 960 |
+
"""
|
| 961 |
+
|
| 962 |
+
if 'c' in kwargs:
|
| 963 |
+
kwargs['cols'] = kwargs.pop('c')
|
| 964 |
+
|
| 965 |
+
return Matrix.ones(*args, **kwargs)
|
| 966 |
+
|
| 967 |
+
|
| 968 |
+
def randMatrix(r, c=None, min=0, max=99, seed=None, symmetric=False,
|
| 969 |
+
percent=100, prng=None):
|
| 970 |
+
"""Create random matrix with dimensions ``r`` x ``c``. If ``c`` is omitted
|
| 971 |
+
the matrix will be square. If ``symmetric`` is True the matrix must be
|
| 972 |
+
square. If ``percent`` is less than 100 then only approximately the given
|
| 973 |
+
percentage of elements will be non-zero.
|
| 974 |
+
|
| 975 |
+
The pseudo-random number generator used to generate matrix is chosen in the
|
| 976 |
+
following way.
|
| 977 |
+
|
| 978 |
+
* If ``prng`` is supplied, it will be used as random number generator.
|
| 979 |
+
It should be an instance of ``random.Random``, or at least have
|
| 980 |
+
``randint`` and ``shuffle`` methods with same signatures.
|
| 981 |
+
* if ``prng`` is not supplied but ``seed`` is supplied, then new
|
| 982 |
+
``random.Random`` with given ``seed`` will be created;
|
| 983 |
+
* otherwise, a new ``random.Random`` with default seed will be used.
|
| 984 |
+
|
| 985 |
+
Examples
|
| 986 |
+
========
|
| 987 |
+
|
| 988 |
+
>>> from sympy import randMatrix
|
| 989 |
+
>>> randMatrix(3) # doctest:+SKIP
|
| 990 |
+
[25, 45, 27]
|
| 991 |
+
[44, 54, 9]
|
| 992 |
+
[23, 96, 46]
|
| 993 |
+
>>> randMatrix(3, 2) # doctest:+SKIP
|
| 994 |
+
[87, 29]
|
| 995 |
+
[23, 37]
|
| 996 |
+
[90, 26]
|
| 997 |
+
>>> randMatrix(3, 3, 0, 2) # doctest:+SKIP
|
| 998 |
+
[0, 2, 0]
|
| 999 |
+
[2, 0, 1]
|
| 1000 |
+
[0, 0, 1]
|
| 1001 |
+
>>> randMatrix(3, symmetric=True) # doctest:+SKIP
|
| 1002 |
+
[85, 26, 29]
|
| 1003 |
+
[26, 71, 43]
|
| 1004 |
+
[29, 43, 57]
|
| 1005 |
+
>>> A = randMatrix(3, seed=1)
|
| 1006 |
+
>>> B = randMatrix(3, seed=2)
|
| 1007 |
+
>>> A == B
|
| 1008 |
+
False
|
| 1009 |
+
>>> A == randMatrix(3, seed=1)
|
| 1010 |
+
True
|
| 1011 |
+
>>> randMatrix(3, symmetric=True, percent=50) # doctest:+SKIP
|
| 1012 |
+
[77, 70, 0],
|
| 1013 |
+
[70, 0, 0],
|
| 1014 |
+
[ 0, 0, 88]
|
| 1015 |
+
"""
|
| 1016 |
+
# Note that ``Random()`` is equivalent to ``Random(None)``
|
| 1017 |
+
prng = prng or random.Random(seed)
|
| 1018 |
+
|
| 1019 |
+
if c is None:
|
| 1020 |
+
c = r
|
| 1021 |
+
|
| 1022 |
+
if symmetric and r != c:
|
| 1023 |
+
raise ValueError('For symmetric matrices, r must equal c, but %i != %i' % (r, c))
|
| 1024 |
+
|
| 1025 |
+
ij = range(r * c)
|
| 1026 |
+
if percent != 100:
|
| 1027 |
+
ij = prng.sample(ij, int(len(ij)*percent // 100))
|
| 1028 |
+
|
| 1029 |
+
m = zeros(r, c)
|
| 1030 |
+
|
| 1031 |
+
if not symmetric:
|
| 1032 |
+
for ijk in ij:
|
| 1033 |
+
i, j = divmod(ijk, c)
|
| 1034 |
+
m[i, j] = prng.randint(min, max)
|
| 1035 |
+
else:
|
| 1036 |
+
for ijk in ij:
|
| 1037 |
+
i, j = divmod(ijk, c)
|
| 1038 |
+
if i <= j:
|
| 1039 |
+
m[i, j] = m[j, i] = prng.randint(min, max)
|
| 1040 |
+
|
| 1041 |
+
return m
|
| 1042 |
+
|
| 1043 |
+
|
| 1044 |
+
def wronskian(functions, var, method='bareiss'):
|
| 1045 |
+
"""
|
| 1046 |
+
Compute Wronskian for [] of functions
|
| 1047 |
+
|
| 1048 |
+
::
|
| 1049 |
+
|
| 1050 |
+
| f1 f2 ... fn |
|
| 1051 |
+
| f1' f2' ... fn' |
|
| 1052 |
+
| . . . . |
|
| 1053 |
+
W(f1, ..., fn) = | . . . . |
|
| 1054 |
+
| . . . . |
|
| 1055 |
+
| (n) (n) (n) |
|
| 1056 |
+
| D (f1) D (f2) ... D (fn) |
|
| 1057 |
+
|
| 1058 |
+
see: https://en.wikipedia.org/wiki/Wronskian
|
| 1059 |
+
|
| 1060 |
+
See Also
|
| 1061 |
+
========
|
| 1062 |
+
|
| 1063 |
+
sympy.matrices.matrices.MatrixCalculus.jacobian
|
| 1064 |
+
hessian
|
| 1065 |
+
"""
|
| 1066 |
+
|
| 1067 |
+
functions = [sympify(f) for f in functions]
|
| 1068 |
+
n = len(functions)
|
| 1069 |
+
if n == 0:
|
| 1070 |
+
return S.One
|
| 1071 |
+
W = Matrix(n, n, lambda i, j: functions[i].diff(var, j))
|
| 1072 |
+
return W.det(method)
|
| 1073 |
+
|
| 1074 |
+
|
| 1075 |
+
def zeros(*args, **kwargs):
|
| 1076 |
+
"""Returns a matrix of zeros with ``rows`` rows and ``cols`` columns;
|
| 1077 |
+
if ``cols`` is omitted a square matrix will be returned.
|
| 1078 |
+
|
| 1079 |
+
See Also
|
| 1080 |
+
========
|
| 1081 |
+
|
| 1082 |
+
ones
|
| 1083 |
+
eye
|
| 1084 |
+
diag
|
| 1085 |
+
"""
|
| 1086 |
+
|
| 1087 |
+
if 'c' in kwargs:
|
| 1088 |
+
kwargs['cols'] = kwargs.pop('c')
|
| 1089 |
+
|
| 1090 |
+
return Matrix.zeros(*args, **kwargs)
|
venv/lib/python3.10/site-packages/sympy/matrices/determinant.py
ADDED
|
@@ -0,0 +1,898 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from types import FunctionType
|
| 2 |
+
|
| 3 |
+
from sympy.core.numbers import Float, Integer
|
| 4 |
+
from sympy.core.singleton import S
|
| 5 |
+
from sympy.core.symbol import uniquely_named_symbol
|
| 6 |
+
from sympy.core.mul import Mul
|
| 7 |
+
from sympy.polys import PurePoly, cancel
|
| 8 |
+
from sympy.functions.combinatorial.numbers import nC
|
| 9 |
+
from sympy.polys.matrices.domainmatrix import DomainMatrix
|
| 10 |
+
|
| 11 |
+
from .common import NonSquareMatrixError
|
| 12 |
+
from .utilities import (
|
| 13 |
+
_get_intermediate_simp, _get_intermediate_simp_bool,
|
| 14 |
+
_iszero, _is_zero_after_expand_mul, _dotprodsimp, _simplify)
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def _find_reasonable_pivot(col, iszerofunc=_iszero, simpfunc=_simplify):
|
| 18 |
+
""" Find the lowest index of an item in ``col`` that is
|
| 19 |
+
suitable for a pivot. If ``col`` consists only of
|
| 20 |
+
Floats, the pivot with the largest norm is returned.
|
| 21 |
+
Otherwise, the first element where ``iszerofunc`` returns
|
| 22 |
+
False is used. If ``iszerofunc`` does not return false,
|
| 23 |
+
items are simplified and retested until a suitable
|
| 24 |
+
pivot is found.
|
| 25 |
+
|
| 26 |
+
Returns a 4-tuple
|
| 27 |
+
(pivot_offset, pivot_val, assumed_nonzero, newly_determined)
|
| 28 |
+
where pivot_offset is the index of the pivot, pivot_val is
|
| 29 |
+
the (possibly simplified) value of the pivot, assumed_nonzero
|
| 30 |
+
is True if an assumption that the pivot was non-zero
|
| 31 |
+
was made without being proved, and newly_determined are
|
| 32 |
+
elements that were simplified during the process of pivot
|
| 33 |
+
finding."""
|
| 34 |
+
|
| 35 |
+
newly_determined = []
|
| 36 |
+
col = list(col)
|
| 37 |
+
# a column that contains a mix of floats and integers
|
| 38 |
+
# but at least one float is considered a numerical
|
| 39 |
+
# column, and so we do partial pivoting
|
| 40 |
+
if all(isinstance(x, (Float, Integer)) for x in col) and any(
|
| 41 |
+
isinstance(x, Float) for x in col):
|
| 42 |
+
col_abs = [abs(x) for x in col]
|
| 43 |
+
max_value = max(col_abs)
|
| 44 |
+
if iszerofunc(max_value):
|
| 45 |
+
# just because iszerofunc returned True, doesn't
|
| 46 |
+
# mean the value is numerically zero. Make sure
|
| 47 |
+
# to replace all entries with numerical zeros
|
| 48 |
+
if max_value != 0:
|
| 49 |
+
newly_determined = [(i, 0) for i, x in enumerate(col) if x != 0]
|
| 50 |
+
return (None, None, False, newly_determined)
|
| 51 |
+
index = col_abs.index(max_value)
|
| 52 |
+
return (index, col[index], False, newly_determined)
|
| 53 |
+
|
| 54 |
+
# PASS 1 (iszerofunc directly)
|
| 55 |
+
possible_zeros = []
|
| 56 |
+
for i, x in enumerate(col):
|
| 57 |
+
is_zero = iszerofunc(x)
|
| 58 |
+
# is someone wrote a custom iszerofunc, it may return
|
| 59 |
+
# BooleanFalse or BooleanTrue instead of True or False,
|
| 60 |
+
# so use == for comparison instead of `is`
|
| 61 |
+
if is_zero == False:
|
| 62 |
+
# we found something that is definitely not zero
|
| 63 |
+
return (i, x, False, newly_determined)
|
| 64 |
+
possible_zeros.append(is_zero)
|
| 65 |
+
|
| 66 |
+
# by this point, we've found no certain non-zeros
|
| 67 |
+
if all(possible_zeros):
|
| 68 |
+
# if everything is definitely zero, we have
|
| 69 |
+
# no pivot
|
| 70 |
+
return (None, None, False, newly_determined)
|
| 71 |
+
|
| 72 |
+
# PASS 2 (iszerofunc after simplify)
|
| 73 |
+
# we haven't found any for-sure non-zeros, so
|
| 74 |
+
# go through the elements iszerofunc couldn't
|
| 75 |
+
# make a determination about and opportunistically
|
| 76 |
+
# simplify to see if we find something
|
| 77 |
+
for i, x in enumerate(col):
|
| 78 |
+
if possible_zeros[i] is not None:
|
| 79 |
+
continue
|
| 80 |
+
simped = simpfunc(x)
|
| 81 |
+
is_zero = iszerofunc(simped)
|
| 82 |
+
if is_zero in (True, False):
|
| 83 |
+
newly_determined.append((i, simped))
|
| 84 |
+
if is_zero == False:
|
| 85 |
+
return (i, simped, False, newly_determined)
|
| 86 |
+
possible_zeros[i] = is_zero
|
| 87 |
+
|
| 88 |
+
# after simplifying, some things that were recognized
|
| 89 |
+
# as zeros might be zeros
|
| 90 |
+
if all(possible_zeros):
|
| 91 |
+
# if everything is definitely zero, we have
|
| 92 |
+
# no pivot
|
| 93 |
+
return (None, None, False, newly_determined)
|
| 94 |
+
|
| 95 |
+
# PASS 3 (.equals(0))
|
| 96 |
+
# some expressions fail to simplify to zero, but
|
| 97 |
+
# ``.equals(0)`` evaluates to True. As a last-ditch
|
| 98 |
+
# attempt, apply ``.equals`` to these expressions
|
| 99 |
+
for i, x in enumerate(col):
|
| 100 |
+
if possible_zeros[i] is not None:
|
| 101 |
+
continue
|
| 102 |
+
if x.equals(S.Zero):
|
| 103 |
+
# ``.iszero`` may return False with
|
| 104 |
+
# an implicit assumption (e.g., ``x.equals(0)``
|
| 105 |
+
# when ``x`` is a symbol), so only treat it
|
| 106 |
+
# as proved when ``.equals(0)`` returns True
|
| 107 |
+
possible_zeros[i] = True
|
| 108 |
+
newly_determined.append((i, S.Zero))
|
| 109 |
+
|
| 110 |
+
if all(possible_zeros):
|
| 111 |
+
return (None, None, False, newly_determined)
|
| 112 |
+
|
| 113 |
+
# at this point there is nothing that could definitely
|
| 114 |
+
# be a pivot. To maintain compatibility with existing
|
| 115 |
+
# behavior, we'll assume that an illdetermined thing is
|
| 116 |
+
# non-zero. We should probably raise a warning in this case
|
| 117 |
+
i = possible_zeros.index(None)
|
| 118 |
+
return (i, col[i], True, newly_determined)
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def _find_reasonable_pivot_naive(col, iszerofunc=_iszero, simpfunc=None):
|
| 122 |
+
"""
|
| 123 |
+
Helper that computes the pivot value and location from a
|
| 124 |
+
sequence of contiguous matrix column elements. As a side effect
|
| 125 |
+
of the pivot search, this function may simplify some of the elements
|
| 126 |
+
of the input column. A list of these simplified entries and their
|
| 127 |
+
indices are also returned.
|
| 128 |
+
This function mimics the behavior of _find_reasonable_pivot(),
|
| 129 |
+
but does less work trying to determine if an indeterminate candidate
|
| 130 |
+
pivot simplifies to zero. This more naive approach can be much faster,
|
| 131 |
+
with the trade-off that it may erroneously return a pivot that is zero.
|
| 132 |
+
|
| 133 |
+
``col`` is a sequence of contiguous column entries to be searched for
|
| 134 |
+
a suitable pivot.
|
| 135 |
+
``iszerofunc`` is a callable that returns a Boolean that indicates
|
| 136 |
+
if its input is zero, or None if no such determination can be made.
|
| 137 |
+
``simpfunc`` is a callable that simplifies its input. It must return
|
| 138 |
+
its input if it does not simplify its input. Passing in
|
| 139 |
+
``simpfunc=None`` indicates that the pivot search should not attempt
|
| 140 |
+
to simplify any candidate pivots.
|
| 141 |
+
|
| 142 |
+
Returns a 4-tuple:
|
| 143 |
+
(pivot_offset, pivot_val, assumed_nonzero, newly_determined)
|
| 144 |
+
``pivot_offset`` is the sequence index of the pivot.
|
| 145 |
+
``pivot_val`` is the value of the pivot.
|
| 146 |
+
pivot_val and col[pivot_index] are equivalent, but will be different
|
| 147 |
+
when col[pivot_index] was simplified during the pivot search.
|
| 148 |
+
``assumed_nonzero`` is a boolean indicating if the pivot cannot be
|
| 149 |
+
guaranteed to be zero. If assumed_nonzero is true, then the pivot
|
| 150 |
+
may or may not be non-zero. If assumed_nonzero is false, then
|
| 151 |
+
the pivot is non-zero.
|
| 152 |
+
``newly_determined`` is a list of index-value pairs of pivot candidates
|
| 153 |
+
that were simplified during the pivot search.
|
| 154 |
+
"""
|
| 155 |
+
|
| 156 |
+
# indeterminates holds the index-value pairs of each pivot candidate
|
| 157 |
+
# that is neither zero or non-zero, as determined by iszerofunc().
|
| 158 |
+
# If iszerofunc() indicates that a candidate pivot is guaranteed
|
| 159 |
+
# non-zero, or that every candidate pivot is zero then the contents
|
| 160 |
+
# of indeterminates are unused.
|
| 161 |
+
# Otherwise, the only viable candidate pivots are symbolic.
|
| 162 |
+
# In this case, indeterminates will have at least one entry,
|
| 163 |
+
# and all but the first entry are ignored when simpfunc is None.
|
| 164 |
+
indeterminates = []
|
| 165 |
+
for i, col_val in enumerate(col):
|
| 166 |
+
col_val_is_zero = iszerofunc(col_val)
|
| 167 |
+
if col_val_is_zero == False:
|
| 168 |
+
# This pivot candidate is non-zero.
|
| 169 |
+
return i, col_val, False, []
|
| 170 |
+
elif col_val_is_zero is None:
|
| 171 |
+
# The candidate pivot's comparison with zero
|
| 172 |
+
# is indeterminate.
|
| 173 |
+
indeterminates.append((i, col_val))
|
| 174 |
+
|
| 175 |
+
if len(indeterminates) == 0:
|
| 176 |
+
# All candidate pivots are guaranteed to be zero, i.e. there is
|
| 177 |
+
# no pivot.
|
| 178 |
+
return None, None, False, []
|
| 179 |
+
|
| 180 |
+
if simpfunc is None:
|
| 181 |
+
# Caller did not pass in a simplification function that might
|
| 182 |
+
# determine if an indeterminate pivot candidate is guaranteed
|
| 183 |
+
# to be nonzero, so assume the first indeterminate candidate
|
| 184 |
+
# is non-zero.
|
| 185 |
+
return indeterminates[0][0], indeterminates[0][1], True, []
|
| 186 |
+
|
| 187 |
+
# newly_determined holds index-value pairs of candidate pivots
|
| 188 |
+
# that were simplified during the search for a non-zero pivot.
|
| 189 |
+
newly_determined = []
|
| 190 |
+
for i, col_val in indeterminates:
|
| 191 |
+
tmp_col_val = simpfunc(col_val)
|
| 192 |
+
if id(col_val) != id(tmp_col_val):
|
| 193 |
+
# simpfunc() simplified this candidate pivot.
|
| 194 |
+
newly_determined.append((i, tmp_col_val))
|
| 195 |
+
if iszerofunc(tmp_col_val) == False:
|
| 196 |
+
# Candidate pivot simplified to a guaranteed non-zero value.
|
| 197 |
+
return i, tmp_col_val, False, newly_determined
|
| 198 |
+
|
| 199 |
+
return indeterminates[0][0], indeterminates[0][1], True, newly_determined
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
# This functions is a candidate for caching if it gets implemented for matrices.
|
| 203 |
+
def _berkowitz_toeplitz_matrix(M):
|
| 204 |
+
"""Return (A,T) where T the Toeplitz matrix used in the Berkowitz algorithm
|
| 205 |
+
corresponding to ``M`` and A is the first principal submatrix.
|
| 206 |
+
"""
|
| 207 |
+
|
| 208 |
+
# the 0 x 0 case is trivial
|
| 209 |
+
if M.rows == 0 and M.cols == 0:
|
| 210 |
+
return M._new(1,1, [M.one])
|
| 211 |
+
|
| 212 |
+
#
|
| 213 |
+
# Partition M = [ a_11 R ]
|
| 214 |
+
# [ C A ]
|
| 215 |
+
#
|
| 216 |
+
|
| 217 |
+
a, R = M[0,0], M[0, 1:]
|
| 218 |
+
C, A = M[1:, 0], M[1:,1:]
|
| 219 |
+
|
| 220 |
+
#
|
| 221 |
+
# The Toeplitz matrix looks like
|
| 222 |
+
#
|
| 223 |
+
# [ 1 ]
|
| 224 |
+
# [ -a 1 ]
|
| 225 |
+
# [ -RC -a 1 ]
|
| 226 |
+
# [ -RAC -RC -a 1 ]
|
| 227 |
+
# [ -RA**2C -RAC -RC -a 1 ]
|
| 228 |
+
# etc.
|
| 229 |
+
|
| 230 |
+
# Compute the diagonal entries.
|
| 231 |
+
# Because multiplying matrix times vector is so much
|
| 232 |
+
# more efficient than matrix times matrix, recursively
|
| 233 |
+
# compute -R * A**n * C.
|
| 234 |
+
diags = [C]
|
| 235 |
+
for i in range(M.rows - 2):
|
| 236 |
+
diags.append(A.multiply(diags[i], dotprodsimp=None))
|
| 237 |
+
diags = [(-R).multiply(d, dotprodsimp=None)[0, 0] for d in diags]
|
| 238 |
+
diags = [M.one, -a] + diags
|
| 239 |
+
|
| 240 |
+
def entry(i,j):
|
| 241 |
+
if j > i:
|
| 242 |
+
return M.zero
|
| 243 |
+
return diags[i - j]
|
| 244 |
+
|
| 245 |
+
toeplitz = M._new(M.cols + 1, M.rows, entry)
|
| 246 |
+
return (A, toeplitz)
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
# This functions is a candidate for caching if it gets implemented for matrices.
|
| 250 |
+
def _berkowitz_vector(M):
|
| 251 |
+
""" Run the Berkowitz algorithm and return a vector whose entries
|
| 252 |
+
are the coefficients of the characteristic polynomial of ``M``.
|
| 253 |
+
|
| 254 |
+
Given N x N matrix, efficiently compute
|
| 255 |
+
coefficients of characteristic polynomials of ``M``
|
| 256 |
+
without division in the ground domain.
|
| 257 |
+
|
| 258 |
+
This method is particularly useful for computing determinant,
|
| 259 |
+
principal minors and characteristic polynomial when ``M``
|
| 260 |
+
has complicated coefficients e.g. polynomials. Semi-direct
|
| 261 |
+
usage of this algorithm is also important in computing
|
| 262 |
+
efficiently sub-resultant PRS.
|
| 263 |
+
|
| 264 |
+
Assuming that M is a square matrix of dimension N x N and
|
| 265 |
+
I is N x N identity matrix, then the Berkowitz vector is
|
| 266 |
+
an N x 1 vector whose entries are coefficients of the
|
| 267 |
+
polynomial
|
| 268 |
+
|
| 269 |
+
charpoly(M) = det(t*I - M)
|
| 270 |
+
|
| 271 |
+
As a consequence, all polynomials generated by Berkowitz
|
| 272 |
+
algorithm are monic.
|
| 273 |
+
|
| 274 |
+
For more information on the implemented algorithm refer to:
|
| 275 |
+
|
| 276 |
+
[1] S.J. Berkowitz, On computing the determinant in small
|
| 277 |
+
parallel time using a small number of processors, ACM,
|
| 278 |
+
Information Processing Letters 18, 1984, pp. 147-150
|
| 279 |
+
|
| 280 |
+
[2] M. Keber, Division-Free computation of sub-resultants
|
| 281 |
+
using Bezout matrices, Tech. Report MPI-I-2006-1-006,
|
| 282 |
+
Saarbrucken, 2006
|
| 283 |
+
"""
|
| 284 |
+
|
| 285 |
+
# handle the trivial cases
|
| 286 |
+
if M.rows == 0 and M.cols == 0:
|
| 287 |
+
return M._new(1, 1, [M.one])
|
| 288 |
+
elif M.rows == 1 and M.cols == 1:
|
| 289 |
+
return M._new(2, 1, [M.one, -M[0,0]])
|
| 290 |
+
|
| 291 |
+
submat, toeplitz = _berkowitz_toeplitz_matrix(M)
|
| 292 |
+
|
| 293 |
+
return toeplitz.multiply(_berkowitz_vector(submat), dotprodsimp=None)
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
def _adjugate(M, method="berkowitz"):
|
| 297 |
+
"""Returns the adjugate, or classical adjoint, of
|
| 298 |
+
a matrix. That is, the transpose of the matrix of cofactors.
|
| 299 |
+
|
| 300 |
+
https://en.wikipedia.org/wiki/Adjugate
|
| 301 |
+
|
| 302 |
+
Parameters
|
| 303 |
+
==========
|
| 304 |
+
|
| 305 |
+
method : string, optional
|
| 306 |
+
Method to use to find the cofactors, can be "bareiss", "berkowitz" or
|
| 307 |
+
"lu".
|
| 308 |
+
|
| 309 |
+
Examples
|
| 310 |
+
========
|
| 311 |
+
|
| 312 |
+
>>> from sympy import Matrix
|
| 313 |
+
>>> M = Matrix([[1, 2], [3, 4]])
|
| 314 |
+
>>> M.adjugate()
|
| 315 |
+
Matrix([
|
| 316 |
+
[ 4, -2],
|
| 317 |
+
[-3, 1]])
|
| 318 |
+
|
| 319 |
+
See Also
|
| 320 |
+
========
|
| 321 |
+
|
| 322 |
+
cofactor_matrix
|
| 323 |
+
sympy.matrices.common.MatrixCommon.transpose
|
| 324 |
+
"""
|
| 325 |
+
|
| 326 |
+
return M.cofactor_matrix(method=method).transpose()
|
| 327 |
+
|
| 328 |
+
|
| 329 |
+
# This functions is a candidate for caching if it gets implemented for matrices.
|
| 330 |
+
def _charpoly(M, x='lambda', simplify=_simplify):
|
| 331 |
+
"""Computes characteristic polynomial det(x*I - M) where I is
|
| 332 |
+
the identity matrix.
|
| 333 |
+
|
| 334 |
+
A PurePoly is returned, so using different variables for ``x`` does
|
| 335 |
+
not affect the comparison or the polynomials:
|
| 336 |
+
|
| 337 |
+
Parameters
|
| 338 |
+
==========
|
| 339 |
+
|
| 340 |
+
x : string, optional
|
| 341 |
+
Name for the "lambda" variable, defaults to "lambda".
|
| 342 |
+
|
| 343 |
+
simplify : function, optional
|
| 344 |
+
Simplification function to use on the characteristic polynomial
|
| 345 |
+
calculated. Defaults to ``simplify``.
|
| 346 |
+
|
| 347 |
+
Examples
|
| 348 |
+
========
|
| 349 |
+
|
| 350 |
+
>>> from sympy import Matrix
|
| 351 |
+
>>> from sympy.abc import x, y
|
| 352 |
+
>>> M = Matrix([[1, 3], [2, 0]])
|
| 353 |
+
>>> M.charpoly()
|
| 354 |
+
PurePoly(lambda**2 - lambda - 6, lambda, domain='ZZ')
|
| 355 |
+
>>> M.charpoly(x) == M.charpoly(y)
|
| 356 |
+
True
|
| 357 |
+
>>> M.charpoly(x) == M.charpoly(y)
|
| 358 |
+
True
|
| 359 |
+
|
| 360 |
+
Specifying ``x`` is optional; a symbol named ``lambda`` is used by
|
| 361 |
+
default (which looks good when pretty-printed in unicode):
|
| 362 |
+
|
| 363 |
+
>>> M.charpoly().as_expr()
|
| 364 |
+
lambda**2 - lambda - 6
|
| 365 |
+
|
| 366 |
+
And if ``x`` clashes with an existing symbol, underscores will
|
| 367 |
+
be prepended to the name to make it unique:
|
| 368 |
+
|
| 369 |
+
>>> M = Matrix([[1, 2], [x, 0]])
|
| 370 |
+
>>> M.charpoly(x).as_expr()
|
| 371 |
+
_x**2 - _x - 2*x
|
| 372 |
+
|
| 373 |
+
Whether you pass a symbol or not, the generator can be obtained
|
| 374 |
+
with the gen attribute since it may not be the same as the symbol
|
| 375 |
+
that was passed:
|
| 376 |
+
|
| 377 |
+
>>> M.charpoly(x).gen
|
| 378 |
+
_x
|
| 379 |
+
>>> M.charpoly(x).gen == x
|
| 380 |
+
False
|
| 381 |
+
|
| 382 |
+
Notes
|
| 383 |
+
=====
|
| 384 |
+
|
| 385 |
+
The Samuelson-Berkowitz algorithm is used to compute
|
| 386 |
+
the characteristic polynomial efficiently and without any
|
| 387 |
+
division operations. Thus the characteristic polynomial over any
|
| 388 |
+
commutative ring without zero divisors can be computed.
|
| 389 |
+
|
| 390 |
+
If the determinant det(x*I - M) can be found out easily as
|
| 391 |
+
in the case of an upper or a lower triangular matrix, then
|
| 392 |
+
instead of Samuelson-Berkowitz algorithm, eigenvalues are computed
|
| 393 |
+
and the characteristic polynomial with their help.
|
| 394 |
+
|
| 395 |
+
See Also
|
| 396 |
+
========
|
| 397 |
+
|
| 398 |
+
det
|
| 399 |
+
"""
|
| 400 |
+
|
| 401 |
+
if not M.is_square:
|
| 402 |
+
raise NonSquareMatrixError()
|
| 403 |
+
if M.is_lower or M.is_upper:
|
| 404 |
+
diagonal_elements = M.diagonal()
|
| 405 |
+
x = uniquely_named_symbol(x, diagonal_elements, modify=lambda s: '_' + s)
|
| 406 |
+
m = 1
|
| 407 |
+
for i in diagonal_elements:
|
| 408 |
+
m = m * (x - simplify(i))
|
| 409 |
+
return PurePoly(m, x)
|
| 410 |
+
|
| 411 |
+
berk_vector = _berkowitz_vector(M)
|
| 412 |
+
x = uniquely_named_symbol(x, berk_vector, modify=lambda s: '_' + s)
|
| 413 |
+
|
| 414 |
+
return PurePoly([simplify(a) for a in berk_vector], x)
|
| 415 |
+
|
| 416 |
+
|
| 417 |
+
def _cofactor(M, i, j, method="berkowitz"):
|
| 418 |
+
"""Calculate the cofactor of an element.
|
| 419 |
+
|
| 420 |
+
Parameters
|
| 421 |
+
==========
|
| 422 |
+
|
| 423 |
+
method : string, optional
|
| 424 |
+
Method to use to find the cofactors, can be "bareiss", "berkowitz" or
|
| 425 |
+
"lu".
|
| 426 |
+
|
| 427 |
+
Examples
|
| 428 |
+
========
|
| 429 |
+
|
| 430 |
+
>>> from sympy import Matrix
|
| 431 |
+
>>> M = Matrix([[1, 2], [3, 4]])
|
| 432 |
+
>>> M.cofactor(0, 1)
|
| 433 |
+
-3
|
| 434 |
+
|
| 435 |
+
See Also
|
| 436 |
+
========
|
| 437 |
+
|
| 438 |
+
cofactor_matrix
|
| 439 |
+
minor
|
| 440 |
+
minor_submatrix
|
| 441 |
+
"""
|
| 442 |
+
|
| 443 |
+
if not M.is_square or M.rows < 1:
|
| 444 |
+
raise NonSquareMatrixError()
|
| 445 |
+
|
| 446 |
+
return S.NegativeOne**((i + j) % 2) * M.minor(i, j, method)
|
| 447 |
+
|
| 448 |
+
|
| 449 |
+
def _cofactor_matrix(M, method="berkowitz"):
|
| 450 |
+
"""Return a matrix containing the cofactor of each element.
|
| 451 |
+
|
| 452 |
+
Parameters
|
| 453 |
+
==========
|
| 454 |
+
|
| 455 |
+
method : string, optional
|
| 456 |
+
Method to use to find the cofactors, can be "bareiss", "berkowitz" or
|
| 457 |
+
"lu".
|
| 458 |
+
|
| 459 |
+
Examples
|
| 460 |
+
========
|
| 461 |
+
|
| 462 |
+
>>> from sympy import Matrix
|
| 463 |
+
>>> M = Matrix([[1, 2], [3, 4]])
|
| 464 |
+
>>> M.cofactor_matrix()
|
| 465 |
+
Matrix([
|
| 466 |
+
[ 4, -3],
|
| 467 |
+
[-2, 1]])
|
| 468 |
+
|
| 469 |
+
See Also
|
| 470 |
+
========
|
| 471 |
+
|
| 472 |
+
cofactor
|
| 473 |
+
minor
|
| 474 |
+
minor_submatrix
|
| 475 |
+
"""
|
| 476 |
+
|
| 477 |
+
if not M.is_square or M.rows < 1:
|
| 478 |
+
raise NonSquareMatrixError()
|
| 479 |
+
|
| 480 |
+
return M._new(M.rows, M.cols,
|
| 481 |
+
lambda i, j: M.cofactor(i, j, method))
|
| 482 |
+
|
| 483 |
+
def _per(M):
|
| 484 |
+
"""Returns the permanent of a matrix. Unlike determinant,
|
| 485 |
+
permanent is defined for both square and non-square matrices.
|
| 486 |
+
|
| 487 |
+
For an m x n matrix, with m less than or equal to n,
|
| 488 |
+
it is given as the sum over the permutations s of size
|
| 489 |
+
less than or equal to m on [1, 2, . . . n] of the product
|
| 490 |
+
from i = 1 to m of M[i, s[i]]. Taking the transpose will
|
| 491 |
+
not affect the value of the permanent.
|
| 492 |
+
|
| 493 |
+
In the case of a square matrix, this is the same as the permutation
|
| 494 |
+
definition of the determinant, but it does not take the sign of the
|
| 495 |
+
permutation into account. Computing the permanent with this definition
|
| 496 |
+
is quite inefficient, so here the Ryser formula is used.
|
| 497 |
+
|
| 498 |
+
Examples
|
| 499 |
+
========
|
| 500 |
+
|
| 501 |
+
>>> from sympy import Matrix
|
| 502 |
+
>>> M = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
|
| 503 |
+
>>> M.per()
|
| 504 |
+
450
|
| 505 |
+
>>> M = Matrix([1, 5, 7])
|
| 506 |
+
>>> M.per()
|
| 507 |
+
13
|
| 508 |
+
|
| 509 |
+
References
|
| 510 |
+
==========
|
| 511 |
+
|
| 512 |
+
.. [1] Prof. Frank Ben's notes: https://math.berkeley.edu/~bernd/ban275.pdf
|
| 513 |
+
.. [2] Wikipedia article on Permanent: https://en.wikipedia.org/wiki/Permanent_%28mathematics%29
|
| 514 |
+
.. [3] https://reference.wolfram.com/language/ref/Permanent.html
|
| 515 |
+
.. [4] Permanent of a rectangular matrix : https://arxiv.org/pdf/0904.3251.pdf
|
| 516 |
+
"""
|
| 517 |
+
import itertools
|
| 518 |
+
|
| 519 |
+
m, n = M.shape
|
| 520 |
+
if m > n:
|
| 521 |
+
M = M.T
|
| 522 |
+
m, n = n, m
|
| 523 |
+
s = list(range(n))
|
| 524 |
+
|
| 525 |
+
subsets = []
|
| 526 |
+
for i in range(1, m + 1):
|
| 527 |
+
subsets += list(map(list, itertools.combinations(s, i)))
|
| 528 |
+
|
| 529 |
+
perm = 0
|
| 530 |
+
for subset in subsets:
|
| 531 |
+
prod = 1
|
| 532 |
+
sub_len = len(subset)
|
| 533 |
+
for i in range(m):
|
| 534 |
+
prod *= sum([M[i, j] for j in subset])
|
| 535 |
+
perm += prod * S.NegativeOne**sub_len * nC(n - sub_len, m - sub_len)
|
| 536 |
+
perm *= S.NegativeOne**m
|
| 537 |
+
return perm.simplify()
|
| 538 |
+
|
| 539 |
+
def _det_DOM(M):
|
| 540 |
+
DOM = DomainMatrix.from_Matrix(M, field=True, extension=True)
|
| 541 |
+
K = DOM.domain
|
| 542 |
+
return K.to_sympy(DOM.det())
|
| 543 |
+
|
| 544 |
+
# This functions is a candidate for caching if it gets implemented for matrices.
|
| 545 |
+
def _det(M, method="bareiss", iszerofunc=None):
|
| 546 |
+
"""Computes the determinant of a matrix if ``M`` is a concrete matrix object
|
| 547 |
+
otherwise return an expressions ``Determinant(M)`` if ``M`` is a
|
| 548 |
+
``MatrixSymbol`` or other expression.
|
| 549 |
+
|
| 550 |
+
Parameters
|
| 551 |
+
==========
|
| 552 |
+
|
| 553 |
+
method : string, optional
|
| 554 |
+
Specifies the algorithm used for computing the matrix determinant.
|
| 555 |
+
|
| 556 |
+
If the matrix is at most 3x3, a hard-coded formula is used and the
|
| 557 |
+
specified method is ignored. Otherwise, it defaults to
|
| 558 |
+
``'bareiss'``.
|
| 559 |
+
|
| 560 |
+
Also, if the matrix is an upper or a lower triangular matrix, determinant
|
| 561 |
+
is computed by simple multiplication of diagonal elements, and the
|
| 562 |
+
specified method is ignored.
|
| 563 |
+
|
| 564 |
+
If it is set to ``'domain-ge'``, then Gaussian elimination method will
|
| 565 |
+
be used via using DomainMatrix.
|
| 566 |
+
|
| 567 |
+
If it is set to ``'bareiss'``, Bareiss' fraction-free algorithm will
|
| 568 |
+
be used.
|
| 569 |
+
|
| 570 |
+
If it is set to ``'berkowitz'``, Berkowitz' algorithm will be used.
|
| 571 |
+
|
| 572 |
+
Otherwise, if it is set to ``'lu'``, LU decomposition will be used.
|
| 573 |
+
|
| 574 |
+
.. note::
|
| 575 |
+
For backward compatibility, legacy keys like "bareis" and
|
| 576 |
+
"det_lu" can still be used to indicate the corresponding
|
| 577 |
+
methods.
|
| 578 |
+
And the keys are also case-insensitive for now. However, it is
|
| 579 |
+
suggested to use the precise keys for specifying the method.
|
| 580 |
+
|
| 581 |
+
iszerofunc : FunctionType or None, optional
|
| 582 |
+
If it is set to ``None``, it will be defaulted to ``_iszero`` if the
|
| 583 |
+
method is set to ``'bareiss'``, and ``_is_zero_after_expand_mul`` if
|
| 584 |
+
the method is set to ``'lu'``.
|
| 585 |
+
|
| 586 |
+
It can also accept any user-specified zero testing function, if it
|
| 587 |
+
is formatted as a function which accepts a single symbolic argument
|
| 588 |
+
and returns ``True`` if it is tested as zero and ``False`` if it
|
| 589 |
+
tested as non-zero, and also ``None`` if it is undecidable.
|
| 590 |
+
|
| 591 |
+
Returns
|
| 592 |
+
=======
|
| 593 |
+
|
| 594 |
+
det : Basic
|
| 595 |
+
Result of determinant.
|
| 596 |
+
|
| 597 |
+
Raises
|
| 598 |
+
======
|
| 599 |
+
|
| 600 |
+
ValueError
|
| 601 |
+
If unrecognized keys are given for ``method`` or ``iszerofunc``.
|
| 602 |
+
|
| 603 |
+
NonSquareMatrixError
|
| 604 |
+
If attempted to calculate determinant from a non-square matrix.
|
| 605 |
+
|
| 606 |
+
Examples
|
| 607 |
+
========
|
| 608 |
+
|
| 609 |
+
>>> from sympy import Matrix, eye, det
|
| 610 |
+
>>> I3 = eye(3)
|
| 611 |
+
>>> det(I3)
|
| 612 |
+
1
|
| 613 |
+
>>> M = Matrix([[1, 2], [3, 4]])
|
| 614 |
+
>>> det(M)
|
| 615 |
+
-2
|
| 616 |
+
>>> det(M) == M.det()
|
| 617 |
+
True
|
| 618 |
+
>>> M.det(method="domain-ge")
|
| 619 |
+
-2
|
| 620 |
+
"""
|
| 621 |
+
|
| 622 |
+
# sanitize `method`
|
| 623 |
+
method = method.lower()
|
| 624 |
+
|
| 625 |
+
if method == "bareis":
|
| 626 |
+
method = "bareiss"
|
| 627 |
+
elif method == "det_lu":
|
| 628 |
+
method = "lu"
|
| 629 |
+
|
| 630 |
+
if method not in ("bareiss", "berkowitz", "lu", "domain-ge"):
|
| 631 |
+
raise ValueError("Determinant method '%s' unrecognized" % method)
|
| 632 |
+
|
| 633 |
+
if iszerofunc is None:
|
| 634 |
+
if method == "bareiss":
|
| 635 |
+
iszerofunc = _is_zero_after_expand_mul
|
| 636 |
+
elif method == "lu":
|
| 637 |
+
iszerofunc = _iszero
|
| 638 |
+
|
| 639 |
+
elif not isinstance(iszerofunc, FunctionType):
|
| 640 |
+
raise ValueError("Zero testing method '%s' unrecognized" % iszerofunc)
|
| 641 |
+
|
| 642 |
+
n = M.rows
|
| 643 |
+
|
| 644 |
+
if n == M.cols: # square check is done in individual method functions
|
| 645 |
+
if n == 0:
|
| 646 |
+
return M.one
|
| 647 |
+
elif n == 1:
|
| 648 |
+
return M[0, 0]
|
| 649 |
+
elif n == 2:
|
| 650 |
+
m = M[0, 0] * M[1, 1] - M[0, 1] * M[1, 0]
|
| 651 |
+
return _get_intermediate_simp(_dotprodsimp)(m)
|
| 652 |
+
elif n == 3:
|
| 653 |
+
m = (M[0, 0] * M[1, 1] * M[2, 2]
|
| 654 |
+
+ M[0, 1] * M[1, 2] * M[2, 0]
|
| 655 |
+
+ M[0, 2] * M[1, 0] * M[2, 1]
|
| 656 |
+
- M[0, 2] * M[1, 1] * M[2, 0]
|
| 657 |
+
- M[0, 0] * M[1, 2] * M[2, 1]
|
| 658 |
+
- M[0, 1] * M[1, 0] * M[2, 2])
|
| 659 |
+
return _get_intermediate_simp(_dotprodsimp)(m)
|
| 660 |
+
|
| 661 |
+
dets = []
|
| 662 |
+
for b in M.strongly_connected_components():
|
| 663 |
+
if method == "domain-ge": # uses DomainMatrix to evaluate determinant
|
| 664 |
+
det = _det_DOM(M[b, b])
|
| 665 |
+
elif method == "bareiss":
|
| 666 |
+
det = M[b, b]._eval_det_bareiss(iszerofunc=iszerofunc)
|
| 667 |
+
elif method == "berkowitz":
|
| 668 |
+
det = M[b, b]._eval_det_berkowitz()
|
| 669 |
+
elif method == "lu":
|
| 670 |
+
det = M[b, b]._eval_det_lu(iszerofunc=iszerofunc)
|
| 671 |
+
dets.append(det)
|
| 672 |
+
return Mul(*dets)
|
| 673 |
+
|
| 674 |
+
|
| 675 |
+
# This functions is a candidate for caching if it gets implemented for matrices.
|
| 676 |
+
def _det_bareiss(M, iszerofunc=_is_zero_after_expand_mul):
|
| 677 |
+
"""Compute matrix determinant using Bareiss' fraction-free
|
| 678 |
+
algorithm which is an extension of the well known Gaussian
|
| 679 |
+
elimination method. This approach is best suited for dense
|
| 680 |
+
symbolic matrices and will result in a determinant with
|
| 681 |
+
minimal number of fractions. It means that less term
|
| 682 |
+
rewriting is needed on resulting formulae.
|
| 683 |
+
|
| 684 |
+
Parameters
|
| 685 |
+
==========
|
| 686 |
+
|
| 687 |
+
iszerofunc : function, optional
|
| 688 |
+
The function to use to determine zeros when doing an LU decomposition.
|
| 689 |
+
Defaults to ``lambda x: x.is_zero``.
|
| 690 |
+
|
| 691 |
+
TODO: Implement algorithm for sparse matrices (SFF),
|
| 692 |
+
http://www.eecis.udel.edu/~saunders/papers/sffge/it5.ps.
|
| 693 |
+
"""
|
| 694 |
+
|
| 695 |
+
# Recursively implemented Bareiss' algorithm as per Deanna Richelle Leggett's
|
| 696 |
+
# thesis http://www.math.usm.edu/perry/Research/Thesis_DRL.pdf
|
| 697 |
+
def bareiss(mat, cumm=1):
|
| 698 |
+
if mat.rows == 0:
|
| 699 |
+
return mat.one
|
| 700 |
+
elif mat.rows == 1:
|
| 701 |
+
return mat[0, 0]
|
| 702 |
+
|
| 703 |
+
# find a pivot and extract the remaining matrix
|
| 704 |
+
# With the default iszerofunc, _find_reasonable_pivot slows down
|
| 705 |
+
# the computation by the factor of 2.5 in one test.
|
| 706 |
+
# Relevant issues: #10279 and #13877.
|
| 707 |
+
pivot_pos, pivot_val, _, _ = _find_reasonable_pivot(mat[:, 0], iszerofunc=iszerofunc)
|
| 708 |
+
if pivot_pos is None:
|
| 709 |
+
return mat.zero
|
| 710 |
+
|
| 711 |
+
# if we have a valid pivot, we'll do a "row swap", so keep the
|
| 712 |
+
# sign of the det
|
| 713 |
+
sign = (-1) ** (pivot_pos % 2)
|
| 714 |
+
|
| 715 |
+
# we want every row but the pivot row and every column
|
| 716 |
+
rows = [i for i in range(mat.rows) if i != pivot_pos]
|
| 717 |
+
cols = list(range(mat.cols))
|
| 718 |
+
tmp_mat = mat.extract(rows, cols)
|
| 719 |
+
|
| 720 |
+
def entry(i, j):
|
| 721 |
+
ret = (pivot_val*tmp_mat[i, j + 1] - mat[pivot_pos, j + 1]*tmp_mat[i, 0]) / cumm
|
| 722 |
+
if _get_intermediate_simp_bool(True):
|
| 723 |
+
return _dotprodsimp(ret)
|
| 724 |
+
elif not ret.is_Atom:
|
| 725 |
+
return cancel(ret)
|
| 726 |
+
return ret
|
| 727 |
+
|
| 728 |
+
return sign*bareiss(M._new(mat.rows - 1, mat.cols - 1, entry), pivot_val)
|
| 729 |
+
|
| 730 |
+
if not M.is_square:
|
| 731 |
+
raise NonSquareMatrixError()
|
| 732 |
+
|
| 733 |
+
if M.rows == 0:
|
| 734 |
+
return M.one
|
| 735 |
+
# sympy/matrices/tests/test_matrices.py contains a test that
|
| 736 |
+
# suggests that the determinant of a 0 x 0 matrix is one, by
|
| 737 |
+
# convention.
|
| 738 |
+
|
| 739 |
+
return bareiss(M)
|
| 740 |
+
|
| 741 |
+
|
| 742 |
+
def _det_berkowitz(M):
|
| 743 |
+
""" Use the Berkowitz algorithm to compute the determinant."""
|
| 744 |
+
|
| 745 |
+
if not M.is_square:
|
| 746 |
+
raise NonSquareMatrixError()
|
| 747 |
+
|
| 748 |
+
if M.rows == 0:
|
| 749 |
+
return M.one
|
| 750 |
+
# sympy/matrices/tests/test_matrices.py contains a test that
|
| 751 |
+
# suggests that the determinant of a 0 x 0 matrix is one, by
|
| 752 |
+
# convention.
|
| 753 |
+
|
| 754 |
+
berk_vector = _berkowitz_vector(M)
|
| 755 |
+
return (-1)**(len(berk_vector) - 1) * berk_vector[-1]
|
| 756 |
+
|
| 757 |
+
|
| 758 |
+
# This functions is a candidate for caching if it gets implemented for matrices.
|
| 759 |
+
def _det_LU(M, iszerofunc=_iszero, simpfunc=None):
|
| 760 |
+
""" Computes the determinant of a matrix from its LU decomposition.
|
| 761 |
+
This function uses the LU decomposition computed by
|
| 762 |
+
LUDecomposition_Simple().
|
| 763 |
+
|
| 764 |
+
The keyword arguments iszerofunc and simpfunc are passed to
|
| 765 |
+
LUDecomposition_Simple().
|
| 766 |
+
iszerofunc is a callable that returns a boolean indicating if its
|
| 767 |
+
input is zero, or None if it cannot make the determination.
|
| 768 |
+
simpfunc is a callable that simplifies its input.
|
| 769 |
+
The default is simpfunc=None, which indicate that the pivot search
|
| 770 |
+
algorithm should not attempt to simplify any candidate pivots.
|
| 771 |
+
If simpfunc fails to simplify its input, then it must return its input
|
| 772 |
+
instead of a copy.
|
| 773 |
+
|
| 774 |
+
Parameters
|
| 775 |
+
==========
|
| 776 |
+
|
| 777 |
+
iszerofunc : function, optional
|
| 778 |
+
The function to use to determine zeros when doing an LU decomposition.
|
| 779 |
+
Defaults to ``lambda x: x.is_zero``.
|
| 780 |
+
|
| 781 |
+
simpfunc : function, optional
|
| 782 |
+
The simplification function to use when looking for zeros for pivots.
|
| 783 |
+
"""
|
| 784 |
+
|
| 785 |
+
if not M.is_square:
|
| 786 |
+
raise NonSquareMatrixError()
|
| 787 |
+
|
| 788 |
+
if M.rows == 0:
|
| 789 |
+
return M.one
|
| 790 |
+
# sympy/matrices/tests/test_matrices.py contains a test that
|
| 791 |
+
# suggests that the determinant of a 0 x 0 matrix is one, by
|
| 792 |
+
# convention.
|
| 793 |
+
|
| 794 |
+
lu, row_swaps = M.LUdecomposition_Simple(iszerofunc=iszerofunc,
|
| 795 |
+
simpfunc=simpfunc)
|
| 796 |
+
# P*A = L*U => det(A) = det(L)*det(U)/det(P) = det(P)*det(U).
|
| 797 |
+
# Lower triangular factor L encoded in lu has unit diagonal => det(L) = 1.
|
| 798 |
+
# P is a permutation matrix => det(P) in {-1, 1} => 1/det(P) = det(P).
|
| 799 |
+
# LUdecomposition_Simple() returns a list of row exchange index pairs, rather
|
| 800 |
+
# than a permutation matrix, but det(P) = (-1)**len(row_swaps).
|
| 801 |
+
|
| 802 |
+
# Avoid forming the potentially time consuming product of U's diagonal entries
|
| 803 |
+
# if the product is zero.
|
| 804 |
+
# Bottom right entry of U is 0 => det(A) = 0.
|
| 805 |
+
# It may be impossible to determine if this entry of U is zero when it is symbolic.
|
| 806 |
+
if iszerofunc(lu[lu.rows-1, lu.rows-1]):
|
| 807 |
+
return M.zero
|
| 808 |
+
|
| 809 |
+
# Compute det(P)
|
| 810 |
+
det = -M.one if len(row_swaps)%2 else M.one
|
| 811 |
+
|
| 812 |
+
# Compute det(U) by calculating the product of U's diagonal entries.
|
| 813 |
+
# The upper triangular portion of lu is the upper triangular portion of the
|
| 814 |
+
# U factor in the LU decomposition.
|
| 815 |
+
for k in range(lu.rows):
|
| 816 |
+
det *= lu[k, k]
|
| 817 |
+
|
| 818 |
+
# return det(P)*det(U)
|
| 819 |
+
return det
|
| 820 |
+
|
| 821 |
+
|
| 822 |
+
def _minor(M, i, j, method="berkowitz"):
|
| 823 |
+
"""Return the (i,j) minor of ``M``. That is,
|
| 824 |
+
return the determinant of the matrix obtained by deleting
|
| 825 |
+
the `i`th row and `j`th column from ``M``.
|
| 826 |
+
|
| 827 |
+
Parameters
|
| 828 |
+
==========
|
| 829 |
+
|
| 830 |
+
i, j : int
|
| 831 |
+
The row and column to exclude to obtain the submatrix.
|
| 832 |
+
|
| 833 |
+
method : string, optional
|
| 834 |
+
Method to use to find the determinant of the submatrix, can be
|
| 835 |
+
"bareiss", "berkowitz" or "lu".
|
| 836 |
+
|
| 837 |
+
Examples
|
| 838 |
+
========
|
| 839 |
+
|
| 840 |
+
>>> from sympy import Matrix
|
| 841 |
+
>>> M = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
|
| 842 |
+
>>> M.minor(1, 1)
|
| 843 |
+
-12
|
| 844 |
+
|
| 845 |
+
See Also
|
| 846 |
+
========
|
| 847 |
+
|
| 848 |
+
minor_submatrix
|
| 849 |
+
cofactor
|
| 850 |
+
det
|
| 851 |
+
"""
|
| 852 |
+
|
| 853 |
+
if not M.is_square:
|
| 854 |
+
raise NonSquareMatrixError()
|
| 855 |
+
|
| 856 |
+
return M.minor_submatrix(i, j).det(method=method)
|
| 857 |
+
|
| 858 |
+
|
| 859 |
+
def _minor_submatrix(M, i, j):
|
| 860 |
+
"""Return the submatrix obtained by removing the `i`th row
|
| 861 |
+
and `j`th column from ``M`` (works with Pythonic negative indices).
|
| 862 |
+
|
| 863 |
+
Parameters
|
| 864 |
+
==========
|
| 865 |
+
|
| 866 |
+
i, j : int
|
| 867 |
+
The row and column to exclude to obtain the submatrix.
|
| 868 |
+
|
| 869 |
+
Examples
|
| 870 |
+
========
|
| 871 |
+
|
| 872 |
+
>>> from sympy import Matrix
|
| 873 |
+
>>> M = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
|
| 874 |
+
>>> M.minor_submatrix(1, 1)
|
| 875 |
+
Matrix([
|
| 876 |
+
[1, 3],
|
| 877 |
+
[7, 9]])
|
| 878 |
+
|
| 879 |
+
See Also
|
| 880 |
+
========
|
| 881 |
+
|
| 882 |
+
minor
|
| 883 |
+
cofactor
|
| 884 |
+
"""
|
| 885 |
+
|
| 886 |
+
if i < 0:
|
| 887 |
+
i += M.rows
|
| 888 |
+
if j < 0:
|
| 889 |
+
j += M.cols
|
| 890 |
+
|
| 891 |
+
if not 0 <= i < M.rows or not 0 <= j < M.cols:
|
| 892 |
+
raise ValueError("`i` and `j` must satisfy 0 <= i < ``M.rows`` "
|
| 893 |
+
"(%d)" % M.rows + "and 0 <= j < ``M.cols`` (%d)." % M.cols)
|
| 894 |
+
|
| 895 |
+
rows = [a for a in range(M.rows) if a != i]
|
| 896 |
+
cols = [a for a in range(M.cols) if a != j]
|
| 897 |
+
|
| 898 |
+
return M.extract(rows, cols)
|
venv/lib/python3.10/site-packages/sympy/matrices/eigen.py
ADDED
|
@@ -0,0 +1,1343 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from types import FunctionType
|
| 2 |
+
from collections import Counter
|
| 3 |
+
|
| 4 |
+
from mpmath import mp, workprec
|
| 5 |
+
from mpmath.libmp.libmpf import prec_to_dps
|
| 6 |
+
|
| 7 |
+
from sympy.core.sorting import default_sort_key
|
| 8 |
+
from sympy.core.evalf import DEFAULT_MAXPREC, PrecisionExhausted
|
| 9 |
+
from sympy.core.logic import fuzzy_and, fuzzy_or
|
| 10 |
+
from sympy.core.numbers import Float
|
| 11 |
+
from sympy.core.sympify import _sympify
|
| 12 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
| 13 |
+
from sympy.polys import roots, CRootOf, ZZ, QQ, EX
|
| 14 |
+
from sympy.polys.matrices import DomainMatrix
|
| 15 |
+
from sympy.polys.matrices.eigen import dom_eigenvects, dom_eigenvects_to_sympy
|
| 16 |
+
from sympy.polys.polytools import gcd
|
| 17 |
+
|
| 18 |
+
from .common import MatrixError, NonSquareMatrixError
|
| 19 |
+
from .determinant import _find_reasonable_pivot
|
| 20 |
+
|
| 21 |
+
from .utilities import _iszero, _simplify
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def _eigenvals_eigenvects_mpmath(M):
|
| 25 |
+
norm2 = lambda v: mp.sqrt(sum(i**2 for i in v))
|
| 26 |
+
|
| 27 |
+
v1 = None
|
| 28 |
+
prec = max([x._prec for x in M.atoms(Float)])
|
| 29 |
+
eps = 2**-prec
|
| 30 |
+
|
| 31 |
+
while prec < DEFAULT_MAXPREC:
|
| 32 |
+
with workprec(prec):
|
| 33 |
+
A = mp.matrix(M.evalf(n=prec_to_dps(prec)))
|
| 34 |
+
E, ER = mp.eig(A)
|
| 35 |
+
v2 = norm2([i for e in E for i in (mp.re(e), mp.im(e))])
|
| 36 |
+
if v1 is not None and mp.fabs(v1 - v2) < eps:
|
| 37 |
+
return E, ER
|
| 38 |
+
v1 = v2
|
| 39 |
+
prec *= 2
|
| 40 |
+
|
| 41 |
+
# we get here because the next step would have taken us
|
| 42 |
+
# past MAXPREC or because we never took a step; in case
|
| 43 |
+
# of the latter, we refuse to send back a solution since
|
| 44 |
+
# it would not have been verified; we also resist taking
|
| 45 |
+
# a small step to arrive exactly at MAXPREC since then
|
| 46 |
+
# the two calculations might be artificially close.
|
| 47 |
+
raise PrecisionExhausted
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def _eigenvals_mpmath(M, multiple=False):
|
| 51 |
+
"""Compute eigenvalues using mpmath"""
|
| 52 |
+
E, _ = _eigenvals_eigenvects_mpmath(M)
|
| 53 |
+
result = [_sympify(x) for x in E]
|
| 54 |
+
if multiple:
|
| 55 |
+
return result
|
| 56 |
+
return dict(Counter(result))
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def _eigenvects_mpmath(M):
|
| 60 |
+
E, ER = _eigenvals_eigenvects_mpmath(M)
|
| 61 |
+
result = []
|
| 62 |
+
for i in range(M.rows):
|
| 63 |
+
eigenval = _sympify(E[i])
|
| 64 |
+
eigenvect = _sympify(ER[:, i])
|
| 65 |
+
result.append((eigenval, 1, [eigenvect]))
|
| 66 |
+
|
| 67 |
+
return result
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
# This function is a candidate for caching if it gets implemented for matrices.
|
| 71 |
+
def _eigenvals(
|
| 72 |
+
M, error_when_incomplete=True, *, simplify=False, multiple=False,
|
| 73 |
+
rational=False, **flags):
|
| 74 |
+
r"""Compute eigenvalues of the matrix.
|
| 75 |
+
|
| 76 |
+
Parameters
|
| 77 |
+
==========
|
| 78 |
+
|
| 79 |
+
error_when_incomplete : bool, optional
|
| 80 |
+
If it is set to ``True``, it will raise an error if not all
|
| 81 |
+
eigenvalues are computed. This is caused by ``roots`` not returning
|
| 82 |
+
a full list of eigenvalues.
|
| 83 |
+
|
| 84 |
+
simplify : bool or function, optional
|
| 85 |
+
If it is set to ``True``, it attempts to return the most
|
| 86 |
+
simplified form of expressions returned by applying default
|
| 87 |
+
simplification method in every routine.
|
| 88 |
+
|
| 89 |
+
If it is set to ``False``, it will skip simplification in this
|
| 90 |
+
particular routine to save computation resources.
|
| 91 |
+
|
| 92 |
+
If a function is passed to, it will attempt to apply
|
| 93 |
+
the particular function as simplification method.
|
| 94 |
+
|
| 95 |
+
rational : bool, optional
|
| 96 |
+
If it is set to ``True``, every floating point numbers would be
|
| 97 |
+
replaced with rationals before computation. It can solve some
|
| 98 |
+
issues of ``roots`` routine not working well with floats.
|
| 99 |
+
|
| 100 |
+
multiple : bool, optional
|
| 101 |
+
If it is set to ``True``, the result will be in the form of a
|
| 102 |
+
list.
|
| 103 |
+
|
| 104 |
+
If it is set to ``False``, the result will be in the form of a
|
| 105 |
+
dictionary.
|
| 106 |
+
|
| 107 |
+
Returns
|
| 108 |
+
=======
|
| 109 |
+
|
| 110 |
+
eigs : list or dict
|
| 111 |
+
Eigenvalues of a matrix. The return format would be specified by
|
| 112 |
+
the key ``multiple``.
|
| 113 |
+
|
| 114 |
+
Raises
|
| 115 |
+
======
|
| 116 |
+
|
| 117 |
+
MatrixError
|
| 118 |
+
If not enough roots had got computed.
|
| 119 |
+
|
| 120 |
+
NonSquareMatrixError
|
| 121 |
+
If attempted to compute eigenvalues from a non-square matrix.
|
| 122 |
+
|
| 123 |
+
Examples
|
| 124 |
+
========
|
| 125 |
+
|
| 126 |
+
>>> from sympy import Matrix
|
| 127 |
+
>>> M = Matrix(3, 3, [0, 1, 1, 1, 0, 0, 1, 1, 1])
|
| 128 |
+
>>> M.eigenvals()
|
| 129 |
+
{-1: 1, 0: 1, 2: 1}
|
| 130 |
+
|
| 131 |
+
See Also
|
| 132 |
+
========
|
| 133 |
+
|
| 134 |
+
MatrixDeterminant.charpoly
|
| 135 |
+
eigenvects
|
| 136 |
+
|
| 137 |
+
Notes
|
| 138 |
+
=====
|
| 139 |
+
|
| 140 |
+
Eigenvalues of a matrix $A$ can be computed by solving a matrix
|
| 141 |
+
equation $\det(A - \lambda I) = 0$
|
| 142 |
+
|
| 143 |
+
It's not always possible to return radical solutions for
|
| 144 |
+
eigenvalues for matrices larger than $4, 4$ shape due to
|
| 145 |
+
Abel-Ruffini theorem.
|
| 146 |
+
|
| 147 |
+
If there is no radical solution is found for the eigenvalue,
|
| 148 |
+
it may return eigenvalues in the form of
|
| 149 |
+
:class:`sympy.polys.rootoftools.ComplexRootOf`.
|
| 150 |
+
"""
|
| 151 |
+
if not M:
|
| 152 |
+
if multiple:
|
| 153 |
+
return []
|
| 154 |
+
return {}
|
| 155 |
+
|
| 156 |
+
if not M.is_square:
|
| 157 |
+
raise NonSquareMatrixError("{} must be a square matrix.".format(M))
|
| 158 |
+
|
| 159 |
+
if M._rep.domain not in (ZZ, QQ):
|
| 160 |
+
# Skip this check for ZZ/QQ because it can be slow
|
| 161 |
+
if all(x.is_number for x in M) and M.has(Float):
|
| 162 |
+
return _eigenvals_mpmath(M, multiple=multiple)
|
| 163 |
+
|
| 164 |
+
if rational:
|
| 165 |
+
from sympy.simplify import nsimplify
|
| 166 |
+
M = M.applyfunc(
|
| 167 |
+
lambda x: nsimplify(x, rational=True) if x.has(Float) else x)
|
| 168 |
+
|
| 169 |
+
if multiple:
|
| 170 |
+
return _eigenvals_list(
|
| 171 |
+
M, error_when_incomplete=error_when_incomplete, simplify=simplify,
|
| 172 |
+
**flags)
|
| 173 |
+
return _eigenvals_dict(
|
| 174 |
+
M, error_when_incomplete=error_when_incomplete, simplify=simplify,
|
| 175 |
+
**flags)
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
eigenvals_error_message = \
|
| 179 |
+
"It is not always possible to express the eigenvalues of a matrix " + \
|
| 180 |
+
"of size 5x5 or higher in radicals. " + \
|
| 181 |
+
"We have CRootOf, but domains other than the rationals are not " + \
|
| 182 |
+
"currently supported. " + \
|
| 183 |
+
"If there are no symbols in the matrix, " + \
|
| 184 |
+
"it should still be possible to compute numeric approximations " + \
|
| 185 |
+
"of the eigenvalues using " + \
|
| 186 |
+
"M.evalf().eigenvals() or M.charpoly().nroots()."
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
def _eigenvals_list(
|
| 190 |
+
M, error_when_incomplete=True, simplify=False, **flags):
|
| 191 |
+
iblocks = M.strongly_connected_components()
|
| 192 |
+
all_eigs = []
|
| 193 |
+
is_dom = M._rep.domain in (ZZ, QQ)
|
| 194 |
+
for b in iblocks:
|
| 195 |
+
|
| 196 |
+
# Fast path for a 1x1 block:
|
| 197 |
+
if is_dom and len(b) == 1:
|
| 198 |
+
index = b[0]
|
| 199 |
+
val = M[index, index]
|
| 200 |
+
all_eigs.append(val)
|
| 201 |
+
continue
|
| 202 |
+
|
| 203 |
+
block = M[b, b]
|
| 204 |
+
|
| 205 |
+
if isinstance(simplify, FunctionType):
|
| 206 |
+
charpoly = block.charpoly(simplify=simplify)
|
| 207 |
+
else:
|
| 208 |
+
charpoly = block.charpoly()
|
| 209 |
+
|
| 210 |
+
eigs = roots(charpoly, multiple=True, **flags)
|
| 211 |
+
|
| 212 |
+
if len(eigs) != block.rows:
|
| 213 |
+
degree = int(charpoly.degree())
|
| 214 |
+
f = charpoly.as_expr()
|
| 215 |
+
x = charpoly.gen
|
| 216 |
+
try:
|
| 217 |
+
eigs = [CRootOf(f, x, idx) for idx in range(degree)]
|
| 218 |
+
except NotImplementedError:
|
| 219 |
+
if error_when_incomplete:
|
| 220 |
+
raise MatrixError(eigenvals_error_message)
|
| 221 |
+
else:
|
| 222 |
+
eigs = []
|
| 223 |
+
|
| 224 |
+
all_eigs += eigs
|
| 225 |
+
|
| 226 |
+
if not simplify:
|
| 227 |
+
return all_eigs
|
| 228 |
+
if not isinstance(simplify, FunctionType):
|
| 229 |
+
simplify = _simplify
|
| 230 |
+
return [simplify(value) for value in all_eigs]
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
def _eigenvals_dict(
|
| 234 |
+
M, error_when_incomplete=True, simplify=False, **flags):
|
| 235 |
+
iblocks = M.strongly_connected_components()
|
| 236 |
+
all_eigs = {}
|
| 237 |
+
is_dom = M._rep.domain in (ZZ, QQ)
|
| 238 |
+
for b in iblocks:
|
| 239 |
+
|
| 240 |
+
# Fast path for a 1x1 block:
|
| 241 |
+
if is_dom and len(b) == 1:
|
| 242 |
+
index = b[0]
|
| 243 |
+
val = M[index, index]
|
| 244 |
+
all_eigs[val] = all_eigs.get(val, 0) + 1
|
| 245 |
+
continue
|
| 246 |
+
|
| 247 |
+
block = M[b, b]
|
| 248 |
+
|
| 249 |
+
if isinstance(simplify, FunctionType):
|
| 250 |
+
charpoly = block.charpoly(simplify=simplify)
|
| 251 |
+
else:
|
| 252 |
+
charpoly = block.charpoly()
|
| 253 |
+
|
| 254 |
+
eigs = roots(charpoly, multiple=False, **flags)
|
| 255 |
+
|
| 256 |
+
if sum(eigs.values()) != block.rows:
|
| 257 |
+
degree = int(charpoly.degree())
|
| 258 |
+
f = charpoly.as_expr()
|
| 259 |
+
x = charpoly.gen
|
| 260 |
+
try:
|
| 261 |
+
eigs = {CRootOf(f, x, idx): 1 for idx in range(degree)}
|
| 262 |
+
except NotImplementedError:
|
| 263 |
+
if error_when_incomplete:
|
| 264 |
+
raise MatrixError(eigenvals_error_message)
|
| 265 |
+
else:
|
| 266 |
+
eigs = {}
|
| 267 |
+
|
| 268 |
+
for k, v in eigs.items():
|
| 269 |
+
if k in all_eigs:
|
| 270 |
+
all_eigs[k] += v
|
| 271 |
+
else:
|
| 272 |
+
all_eigs[k] = v
|
| 273 |
+
|
| 274 |
+
if not simplify:
|
| 275 |
+
return all_eigs
|
| 276 |
+
if not isinstance(simplify, FunctionType):
|
| 277 |
+
simplify = _simplify
|
| 278 |
+
return {simplify(key): value for key, value in all_eigs.items()}
|
| 279 |
+
|
| 280 |
+
|
| 281 |
+
def _eigenspace(M, eigenval, iszerofunc=_iszero, simplify=False):
|
| 282 |
+
"""Get a basis for the eigenspace for a particular eigenvalue"""
|
| 283 |
+
m = M - M.eye(M.rows) * eigenval
|
| 284 |
+
ret = m.nullspace(iszerofunc=iszerofunc)
|
| 285 |
+
|
| 286 |
+
# The nullspace for a real eigenvalue should be non-trivial.
|
| 287 |
+
# If we didn't find an eigenvector, try once more a little harder
|
| 288 |
+
if len(ret) == 0 and simplify:
|
| 289 |
+
ret = m.nullspace(iszerofunc=iszerofunc, simplify=True)
|
| 290 |
+
if len(ret) == 0:
|
| 291 |
+
raise NotImplementedError(
|
| 292 |
+
"Can't evaluate eigenvector for eigenvalue {}".format(eigenval))
|
| 293 |
+
return ret
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
def _eigenvects_DOM(M, **kwargs):
|
| 297 |
+
DOM = DomainMatrix.from_Matrix(M, field=True, extension=True)
|
| 298 |
+
DOM = DOM.to_dense()
|
| 299 |
+
|
| 300 |
+
if DOM.domain != EX:
|
| 301 |
+
rational, algebraic = dom_eigenvects(DOM)
|
| 302 |
+
eigenvects = dom_eigenvects_to_sympy(
|
| 303 |
+
rational, algebraic, M.__class__, **kwargs)
|
| 304 |
+
eigenvects = sorted(eigenvects, key=lambda x: default_sort_key(x[0]))
|
| 305 |
+
|
| 306 |
+
return eigenvects
|
| 307 |
+
return None
|
| 308 |
+
|
| 309 |
+
|
| 310 |
+
def _eigenvects_sympy(M, iszerofunc, simplify=True, **flags):
|
| 311 |
+
eigenvals = M.eigenvals(rational=False, **flags)
|
| 312 |
+
|
| 313 |
+
# Make sure that we have all roots in radical form
|
| 314 |
+
for x in eigenvals:
|
| 315 |
+
if x.has(CRootOf):
|
| 316 |
+
raise MatrixError(
|
| 317 |
+
"Eigenvector computation is not implemented if the matrix have "
|
| 318 |
+
"eigenvalues in CRootOf form")
|
| 319 |
+
|
| 320 |
+
eigenvals = sorted(eigenvals.items(), key=default_sort_key)
|
| 321 |
+
ret = []
|
| 322 |
+
for val, mult in eigenvals:
|
| 323 |
+
vects = _eigenspace(M, val, iszerofunc=iszerofunc, simplify=simplify)
|
| 324 |
+
ret.append((val, mult, vects))
|
| 325 |
+
return ret
|
| 326 |
+
|
| 327 |
+
|
| 328 |
+
# This functions is a candidate for caching if it gets implemented for matrices.
|
| 329 |
+
def _eigenvects(M, error_when_incomplete=True, iszerofunc=_iszero, *, chop=False, **flags):
|
| 330 |
+
"""Compute eigenvectors of the matrix.
|
| 331 |
+
|
| 332 |
+
Parameters
|
| 333 |
+
==========
|
| 334 |
+
|
| 335 |
+
error_when_incomplete : bool, optional
|
| 336 |
+
Raise an error when not all eigenvalues are computed. This is
|
| 337 |
+
caused by ``roots`` not returning a full list of eigenvalues.
|
| 338 |
+
|
| 339 |
+
iszerofunc : function, optional
|
| 340 |
+
Specifies a zero testing function to be used in ``rref``.
|
| 341 |
+
|
| 342 |
+
Default value is ``_iszero``, which uses SymPy's naive and fast
|
| 343 |
+
default assumption handler.
|
| 344 |
+
|
| 345 |
+
It can also accept any user-specified zero testing function, if it
|
| 346 |
+
is formatted as a function which accepts a single symbolic argument
|
| 347 |
+
and returns ``True`` if it is tested as zero and ``False`` if it
|
| 348 |
+
is tested as non-zero, and ``None`` if it is undecidable.
|
| 349 |
+
|
| 350 |
+
simplify : bool or function, optional
|
| 351 |
+
If ``True``, ``as_content_primitive()`` will be used to tidy up
|
| 352 |
+
normalization artifacts.
|
| 353 |
+
|
| 354 |
+
It will also be used by the ``nullspace`` routine.
|
| 355 |
+
|
| 356 |
+
chop : bool or positive number, optional
|
| 357 |
+
If the matrix contains any Floats, they will be changed to Rationals
|
| 358 |
+
for computation purposes, but the answers will be returned after
|
| 359 |
+
being evaluated with evalf. The ``chop`` flag is passed to ``evalf``.
|
| 360 |
+
When ``chop=True`` a default precision will be used; a number will
|
| 361 |
+
be interpreted as the desired level of precision.
|
| 362 |
+
|
| 363 |
+
Returns
|
| 364 |
+
=======
|
| 365 |
+
|
| 366 |
+
ret : [(eigenval, multiplicity, eigenspace), ...]
|
| 367 |
+
A ragged list containing tuples of data obtained by ``eigenvals``
|
| 368 |
+
and ``nullspace``.
|
| 369 |
+
|
| 370 |
+
``eigenspace`` is a list containing the ``eigenvector`` for each
|
| 371 |
+
eigenvalue.
|
| 372 |
+
|
| 373 |
+
``eigenvector`` is a vector in the form of a ``Matrix``. e.g.
|
| 374 |
+
a vector of length 3 is returned as ``Matrix([a_1, a_2, a_3])``.
|
| 375 |
+
|
| 376 |
+
Raises
|
| 377 |
+
======
|
| 378 |
+
|
| 379 |
+
NotImplementedError
|
| 380 |
+
If failed to compute nullspace.
|
| 381 |
+
|
| 382 |
+
Examples
|
| 383 |
+
========
|
| 384 |
+
|
| 385 |
+
>>> from sympy import Matrix
|
| 386 |
+
>>> M = Matrix(3, 3, [0, 1, 1, 1, 0, 0, 1, 1, 1])
|
| 387 |
+
>>> M.eigenvects()
|
| 388 |
+
[(-1, 1, [Matrix([
|
| 389 |
+
[-1],
|
| 390 |
+
[ 1],
|
| 391 |
+
[ 0]])]), (0, 1, [Matrix([
|
| 392 |
+
[ 0],
|
| 393 |
+
[-1],
|
| 394 |
+
[ 1]])]), (2, 1, [Matrix([
|
| 395 |
+
[2/3],
|
| 396 |
+
[1/3],
|
| 397 |
+
[ 1]])])]
|
| 398 |
+
|
| 399 |
+
See Also
|
| 400 |
+
========
|
| 401 |
+
|
| 402 |
+
eigenvals
|
| 403 |
+
MatrixSubspaces.nullspace
|
| 404 |
+
"""
|
| 405 |
+
simplify = flags.get('simplify', True)
|
| 406 |
+
primitive = flags.get('simplify', False)
|
| 407 |
+
flags.pop('simplify', None) # remove this if it's there
|
| 408 |
+
flags.pop('multiple', None) # remove this if it's there
|
| 409 |
+
|
| 410 |
+
if not isinstance(simplify, FunctionType):
|
| 411 |
+
simpfunc = _simplify if simplify else lambda x: x
|
| 412 |
+
|
| 413 |
+
has_floats = M.has(Float)
|
| 414 |
+
if has_floats:
|
| 415 |
+
if all(x.is_number for x in M):
|
| 416 |
+
return _eigenvects_mpmath(M)
|
| 417 |
+
from sympy.simplify import nsimplify
|
| 418 |
+
M = M.applyfunc(lambda x: nsimplify(x, rational=True))
|
| 419 |
+
|
| 420 |
+
ret = _eigenvects_DOM(M)
|
| 421 |
+
if ret is None:
|
| 422 |
+
ret = _eigenvects_sympy(M, iszerofunc, simplify=simplify, **flags)
|
| 423 |
+
|
| 424 |
+
if primitive:
|
| 425 |
+
# if the primitive flag is set, get rid of any common
|
| 426 |
+
# integer denominators
|
| 427 |
+
def denom_clean(l):
|
| 428 |
+
return [(v / gcd(list(v))).applyfunc(simpfunc) for v in l]
|
| 429 |
+
|
| 430 |
+
ret = [(val, mult, denom_clean(es)) for val, mult, es in ret]
|
| 431 |
+
|
| 432 |
+
if has_floats:
|
| 433 |
+
# if we had floats to start with, turn the eigenvectors to floats
|
| 434 |
+
ret = [(val.evalf(chop=chop), mult, [v.evalf(chop=chop) for v in es])
|
| 435 |
+
for val, mult, es in ret]
|
| 436 |
+
|
| 437 |
+
return ret
|
| 438 |
+
|
| 439 |
+
|
| 440 |
+
def _is_diagonalizable_with_eigen(M, reals_only=False):
|
| 441 |
+
"""See _is_diagonalizable. This function returns the bool along with the
|
| 442 |
+
eigenvectors to avoid calculating them again in functions like
|
| 443 |
+
``diagonalize``."""
|
| 444 |
+
|
| 445 |
+
if not M.is_square:
|
| 446 |
+
return False, []
|
| 447 |
+
|
| 448 |
+
eigenvecs = M.eigenvects(simplify=True)
|
| 449 |
+
|
| 450 |
+
for val, mult, basis in eigenvecs:
|
| 451 |
+
if reals_only and not val.is_real: # if we have a complex eigenvalue
|
| 452 |
+
return False, eigenvecs
|
| 453 |
+
|
| 454 |
+
if mult != len(basis): # if the geometric multiplicity doesn't equal the algebraic
|
| 455 |
+
return False, eigenvecs
|
| 456 |
+
|
| 457 |
+
return True, eigenvecs
|
| 458 |
+
|
| 459 |
+
def _is_diagonalizable(M, reals_only=False, **kwargs):
|
| 460 |
+
"""Returns ``True`` if a matrix is diagonalizable.
|
| 461 |
+
|
| 462 |
+
Parameters
|
| 463 |
+
==========
|
| 464 |
+
|
| 465 |
+
reals_only : bool, optional
|
| 466 |
+
If ``True``, it tests whether the matrix can be diagonalized
|
| 467 |
+
to contain only real numbers on the diagonal.
|
| 468 |
+
|
| 469 |
+
|
| 470 |
+
If ``False``, it tests whether the matrix can be diagonalized
|
| 471 |
+
at all, even with numbers that may not be real.
|
| 472 |
+
|
| 473 |
+
Examples
|
| 474 |
+
========
|
| 475 |
+
|
| 476 |
+
Example of a diagonalizable matrix:
|
| 477 |
+
|
| 478 |
+
>>> from sympy import Matrix
|
| 479 |
+
>>> M = Matrix([[1, 2, 0], [0, 3, 0], [2, -4, 2]])
|
| 480 |
+
>>> M.is_diagonalizable()
|
| 481 |
+
True
|
| 482 |
+
|
| 483 |
+
Example of a non-diagonalizable matrix:
|
| 484 |
+
|
| 485 |
+
>>> M = Matrix([[0, 1], [0, 0]])
|
| 486 |
+
>>> M.is_diagonalizable()
|
| 487 |
+
False
|
| 488 |
+
|
| 489 |
+
Example of a matrix that is diagonalized in terms of non-real entries:
|
| 490 |
+
|
| 491 |
+
>>> M = Matrix([[0, 1], [-1, 0]])
|
| 492 |
+
>>> M.is_diagonalizable(reals_only=False)
|
| 493 |
+
True
|
| 494 |
+
>>> M.is_diagonalizable(reals_only=True)
|
| 495 |
+
False
|
| 496 |
+
|
| 497 |
+
See Also
|
| 498 |
+
========
|
| 499 |
+
|
| 500 |
+
is_diagonal
|
| 501 |
+
diagonalize
|
| 502 |
+
"""
|
| 503 |
+
if not M.is_square:
|
| 504 |
+
return False
|
| 505 |
+
|
| 506 |
+
if all(e.is_real for e in M) and M.is_symmetric():
|
| 507 |
+
return True
|
| 508 |
+
|
| 509 |
+
if all(e.is_complex for e in M) and M.is_hermitian:
|
| 510 |
+
return True
|
| 511 |
+
|
| 512 |
+
return _is_diagonalizable_with_eigen(M, reals_only=reals_only)[0]
|
| 513 |
+
|
| 514 |
+
|
| 515 |
+
#G&VL, Matrix Computations, Algo 5.4.2
|
| 516 |
+
def _householder_vector(x):
|
| 517 |
+
if not x.cols == 1:
|
| 518 |
+
raise ValueError("Input must be a column matrix")
|
| 519 |
+
v = x.copy()
|
| 520 |
+
v_plus = x.copy()
|
| 521 |
+
v_minus = x.copy()
|
| 522 |
+
q = x[0, 0] / abs(x[0, 0])
|
| 523 |
+
norm_x = x.norm()
|
| 524 |
+
v_plus[0, 0] = x[0, 0] + q * norm_x
|
| 525 |
+
v_minus[0, 0] = x[0, 0] - q * norm_x
|
| 526 |
+
if x[1:, 0].norm() == 0:
|
| 527 |
+
bet = 0
|
| 528 |
+
v[0, 0] = 1
|
| 529 |
+
else:
|
| 530 |
+
if v_plus.norm() <= v_minus.norm():
|
| 531 |
+
v = v_plus
|
| 532 |
+
else:
|
| 533 |
+
v = v_minus
|
| 534 |
+
v = v / v[0]
|
| 535 |
+
bet = 2 / (v.norm() ** 2)
|
| 536 |
+
return v, bet
|
| 537 |
+
|
| 538 |
+
|
| 539 |
+
def _bidiagonal_decmp_hholder(M):
|
| 540 |
+
m = M.rows
|
| 541 |
+
n = M.cols
|
| 542 |
+
A = M.as_mutable()
|
| 543 |
+
U, V = A.eye(m), A.eye(n)
|
| 544 |
+
for i in range(min(m, n)):
|
| 545 |
+
v, bet = _householder_vector(A[i:, i])
|
| 546 |
+
hh_mat = A.eye(m - i) - bet * v * v.H
|
| 547 |
+
A[i:, i:] = hh_mat * A[i:, i:]
|
| 548 |
+
temp = A.eye(m)
|
| 549 |
+
temp[i:, i:] = hh_mat
|
| 550 |
+
U = U * temp
|
| 551 |
+
if i + 1 <= n - 2:
|
| 552 |
+
v, bet = _householder_vector(A[i, i+1:].T)
|
| 553 |
+
hh_mat = A.eye(n - i - 1) - bet * v * v.H
|
| 554 |
+
A[i:, i+1:] = A[i:, i+1:] * hh_mat
|
| 555 |
+
temp = A.eye(n)
|
| 556 |
+
temp[i+1:, i+1:] = hh_mat
|
| 557 |
+
V = temp * V
|
| 558 |
+
return U, A, V
|
| 559 |
+
|
| 560 |
+
|
| 561 |
+
def _eval_bidiag_hholder(M):
|
| 562 |
+
m = M.rows
|
| 563 |
+
n = M.cols
|
| 564 |
+
A = M.as_mutable()
|
| 565 |
+
for i in range(min(m, n)):
|
| 566 |
+
v, bet = _householder_vector(A[i:, i])
|
| 567 |
+
hh_mat = A.eye(m-i) - bet * v * v.H
|
| 568 |
+
A[i:, i:] = hh_mat * A[i:, i:]
|
| 569 |
+
if i + 1 <= n - 2:
|
| 570 |
+
v, bet = _householder_vector(A[i, i+1:].T)
|
| 571 |
+
hh_mat = A.eye(n - i - 1) - bet * v * v.H
|
| 572 |
+
A[i:, i+1:] = A[i:, i+1:] * hh_mat
|
| 573 |
+
return A
|
| 574 |
+
|
| 575 |
+
|
| 576 |
+
def _bidiagonal_decomposition(M, upper=True):
|
| 577 |
+
"""
|
| 578 |
+
Returns $(U,B,V.H)$ for
|
| 579 |
+
|
| 580 |
+
$$A = UBV^{H}$$
|
| 581 |
+
|
| 582 |
+
where $A$ is the input matrix, and $B$ is its Bidiagonalized form
|
| 583 |
+
|
| 584 |
+
Note: Bidiagonal Computation can hang for symbolic matrices.
|
| 585 |
+
|
| 586 |
+
Parameters
|
| 587 |
+
==========
|
| 588 |
+
|
| 589 |
+
upper : bool. Whether to do upper bidiagnalization or lower.
|
| 590 |
+
True for upper and False for lower.
|
| 591 |
+
|
| 592 |
+
References
|
| 593 |
+
==========
|
| 594 |
+
|
| 595 |
+
.. [1] Algorithm 5.4.2, Matrix computations by Golub and Van Loan, 4th edition
|
| 596 |
+
.. [2] Complex Matrix Bidiagonalization, https://github.com/vslobody/Householder-Bidiagonalization
|
| 597 |
+
|
| 598 |
+
"""
|
| 599 |
+
|
| 600 |
+
if not isinstance(upper, bool):
|
| 601 |
+
raise ValueError("upper must be a boolean")
|
| 602 |
+
|
| 603 |
+
if upper:
|
| 604 |
+
return _bidiagonal_decmp_hholder(M)
|
| 605 |
+
|
| 606 |
+
X = _bidiagonal_decmp_hholder(M.H)
|
| 607 |
+
return X[2].H, X[1].H, X[0].H
|
| 608 |
+
|
| 609 |
+
|
| 610 |
+
def _bidiagonalize(M, upper=True):
|
| 611 |
+
"""
|
| 612 |
+
Returns $B$, the Bidiagonalized form of the input matrix.
|
| 613 |
+
|
| 614 |
+
Note: Bidiagonal Computation can hang for symbolic matrices.
|
| 615 |
+
|
| 616 |
+
Parameters
|
| 617 |
+
==========
|
| 618 |
+
|
| 619 |
+
upper : bool. Whether to do upper bidiagnalization or lower.
|
| 620 |
+
True for upper and False for lower.
|
| 621 |
+
|
| 622 |
+
References
|
| 623 |
+
==========
|
| 624 |
+
|
| 625 |
+
.. [1] Algorithm 5.4.2, Matrix computations by Golub and Van Loan, 4th edition
|
| 626 |
+
.. [2] Complex Matrix Bidiagonalization : https://github.com/vslobody/Householder-Bidiagonalization
|
| 627 |
+
|
| 628 |
+
"""
|
| 629 |
+
|
| 630 |
+
if not isinstance(upper, bool):
|
| 631 |
+
raise ValueError("upper must be a boolean")
|
| 632 |
+
|
| 633 |
+
if upper:
|
| 634 |
+
return _eval_bidiag_hholder(M)
|
| 635 |
+
return _eval_bidiag_hholder(M.H).H
|
| 636 |
+
|
| 637 |
+
|
| 638 |
+
def _diagonalize(M, reals_only=False, sort=False, normalize=False):
|
| 639 |
+
"""
|
| 640 |
+
Return (P, D), where D is diagonal and
|
| 641 |
+
|
| 642 |
+
D = P^-1 * M * P
|
| 643 |
+
|
| 644 |
+
where M is current matrix.
|
| 645 |
+
|
| 646 |
+
Parameters
|
| 647 |
+
==========
|
| 648 |
+
|
| 649 |
+
reals_only : bool. Whether to throw an error if complex numbers are need
|
| 650 |
+
to diagonalize. (Default: False)
|
| 651 |
+
|
| 652 |
+
sort : bool. Sort the eigenvalues along the diagonal. (Default: False)
|
| 653 |
+
|
| 654 |
+
normalize : bool. If True, normalize the columns of P. (Default: False)
|
| 655 |
+
|
| 656 |
+
Examples
|
| 657 |
+
========
|
| 658 |
+
|
| 659 |
+
>>> from sympy import Matrix
|
| 660 |
+
>>> M = Matrix(3, 3, [1, 2, 0, 0, 3, 0, 2, -4, 2])
|
| 661 |
+
>>> M
|
| 662 |
+
Matrix([
|
| 663 |
+
[1, 2, 0],
|
| 664 |
+
[0, 3, 0],
|
| 665 |
+
[2, -4, 2]])
|
| 666 |
+
>>> (P, D) = M.diagonalize()
|
| 667 |
+
>>> D
|
| 668 |
+
Matrix([
|
| 669 |
+
[1, 0, 0],
|
| 670 |
+
[0, 2, 0],
|
| 671 |
+
[0, 0, 3]])
|
| 672 |
+
>>> P
|
| 673 |
+
Matrix([
|
| 674 |
+
[-1, 0, -1],
|
| 675 |
+
[ 0, 0, -1],
|
| 676 |
+
[ 2, 1, 2]])
|
| 677 |
+
>>> P.inv() * M * P
|
| 678 |
+
Matrix([
|
| 679 |
+
[1, 0, 0],
|
| 680 |
+
[0, 2, 0],
|
| 681 |
+
[0, 0, 3]])
|
| 682 |
+
|
| 683 |
+
See Also
|
| 684 |
+
========
|
| 685 |
+
|
| 686 |
+
is_diagonal
|
| 687 |
+
is_diagonalizable
|
| 688 |
+
"""
|
| 689 |
+
|
| 690 |
+
if not M.is_square:
|
| 691 |
+
raise NonSquareMatrixError()
|
| 692 |
+
|
| 693 |
+
is_diagonalizable, eigenvecs = _is_diagonalizable_with_eigen(M,
|
| 694 |
+
reals_only=reals_only)
|
| 695 |
+
|
| 696 |
+
if not is_diagonalizable:
|
| 697 |
+
raise MatrixError("Matrix is not diagonalizable")
|
| 698 |
+
|
| 699 |
+
if sort:
|
| 700 |
+
eigenvecs = sorted(eigenvecs, key=default_sort_key)
|
| 701 |
+
|
| 702 |
+
p_cols, diag = [], []
|
| 703 |
+
|
| 704 |
+
for val, mult, basis in eigenvecs:
|
| 705 |
+
diag += [val] * mult
|
| 706 |
+
p_cols += basis
|
| 707 |
+
|
| 708 |
+
if normalize:
|
| 709 |
+
p_cols = [v / v.norm() for v in p_cols]
|
| 710 |
+
|
| 711 |
+
return M.hstack(*p_cols), M.diag(*diag)
|
| 712 |
+
|
| 713 |
+
|
| 714 |
+
def _fuzzy_positive_definite(M):
|
| 715 |
+
positive_diagonals = M._has_positive_diagonals()
|
| 716 |
+
if positive_diagonals is False:
|
| 717 |
+
return False
|
| 718 |
+
|
| 719 |
+
if positive_diagonals and M.is_strongly_diagonally_dominant:
|
| 720 |
+
return True
|
| 721 |
+
|
| 722 |
+
return None
|
| 723 |
+
|
| 724 |
+
|
| 725 |
+
def _fuzzy_positive_semidefinite(M):
|
| 726 |
+
nonnegative_diagonals = M._has_nonnegative_diagonals()
|
| 727 |
+
if nonnegative_diagonals is False:
|
| 728 |
+
return False
|
| 729 |
+
|
| 730 |
+
if nonnegative_diagonals and M.is_weakly_diagonally_dominant:
|
| 731 |
+
return True
|
| 732 |
+
|
| 733 |
+
return None
|
| 734 |
+
|
| 735 |
+
|
| 736 |
+
def _is_positive_definite(M):
|
| 737 |
+
if not M.is_hermitian:
|
| 738 |
+
if not M.is_square:
|
| 739 |
+
return False
|
| 740 |
+
M = M + M.H
|
| 741 |
+
|
| 742 |
+
fuzzy = _fuzzy_positive_definite(M)
|
| 743 |
+
if fuzzy is not None:
|
| 744 |
+
return fuzzy
|
| 745 |
+
|
| 746 |
+
return _is_positive_definite_GE(M)
|
| 747 |
+
|
| 748 |
+
|
| 749 |
+
def _is_positive_semidefinite(M):
|
| 750 |
+
if not M.is_hermitian:
|
| 751 |
+
if not M.is_square:
|
| 752 |
+
return False
|
| 753 |
+
M = M + M.H
|
| 754 |
+
|
| 755 |
+
fuzzy = _fuzzy_positive_semidefinite(M)
|
| 756 |
+
if fuzzy is not None:
|
| 757 |
+
return fuzzy
|
| 758 |
+
|
| 759 |
+
return _is_positive_semidefinite_cholesky(M)
|
| 760 |
+
|
| 761 |
+
|
| 762 |
+
def _is_negative_definite(M):
|
| 763 |
+
return _is_positive_definite(-M)
|
| 764 |
+
|
| 765 |
+
|
| 766 |
+
def _is_negative_semidefinite(M):
|
| 767 |
+
return _is_positive_semidefinite(-M)
|
| 768 |
+
|
| 769 |
+
|
| 770 |
+
def _is_indefinite(M):
|
| 771 |
+
if M.is_hermitian:
|
| 772 |
+
eigen = M.eigenvals()
|
| 773 |
+
args1 = [x.is_positive for x in eigen.keys()]
|
| 774 |
+
any_positive = fuzzy_or(args1)
|
| 775 |
+
args2 = [x.is_negative for x in eigen.keys()]
|
| 776 |
+
any_negative = fuzzy_or(args2)
|
| 777 |
+
|
| 778 |
+
return fuzzy_and([any_positive, any_negative])
|
| 779 |
+
|
| 780 |
+
elif M.is_square:
|
| 781 |
+
return (M + M.H).is_indefinite
|
| 782 |
+
|
| 783 |
+
return False
|
| 784 |
+
|
| 785 |
+
|
| 786 |
+
def _is_positive_definite_GE(M):
|
| 787 |
+
"""A division-free gaussian elimination method for testing
|
| 788 |
+
positive-definiteness."""
|
| 789 |
+
M = M.as_mutable()
|
| 790 |
+
size = M.rows
|
| 791 |
+
|
| 792 |
+
for i in range(size):
|
| 793 |
+
is_positive = M[i, i].is_positive
|
| 794 |
+
if is_positive is not True:
|
| 795 |
+
return is_positive
|
| 796 |
+
for j in range(i+1, size):
|
| 797 |
+
M[j, i+1:] = M[i, i] * M[j, i+1:] - M[j, i] * M[i, i+1:]
|
| 798 |
+
return True
|
| 799 |
+
|
| 800 |
+
|
| 801 |
+
def _is_positive_semidefinite_cholesky(M):
|
| 802 |
+
"""Uses Cholesky factorization with complete pivoting
|
| 803 |
+
|
| 804 |
+
References
|
| 805 |
+
==========
|
| 806 |
+
|
| 807 |
+
.. [1] http://eprints.ma.man.ac.uk/1199/1/covered/MIMS_ep2008_116.pdf
|
| 808 |
+
|
| 809 |
+
.. [2] https://www.value-at-risk.net/cholesky-factorization/
|
| 810 |
+
"""
|
| 811 |
+
M = M.as_mutable()
|
| 812 |
+
for k in range(M.rows):
|
| 813 |
+
diags = [M[i, i] for i in range(k, M.rows)]
|
| 814 |
+
pivot, pivot_val, nonzero, _ = _find_reasonable_pivot(diags)
|
| 815 |
+
|
| 816 |
+
if nonzero:
|
| 817 |
+
return None
|
| 818 |
+
|
| 819 |
+
if pivot is None:
|
| 820 |
+
for i in range(k+1, M.rows):
|
| 821 |
+
for j in range(k, M.cols):
|
| 822 |
+
iszero = M[i, j].is_zero
|
| 823 |
+
if iszero is None:
|
| 824 |
+
return None
|
| 825 |
+
elif iszero is False:
|
| 826 |
+
return False
|
| 827 |
+
return True
|
| 828 |
+
|
| 829 |
+
if M[k, k].is_negative or pivot_val.is_negative:
|
| 830 |
+
return False
|
| 831 |
+
elif not (M[k, k].is_nonnegative and pivot_val.is_nonnegative):
|
| 832 |
+
return None
|
| 833 |
+
|
| 834 |
+
if pivot > 0:
|
| 835 |
+
M.col_swap(k, k+pivot)
|
| 836 |
+
M.row_swap(k, k+pivot)
|
| 837 |
+
|
| 838 |
+
M[k, k] = sqrt(M[k, k])
|
| 839 |
+
M[k, k+1:] /= M[k, k]
|
| 840 |
+
M[k+1:, k+1:] -= M[k, k+1:].H * M[k, k+1:]
|
| 841 |
+
|
| 842 |
+
return M[-1, -1].is_nonnegative
|
| 843 |
+
|
| 844 |
+
|
| 845 |
+
_doc_positive_definite = \
|
| 846 |
+
r"""Finds out the definiteness of a matrix.
|
| 847 |
+
|
| 848 |
+
Explanation
|
| 849 |
+
===========
|
| 850 |
+
|
| 851 |
+
A square real matrix $A$ is:
|
| 852 |
+
|
| 853 |
+
- A positive definite matrix if $x^T A x > 0$
|
| 854 |
+
for all non-zero real vectors $x$.
|
| 855 |
+
- A positive semidefinite matrix if $x^T A x \geq 0$
|
| 856 |
+
for all non-zero real vectors $x$.
|
| 857 |
+
- A negative definite matrix if $x^T A x < 0$
|
| 858 |
+
for all non-zero real vectors $x$.
|
| 859 |
+
- A negative semidefinite matrix if $x^T A x \leq 0$
|
| 860 |
+
for all non-zero real vectors $x$.
|
| 861 |
+
- An indefinite matrix if there exists non-zero real vectors
|
| 862 |
+
$x, y$ with $x^T A x > 0 > y^T A y$.
|
| 863 |
+
|
| 864 |
+
A square complex matrix $A$ is:
|
| 865 |
+
|
| 866 |
+
- A positive definite matrix if $\text{re}(x^H A x) > 0$
|
| 867 |
+
for all non-zero complex vectors $x$.
|
| 868 |
+
- A positive semidefinite matrix if $\text{re}(x^H A x) \geq 0$
|
| 869 |
+
for all non-zero complex vectors $x$.
|
| 870 |
+
- A negative definite matrix if $\text{re}(x^H A x) < 0$
|
| 871 |
+
for all non-zero complex vectors $x$.
|
| 872 |
+
- A negative semidefinite matrix if $\text{re}(x^H A x) \leq 0$
|
| 873 |
+
for all non-zero complex vectors $x$.
|
| 874 |
+
- An indefinite matrix if there exists non-zero complex vectors
|
| 875 |
+
$x, y$ with $\text{re}(x^H A x) > 0 > \text{re}(y^H A y)$.
|
| 876 |
+
|
| 877 |
+
A matrix need not be symmetric or hermitian to be positive definite.
|
| 878 |
+
|
| 879 |
+
- A real non-symmetric matrix is positive definite if and only if
|
| 880 |
+
$\frac{A + A^T}{2}$ is positive definite.
|
| 881 |
+
- A complex non-hermitian matrix is positive definite if and only if
|
| 882 |
+
$\frac{A + A^H}{2}$ is positive definite.
|
| 883 |
+
|
| 884 |
+
And this extension can apply for all the definitions above.
|
| 885 |
+
|
| 886 |
+
However, for complex cases, you can restrict the definition of
|
| 887 |
+
$\text{re}(x^H A x) > 0$ to $x^H A x > 0$ and require the matrix
|
| 888 |
+
to be hermitian.
|
| 889 |
+
But we do not present this restriction for computation because you
|
| 890 |
+
can check ``M.is_hermitian`` independently with this and use
|
| 891 |
+
the same procedure.
|
| 892 |
+
|
| 893 |
+
Examples
|
| 894 |
+
========
|
| 895 |
+
|
| 896 |
+
An example of symmetric positive definite matrix:
|
| 897 |
+
|
| 898 |
+
.. plot::
|
| 899 |
+
:context: reset
|
| 900 |
+
:format: doctest
|
| 901 |
+
:include-source: True
|
| 902 |
+
|
| 903 |
+
>>> from sympy import Matrix, symbols
|
| 904 |
+
>>> from sympy.plotting import plot3d
|
| 905 |
+
>>> a, b = symbols('a b')
|
| 906 |
+
>>> x = Matrix([a, b])
|
| 907 |
+
|
| 908 |
+
>>> A = Matrix([[1, 0], [0, 1]])
|
| 909 |
+
>>> A.is_positive_definite
|
| 910 |
+
True
|
| 911 |
+
>>> A.is_positive_semidefinite
|
| 912 |
+
True
|
| 913 |
+
|
| 914 |
+
>>> p = plot3d((x.T*A*x)[0, 0], (a, -1, 1), (b, -1, 1))
|
| 915 |
+
|
| 916 |
+
An example of symmetric positive semidefinite matrix:
|
| 917 |
+
|
| 918 |
+
.. plot::
|
| 919 |
+
:context: close-figs
|
| 920 |
+
:format: doctest
|
| 921 |
+
:include-source: True
|
| 922 |
+
|
| 923 |
+
>>> A = Matrix([[1, -1], [-1, 1]])
|
| 924 |
+
>>> A.is_positive_definite
|
| 925 |
+
False
|
| 926 |
+
>>> A.is_positive_semidefinite
|
| 927 |
+
True
|
| 928 |
+
|
| 929 |
+
>>> p = plot3d((x.T*A*x)[0, 0], (a, -1, 1), (b, -1, 1))
|
| 930 |
+
|
| 931 |
+
An example of symmetric negative definite matrix:
|
| 932 |
+
|
| 933 |
+
.. plot::
|
| 934 |
+
:context: close-figs
|
| 935 |
+
:format: doctest
|
| 936 |
+
:include-source: True
|
| 937 |
+
|
| 938 |
+
>>> A = Matrix([[-1, 0], [0, -1]])
|
| 939 |
+
>>> A.is_negative_definite
|
| 940 |
+
True
|
| 941 |
+
>>> A.is_negative_semidefinite
|
| 942 |
+
True
|
| 943 |
+
>>> A.is_indefinite
|
| 944 |
+
False
|
| 945 |
+
|
| 946 |
+
>>> p = plot3d((x.T*A*x)[0, 0], (a, -1, 1), (b, -1, 1))
|
| 947 |
+
|
| 948 |
+
An example of symmetric indefinite matrix:
|
| 949 |
+
|
| 950 |
+
.. plot::
|
| 951 |
+
:context: close-figs
|
| 952 |
+
:format: doctest
|
| 953 |
+
:include-source: True
|
| 954 |
+
|
| 955 |
+
>>> A = Matrix([[1, 2], [2, -1]])
|
| 956 |
+
>>> A.is_indefinite
|
| 957 |
+
True
|
| 958 |
+
|
| 959 |
+
>>> p = plot3d((x.T*A*x)[0, 0], (a, -1, 1), (b, -1, 1))
|
| 960 |
+
|
| 961 |
+
An example of non-symmetric positive definite matrix.
|
| 962 |
+
|
| 963 |
+
.. plot::
|
| 964 |
+
:context: close-figs
|
| 965 |
+
:format: doctest
|
| 966 |
+
:include-source: True
|
| 967 |
+
|
| 968 |
+
>>> A = Matrix([[1, 2], [-2, 1]])
|
| 969 |
+
>>> A.is_positive_definite
|
| 970 |
+
True
|
| 971 |
+
>>> A.is_positive_semidefinite
|
| 972 |
+
True
|
| 973 |
+
|
| 974 |
+
>>> p = plot3d((x.T*A*x)[0, 0], (a, -1, 1), (b, -1, 1))
|
| 975 |
+
|
| 976 |
+
Notes
|
| 977 |
+
=====
|
| 978 |
+
|
| 979 |
+
Although some people trivialize the definition of positive definite
|
| 980 |
+
matrices only for symmetric or hermitian matrices, this restriction
|
| 981 |
+
is not correct because it does not classify all instances of
|
| 982 |
+
positive definite matrices from the definition $x^T A x > 0$ or
|
| 983 |
+
$\text{re}(x^H A x) > 0$.
|
| 984 |
+
|
| 985 |
+
For instance, ``Matrix([[1, 2], [-2, 1]])`` presented in
|
| 986 |
+
the example above is an example of real positive definite matrix
|
| 987 |
+
that is not symmetric.
|
| 988 |
+
|
| 989 |
+
However, since the following formula holds true;
|
| 990 |
+
|
| 991 |
+
.. math::
|
| 992 |
+
\text{re}(x^H A x) > 0 \iff
|
| 993 |
+
\text{re}(x^H \frac{A + A^H}{2} x) > 0
|
| 994 |
+
|
| 995 |
+
We can classify all positive definite matrices that may or may not
|
| 996 |
+
be symmetric or hermitian by transforming the matrix to
|
| 997 |
+
$\frac{A + A^T}{2}$ or $\frac{A + A^H}{2}$
|
| 998 |
+
(which is guaranteed to be always real symmetric or complex
|
| 999 |
+
hermitian) and we can defer most of the studies to symmetric or
|
| 1000 |
+
hermitian positive definite matrices.
|
| 1001 |
+
|
| 1002 |
+
But it is a different problem for the existance of Cholesky
|
| 1003 |
+
decomposition. Because even though a non symmetric or a non
|
| 1004 |
+
hermitian matrix can be positive definite, Cholesky or LDL
|
| 1005 |
+
decomposition does not exist because the decompositions require the
|
| 1006 |
+
matrix to be symmetric or hermitian.
|
| 1007 |
+
|
| 1008 |
+
References
|
| 1009 |
+
==========
|
| 1010 |
+
|
| 1011 |
+
.. [1] https://en.wikipedia.org/wiki/Definiteness_of_a_matrix#Eigenvalues
|
| 1012 |
+
|
| 1013 |
+
.. [2] https://mathworld.wolfram.com/PositiveDefiniteMatrix.html
|
| 1014 |
+
|
| 1015 |
+
.. [3] Johnson, C. R. "Positive Definite Matrices." Amer.
|
| 1016 |
+
Math. Monthly 77, 259-264 1970.
|
| 1017 |
+
"""
|
| 1018 |
+
|
| 1019 |
+
_is_positive_definite.__doc__ = _doc_positive_definite
|
| 1020 |
+
_is_positive_semidefinite.__doc__ = _doc_positive_definite
|
| 1021 |
+
_is_negative_definite.__doc__ = _doc_positive_definite
|
| 1022 |
+
_is_negative_semidefinite.__doc__ = _doc_positive_definite
|
| 1023 |
+
_is_indefinite.__doc__ = _doc_positive_definite
|
| 1024 |
+
|
| 1025 |
+
|
| 1026 |
+
def _jordan_form(M, calc_transform=True, *, chop=False):
|
| 1027 |
+
"""Return $(P, J)$ where $J$ is a Jordan block
|
| 1028 |
+
matrix and $P$ is a matrix such that $M = P J P^{-1}$
|
| 1029 |
+
|
| 1030 |
+
Parameters
|
| 1031 |
+
==========
|
| 1032 |
+
|
| 1033 |
+
calc_transform : bool
|
| 1034 |
+
If ``False``, then only $J$ is returned.
|
| 1035 |
+
|
| 1036 |
+
chop : bool
|
| 1037 |
+
All matrices are converted to exact types when computing
|
| 1038 |
+
eigenvalues and eigenvectors. As a result, there may be
|
| 1039 |
+
approximation errors. If ``chop==True``, these errors
|
| 1040 |
+
will be truncated.
|
| 1041 |
+
|
| 1042 |
+
Examples
|
| 1043 |
+
========
|
| 1044 |
+
|
| 1045 |
+
>>> from sympy import Matrix
|
| 1046 |
+
>>> M = Matrix([[ 6, 5, -2, -3], [-3, -1, 3, 3], [ 2, 1, -2, -3], [-1, 1, 5, 5]])
|
| 1047 |
+
>>> P, J = M.jordan_form()
|
| 1048 |
+
>>> J
|
| 1049 |
+
Matrix([
|
| 1050 |
+
[2, 1, 0, 0],
|
| 1051 |
+
[0, 2, 0, 0],
|
| 1052 |
+
[0, 0, 2, 1],
|
| 1053 |
+
[0, 0, 0, 2]])
|
| 1054 |
+
|
| 1055 |
+
See Also
|
| 1056 |
+
========
|
| 1057 |
+
|
| 1058 |
+
jordan_block
|
| 1059 |
+
"""
|
| 1060 |
+
|
| 1061 |
+
if not M.is_square:
|
| 1062 |
+
raise NonSquareMatrixError("Only square matrices have Jordan forms")
|
| 1063 |
+
|
| 1064 |
+
mat = M
|
| 1065 |
+
has_floats = M.has(Float)
|
| 1066 |
+
|
| 1067 |
+
if has_floats:
|
| 1068 |
+
try:
|
| 1069 |
+
max_prec = max(term._prec for term in M.values() if isinstance(term, Float))
|
| 1070 |
+
except ValueError:
|
| 1071 |
+
# if no term in the matrix is explicitly a Float calling max()
|
| 1072 |
+
# will throw a error so setting max_prec to default value of 53
|
| 1073 |
+
max_prec = 53
|
| 1074 |
+
|
| 1075 |
+
# setting minimum max_dps to 15 to prevent loss of precision in
|
| 1076 |
+
# matrix containing non evaluated expressions
|
| 1077 |
+
max_dps = max(prec_to_dps(max_prec), 15)
|
| 1078 |
+
|
| 1079 |
+
def restore_floats(*args):
|
| 1080 |
+
"""If ``has_floats`` is `True`, cast all ``args`` as
|
| 1081 |
+
matrices of floats."""
|
| 1082 |
+
|
| 1083 |
+
if has_floats:
|
| 1084 |
+
args = [m.evalf(n=max_dps, chop=chop) for m in args]
|
| 1085 |
+
if len(args) == 1:
|
| 1086 |
+
return args[0]
|
| 1087 |
+
|
| 1088 |
+
return args
|
| 1089 |
+
|
| 1090 |
+
# cache calculations for some speedup
|
| 1091 |
+
mat_cache = {}
|
| 1092 |
+
|
| 1093 |
+
def eig_mat(val, pow):
|
| 1094 |
+
"""Cache computations of ``(M - val*I)**pow`` for quick
|
| 1095 |
+
retrieval"""
|
| 1096 |
+
|
| 1097 |
+
if (val, pow) in mat_cache:
|
| 1098 |
+
return mat_cache[(val, pow)]
|
| 1099 |
+
|
| 1100 |
+
if (val, pow - 1) in mat_cache:
|
| 1101 |
+
mat_cache[(val, pow)] = mat_cache[(val, pow - 1)].multiply(
|
| 1102 |
+
mat_cache[(val, 1)], dotprodsimp=None)
|
| 1103 |
+
else:
|
| 1104 |
+
mat_cache[(val, pow)] = (mat - val*M.eye(M.rows)).pow(pow)
|
| 1105 |
+
|
| 1106 |
+
return mat_cache[(val, pow)]
|
| 1107 |
+
|
| 1108 |
+
# helper functions
|
| 1109 |
+
def nullity_chain(val, algebraic_multiplicity):
|
| 1110 |
+
"""Calculate the sequence [0, nullity(E), nullity(E**2), ...]
|
| 1111 |
+
until it is constant where ``E = M - val*I``"""
|
| 1112 |
+
|
| 1113 |
+
# mat.rank() is faster than computing the null space,
|
| 1114 |
+
# so use the rank-nullity theorem
|
| 1115 |
+
cols = M.cols
|
| 1116 |
+
ret = [0]
|
| 1117 |
+
nullity = cols - eig_mat(val, 1).rank()
|
| 1118 |
+
i = 2
|
| 1119 |
+
|
| 1120 |
+
while nullity != ret[-1]:
|
| 1121 |
+
ret.append(nullity)
|
| 1122 |
+
|
| 1123 |
+
if nullity == algebraic_multiplicity:
|
| 1124 |
+
break
|
| 1125 |
+
|
| 1126 |
+
nullity = cols - eig_mat(val, i).rank()
|
| 1127 |
+
i += 1
|
| 1128 |
+
|
| 1129 |
+
# Due to issues like #7146 and #15872, SymPy sometimes
|
| 1130 |
+
# gives the wrong rank. In this case, raise an error
|
| 1131 |
+
# instead of returning an incorrect matrix
|
| 1132 |
+
if nullity < ret[-1] or nullity > algebraic_multiplicity:
|
| 1133 |
+
raise MatrixError(
|
| 1134 |
+
"SymPy had encountered an inconsistent "
|
| 1135 |
+
"result while computing Jordan block: "
|
| 1136 |
+
"{}".format(M))
|
| 1137 |
+
|
| 1138 |
+
return ret
|
| 1139 |
+
|
| 1140 |
+
def blocks_from_nullity_chain(d):
|
| 1141 |
+
"""Return a list of the size of each Jordan block.
|
| 1142 |
+
If d_n is the nullity of E**n, then the number
|
| 1143 |
+
of Jordan blocks of size n is
|
| 1144 |
+
|
| 1145 |
+
2*d_n - d_(n-1) - d_(n+1)"""
|
| 1146 |
+
|
| 1147 |
+
# d[0] is always the number of columns, so skip past it
|
| 1148 |
+
mid = [2*d[n] - d[n - 1] - d[n + 1] for n in range(1, len(d) - 1)]
|
| 1149 |
+
# d is assumed to plateau with "d[ len(d) ] == d[-1]", so
|
| 1150 |
+
# 2*d_n - d_(n-1) - d_(n+1) == d_n - d_(n-1)
|
| 1151 |
+
end = [d[-1] - d[-2]] if len(d) > 1 else [d[0]]
|
| 1152 |
+
|
| 1153 |
+
return mid + end
|
| 1154 |
+
|
| 1155 |
+
def pick_vec(small_basis, big_basis):
|
| 1156 |
+
"""Picks a vector from big_basis that isn't in
|
| 1157 |
+
the subspace spanned by small_basis"""
|
| 1158 |
+
|
| 1159 |
+
if len(small_basis) == 0:
|
| 1160 |
+
return big_basis[0]
|
| 1161 |
+
|
| 1162 |
+
for v in big_basis:
|
| 1163 |
+
_, pivots = M.hstack(*(small_basis + [v])).echelon_form(
|
| 1164 |
+
with_pivots=True)
|
| 1165 |
+
|
| 1166 |
+
if pivots[-1] == len(small_basis):
|
| 1167 |
+
return v
|
| 1168 |
+
|
| 1169 |
+
# roots doesn't like Floats, so replace them with Rationals
|
| 1170 |
+
if has_floats:
|
| 1171 |
+
from sympy.simplify import nsimplify
|
| 1172 |
+
mat = mat.applyfunc(lambda x: nsimplify(x, rational=True))
|
| 1173 |
+
|
| 1174 |
+
# first calculate the jordan block structure
|
| 1175 |
+
eigs = mat.eigenvals()
|
| 1176 |
+
|
| 1177 |
+
# Make sure that we have all roots in radical form
|
| 1178 |
+
for x in eigs:
|
| 1179 |
+
if x.has(CRootOf):
|
| 1180 |
+
raise MatrixError(
|
| 1181 |
+
"Jordan normal form is not implemented if the matrix have "
|
| 1182 |
+
"eigenvalues in CRootOf form")
|
| 1183 |
+
|
| 1184 |
+
# most matrices have distinct eigenvalues
|
| 1185 |
+
# and so are diagonalizable. In this case, don't
|
| 1186 |
+
# do extra work!
|
| 1187 |
+
if len(eigs.keys()) == mat.cols:
|
| 1188 |
+
blocks = sorted(eigs.keys(), key=default_sort_key)
|
| 1189 |
+
jordan_mat = mat.diag(*blocks)
|
| 1190 |
+
|
| 1191 |
+
if not calc_transform:
|
| 1192 |
+
return restore_floats(jordan_mat)
|
| 1193 |
+
|
| 1194 |
+
jordan_basis = [eig_mat(eig, 1).nullspace()[0]
|
| 1195 |
+
for eig in blocks]
|
| 1196 |
+
basis_mat = mat.hstack(*jordan_basis)
|
| 1197 |
+
|
| 1198 |
+
return restore_floats(basis_mat, jordan_mat)
|
| 1199 |
+
|
| 1200 |
+
block_structure = []
|
| 1201 |
+
|
| 1202 |
+
for eig in sorted(eigs.keys(), key=default_sort_key):
|
| 1203 |
+
algebraic_multiplicity = eigs[eig]
|
| 1204 |
+
chain = nullity_chain(eig, algebraic_multiplicity)
|
| 1205 |
+
block_sizes = blocks_from_nullity_chain(chain)
|
| 1206 |
+
|
| 1207 |
+
# if block_sizes = = [a, b, c, ...], then the number of
|
| 1208 |
+
# Jordan blocks of size 1 is a, of size 2 is b, etc.
|
| 1209 |
+
# create an array that has (eig, block_size) with one
|
| 1210 |
+
# entry for each block
|
| 1211 |
+
size_nums = [(i+1, num) for i, num in enumerate(block_sizes)]
|
| 1212 |
+
|
| 1213 |
+
# we expect larger Jordan blocks to come earlier
|
| 1214 |
+
size_nums.reverse()
|
| 1215 |
+
|
| 1216 |
+
block_structure.extend(
|
| 1217 |
+
[(eig, size) for size, num in size_nums for _ in range(num)])
|
| 1218 |
+
|
| 1219 |
+
jordan_form_size = sum(size for eig, size in block_structure)
|
| 1220 |
+
|
| 1221 |
+
if jordan_form_size != M.rows:
|
| 1222 |
+
raise MatrixError(
|
| 1223 |
+
"SymPy had encountered an inconsistent result while "
|
| 1224 |
+
"computing Jordan block. : {}".format(M))
|
| 1225 |
+
|
| 1226 |
+
blocks = (mat.jordan_block(size=size, eigenvalue=eig) for eig, size in block_structure)
|
| 1227 |
+
jordan_mat = mat.diag(*blocks)
|
| 1228 |
+
|
| 1229 |
+
if not calc_transform:
|
| 1230 |
+
return restore_floats(jordan_mat)
|
| 1231 |
+
|
| 1232 |
+
# For each generalized eigenspace, calculate a basis.
|
| 1233 |
+
# We start by looking for a vector in null( (A - eig*I)**n )
|
| 1234 |
+
# which isn't in null( (A - eig*I)**(n-1) ) where n is
|
| 1235 |
+
# the size of the Jordan block
|
| 1236 |
+
#
|
| 1237 |
+
# Ideally we'd just loop through block_structure and
|
| 1238 |
+
# compute each generalized eigenspace. However, this
|
| 1239 |
+
# causes a lot of unneeded computation. Instead, we
|
| 1240 |
+
# go through the eigenvalues separately, since we know
|
| 1241 |
+
# their generalized eigenspaces must have bases that
|
| 1242 |
+
# are linearly independent.
|
| 1243 |
+
jordan_basis = []
|
| 1244 |
+
|
| 1245 |
+
for eig in sorted(eigs.keys(), key=default_sort_key):
|
| 1246 |
+
eig_basis = []
|
| 1247 |
+
|
| 1248 |
+
for block_eig, size in block_structure:
|
| 1249 |
+
if block_eig != eig:
|
| 1250 |
+
continue
|
| 1251 |
+
|
| 1252 |
+
null_big = (eig_mat(eig, size)).nullspace()
|
| 1253 |
+
null_small = (eig_mat(eig, size - 1)).nullspace()
|
| 1254 |
+
|
| 1255 |
+
# we want to pick something that is in the big basis
|
| 1256 |
+
# and not the small, but also something that is independent
|
| 1257 |
+
# of any other generalized eigenvectors from a different
|
| 1258 |
+
# generalized eigenspace sharing the same eigenvalue.
|
| 1259 |
+
vec = pick_vec(null_small + eig_basis, null_big)
|
| 1260 |
+
new_vecs = [eig_mat(eig, i).multiply(vec, dotprodsimp=None)
|
| 1261 |
+
for i in range(size)]
|
| 1262 |
+
|
| 1263 |
+
eig_basis.extend(new_vecs)
|
| 1264 |
+
jordan_basis.extend(reversed(new_vecs))
|
| 1265 |
+
|
| 1266 |
+
basis_mat = mat.hstack(*jordan_basis)
|
| 1267 |
+
|
| 1268 |
+
return restore_floats(basis_mat, jordan_mat)
|
| 1269 |
+
|
| 1270 |
+
|
| 1271 |
+
def _left_eigenvects(M, **flags):
|
| 1272 |
+
"""Returns left eigenvectors and eigenvalues.
|
| 1273 |
+
|
| 1274 |
+
This function returns the list of triples (eigenval, multiplicity,
|
| 1275 |
+
basis) for the left eigenvectors. Options are the same as for
|
| 1276 |
+
eigenvects(), i.e. the ``**flags`` arguments gets passed directly to
|
| 1277 |
+
eigenvects().
|
| 1278 |
+
|
| 1279 |
+
Examples
|
| 1280 |
+
========
|
| 1281 |
+
|
| 1282 |
+
>>> from sympy import Matrix
|
| 1283 |
+
>>> M = Matrix([[0, 1, 1], [1, 0, 0], [1, 1, 1]])
|
| 1284 |
+
>>> M.eigenvects()
|
| 1285 |
+
[(-1, 1, [Matrix([
|
| 1286 |
+
[-1],
|
| 1287 |
+
[ 1],
|
| 1288 |
+
[ 0]])]), (0, 1, [Matrix([
|
| 1289 |
+
[ 0],
|
| 1290 |
+
[-1],
|
| 1291 |
+
[ 1]])]), (2, 1, [Matrix([
|
| 1292 |
+
[2/3],
|
| 1293 |
+
[1/3],
|
| 1294 |
+
[ 1]])])]
|
| 1295 |
+
>>> M.left_eigenvects()
|
| 1296 |
+
[(-1, 1, [Matrix([[-2, 1, 1]])]), (0, 1, [Matrix([[-1, -1, 1]])]), (2,
|
| 1297 |
+
1, [Matrix([[1, 1, 1]])])]
|
| 1298 |
+
|
| 1299 |
+
"""
|
| 1300 |
+
|
| 1301 |
+
eigs = M.transpose().eigenvects(**flags)
|
| 1302 |
+
|
| 1303 |
+
return [(val, mult, [l.transpose() for l in basis]) for val, mult, basis in eigs]
|
| 1304 |
+
|
| 1305 |
+
|
| 1306 |
+
def _singular_values(M):
|
| 1307 |
+
"""Compute the singular values of a Matrix
|
| 1308 |
+
|
| 1309 |
+
Examples
|
| 1310 |
+
========
|
| 1311 |
+
|
| 1312 |
+
>>> from sympy import Matrix, Symbol
|
| 1313 |
+
>>> x = Symbol('x', real=True)
|
| 1314 |
+
>>> M = Matrix([[0, 1, 0], [0, x, 0], [-1, 0, 0]])
|
| 1315 |
+
>>> M.singular_values()
|
| 1316 |
+
[sqrt(x**2 + 1), 1, 0]
|
| 1317 |
+
|
| 1318 |
+
See Also
|
| 1319 |
+
========
|
| 1320 |
+
|
| 1321 |
+
condition_number
|
| 1322 |
+
"""
|
| 1323 |
+
|
| 1324 |
+
if M.rows >= M.cols:
|
| 1325 |
+
valmultpairs = M.H.multiply(M).eigenvals()
|
| 1326 |
+
else:
|
| 1327 |
+
valmultpairs = M.multiply(M.H).eigenvals()
|
| 1328 |
+
|
| 1329 |
+
# Expands result from eigenvals into a simple list
|
| 1330 |
+
vals = []
|
| 1331 |
+
|
| 1332 |
+
for k, v in valmultpairs.items():
|
| 1333 |
+
vals += [sqrt(k)] * v # dangerous! same k in several spots!
|
| 1334 |
+
|
| 1335 |
+
# Pad with zeros if singular values are computed in reverse way,
|
| 1336 |
+
# to give consistent format.
|
| 1337 |
+
if len(vals) < M.cols:
|
| 1338 |
+
vals += [M.zero] * (M.cols - len(vals))
|
| 1339 |
+
|
| 1340 |
+
# sort them in descending order
|
| 1341 |
+
vals.sort(reverse=True, key=default_sort_key)
|
| 1342 |
+
|
| 1343 |
+
return vals
|
venv/lib/python3.10/site-packages/sympy/matrices/expressions/__init__.py
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
""" A module which handles Matrix Expressions """
|
| 2 |
+
|
| 3 |
+
from .slice import MatrixSlice
|
| 4 |
+
from .blockmatrix import BlockMatrix, BlockDiagMatrix, block_collapse, blockcut
|
| 5 |
+
from .companion import CompanionMatrix
|
| 6 |
+
from .funcmatrix import FunctionMatrix
|
| 7 |
+
from .inverse import Inverse
|
| 8 |
+
from .matadd import MatAdd
|
| 9 |
+
from .matexpr import MatrixExpr, MatrixSymbol, matrix_symbols
|
| 10 |
+
from .matmul import MatMul
|
| 11 |
+
from .matpow import MatPow
|
| 12 |
+
from .trace import Trace, trace
|
| 13 |
+
from .determinant import Determinant, det, Permanent, per
|
| 14 |
+
from .transpose import Transpose
|
| 15 |
+
from .adjoint import Adjoint
|
| 16 |
+
from .hadamard import hadamard_product, HadamardProduct, hadamard_power, HadamardPower
|
| 17 |
+
from .diagonal import DiagonalMatrix, DiagonalOf, DiagMatrix, diagonalize_vector
|
| 18 |
+
from .dotproduct import DotProduct
|
| 19 |
+
from .kronecker import kronecker_product, KroneckerProduct, combine_kronecker
|
| 20 |
+
from .permutation import PermutationMatrix, MatrixPermute
|
| 21 |
+
from .sets import MatrixSet
|
| 22 |
+
from .special import ZeroMatrix, Identity, OneMatrix
|
| 23 |
+
|
| 24 |
+
__all__ = [
|
| 25 |
+
'MatrixSlice',
|
| 26 |
+
|
| 27 |
+
'BlockMatrix', 'BlockDiagMatrix', 'block_collapse', 'blockcut',
|
| 28 |
+
'FunctionMatrix',
|
| 29 |
+
|
| 30 |
+
'CompanionMatrix',
|
| 31 |
+
|
| 32 |
+
'Inverse',
|
| 33 |
+
|
| 34 |
+
'MatAdd',
|
| 35 |
+
|
| 36 |
+
'Identity', 'MatrixExpr', 'MatrixSymbol', 'ZeroMatrix', 'OneMatrix',
|
| 37 |
+
'matrix_symbols', 'MatrixSet',
|
| 38 |
+
|
| 39 |
+
'MatMul',
|
| 40 |
+
|
| 41 |
+
'MatPow',
|
| 42 |
+
|
| 43 |
+
'Trace', 'trace',
|
| 44 |
+
|
| 45 |
+
'Determinant', 'det',
|
| 46 |
+
|
| 47 |
+
'Transpose',
|
| 48 |
+
|
| 49 |
+
'Adjoint',
|
| 50 |
+
|
| 51 |
+
'hadamard_product', 'HadamardProduct', 'hadamard_power', 'HadamardPower',
|
| 52 |
+
|
| 53 |
+
'DiagonalMatrix', 'DiagonalOf', 'DiagMatrix', 'diagonalize_vector',
|
| 54 |
+
|
| 55 |
+
'DotProduct',
|
| 56 |
+
|
| 57 |
+
'kronecker_product', 'KroneckerProduct', 'combine_kronecker',
|
| 58 |
+
|
| 59 |
+
'PermutationMatrix', 'MatrixPermute',
|
| 60 |
+
|
| 61 |
+
'Permanent', 'per'
|
| 62 |
+
]
|
venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (1.78 kB). View file
|
|
|
venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/_shape.cpython-310.pyc
ADDED
|
Binary file (4.26 kB). View file
|
|
|
venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/adjoint.cpython-310.pyc
ADDED
|
Binary file (2.48 kB). View file
|
|
|
venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/applyfunc.cpython-310.pyc
ADDED
|
Binary file (5.52 kB). View file
|
|
|
venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/blockmatrix.cpython-310.pyc
ADDED
|
Binary file (33.8 kB). View file
|
|
|
venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/companion.cpython-310.pyc
ADDED
|
Binary file (2.22 kB). View file
|
|
|
venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/determinant.cpython-310.pyc
ADDED
|
Binary file (3.99 kB). View file
|
|
|
venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/diagonal.cpython-310.pyc
ADDED
|
Binary file (7.07 kB). View file
|
|
|
venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/dotproduct.cpython-310.pyc
ADDED
|
Binary file (2.04 kB). View file
|
|
|
venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/factorizations.cpython-310.pyc
ADDED
|
Binary file (3.4 kB). View file
|
|
|
venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/fourier.cpython-310.pyc
ADDED
|
Binary file (3.08 kB). View file
|
|
|
venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/funcmatrix.cpython-310.pyc
ADDED
|
Binary file (4.25 kB). View file
|
|
|
venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/hadamard.cpython-310.pyc
ADDED
|
Binary file (14.2 kB). View file
|
|
|
venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/inverse.cpython-310.pyc
ADDED
|
Binary file (3.32 kB). View file
|
|
|
venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/kronecker.cpython-310.pyc
ADDED
|
Binary file (16.4 kB). View file
|
|
|
venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/matadd.cpython-310.pyc
ADDED
|
Binary file (6.92 kB). View file
|
|
|
venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/matexpr.cpython-310.pyc
ADDED
|
Binary file (29.9 kB). View file
|
|
|
venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/matmul.cpython-310.pyc
ADDED
|
Binary file (16.2 kB). View file
|
|
|
venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/matpow.cpython-310.pyc
ADDED
|
Binary file (4.95 kB). View file
|
|
|
venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/permutation.cpython-310.pyc
ADDED
|
Binary file (7.66 kB). View file
|
|
|
venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/sets.cpython-310.pyc
ADDED
|
Binary file (2.82 kB). View file
|
|
|
venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/slice.cpython-310.pyc
ADDED
|
Binary file (3.56 kB). View file
|
|
|
venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/special.cpython-310.pyc
ADDED
|
Binary file (10.7 kB). View file
|
|
|
venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/trace.cpython-310.pyc
ADDED
|
Binary file (4.86 kB). View file
|
|
|
venv/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/transpose.cpython-310.pyc
ADDED
|
Binary file (3.89 kB). View file
|
|
|
venv/lib/python3.10/site-packages/sympy/matrices/expressions/_shape.py
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.core.relational import Eq
|
| 2 |
+
from sympy.core.expr import Expr
|
| 3 |
+
from sympy.core.numbers import Integer
|
| 4 |
+
from sympy.logic.boolalg import Boolean, And
|
| 5 |
+
from sympy.matrices.expressions.matexpr import MatrixExpr
|
| 6 |
+
from sympy.matrices.common import ShapeError
|
| 7 |
+
from typing import Union
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def is_matadd_valid(*args: MatrixExpr) -> Boolean:
|
| 11 |
+
"""Return the symbolic condition how ``MatAdd``, ``HadamardProduct``
|
| 12 |
+
makes sense.
|
| 13 |
+
|
| 14 |
+
Parameters
|
| 15 |
+
==========
|
| 16 |
+
|
| 17 |
+
args
|
| 18 |
+
The list of arguments of matrices to be tested for.
|
| 19 |
+
|
| 20 |
+
Examples
|
| 21 |
+
========
|
| 22 |
+
|
| 23 |
+
>>> from sympy import MatrixSymbol, symbols
|
| 24 |
+
>>> from sympy.matrices.expressions._shape import is_matadd_valid
|
| 25 |
+
|
| 26 |
+
>>> m, n, p, q = symbols('m n p q')
|
| 27 |
+
>>> A = MatrixSymbol('A', m, n)
|
| 28 |
+
>>> B = MatrixSymbol('B', p, q)
|
| 29 |
+
>>> is_matadd_valid(A, B)
|
| 30 |
+
Eq(m, p) & Eq(n, q)
|
| 31 |
+
"""
|
| 32 |
+
rows, cols = zip(*(arg.shape for arg in args))
|
| 33 |
+
return And(
|
| 34 |
+
*(Eq(i, j) for i, j in zip(rows[:-1], rows[1:])),
|
| 35 |
+
*(Eq(i, j) for i, j in zip(cols[:-1], cols[1:])),
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def is_matmul_valid(*args: Union[MatrixExpr, Expr]) -> Boolean:
|
| 40 |
+
"""Return the symbolic condition how ``MatMul`` makes sense
|
| 41 |
+
|
| 42 |
+
Parameters
|
| 43 |
+
==========
|
| 44 |
+
|
| 45 |
+
args
|
| 46 |
+
The list of arguments of matrices and scalar expressions to be tested
|
| 47 |
+
for.
|
| 48 |
+
|
| 49 |
+
Examples
|
| 50 |
+
========
|
| 51 |
+
|
| 52 |
+
>>> from sympy import MatrixSymbol, symbols
|
| 53 |
+
>>> from sympy.matrices.expressions._shape import is_matmul_valid
|
| 54 |
+
|
| 55 |
+
>>> m, n, p, q = symbols('m n p q')
|
| 56 |
+
>>> A = MatrixSymbol('A', m, n)
|
| 57 |
+
>>> B = MatrixSymbol('B', p, q)
|
| 58 |
+
>>> is_matmul_valid(A, B)
|
| 59 |
+
Eq(n, p)
|
| 60 |
+
"""
|
| 61 |
+
rows, cols = zip(*(arg.shape for arg in args if isinstance(arg, MatrixExpr)))
|
| 62 |
+
return And(*(Eq(i, j) for i, j in zip(cols[:-1], rows[1:])))
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def is_square(arg: MatrixExpr, /) -> Boolean:
|
| 66 |
+
"""Return the symbolic condition how the matrix is assumed to be square
|
| 67 |
+
|
| 68 |
+
Parameters
|
| 69 |
+
==========
|
| 70 |
+
|
| 71 |
+
arg
|
| 72 |
+
The matrix to be tested for.
|
| 73 |
+
|
| 74 |
+
Examples
|
| 75 |
+
========
|
| 76 |
+
|
| 77 |
+
>>> from sympy import MatrixSymbol, symbols
|
| 78 |
+
>>> from sympy.matrices.expressions._shape import is_square
|
| 79 |
+
|
| 80 |
+
>>> m, n = symbols('m n')
|
| 81 |
+
>>> A = MatrixSymbol('A', m, n)
|
| 82 |
+
>>> is_square(A)
|
| 83 |
+
Eq(m, n)
|
| 84 |
+
"""
|
| 85 |
+
return Eq(arg.rows, arg.cols)
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def validate_matadd_integer(*args: MatrixExpr) -> None:
|
| 89 |
+
"""Validate matrix shape for addition only for integer values"""
|
| 90 |
+
rows, cols = zip(*(x.shape for x in args))
|
| 91 |
+
if len(set(filter(lambda x: isinstance(x, (int, Integer)), rows))) > 1:
|
| 92 |
+
raise ShapeError(f"Matrices have mismatching shape: {rows}")
|
| 93 |
+
if len(set(filter(lambda x: isinstance(x, (int, Integer)), cols))) > 1:
|
| 94 |
+
raise ShapeError(f"Matrices have mismatching shape: {cols}")
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def validate_matmul_integer(*args: MatrixExpr) -> None:
|
| 98 |
+
"""Validate matrix shape for multiplication only for integer values"""
|
| 99 |
+
for A, B in zip(args[:-1], args[1:]):
|
| 100 |
+
i, j = A.cols, B.rows
|
| 101 |
+
if isinstance(i, (int, Integer)) and isinstance(j, (int, Integer)) and i != j:
|
| 102 |
+
raise ShapeError("Matrices are not aligned", i, j)
|
venv/lib/python3.10/site-packages/sympy/matrices/expressions/adjoint.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.core import Basic
|
| 2 |
+
from sympy.functions import adjoint, conjugate
|
| 3 |
+
from sympy.matrices.expressions.transpose import transpose
|
| 4 |
+
from sympy.matrices.expressions.matexpr import MatrixExpr
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class Adjoint(MatrixExpr):
|
| 8 |
+
"""
|
| 9 |
+
The Hermitian adjoint of a matrix expression.
|
| 10 |
+
|
| 11 |
+
This is a symbolic object that simply stores its argument without
|
| 12 |
+
evaluating it. To actually compute the adjoint, use the ``adjoint()``
|
| 13 |
+
function.
|
| 14 |
+
|
| 15 |
+
Examples
|
| 16 |
+
========
|
| 17 |
+
|
| 18 |
+
>>> from sympy import MatrixSymbol, Adjoint, adjoint
|
| 19 |
+
>>> A = MatrixSymbol('A', 3, 5)
|
| 20 |
+
>>> B = MatrixSymbol('B', 5, 3)
|
| 21 |
+
>>> Adjoint(A*B)
|
| 22 |
+
Adjoint(A*B)
|
| 23 |
+
>>> adjoint(A*B)
|
| 24 |
+
Adjoint(B)*Adjoint(A)
|
| 25 |
+
>>> adjoint(A*B) == Adjoint(A*B)
|
| 26 |
+
False
|
| 27 |
+
>>> adjoint(A*B) == Adjoint(A*B).doit()
|
| 28 |
+
True
|
| 29 |
+
"""
|
| 30 |
+
is_Adjoint = True
|
| 31 |
+
|
| 32 |
+
def doit(self, **hints):
|
| 33 |
+
arg = self.arg
|
| 34 |
+
if hints.get('deep', True) and isinstance(arg, Basic):
|
| 35 |
+
return adjoint(arg.doit(**hints))
|
| 36 |
+
else:
|
| 37 |
+
return adjoint(self.arg)
|
| 38 |
+
|
| 39 |
+
@property
|
| 40 |
+
def arg(self):
|
| 41 |
+
return self.args[0]
|
| 42 |
+
|
| 43 |
+
@property
|
| 44 |
+
def shape(self):
|
| 45 |
+
return self.arg.shape[::-1]
|
| 46 |
+
|
| 47 |
+
def _entry(self, i, j, **kwargs):
|
| 48 |
+
return conjugate(self.arg._entry(j, i, **kwargs))
|
| 49 |
+
|
| 50 |
+
def _eval_adjoint(self):
|
| 51 |
+
return self.arg
|
| 52 |
+
|
| 53 |
+
def _eval_conjugate(self):
|
| 54 |
+
return transpose(self.arg)
|
| 55 |
+
|
| 56 |
+
def _eval_trace(self):
|
| 57 |
+
from sympy.matrices.expressions.trace import Trace
|
| 58 |
+
return conjugate(Trace(self.arg))
|
| 59 |
+
|
| 60 |
+
def _eval_transpose(self):
|
| 61 |
+
return conjugate(self.arg)
|
venv/lib/python3.10/site-packages/sympy/matrices/expressions/applyfunc.py
ADDED
|
@@ -0,0 +1,204 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.core.expr import ExprBuilder
|
| 2 |
+
from sympy.core.function import (Function, FunctionClass, Lambda)
|
| 3 |
+
from sympy.core.symbol import Dummy
|
| 4 |
+
from sympy.core.sympify import sympify, _sympify
|
| 5 |
+
from sympy.matrices.expressions import MatrixExpr
|
| 6 |
+
from sympy.matrices.matrices import MatrixBase
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class ElementwiseApplyFunction(MatrixExpr):
|
| 10 |
+
r"""
|
| 11 |
+
Apply function to a matrix elementwise without evaluating.
|
| 12 |
+
|
| 13 |
+
Examples
|
| 14 |
+
========
|
| 15 |
+
|
| 16 |
+
It can be created by calling ``.applyfunc(<function>)`` on a matrix
|
| 17 |
+
expression:
|
| 18 |
+
|
| 19 |
+
>>> from sympy import MatrixSymbol
|
| 20 |
+
>>> from sympy.matrices.expressions.applyfunc import ElementwiseApplyFunction
|
| 21 |
+
>>> from sympy import exp
|
| 22 |
+
>>> X = MatrixSymbol("X", 3, 3)
|
| 23 |
+
>>> X.applyfunc(exp)
|
| 24 |
+
Lambda(_d, exp(_d)).(X)
|
| 25 |
+
|
| 26 |
+
Otherwise using the class constructor:
|
| 27 |
+
|
| 28 |
+
>>> from sympy import eye
|
| 29 |
+
>>> expr = ElementwiseApplyFunction(exp, eye(3))
|
| 30 |
+
>>> expr
|
| 31 |
+
Lambda(_d, exp(_d)).(Matrix([
|
| 32 |
+
[1, 0, 0],
|
| 33 |
+
[0, 1, 0],
|
| 34 |
+
[0, 0, 1]]))
|
| 35 |
+
>>> expr.doit()
|
| 36 |
+
Matrix([
|
| 37 |
+
[E, 1, 1],
|
| 38 |
+
[1, E, 1],
|
| 39 |
+
[1, 1, E]])
|
| 40 |
+
|
| 41 |
+
Notice the difference with the real mathematical functions:
|
| 42 |
+
|
| 43 |
+
>>> exp(eye(3))
|
| 44 |
+
Matrix([
|
| 45 |
+
[E, 0, 0],
|
| 46 |
+
[0, E, 0],
|
| 47 |
+
[0, 0, E]])
|
| 48 |
+
"""
|
| 49 |
+
|
| 50 |
+
def __new__(cls, function, expr):
|
| 51 |
+
expr = _sympify(expr)
|
| 52 |
+
if not expr.is_Matrix:
|
| 53 |
+
raise ValueError("{} must be a matrix instance.".format(expr))
|
| 54 |
+
|
| 55 |
+
if expr.shape == (1, 1):
|
| 56 |
+
# Check if the function returns a matrix, in that case, just apply
|
| 57 |
+
# the function instead of creating an ElementwiseApplyFunc object:
|
| 58 |
+
ret = function(expr)
|
| 59 |
+
if isinstance(ret, MatrixExpr):
|
| 60 |
+
return ret
|
| 61 |
+
|
| 62 |
+
if not isinstance(function, (FunctionClass, Lambda)):
|
| 63 |
+
d = Dummy('d')
|
| 64 |
+
function = Lambda(d, function(d))
|
| 65 |
+
|
| 66 |
+
function = sympify(function)
|
| 67 |
+
if not isinstance(function, (FunctionClass, Lambda)):
|
| 68 |
+
raise ValueError(
|
| 69 |
+
"{} should be compatible with SymPy function classes."
|
| 70 |
+
.format(function))
|
| 71 |
+
|
| 72 |
+
if 1 not in function.nargs:
|
| 73 |
+
raise ValueError(
|
| 74 |
+
'{} should be able to accept 1 arguments.'.format(function))
|
| 75 |
+
|
| 76 |
+
if not isinstance(function, Lambda):
|
| 77 |
+
d = Dummy('d')
|
| 78 |
+
function = Lambda(d, function(d))
|
| 79 |
+
|
| 80 |
+
obj = MatrixExpr.__new__(cls, function, expr)
|
| 81 |
+
return obj
|
| 82 |
+
|
| 83 |
+
@property
|
| 84 |
+
def function(self):
|
| 85 |
+
return self.args[0]
|
| 86 |
+
|
| 87 |
+
@property
|
| 88 |
+
def expr(self):
|
| 89 |
+
return self.args[1]
|
| 90 |
+
|
| 91 |
+
@property
|
| 92 |
+
def shape(self):
|
| 93 |
+
return self.expr.shape
|
| 94 |
+
|
| 95 |
+
def doit(self, **hints):
|
| 96 |
+
deep = hints.get("deep", True)
|
| 97 |
+
expr = self.expr
|
| 98 |
+
if deep:
|
| 99 |
+
expr = expr.doit(**hints)
|
| 100 |
+
function = self.function
|
| 101 |
+
if isinstance(function, Lambda) and function.is_identity:
|
| 102 |
+
# This is a Lambda containing the identity function.
|
| 103 |
+
return expr
|
| 104 |
+
if isinstance(expr, MatrixBase):
|
| 105 |
+
return expr.applyfunc(self.function)
|
| 106 |
+
elif isinstance(expr, ElementwiseApplyFunction):
|
| 107 |
+
return ElementwiseApplyFunction(
|
| 108 |
+
lambda x: self.function(expr.function(x)),
|
| 109 |
+
expr.expr
|
| 110 |
+
).doit(**hints)
|
| 111 |
+
else:
|
| 112 |
+
return self
|
| 113 |
+
|
| 114 |
+
def _entry(self, i, j, **kwargs):
|
| 115 |
+
return self.function(self.expr._entry(i, j, **kwargs))
|
| 116 |
+
|
| 117 |
+
def _get_function_fdiff(self):
|
| 118 |
+
d = Dummy("d")
|
| 119 |
+
function = self.function(d)
|
| 120 |
+
fdiff = function.diff(d)
|
| 121 |
+
if isinstance(fdiff, Function):
|
| 122 |
+
fdiff = type(fdiff)
|
| 123 |
+
else:
|
| 124 |
+
fdiff = Lambda(d, fdiff)
|
| 125 |
+
return fdiff
|
| 126 |
+
|
| 127 |
+
def _eval_derivative(self, x):
|
| 128 |
+
from sympy.matrices.expressions.hadamard import hadamard_product
|
| 129 |
+
dexpr = self.expr.diff(x)
|
| 130 |
+
fdiff = self._get_function_fdiff()
|
| 131 |
+
return hadamard_product(
|
| 132 |
+
dexpr,
|
| 133 |
+
ElementwiseApplyFunction(fdiff, self.expr)
|
| 134 |
+
)
|
| 135 |
+
|
| 136 |
+
def _eval_derivative_matrix_lines(self, x):
|
| 137 |
+
from sympy.matrices.expressions.special import Identity
|
| 138 |
+
from sympy.tensor.array.expressions.array_expressions import ArrayContraction
|
| 139 |
+
from sympy.tensor.array.expressions.array_expressions import ArrayDiagonal
|
| 140 |
+
from sympy.tensor.array.expressions.array_expressions import ArrayTensorProduct
|
| 141 |
+
|
| 142 |
+
fdiff = self._get_function_fdiff()
|
| 143 |
+
lr = self.expr._eval_derivative_matrix_lines(x)
|
| 144 |
+
ewdiff = ElementwiseApplyFunction(fdiff, self.expr)
|
| 145 |
+
if 1 in x.shape:
|
| 146 |
+
# Vector:
|
| 147 |
+
iscolumn = self.shape[1] == 1
|
| 148 |
+
for i in lr:
|
| 149 |
+
if iscolumn:
|
| 150 |
+
ptr1 = i.first_pointer
|
| 151 |
+
ptr2 = Identity(self.shape[1])
|
| 152 |
+
else:
|
| 153 |
+
ptr1 = Identity(self.shape[0])
|
| 154 |
+
ptr2 = i.second_pointer
|
| 155 |
+
|
| 156 |
+
subexpr = ExprBuilder(
|
| 157 |
+
ArrayDiagonal,
|
| 158 |
+
[
|
| 159 |
+
ExprBuilder(
|
| 160 |
+
ArrayTensorProduct,
|
| 161 |
+
[
|
| 162 |
+
ewdiff,
|
| 163 |
+
ptr1,
|
| 164 |
+
ptr2,
|
| 165 |
+
]
|
| 166 |
+
),
|
| 167 |
+
(0, 2) if iscolumn else (1, 4)
|
| 168 |
+
],
|
| 169 |
+
validator=ArrayDiagonal._validate
|
| 170 |
+
)
|
| 171 |
+
i._lines = [subexpr]
|
| 172 |
+
i._first_pointer_parent = subexpr.args[0].args
|
| 173 |
+
i._first_pointer_index = 1
|
| 174 |
+
i._second_pointer_parent = subexpr.args[0].args
|
| 175 |
+
i._second_pointer_index = 2
|
| 176 |
+
else:
|
| 177 |
+
# Matrix case:
|
| 178 |
+
for i in lr:
|
| 179 |
+
ptr1 = i.first_pointer
|
| 180 |
+
ptr2 = i.second_pointer
|
| 181 |
+
newptr1 = Identity(ptr1.shape[1])
|
| 182 |
+
newptr2 = Identity(ptr2.shape[1])
|
| 183 |
+
subexpr = ExprBuilder(
|
| 184 |
+
ArrayContraction,
|
| 185 |
+
[
|
| 186 |
+
ExprBuilder(
|
| 187 |
+
ArrayTensorProduct,
|
| 188 |
+
[ptr1, newptr1, ewdiff, ptr2, newptr2]
|
| 189 |
+
),
|
| 190 |
+
(1, 2, 4),
|
| 191 |
+
(5, 7, 8),
|
| 192 |
+
],
|
| 193 |
+
validator=ArrayContraction._validate
|
| 194 |
+
)
|
| 195 |
+
i._first_pointer_parent = subexpr.args[0].args
|
| 196 |
+
i._first_pointer_index = 1
|
| 197 |
+
i._second_pointer_parent = subexpr.args[0].args
|
| 198 |
+
i._second_pointer_index = 4
|
| 199 |
+
i._lines = [subexpr]
|
| 200 |
+
return lr
|
| 201 |
+
|
| 202 |
+
def _eval_transpose(self):
|
| 203 |
+
from sympy.matrices.expressions.transpose import Transpose
|
| 204 |
+
return self.func(self.function, Transpose(self.expr).doit())
|
venv/lib/python3.10/site-packages/sympy/matrices/expressions/blockmatrix.py
ADDED
|
@@ -0,0 +1,979 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.assumptions.ask import (Q, ask)
|
| 2 |
+
from sympy.core import Basic, Add, Mul, S
|
| 3 |
+
from sympy.core.sympify import _sympify
|
| 4 |
+
from sympy.functions import adjoint
|
| 5 |
+
from sympy.functions.elementary.complexes import re, im
|
| 6 |
+
from sympy.strategies import typed, exhaust, condition, do_one, unpack
|
| 7 |
+
from sympy.strategies.traverse import bottom_up
|
| 8 |
+
from sympy.utilities.iterables import is_sequence, sift
|
| 9 |
+
from sympy.utilities.misc import filldedent
|
| 10 |
+
|
| 11 |
+
from sympy.matrices import Matrix, ShapeError
|
| 12 |
+
from sympy.matrices.common import NonInvertibleMatrixError
|
| 13 |
+
from sympy.matrices.expressions.determinant import det, Determinant
|
| 14 |
+
from sympy.matrices.expressions.inverse import Inverse
|
| 15 |
+
from sympy.matrices.expressions.matadd import MatAdd
|
| 16 |
+
from sympy.matrices.expressions.matexpr import MatrixExpr, MatrixElement
|
| 17 |
+
from sympy.matrices.expressions.matmul import MatMul
|
| 18 |
+
from sympy.matrices.expressions.matpow import MatPow
|
| 19 |
+
from sympy.matrices.expressions.slice import MatrixSlice
|
| 20 |
+
from sympy.matrices.expressions.special import ZeroMatrix, Identity
|
| 21 |
+
from sympy.matrices.expressions.trace import trace
|
| 22 |
+
from sympy.matrices.expressions.transpose import Transpose, transpose
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class BlockMatrix(MatrixExpr):
|
| 26 |
+
"""A BlockMatrix is a Matrix comprised of other matrices.
|
| 27 |
+
|
| 28 |
+
The submatrices are stored in a SymPy Matrix object but accessed as part of
|
| 29 |
+
a Matrix Expression
|
| 30 |
+
|
| 31 |
+
>>> from sympy import (MatrixSymbol, BlockMatrix, symbols,
|
| 32 |
+
... Identity, ZeroMatrix, block_collapse)
|
| 33 |
+
>>> n,m,l = symbols('n m l')
|
| 34 |
+
>>> X = MatrixSymbol('X', n, n)
|
| 35 |
+
>>> Y = MatrixSymbol('Y', m, m)
|
| 36 |
+
>>> Z = MatrixSymbol('Z', n, m)
|
| 37 |
+
>>> B = BlockMatrix([[X, Z], [ZeroMatrix(m,n), Y]])
|
| 38 |
+
>>> print(B)
|
| 39 |
+
Matrix([
|
| 40 |
+
[X, Z],
|
| 41 |
+
[0, Y]])
|
| 42 |
+
|
| 43 |
+
>>> C = BlockMatrix([[Identity(n), Z]])
|
| 44 |
+
>>> print(C)
|
| 45 |
+
Matrix([[I, Z]])
|
| 46 |
+
|
| 47 |
+
>>> print(block_collapse(C*B))
|
| 48 |
+
Matrix([[X, Z + Z*Y]])
|
| 49 |
+
|
| 50 |
+
Some matrices might be comprised of rows of blocks with
|
| 51 |
+
the matrices in each row having the same height and the
|
| 52 |
+
rows all having the same total number of columns but
|
| 53 |
+
not having the same number of columns for each matrix
|
| 54 |
+
in each row. In this case, the matrix is not a block
|
| 55 |
+
matrix and should be instantiated by Matrix.
|
| 56 |
+
|
| 57 |
+
>>> from sympy import ones, Matrix
|
| 58 |
+
>>> dat = [
|
| 59 |
+
... [ones(3,2), ones(3,3)*2],
|
| 60 |
+
... [ones(2,3)*3, ones(2,2)*4]]
|
| 61 |
+
...
|
| 62 |
+
>>> BlockMatrix(dat)
|
| 63 |
+
Traceback (most recent call last):
|
| 64 |
+
...
|
| 65 |
+
ValueError:
|
| 66 |
+
Although this matrix is comprised of blocks, the blocks do not fill
|
| 67 |
+
the matrix in a size-symmetric fashion. To create a full matrix from
|
| 68 |
+
these arguments, pass them directly to Matrix.
|
| 69 |
+
>>> Matrix(dat)
|
| 70 |
+
Matrix([
|
| 71 |
+
[1, 1, 2, 2, 2],
|
| 72 |
+
[1, 1, 2, 2, 2],
|
| 73 |
+
[1, 1, 2, 2, 2],
|
| 74 |
+
[3, 3, 3, 4, 4],
|
| 75 |
+
[3, 3, 3, 4, 4]])
|
| 76 |
+
|
| 77 |
+
See Also
|
| 78 |
+
========
|
| 79 |
+
sympy.matrices.matrices.MatrixBase.irregular
|
| 80 |
+
"""
|
| 81 |
+
def __new__(cls, *args, **kwargs):
|
| 82 |
+
from sympy.matrices.immutable import ImmutableDenseMatrix
|
| 83 |
+
isMat = lambda i: getattr(i, 'is_Matrix', False)
|
| 84 |
+
if len(args) != 1 or \
|
| 85 |
+
not is_sequence(args[0]) or \
|
| 86 |
+
len({isMat(r) for r in args[0]}) != 1:
|
| 87 |
+
raise ValueError(filldedent('''
|
| 88 |
+
expecting a sequence of 1 or more rows
|
| 89 |
+
containing Matrices.'''))
|
| 90 |
+
rows = args[0] if args else []
|
| 91 |
+
if not isMat(rows):
|
| 92 |
+
if rows and isMat(rows[0]):
|
| 93 |
+
rows = [rows] # rows is not list of lists or []
|
| 94 |
+
# regularity check
|
| 95 |
+
# same number of matrices in each row
|
| 96 |
+
blocky = ok = len({len(r) for r in rows}) == 1
|
| 97 |
+
if ok:
|
| 98 |
+
# same number of rows for each matrix in a row
|
| 99 |
+
for r in rows:
|
| 100 |
+
ok = len({i.rows for i in r}) == 1
|
| 101 |
+
if not ok:
|
| 102 |
+
break
|
| 103 |
+
blocky = ok
|
| 104 |
+
if ok:
|
| 105 |
+
# same number of cols for each matrix in each col
|
| 106 |
+
for c in range(len(rows[0])):
|
| 107 |
+
ok = len({rows[i][c].cols
|
| 108 |
+
for i in range(len(rows))}) == 1
|
| 109 |
+
if not ok:
|
| 110 |
+
break
|
| 111 |
+
if not ok:
|
| 112 |
+
# same total cols in each row
|
| 113 |
+
ok = len({
|
| 114 |
+
sum([i.cols for i in r]) for r in rows}) == 1
|
| 115 |
+
if blocky and ok:
|
| 116 |
+
raise ValueError(filldedent('''
|
| 117 |
+
Although this matrix is comprised of blocks,
|
| 118 |
+
the blocks do not fill the matrix in a
|
| 119 |
+
size-symmetric fashion. To create a full matrix
|
| 120 |
+
from these arguments, pass them directly to
|
| 121 |
+
Matrix.'''))
|
| 122 |
+
raise ValueError(filldedent('''
|
| 123 |
+
When there are not the same number of rows in each
|
| 124 |
+
row's matrices or there are not the same number of
|
| 125 |
+
total columns in each row, the matrix is not a
|
| 126 |
+
block matrix. If this matrix is known to consist of
|
| 127 |
+
blocks fully filling a 2-D space then see
|
| 128 |
+
Matrix.irregular.'''))
|
| 129 |
+
mat = ImmutableDenseMatrix(rows, evaluate=False)
|
| 130 |
+
obj = Basic.__new__(cls, mat)
|
| 131 |
+
return obj
|
| 132 |
+
|
| 133 |
+
@property
|
| 134 |
+
def shape(self):
|
| 135 |
+
numrows = numcols = 0
|
| 136 |
+
M = self.blocks
|
| 137 |
+
for i in range(M.shape[0]):
|
| 138 |
+
numrows += M[i, 0].shape[0]
|
| 139 |
+
for i in range(M.shape[1]):
|
| 140 |
+
numcols += M[0, i].shape[1]
|
| 141 |
+
return (numrows, numcols)
|
| 142 |
+
|
| 143 |
+
@property
|
| 144 |
+
def blockshape(self):
|
| 145 |
+
return self.blocks.shape
|
| 146 |
+
|
| 147 |
+
@property
|
| 148 |
+
def blocks(self):
|
| 149 |
+
return self.args[0]
|
| 150 |
+
|
| 151 |
+
@property
|
| 152 |
+
def rowblocksizes(self):
|
| 153 |
+
return [self.blocks[i, 0].rows for i in range(self.blockshape[0])]
|
| 154 |
+
|
| 155 |
+
@property
|
| 156 |
+
def colblocksizes(self):
|
| 157 |
+
return [self.blocks[0, i].cols for i in range(self.blockshape[1])]
|
| 158 |
+
|
| 159 |
+
def structurally_equal(self, other):
|
| 160 |
+
return (isinstance(other, BlockMatrix)
|
| 161 |
+
and self.shape == other.shape
|
| 162 |
+
and self.blockshape == other.blockshape
|
| 163 |
+
and self.rowblocksizes == other.rowblocksizes
|
| 164 |
+
and self.colblocksizes == other.colblocksizes)
|
| 165 |
+
|
| 166 |
+
def _blockmul(self, other):
|
| 167 |
+
if (isinstance(other, BlockMatrix) and
|
| 168 |
+
self.colblocksizes == other.rowblocksizes):
|
| 169 |
+
return BlockMatrix(self.blocks*other.blocks)
|
| 170 |
+
|
| 171 |
+
return self * other
|
| 172 |
+
|
| 173 |
+
def _blockadd(self, other):
|
| 174 |
+
if (isinstance(other, BlockMatrix)
|
| 175 |
+
and self.structurally_equal(other)):
|
| 176 |
+
return BlockMatrix(self.blocks + other.blocks)
|
| 177 |
+
|
| 178 |
+
return self + other
|
| 179 |
+
|
| 180 |
+
def _eval_transpose(self):
|
| 181 |
+
# Flip all the individual matrices
|
| 182 |
+
matrices = [transpose(matrix) for matrix in self.blocks]
|
| 183 |
+
# Make a copy
|
| 184 |
+
M = Matrix(self.blockshape[0], self.blockshape[1], matrices)
|
| 185 |
+
# Transpose the block structure
|
| 186 |
+
M = M.transpose()
|
| 187 |
+
return BlockMatrix(M)
|
| 188 |
+
|
| 189 |
+
def _eval_adjoint(self):
|
| 190 |
+
# Adjoint all the individual matrices
|
| 191 |
+
matrices = [adjoint(matrix) for matrix in self.blocks]
|
| 192 |
+
# Make a copy
|
| 193 |
+
M = Matrix(self.blockshape[0], self.blockshape[1], matrices)
|
| 194 |
+
# Transpose the block structure
|
| 195 |
+
M = M.transpose()
|
| 196 |
+
return BlockMatrix(M)
|
| 197 |
+
|
| 198 |
+
def _eval_trace(self):
|
| 199 |
+
if self.rowblocksizes == self.colblocksizes:
|
| 200 |
+
return Add(*[trace(self.blocks[i, i])
|
| 201 |
+
for i in range(self.blockshape[0])])
|
| 202 |
+
raise NotImplementedError(
|
| 203 |
+
"Can't perform trace of irregular blockshape")
|
| 204 |
+
|
| 205 |
+
def _eval_determinant(self):
|
| 206 |
+
if self.blockshape == (1, 1):
|
| 207 |
+
return det(self.blocks[0, 0])
|
| 208 |
+
if self.blockshape == (2, 2):
|
| 209 |
+
[[A, B],
|
| 210 |
+
[C, D]] = self.blocks.tolist()
|
| 211 |
+
if ask(Q.invertible(A)):
|
| 212 |
+
return det(A)*det(D - C*A.I*B)
|
| 213 |
+
elif ask(Q.invertible(D)):
|
| 214 |
+
return det(D)*det(A - B*D.I*C)
|
| 215 |
+
return Determinant(self)
|
| 216 |
+
|
| 217 |
+
def _eval_as_real_imag(self):
|
| 218 |
+
real_matrices = [re(matrix) for matrix in self.blocks]
|
| 219 |
+
real_matrices = Matrix(self.blockshape[0], self.blockshape[1], real_matrices)
|
| 220 |
+
|
| 221 |
+
im_matrices = [im(matrix) for matrix in self.blocks]
|
| 222 |
+
im_matrices = Matrix(self.blockshape[0], self.blockshape[1], im_matrices)
|
| 223 |
+
|
| 224 |
+
return (BlockMatrix(real_matrices), BlockMatrix(im_matrices))
|
| 225 |
+
|
| 226 |
+
def transpose(self):
|
| 227 |
+
"""Return transpose of matrix.
|
| 228 |
+
|
| 229 |
+
Examples
|
| 230 |
+
========
|
| 231 |
+
|
| 232 |
+
>>> from sympy import MatrixSymbol, BlockMatrix, ZeroMatrix
|
| 233 |
+
>>> from sympy.abc import m, n
|
| 234 |
+
>>> X = MatrixSymbol('X', n, n)
|
| 235 |
+
>>> Y = MatrixSymbol('Y', m, m)
|
| 236 |
+
>>> Z = MatrixSymbol('Z', n, m)
|
| 237 |
+
>>> B = BlockMatrix([[X, Z], [ZeroMatrix(m,n), Y]])
|
| 238 |
+
>>> B.transpose()
|
| 239 |
+
Matrix([
|
| 240 |
+
[X.T, 0],
|
| 241 |
+
[Z.T, Y.T]])
|
| 242 |
+
>>> _.transpose()
|
| 243 |
+
Matrix([
|
| 244 |
+
[X, Z],
|
| 245 |
+
[0, Y]])
|
| 246 |
+
"""
|
| 247 |
+
return self._eval_transpose()
|
| 248 |
+
|
| 249 |
+
def schur(self, mat = 'A', generalized = False):
|
| 250 |
+
"""Return the Schur Complement of the 2x2 BlockMatrix
|
| 251 |
+
|
| 252 |
+
Parameters
|
| 253 |
+
==========
|
| 254 |
+
|
| 255 |
+
mat : String, optional
|
| 256 |
+
The matrix with respect to which the
|
| 257 |
+
Schur Complement is calculated. 'A' is
|
| 258 |
+
used by default
|
| 259 |
+
|
| 260 |
+
generalized : bool, optional
|
| 261 |
+
If True, returns the generalized Schur
|
| 262 |
+
Component which uses Moore-Penrose Inverse
|
| 263 |
+
|
| 264 |
+
Examples
|
| 265 |
+
========
|
| 266 |
+
|
| 267 |
+
>>> from sympy import symbols, MatrixSymbol, BlockMatrix
|
| 268 |
+
>>> m, n = symbols('m n')
|
| 269 |
+
>>> A = MatrixSymbol('A', n, n)
|
| 270 |
+
>>> B = MatrixSymbol('B', n, m)
|
| 271 |
+
>>> C = MatrixSymbol('C', m, n)
|
| 272 |
+
>>> D = MatrixSymbol('D', m, m)
|
| 273 |
+
>>> X = BlockMatrix([[A, B], [C, D]])
|
| 274 |
+
|
| 275 |
+
The default Schur Complement is evaluated with "A"
|
| 276 |
+
|
| 277 |
+
>>> X.schur()
|
| 278 |
+
-C*A**(-1)*B + D
|
| 279 |
+
>>> X.schur('D')
|
| 280 |
+
A - B*D**(-1)*C
|
| 281 |
+
|
| 282 |
+
Schur complement with non-invertible matrices is not
|
| 283 |
+
defined. Instead, the generalized Schur complement can
|
| 284 |
+
be calculated which uses the Moore-Penrose Inverse. To
|
| 285 |
+
achieve this, `generalized` must be set to `True`
|
| 286 |
+
|
| 287 |
+
>>> X.schur('B', generalized=True)
|
| 288 |
+
C - D*(B.T*B)**(-1)*B.T*A
|
| 289 |
+
>>> X.schur('C', generalized=True)
|
| 290 |
+
-A*(C.T*C)**(-1)*C.T*D + B
|
| 291 |
+
|
| 292 |
+
Returns
|
| 293 |
+
=======
|
| 294 |
+
|
| 295 |
+
M : Matrix
|
| 296 |
+
The Schur Complement Matrix
|
| 297 |
+
|
| 298 |
+
Raises
|
| 299 |
+
======
|
| 300 |
+
|
| 301 |
+
ShapeError
|
| 302 |
+
If the block matrix is not a 2x2 matrix
|
| 303 |
+
|
| 304 |
+
NonInvertibleMatrixError
|
| 305 |
+
If given matrix is non-invertible
|
| 306 |
+
|
| 307 |
+
References
|
| 308 |
+
==========
|
| 309 |
+
|
| 310 |
+
.. [1] Wikipedia Article on Schur Component : https://en.wikipedia.org/wiki/Schur_complement
|
| 311 |
+
|
| 312 |
+
See Also
|
| 313 |
+
========
|
| 314 |
+
|
| 315 |
+
sympy.matrices.matrices.MatrixBase.pinv
|
| 316 |
+
"""
|
| 317 |
+
|
| 318 |
+
if self.blockshape == (2, 2):
|
| 319 |
+
[[A, B],
|
| 320 |
+
[C, D]] = self.blocks.tolist()
|
| 321 |
+
d={'A' : A, 'B' : B, 'C' : C, 'D' : D}
|
| 322 |
+
try:
|
| 323 |
+
inv = (d[mat].T*d[mat]).inv()*d[mat].T if generalized else d[mat].inv()
|
| 324 |
+
if mat == 'A':
|
| 325 |
+
return D - C * inv * B
|
| 326 |
+
elif mat == 'B':
|
| 327 |
+
return C - D * inv * A
|
| 328 |
+
elif mat == 'C':
|
| 329 |
+
return B - A * inv * D
|
| 330 |
+
elif mat == 'D':
|
| 331 |
+
return A - B * inv * C
|
| 332 |
+
#For matrices where no sub-matrix is square
|
| 333 |
+
return self
|
| 334 |
+
except NonInvertibleMatrixError:
|
| 335 |
+
raise NonInvertibleMatrixError('The given matrix is not invertible. Please set generalized=True \
|
| 336 |
+
to compute the generalized Schur Complement which uses Moore-Penrose Inverse')
|
| 337 |
+
else:
|
| 338 |
+
raise ShapeError('Schur Complement can only be calculated for 2x2 block matrices')
|
| 339 |
+
|
| 340 |
+
def LDUdecomposition(self):
|
| 341 |
+
"""Returns the Block LDU decomposition of
|
| 342 |
+
a 2x2 Block Matrix
|
| 343 |
+
|
| 344 |
+
Returns
|
| 345 |
+
=======
|
| 346 |
+
|
| 347 |
+
(L, D, U) : Matrices
|
| 348 |
+
L : Lower Diagonal Matrix
|
| 349 |
+
D : Diagonal Matrix
|
| 350 |
+
U : Upper Diagonal Matrix
|
| 351 |
+
|
| 352 |
+
Examples
|
| 353 |
+
========
|
| 354 |
+
|
| 355 |
+
>>> from sympy import symbols, MatrixSymbol, BlockMatrix, block_collapse
|
| 356 |
+
>>> m, n = symbols('m n')
|
| 357 |
+
>>> A = MatrixSymbol('A', n, n)
|
| 358 |
+
>>> B = MatrixSymbol('B', n, m)
|
| 359 |
+
>>> C = MatrixSymbol('C', m, n)
|
| 360 |
+
>>> D = MatrixSymbol('D', m, m)
|
| 361 |
+
>>> X = BlockMatrix([[A, B], [C, D]])
|
| 362 |
+
>>> L, D, U = X.LDUdecomposition()
|
| 363 |
+
>>> block_collapse(L*D*U)
|
| 364 |
+
Matrix([
|
| 365 |
+
[A, B],
|
| 366 |
+
[C, D]])
|
| 367 |
+
|
| 368 |
+
Raises
|
| 369 |
+
======
|
| 370 |
+
|
| 371 |
+
ShapeError
|
| 372 |
+
If the block matrix is not a 2x2 matrix
|
| 373 |
+
|
| 374 |
+
NonInvertibleMatrixError
|
| 375 |
+
If the matrix "A" is non-invertible
|
| 376 |
+
|
| 377 |
+
See Also
|
| 378 |
+
========
|
| 379 |
+
sympy.matrices.expressions.blockmatrix.BlockMatrix.UDLdecomposition
|
| 380 |
+
sympy.matrices.expressions.blockmatrix.BlockMatrix.LUdecomposition
|
| 381 |
+
"""
|
| 382 |
+
if self.blockshape == (2,2):
|
| 383 |
+
[[A, B],
|
| 384 |
+
[C, D]] = self.blocks.tolist()
|
| 385 |
+
try:
|
| 386 |
+
AI = A.I
|
| 387 |
+
except NonInvertibleMatrixError:
|
| 388 |
+
raise NonInvertibleMatrixError('Block LDU decomposition cannot be calculated when\
|
| 389 |
+
"A" is singular')
|
| 390 |
+
Ip = Identity(B.shape[0])
|
| 391 |
+
Iq = Identity(B.shape[1])
|
| 392 |
+
Z = ZeroMatrix(*B.shape)
|
| 393 |
+
L = BlockMatrix([[Ip, Z], [C*AI, Iq]])
|
| 394 |
+
D = BlockDiagMatrix(A, self.schur())
|
| 395 |
+
U = BlockMatrix([[Ip, AI*B],[Z.T, Iq]])
|
| 396 |
+
return L, D, U
|
| 397 |
+
else:
|
| 398 |
+
raise ShapeError("Block LDU decomposition is supported only for 2x2 block matrices")
|
| 399 |
+
|
| 400 |
+
def UDLdecomposition(self):
|
| 401 |
+
"""Returns the Block UDL decomposition of
|
| 402 |
+
a 2x2 Block Matrix
|
| 403 |
+
|
| 404 |
+
Returns
|
| 405 |
+
=======
|
| 406 |
+
|
| 407 |
+
(U, D, L) : Matrices
|
| 408 |
+
U : Upper Diagonal Matrix
|
| 409 |
+
D : Diagonal Matrix
|
| 410 |
+
L : Lower Diagonal Matrix
|
| 411 |
+
|
| 412 |
+
Examples
|
| 413 |
+
========
|
| 414 |
+
|
| 415 |
+
>>> from sympy import symbols, MatrixSymbol, BlockMatrix, block_collapse
|
| 416 |
+
>>> m, n = symbols('m n')
|
| 417 |
+
>>> A = MatrixSymbol('A', n, n)
|
| 418 |
+
>>> B = MatrixSymbol('B', n, m)
|
| 419 |
+
>>> C = MatrixSymbol('C', m, n)
|
| 420 |
+
>>> D = MatrixSymbol('D', m, m)
|
| 421 |
+
>>> X = BlockMatrix([[A, B], [C, D]])
|
| 422 |
+
>>> U, D, L = X.UDLdecomposition()
|
| 423 |
+
>>> block_collapse(U*D*L)
|
| 424 |
+
Matrix([
|
| 425 |
+
[A, B],
|
| 426 |
+
[C, D]])
|
| 427 |
+
|
| 428 |
+
Raises
|
| 429 |
+
======
|
| 430 |
+
|
| 431 |
+
ShapeError
|
| 432 |
+
If the block matrix is not a 2x2 matrix
|
| 433 |
+
|
| 434 |
+
NonInvertibleMatrixError
|
| 435 |
+
If the matrix "D" is non-invertible
|
| 436 |
+
|
| 437 |
+
See Also
|
| 438 |
+
========
|
| 439 |
+
sympy.matrices.expressions.blockmatrix.BlockMatrix.LDUdecomposition
|
| 440 |
+
sympy.matrices.expressions.blockmatrix.BlockMatrix.LUdecomposition
|
| 441 |
+
"""
|
| 442 |
+
if self.blockshape == (2,2):
|
| 443 |
+
[[A, B],
|
| 444 |
+
[C, D]] = self.blocks.tolist()
|
| 445 |
+
try:
|
| 446 |
+
DI = D.I
|
| 447 |
+
except NonInvertibleMatrixError:
|
| 448 |
+
raise NonInvertibleMatrixError('Block UDL decomposition cannot be calculated when\
|
| 449 |
+
"D" is singular')
|
| 450 |
+
Ip = Identity(A.shape[0])
|
| 451 |
+
Iq = Identity(B.shape[1])
|
| 452 |
+
Z = ZeroMatrix(*B.shape)
|
| 453 |
+
U = BlockMatrix([[Ip, B*DI], [Z.T, Iq]])
|
| 454 |
+
D = BlockDiagMatrix(self.schur('D'), D)
|
| 455 |
+
L = BlockMatrix([[Ip, Z],[DI*C, Iq]])
|
| 456 |
+
return U, D, L
|
| 457 |
+
else:
|
| 458 |
+
raise ShapeError("Block UDL decomposition is supported only for 2x2 block matrices")
|
| 459 |
+
|
| 460 |
+
def LUdecomposition(self):
|
| 461 |
+
"""Returns the Block LU decomposition of
|
| 462 |
+
a 2x2 Block Matrix
|
| 463 |
+
|
| 464 |
+
Returns
|
| 465 |
+
=======
|
| 466 |
+
|
| 467 |
+
(L, U) : Matrices
|
| 468 |
+
L : Lower Diagonal Matrix
|
| 469 |
+
U : Upper Diagonal Matrix
|
| 470 |
+
|
| 471 |
+
Examples
|
| 472 |
+
========
|
| 473 |
+
|
| 474 |
+
>>> from sympy import symbols, MatrixSymbol, BlockMatrix, block_collapse
|
| 475 |
+
>>> m, n = symbols('m n')
|
| 476 |
+
>>> A = MatrixSymbol('A', n, n)
|
| 477 |
+
>>> B = MatrixSymbol('B', n, m)
|
| 478 |
+
>>> C = MatrixSymbol('C', m, n)
|
| 479 |
+
>>> D = MatrixSymbol('D', m, m)
|
| 480 |
+
>>> X = BlockMatrix([[A, B], [C, D]])
|
| 481 |
+
>>> L, U = X.LUdecomposition()
|
| 482 |
+
>>> block_collapse(L*U)
|
| 483 |
+
Matrix([
|
| 484 |
+
[A, B],
|
| 485 |
+
[C, D]])
|
| 486 |
+
|
| 487 |
+
Raises
|
| 488 |
+
======
|
| 489 |
+
|
| 490 |
+
ShapeError
|
| 491 |
+
If the block matrix is not a 2x2 matrix
|
| 492 |
+
|
| 493 |
+
NonInvertibleMatrixError
|
| 494 |
+
If the matrix "A" is non-invertible
|
| 495 |
+
|
| 496 |
+
See Also
|
| 497 |
+
========
|
| 498 |
+
sympy.matrices.expressions.blockmatrix.BlockMatrix.UDLdecomposition
|
| 499 |
+
sympy.matrices.expressions.blockmatrix.BlockMatrix.LDUdecomposition
|
| 500 |
+
"""
|
| 501 |
+
if self.blockshape == (2,2):
|
| 502 |
+
[[A, B],
|
| 503 |
+
[C, D]] = self.blocks.tolist()
|
| 504 |
+
try:
|
| 505 |
+
A = A**0.5
|
| 506 |
+
AI = A.I
|
| 507 |
+
except NonInvertibleMatrixError:
|
| 508 |
+
raise NonInvertibleMatrixError('Block LU decomposition cannot be calculated when\
|
| 509 |
+
"A" is singular')
|
| 510 |
+
Z = ZeroMatrix(*B.shape)
|
| 511 |
+
Q = self.schur()**0.5
|
| 512 |
+
L = BlockMatrix([[A, Z], [C*AI, Q]])
|
| 513 |
+
U = BlockMatrix([[A, AI*B],[Z.T, Q]])
|
| 514 |
+
return L, U
|
| 515 |
+
else:
|
| 516 |
+
raise ShapeError("Block LU decomposition is supported only for 2x2 block matrices")
|
| 517 |
+
|
| 518 |
+
def _entry(self, i, j, **kwargs):
|
| 519 |
+
# Find row entry
|
| 520 |
+
orig_i, orig_j = i, j
|
| 521 |
+
for row_block, numrows in enumerate(self.rowblocksizes):
|
| 522 |
+
cmp = i < numrows
|
| 523 |
+
if cmp == True:
|
| 524 |
+
break
|
| 525 |
+
elif cmp == False:
|
| 526 |
+
i -= numrows
|
| 527 |
+
elif row_block < self.blockshape[0] - 1:
|
| 528 |
+
# Can't tell which block and it's not the last one, return unevaluated
|
| 529 |
+
return MatrixElement(self, orig_i, orig_j)
|
| 530 |
+
for col_block, numcols in enumerate(self.colblocksizes):
|
| 531 |
+
cmp = j < numcols
|
| 532 |
+
if cmp == True:
|
| 533 |
+
break
|
| 534 |
+
elif cmp == False:
|
| 535 |
+
j -= numcols
|
| 536 |
+
elif col_block < self.blockshape[1] - 1:
|
| 537 |
+
return MatrixElement(self, orig_i, orig_j)
|
| 538 |
+
return self.blocks[row_block, col_block][i, j]
|
| 539 |
+
|
| 540 |
+
@property
|
| 541 |
+
def is_Identity(self):
|
| 542 |
+
if self.blockshape[0] != self.blockshape[1]:
|
| 543 |
+
return False
|
| 544 |
+
for i in range(self.blockshape[0]):
|
| 545 |
+
for j in range(self.blockshape[1]):
|
| 546 |
+
if i==j and not self.blocks[i, j].is_Identity:
|
| 547 |
+
return False
|
| 548 |
+
if i!=j and not self.blocks[i, j].is_ZeroMatrix:
|
| 549 |
+
return False
|
| 550 |
+
return True
|
| 551 |
+
|
| 552 |
+
@property
|
| 553 |
+
def is_structurally_symmetric(self):
|
| 554 |
+
return self.rowblocksizes == self.colblocksizes
|
| 555 |
+
|
| 556 |
+
def equals(self, other):
|
| 557 |
+
if self == other:
|
| 558 |
+
return True
|
| 559 |
+
if (isinstance(other, BlockMatrix) and self.blocks == other.blocks):
|
| 560 |
+
return True
|
| 561 |
+
return super().equals(other)
|
| 562 |
+
|
| 563 |
+
|
| 564 |
+
class BlockDiagMatrix(BlockMatrix):
|
| 565 |
+
"""A sparse matrix with block matrices along its diagonals
|
| 566 |
+
|
| 567 |
+
Examples
|
| 568 |
+
========
|
| 569 |
+
|
| 570 |
+
>>> from sympy import MatrixSymbol, BlockDiagMatrix, symbols
|
| 571 |
+
>>> n, m, l = symbols('n m l')
|
| 572 |
+
>>> X = MatrixSymbol('X', n, n)
|
| 573 |
+
>>> Y = MatrixSymbol('Y', m, m)
|
| 574 |
+
>>> BlockDiagMatrix(X, Y)
|
| 575 |
+
Matrix([
|
| 576 |
+
[X, 0],
|
| 577 |
+
[0, Y]])
|
| 578 |
+
|
| 579 |
+
Notes
|
| 580 |
+
=====
|
| 581 |
+
|
| 582 |
+
If you want to get the individual diagonal blocks, use
|
| 583 |
+
:meth:`get_diag_blocks`.
|
| 584 |
+
|
| 585 |
+
See Also
|
| 586 |
+
========
|
| 587 |
+
|
| 588 |
+
sympy.matrices.dense.diag
|
| 589 |
+
"""
|
| 590 |
+
def __new__(cls, *mats):
|
| 591 |
+
return Basic.__new__(BlockDiagMatrix, *[_sympify(m) for m in mats])
|
| 592 |
+
|
| 593 |
+
@property
|
| 594 |
+
def diag(self):
|
| 595 |
+
return self.args
|
| 596 |
+
|
| 597 |
+
@property
|
| 598 |
+
def blocks(self):
|
| 599 |
+
from sympy.matrices.immutable import ImmutableDenseMatrix
|
| 600 |
+
mats = self.args
|
| 601 |
+
data = [[mats[i] if i == j else ZeroMatrix(mats[i].rows, mats[j].cols)
|
| 602 |
+
for j in range(len(mats))]
|
| 603 |
+
for i in range(len(mats))]
|
| 604 |
+
return ImmutableDenseMatrix(data, evaluate=False)
|
| 605 |
+
|
| 606 |
+
@property
|
| 607 |
+
def shape(self):
|
| 608 |
+
return (sum(block.rows for block in self.args),
|
| 609 |
+
sum(block.cols for block in self.args))
|
| 610 |
+
|
| 611 |
+
@property
|
| 612 |
+
def blockshape(self):
|
| 613 |
+
n = len(self.args)
|
| 614 |
+
return (n, n)
|
| 615 |
+
|
| 616 |
+
@property
|
| 617 |
+
def rowblocksizes(self):
|
| 618 |
+
return [block.rows for block in self.args]
|
| 619 |
+
|
| 620 |
+
@property
|
| 621 |
+
def colblocksizes(self):
|
| 622 |
+
return [block.cols for block in self.args]
|
| 623 |
+
|
| 624 |
+
def _all_square_blocks(self):
|
| 625 |
+
"""Returns true if all blocks are square"""
|
| 626 |
+
return all(mat.is_square for mat in self.args)
|
| 627 |
+
|
| 628 |
+
def _eval_determinant(self):
|
| 629 |
+
if self._all_square_blocks():
|
| 630 |
+
return Mul(*[det(mat) for mat in self.args])
|
| 631 |
+
# At least one block is non-square. Since the entire matrix must be square we know there must
|
| 632 |
+
# be at least two blocks in this matrix, in which case the entire matrix is necessarily rank-deficient
|
| 633 |
+
return S.Zero
|
| 634 |
+
|
| 635 |
+
def _eval_inverse(self, expand='ignored'):
|
| 636 |
+
if self._all_square_blocks():
|
| 637 |
+
return BlockDiagMatrix(*[mat.inverse() for mat in self.args])
|
| 638 |
+
# See comment in _eval_determinant()
|
| 639 |
+
raise NonInvertibleMatrixError('Matrix det == 0; not invertible.')
|
| 640 |
+
|
| 641 |
+
def _eval_transpose(self):
|
| 642 |
+
return BlockDiagMatrix(*[mat.transpose() for mat in self.args])
|
| 643 |
+
|
| 644 |
+
def _blockmul(self, other):
|
| 645 |
+
if (isinstance(other, BlockDiagMatrix) and
|
| 646 |
+
self.colblocksizes == other.rowblocksizes):
|
| 647 |
+
return BlockDiagMatrix(*[a*b for a, b in zip(self.args, other.args)])
|
| 648 |
+
else:
|
| 649 |
+
return BlockMatrix._blockmul(self, other)
|
| 650 |
+
|
| 651 |
+
def _blockadd(self, other):
|
| 652 |
+
if (isinstance(other, BlockDiagMatrix) and
|
| 653 |
+
self.blockshape == other.blockshape and
|
| 654 |
+
self.rowblocksizes == other.rowblocksizes and
|
| 655 |
+
self.colblocksizes == other.colblocksizes):
|
| 656 |
+
return BlockDiagMatrix(*[a + b for a, b in zip(self.args, other.args)])
|
| 657 |
+
else:
|
| 658 |
+
return BlockMatrix._blockadd(self, other)
|
| 659 |
+
|
| 660 |
+
def get_diag_blocks(self):
|
| 661 |
+
"""Return the list of diagonal blocks of the matrix.
|
| 662 |
+
|
| 663 |
+
Examples
|
| 664 |
+
========
|
| 665 |
+
|
| 666 |
+
>>> from sympy import BlockDiagMatrix, Matrix
|
| 667 |
+
|
| 668 |
+
>>> A = Matrix([[1, 2], [3, 4]])
|
| 669 |
+
>>> B = Matrix([[5, 6], [7, 8]])
|
| 670 |
+
>>> M = BlockDiagMatrix(A, B)
|
| 671 |
+
|
| 672 |
+
How to get diagonal blocks from the block diagonal matrix:
|
| 673 |
+
|
| 674 |
+
>>> diag_blocks = M.get_diag_blocks()
|
| 675 |
+
>>> diag_blocks[0]
|
| 676 |
+
Matrix([
|
| 677 |
+
[1, 2],
|
| 678 |
+
[3, 4]])
|
| 679 |
+
>>> diag_blocks[1]
|
| 680 |
+
Matrix([
|
| 681 |
+
[5, 6],
|
| 682 |
+
[7, 8]])
|
| 683 |
+
"""
|
| 684 |
+
return self.args
|
| 685 |
+
|
| 686 |
+
|
| 687 |
+
def block_collapse(expr):
|
| 688 |
+
"""Evaluates a block matrix expression
|
| 689 |
+
|
| 690 |
+
>>> from sympy import MatrixSymbol, BlockMatrix, symbols, Identity, ZeroMatrix, block_collapse
|
| 691 |
+
>>> n,m,l = symbols('n m l')
|
| 692 |
+
>>> X = MatrixSymbol('X', n, n)
|
| 693 |
+
>>> Y = MatrixSymbol('Y', m, m)
|
| 694 |
+
>>> Z = MatrixSymbol('Z', n, m)
|
| 695 |
+
>>> B = BlockMatrix([[X, Z], [ZeroMatrix(m, n), Y]])
|
| 696 |
+
>>> print(B)
|
| 697 |
+
Matrix([
|
| 698 |
+
[X, Z],
|
| 699 |
+
[0, Y]])
|
| 700 |
+
|
| 701 |
+
>>> C = BlockMatrix([[Identity(n), Z]])
|
| 702 |
+
>>> print(C)
|
| 703 |
+
Matrix([[I, Z]])
|
| 704 |
+
|
| 705 |
+
>>> print(block_collapse(C*B))
|
| 706 |
+
Matrix([[X, Z + Z*Y]])
|
| 707 |
+
"""
|
| 708 |
+
from sympy.strategies.util import expr_fns
|
| 709 |
+
|
| 710 |
+
hasbm = lambda expr: isinstance(expr, MatrixExpr) and expr.has(BlockMatrix)
|
| 711 |
+
|
| 712 |
+
conditioned_rl = condition(
|
| 713 |
+
hasbm,
|
| 714 |
+
typed(
|
| 715 |
+
{MatAdd: do_one(bc_matadd, bc_block_plus_ident),
|
| 716 |
+
MatMul: do_one(bc_matmul, bc_dist),
|
| 717 |
+
MatPow: bc_matmul,
|
| 718 |
+
Transpose: bc_transpose,
|
| 719 |
+
Inverse: bc_inverse,
|
| 720 |
+
BlockMatrix: do_one(bc_unpack, deblock)}
|
| 721 |
+
)
|
| 722 |
+
)
|
| 723 |
+
|
| 724 |
+
rule = exhaust(
|
| 725 |
+
bottom_up(
|
| 726 |
+
exhaust(conditioned_rl),
|
| 727 |
+
fns=expr_fns
|
| 728 |
+
)
|
| 729 |
+
)
|
| 730 |
+
|
| 731 |
+
result = rule(expr)
|
| 732 |
+
doit = getattr(result, 'doit', None)
|
| 733 |
+
if doit is not None:
|
| 734 |
+
return doit()
|
| 735 |
+
else:
|
| 736 |
+
return result
|
| 737 |
+
|
| 738 |
+
def bc_unpack(expr):
|
| 739 |
+
if expr.blockshape == (1, 1):
|
| 740 |
+
return expr.blocks[0, 0]
|
| 741 |
+
return expr
|
| 742 |
+
|
| 743 |
+
def bc_matadd(expr):
|
| 744 |
+
args = sift(expr.args, lambda M: isinstance(M, BlockMatrix))
|
| 745 |
+
blocks = args[True]
|
| 746 |
+
if not blocks:
|
| 747 |
+
return expr
|
| 748 |
+
|
| 749 |
+
nonblocks = args[False]
|
| 750 |
+
block = blocks[0]
|
| 751 |
+
for b in blocks[1:]:
|
| 752 |
+
block = block._blockadd(b)
|
| 753 |
+
if nonblocks:
|
| 754 |
+
return MatAdd(*nonblocks) + block
|
| 755 |
+
else:
|
| 756 |
+
return block
|
| 757 |
+
|
| 758 |
+
def bc_block_plus_ident(expr):
|
| 759 |
+
idents = [arg for arg in expr.args if arg.is_Identity]
|
| 760 |
+
if not idents:
|
| 761 |
+
return expr
|
| 762 |
+
|
| 763 |
+
blocks = [arg for arg in expr.args if isinstance(arg, BlockMatrix)]
|
| 764 |
+
if (blocks and all(b.structurally_equal(blocks[0]) for b in blocks)
|
| 765 |
+
and blocks[0].is_structurally_symmetric):
|
| 766 |
+
block_id = BlockDiagMatrix(*[Identity(k)
|
| 767 |
+
for k in blocks[0].rowblocksizes])
|
| 768 |
+
rest = [arg for arg in expr.args if not arg.is_Identity and not isinstance(arg, BlockMatrix)]
|
| 769 |
+
return MatAdd(block_id * len(idents), *blocks, *rest).doit()
|
| 770 |
+
|
| 771 |
+
return expr
|
| 772 |
+
|
| 773 |
+
def bc_dist(expr):
|
| 774 |
+
""" Turn a*[X, Y] into [a*X, a*Y] """
|
| 775 |
+
factor, mat = expr.as_coeff_mmul()
|
| 776 |
+
if factor == 1:
|
| 777 |
+
return expr
|
| 778 |
+
|
| 779 |
+
unpacked = unpack(mat)
|
| 780 |
+
|
| 781 |
+
if isinstance(unpacked, BlockDiagMatrix):
|
| 782 |
+
B = unpacked.diag
|
| 783 |
+
new_B = [factor * mat for mat in B]
|
| 784 |
+
return BlockDiagMatrix(*new_B)
|
| 785 |
+
elif isinstance(unpacked, BlockMatrix):
|
| 786 |
+
B = unpacked.blocks
|
| 787 |
+
new_B = [
|
| 788 |
+
[factor * B[i, j] for j in range(B.cols)] for i in range(B.rows)]
|
| 789 |
+
return BlockMatrix(new_B)
|
| 790 |
+
return expr
|
| 791 |
+
|
| 792 |
+
|
| 793 |
+
def bc_matmul(expr):
|
| 794 |
+
if isinstance(expr, MatPow):
|
| 795 |
+
if expr.args[1].is_Integer:
|
| 796 |
+
factor, matrices = (1, [expr.args[0]]*expr.args[1])
|
| 797 |
+
else:
|
| 798 |
+
return expr
|
| 799 |
+
else:
|
| 800 |
+
factor, matrices = expr.as_coeff_matrices()
|
| 801 |
+
|
| 802 |
+
i = 0
|
| 803 |
+
while (i+1 < len(matrices)):
|
| 804 |
+
A, B = matrices[i:i+2]
|
| 805 |
+
if isinstance(A, BlockMatrix) and isinstance(B, BlockMatrix):
|
| 806 |
+
matrices[i] = A._blockmul(B)
|
| 807 |
+
matrices.pop(i+1)
|
| 808 |
+
elif isinstance(A, BlockMatrix):
|
| 809 |
+
matrices[i] = A._blockmul(BlockMatrix([[B]]))
|
| 810 |
+
matrices.pop(i+1)
|
| 811 |
+
elif isinstance(B, BlockMatrix):
|
| 812 |
+
matrices[i] = BlockMatrix([[A]])._blockmul(B)
|
| 813 |
+
matrices.pop(i+1)
|
| 814 |
+
else:
|
| 815 |
+
i+=1
|
| 816 |
+
return MatMul(factor, *matrices).doit()
|
| 817 |
+
|
| 818 |
+
def bc_transpose(expr):
|
| 819 |
+
collapse = block_collapse(expr.arg)
|
| 820 |
+
return collapse._eval_transpose()
|
| 821 |
+
|
| 822 |
+
|
| 823 |
+
def bc_inverse(expr):
|
| 824 |
+
if isinstance(expr.arg, BlockDiagMatrix):
|
| 825 |
+
return expr.inverse()
|
| 826 |
+
|
| 827 |
+
expr2 = blockinverse_1x1(expr)
|
| 828 |
+
if expr != expr2:
|
| 829 |
+
return expr2
|
| 830 |
+
return blockinverse_2x2(Inverse(reblock_2x2(expr.arg)))
|
| 831 |
+
|
| 832 |
+
def blockinverse_1x1(expr):
|
| 833 |
+
if isinstance(expr.arg, BlockMatrix) and expr.arg.blockshape == (1, 1):
|
| 834 |
+
mat = Matrix([[expr.arg.blocks[0].inverse()]])
|
| 835 |
+
return BlockMatrix(mat)
|
| 836 |
+
return expr
|
| 837 |
+
|
| 838 |
+
|
| 839 |
+
def blockinverse_2x2(expr):
|
| 840 |
+
if isinstance(expr.arg, BlockMatrix) and expr.arg.blockshape == (2, 2):
|
| 841 |
+
# See: Inverses of 2x2 Block Matrices, Tzon-Tzer Lu and Sheng-Hua Shiou
|
| 842 |
+
[[A, B],
|
| 843 |
+
[C, D]] = expr.arg.blocks.tolist()
|
| 844 |
+
|
| 845 |
+
formula = _choose_2x2_inversion_formula(A, B, C, D)
|
| 846 |
+
if formula != None:
|
| 847 |
+
MI = expr.arg.schur(formula).I
|
| 848 |
+
if formula == 'A':
|
| 849 |
+
AI = A.I
|
| 850 |
+
return BlockMatrix([[AI + AI * B * MI * C * AI, -AI * B * MI], [-MI * C * AI, MI]])
|
| 851 |
+
if formula == 'B':
|
| 852 |
+
BI = B.I
|
| 853 |
+
return BlockMatrix([[-MI * D * BI, MI], [BI + BI * A * MI * D * BI, -BI * A * MI]])
|
| 854 |
+
if formula == 'C':
|
| 855 |
+
CI = C.I
|
| 856 |
+
return BlockMatrix([[-CI * D * MI, CI + CI * D * MI * A * CI], [MI, -MI * A * CI]])
|
| 857 |
+
if formula == 'D':
|
| 858 |
+
DI = D.I
|
| 859 |
+
return BlockMatrix([[MI, -MI * B * DI], [-DI * C * MI, DI + DI * C * MI * B * DI]])
|
| 860 |
+
|
| 861 |
+
return expr
|
| 862 |
+
|
| 863 |
+
|
| 864 |
+
def _choose_2x2_inversion_formula(A, B, C, D):
|
| 865 |
+
"""
|
| 866 |
+
Assuming [[A, B], [C, D]] would form a valid square block matrix, find
|
| 867 |
+
which of the classical 2x2 block matrix inversion formulas would be
|
| 868 |
+
best suited.
|
| 869 |
+
|
| 870 |
+
Returns 'A', 'B', 'C', 'D' to represent the algorithm involving inversion
|
| 871 |
+
of the given argument or None if the matrix cannot be inverted using
|
| 872 |
+
any of those formulas.
|
| 873 |
+
"""
|
| 874 |
+
# Try to find a known invertible matrix. Note that the Schur complement
|
| 875 |
+
# is currently not being considered for this
|
| 876 |
+
A_inv = ask(Q.invertible(A))
|
| 877 |
+
if A_inv == True:
|
| 878 |
+
return 'A'
|
| 879 |
+
B_inv = ask(Q.invertible(B))
|
| 880 |
+
if B_inv == True:
|
| 881 |
+
return 'B'
|
| 882 |
+
C_inv = ask(Q.invertible(C))
|
| 883 |
+
if C_inv == True:
|
| 884 |
+
return 'C'
|
| 885 |
+
D_inv = ask(Q.invertible(D))
|
| 886 |
+
if D_inv == True:
|
| 887 |
+
return 'D'
|
| 888 |
+
# Otherwise try to find a matrix that isn't known to be non-invertible
|
| 889 |
+
if A_inv != False:
|
| 890 |
+
return 'A'
|
| 891 |
+
if B_inv != False:
|
| 892 |
+
return 'B'
|
| 893 |
+
if C_inv != False:
|
| 894 |
+
return 'C'
|
| 895 |
+
if D_inv != False:
|
| 896 |
+
return 'D'
|
| 897 |
+
return None
|
| 898 |
+
|
| 899 |
+
|
| 900 |
+
def deblock(B):
|
| 901 |
+
""" Flatten a BlockMatrix of BlockMatrices """
|
| 902 |
+
if not isinstance(B, BlockMatrix) or not B.blocks.has(BlockMatrix):
|
| 903 |
+
return B
|
| 904 |
+
wrap = lambda x: x if isinstance(x, BlockMatrix) else BlockMatrix([[x]])
|
| 905 |
+
bb = B.blocks.applyfunc(wrap) # everything is a block
|
| 906 |
+
|
| 907 |
+
try:
|
| 908 |
+
MM = Matrix(0, sum(bb[0, i].blocks.shape[1] for i in range(bb.shape[1])), [])
|
| 909 |
+
for row in range(0, bb.shape[0]):
|
| 910 |
+
M = Matrix(bb[row, 0].blocks)
|
| 911 |
+
for col in range(1, bb.shape[1]):
|
| 912 |
+
M = M.row_join(bb[row, col].blocks)
|
| 913 |
+
MM = MM.col_join(M)
|
| 914 |
+
|
| 915 |
+
return BlockMatrix(MM)
|
| 916 |
+
except ShapeError:
|
| 917 |
+
return B
|
| 918 |
+
|
| 919 |
+
|
| 920 |
+
def reblock_2x2(expr):
|
| 921 |
+
"""
|
| 922 |
+
Reblock a BlockMatrix so that it has 2x2 blocks of block matrices. If
|
| 923 |
+
possible in such a way that the matrix continues to be invertible using the
|
| 924 |
+
classical 2x2 block inversion formulas.
|
| 925 |
+
"""
|
| 926 |
+
if not isinstance(expr, BlockMatrix) or not all(d > 2 for d in expr.blockshape):
|
| 927 |
+
return expr
|
| 928 |
+
|
| 929 |
+
BM = BlockMatrix # for brevity's sake
|
| 930 |
+
rowblocks, colblocks = expr.blockshape
|
| 931 |
+
blocks = expr.blocks
|
| 932 |
+
for i in range(1, rowblocks):
|
| 933 |
+
for j in range(1, colblocks):
|
| 934 |
+
# try to split rows at i and cols at j
|
| 935 |
+
A = bc_unpack(BM(blocks[:i, :j]))
|
| 936 |
+
B = bc_unpack(BM(blocks[:i, j:]))
|
| 937 |
+
C = bc_unpack(BM(blocks[i:, :j]))
|
| 938 |
+
D = bc_unpack(BM(blocks[i:, j:]))
|
| 939 |
+
|
| 940 |
+
formula = _choose_2x2_inversion_formula(A, B, C, D)
|
| 941 |
+
if formula is not None:
|
| 942 |
+
return BlockMatrix([[A, B], [C, D]])
|
| 943 |
+
|
| 944 |
+
# else: nothing worked, just split upper left corner
|
| 945 |
+
return BM([[blocks[0, 0], BM(blocks[0, 1:])],
|
| 946 |
+
[BM(blocks[1:, 0]), BM(blocks[1:, 1:])]])
|
| 947 |
+
|
| 948 |
+
|
| 949 |
+
def bounds(sizes):
|
| 950 |
+
""" Convert sequence of numbers into pairs of low-high pairs
|
| 951 |
+
|
| 952 |
+
>>> from sympy.matrices.expressions.blockmatrix import bounds
|
| 953 |
+
>>> bounds((1, 10, 50))
|
| 954 |
+
[(0, 1), (1, 11), (11, 61)]
|
| 955 |
+
"""
|
| 956 |
+
low = 0
|
| 957 |
+
rv = []
|
| 958 |
+
for size in sizes:
|
| 959 |
+
rv.append((low, low + size))
|
| 960 |
+
low += size
|
| 961 |
+
return rv
|
| 962 |
+
|
| 963 |
+
def blockcut(expr, rowsizes, colsizes):
|
| 964 |
+
""" Cut a matrix expression into Blocks
|
| 965 |
+
|
| 966 |
+
>>> from sympy import ImmutableMatrix, blockcut
|
| 967 |
+
>>> M = ImmutableMatrix(4, 4, range(16))
|
| 968 |
+
>>> B = blockcut(M, (1, 3), (1, 3))
|
| 969 |
+
>>> type(B).__name__
|
| 970 |
+
'BlockMatrix'
|
| 971 |
+
>>> ImmutableMatrix(B.blocks[0, 1])
|
| 972 |
+
Matrix([[1, 2, 3]])
|
| 973 |
+
"""
|
| 974 |
+
|
| 975 |
+
rowbounds = bounds(rowsizes)
|
| 976 |
+
colbounds = bounds(colsizes)
|
| 977 |
+
return BlockMatrix([[MatrixSlice(expr, rowbound, colbound)
|
| 978 |
+
for colbound in colbounds]
|
| 979 |
+
for rowbound in rowbounds])
|
venv/lib/python3.10/site-packages/sympy/matrices/expressions/companion.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.core.singleton import S
|
| 2 |
+
from sympy.core.sympify import _sympify
|
| 3 |
+
from sympy.polys.polytools import Poly
|
| 4 |
+
|
| 5 |
+
from .matexpr import MatrixExpr
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class CompanionMatrix(MatrixExpr):
|
| 9 |
+
"""A symbolic companion matrix of a polynomial.
|
| 10 |
+
|
| 11 |
+
Examples
|
| 12 |
+
========
|
| 13 |
+
|
| 14 |
+
>>> from sympy import Poly, Symbol, symbols
|
| 15 |
+
>>> from sympy.matrices.expressions import CompanionMatrix
|
| 16 |
+
>>> x = Symbol('x')
|
| 17 |
+
>>> c0, c1, c2, c3, c4 = symbols('c0:5')
|
| 18 |
+
>>> p = Poly(c0 + c1*x + c2*x**2 + c3*x**3 + c4*x**4 + x**5, x)
|
| 19 |
+
>>> CompanionMatrix(p)
|
| 20 |
+
CompanionMatrix(Poly(x**5 + c4*x**4 + c3*x**3 + c2*x**2 + c1*x + c0,
|
| 21 |
+
x, domain='ZZ[c0,c1,c2,c3,c4]'))
|
| 22 |
+
"""
|
| 23 |
+
def __new__(cls, poly):
|
| 24 |
+
poly = _sympify(poly)
|
| 25 |
+
if not isinstance(poly, Poly):
|
| 26 |
+
raise ValueError("{} must be a Poly instance.".format(poly))
|
| 27 |
+
if not poly.is_monic:
|
| 28 |
+
raise ValueError("{} must be a monic polynomial.".format(poly))
|
| 29 |
+
if not poly.is_univariate:
|
| 30 |
+
raise ValueError(
|
| 31 |
+
"{} must be a univariate polynomial.".format(poly))
|
| 32 |
+
if not poly.degree() >= 1:
|
| 33 |
+
raise ValueError(
|
| 34 |
+
"{} must have degree not less than 1.".format(poly))
|
| 35 |
+
|
| 36 |
+
return super().__new__(cls, poly)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
@property
|
| 40 |
+
def shape(self):
|
| 41 |
+
poly = self.args[0]
|
| 42 |
+
size = poly.degree()
|
| 43 |
+
return size, size
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def _entry(self, i, j):
|
| 47 |
+
if j == self.cols - 1:
|
| 48 |
+
return -self.args[0].all_coeffs()[-1 - i]
|
| 49 |
+
elif i == j + 1:
|
| 50 |
+
return S.One
|
| 51 |
+
return S.Zero
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def as_explicit(self):
|
| 55 |
+
from sympy.matrices.immutable import ImmutableDenseMatrix
|
| 56 |
+
return ImmutableDenseMatrix.companion(self.args[0])
|
venv/lib/python3.10/site-packages/sympy/matrices/expressions/determinant.py
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.core.basic import Basic
|
| 2 |
+
from sympy.core.expr import Expr
|
| 3 |
+
from sympy.core.singleton import S
|
| 4 |
+
from sympy.core.sympify import sympify
|
| 5 |
+
from sympy.matrices.common import NonSquareMatrixError
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class Determinant(Expr):
|
| 9 |
+
"""Matrix Determinant
|
| 10 |
+
|
| 11 |
+
Represents the determinant of a matrix expression.
|
| 12 |
+
|
| 13 |
+
Examples
|
| 14 |
+
========
|
| 15 |
+
|
| 16 |
+
>>> from sympy import MatrixSymbol, Determinant, eye
|
| 17 |
+
>>> A = MatrixSymbol('A', 3, 3)
|
| 18 |
+
>>> Determinant(A)
|
| 19 |
+
Determinant(A)
|
| 20 |
+
>>> Determinant(eye(3)).doit()
|
| 21 |
+
1
|
| 22 |
+
"""
|
| 23 |
+
is_commutative = True
|
| 24 |
+
|
| 25 |
+
def __new__(cls, mat):
|
| 26 |
+
mat = sympify(mat)
|
| 27 |
+
if not mat.is_Matrix:
|
| 28 |
+
raise TypeError("Input to Determinant, %s, not a matrix" % str(mat))
|
| 29 |
+
|
| 30 |
+
if mat.is_square is False:
|
| 31 |
+
raise NonSquareMatrixError("Det of a non-square matrix")
|
| 32 |
+
|
| 33 |
+
return Basic.__new__(cls, mat)
|
| 34 |
+
|
| 35 |
+
@property
|
| 36 |
+
def arg(self):
|
| 37 |
+
return self.args[0]
|
| 38 |
+
|
| 39 |
+
@property
|
| 40 |
+
def kind(self):
|
| 41 |
+
return self.arg.kind.element_kind
|
| 42 |
+
|
| 43 |
+
def doit(self, expand=False, **hints):
|
| 44 |
+
try:
|
| 45 |
+
return self.arg._eval_determinant()
|
| 46 |
+
except (AttributeError, NotImplementedError):
|
| 47 |
+
return self
|
| 48 |
+
|
| 49 |
+
def det(matexpr):
|
| 50 |
+
""" Matrix Determinant
|
| 51 |
+
|
| 52 |
+
Examples
|
| 53 |
+
========
|
| 54 |
+
|
| 55 |
+
>>> from sympy import MatrixSymbol, det, eye
|
| 56 |
+
>>> A = MatrixSymbol('A', 3, 3)
|
| 57 |
+
>>> det(A)
|
| 58 |
+
Determinant(A)
|
| 59 |
+
>>> det(eye(3))
|
| 60 |
+
1
|
| 61 |
+
"""
|
| 62 |
+
|
| 63 |
+
return Determinant(matexpr).doit()
|
| 64 |
+
|
| 65 |
+
class Permanent(Expr):
|
| 66 |
+
"""Matrix Permanent
|
| 67 |
+
|
| 68 |
+
Represents the permanent of a matrix expression.
|
| 69 |
+
|
| 70 |
+
Examples
|
| 71 |
+
========
|
| 72 |
+
|
| 73 |
+
>>> from sympy import MatrixSymbol, Permanent, ones
|
| 74 |
+
>>> A = MatrixSymbol('A', 3, 3)
|
| 75 |
+
>>> Permanent(A)
|
| 76 |
+
Permanent(A)
|
| 77 |
+
>>> Permanent(ones(3, 3)).doit()
|
| 78 |
+
6
|
| 79 |
+
"""
|
| 80 |
+
|
| 81 |
+
def __new__(cls, mat):
|
| 82 |
+
mat = sympify(mat)
|
| 83 |
+
if not mat.is_Matrix:
|
| 84 |
+
raise TypeError("Input to Permanent, %s, not a matrix" % str(mat))
|
| 85 |
+
|
| 86 |
+
return Basic.__new__(cls, mat)
|
| 87 |
+
|
| 88 |
+
@property
|
| 89 |
+
def arg(self):
|
| 90 |
+
return self.args[0]
|
| 91 |
+
|
| 92 |
+
def doit(self, expand=False, **hints):
|
| 93 |
+
try:
|
| 94 |
+
return self.arg.per()
|
| 95 |
+
except (AttributeError, NotImplementedError):
|
| 96 |
+
return self
|
| 97 |
+
|
| 98 |
+
def per(matexpr):
|
| 99 |
+
""" Matrix Permanent
|
| 100 |
+
|
| 101 |
+
Examples
|
| 102 |
+
========
|
| 103 |
+
|
| 104 |
+
>>> from sympy import MatrixSymbol, Matrix, per, ones
|
| 105 |
+
>>> A = MatrixSymbol('A', 3, 3)
|
| 106 |
+
>>> per(A)
|
| 107 |
+
Permanent(A)
|
| 108 |
+
>>> per(ones(5, 5))
|
| 109 |
+
120
|
| 110 |
+
>>> M = Matrix([1, 2, 5])
|
| 111 |
+
>>> per(M)
|
| 112 |
+
8
|
| 113 |
+
"""
|
| 114 |
+
|
| 115 |
+
return Permanent(matexpr).doit()
|
| 116 |
+
|
| 117 |
+
from sympy.assumptions.ask import ask, Q
|
| 118 |
+
from sympy.assumptions.refine import handlers_dict
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def refine_Determinant(expr, assumptions):
|
| 122 |
+
"""
|
| 123 |
+
>>> from sympy import MatrixSymbol, Q, assuming, refine, det
|
| 124 |
+
>>> X = MatrixSymbol('X', 2, 2)
|
| 125 |
+
>>> det(X)
|
| 126 |
+
Determinant(X)
|
| 127 |
+
>>> with assuming(Q.orthogonal(X)):
|
| 128 |
+
... print(refine(det(X)))
|
| 129 |
+
1
|
| 130 |
+
"""
|
| 131 |
+
if ask(Q.orthogonal(expr.arg), assumptions):
|
| 132 |
+
return S.One
|
| 133 |
+
elif ask(Q.singular(expr.arg), assumptions):
|
| 134 |
+
return S.Zero
|
| 135 |
+
elif ask(Q.unit_triangular(expr.arg), assumptions):
|
| 136 |
+
return S.One
|
| 137 |
+
|
| 138 |
+
return expr
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
handlers_dict['Determinant'] = refine_Determinant
|
venv/lib/python3.10/site-packages/sympy/matrices/expressions/diagonal.py
ADDED
|
@@ -0,0 +1,220 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.core.sympify import _sympify
|
| 2 |
+
|
| 3 |
+
from sympy.matrices.expressions import MatrixExpr
|
| 4 |
+
from sympy.core import S, Eq, Ge
|
| 5 |
+
from sympy.core.mul import Mul
|
| 6 |
+
from sympy.functions.special.tensor_functions import KroneckerDelta
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class DiagonalMatrix(MatrixExpr):
|
| 10 |
+
"""DiagonalMatrix(M) will create a matrix expression that
|
| 11 |
+
behaves as though all off-diagonal elements,
|
| 12 |
+
`M[i, j]` where `i != j`, are zero.
|
| 13 |
+
|
| 14 |
+
Examples
|
| 15 |
+
========
|
| 16 |
+
|
| 17 |
+
>>> from sympy import MatrixSymbol, DiagonalMatrix, Symbol
|
| 18 |
+
>>> n = Symbol('n', integer=True)
|
| 19 |
+
>>> m = Symbol('m', integer=True)
|
| 20 |
+
>>> D = DiagonalMatrix(MatrixSymbol('x', 2, 3))
|
| 21 |
+
>>> D[1, 2]
|
| 22 |
+
0
|
| 23 |
+
>>> D[1, 1]
|
| 24 |
+
x[1, 1]
|
| 25 |
+
|
| 26 |
+
The length of the diagonal -- the lesser of the two dimensions of `M` --
|
| 27 |
+
is accessed through the `diagonal_length` property:
|
| 28 |
+
|
| 29 |
+
>>> D.diagonal_length
|
| 30 |
+
2
|
| 31 |
+
>>> DiagonalMatrix(MatrixSymbol('x', n + 1, n)).diagonal_length
|
| 32 |
+
n
|
| 33 |
+
|
| 34 |
+
When one of the dimensions is symbolic the other will be treated as
|
| 35 |
+
though it is smaller:
|
| 36 |
+
|
| 37 |
+
>>> tall = DiagonalMatrix(MatrixSymbol('x', n, 3))
|
| 38 |
+
>>> tall.diagonal_length
|
| 39 |
+
3
|
| 40 |
+
>>> tall[10, 1]
|
| 41 |
+
0
|
| 42 |
+
|
| 43 |
+
When the size of the diagonal is not known, a value of None will
|
| 44 |
+
be returned:
|
| 45 |
+
|
| 46 |
+
>>> DiagonalMatrix(MatrixSymbol('x', n, m)).diagonal_length is None
|
| 47 |
+
True
|
| 48 |
+
|
| 49 |
+
"""
|
| 50 |
+
arg = property(lambda self: self.args[0])
|
| 51 |
+
|
| 52 |
+
shape = property(lambda self: self.arg.shape) # type:ignore
|
| 53 |
+
|
| 54 |
+
@property
|
| 55 |
+
def diagonal_length(self):
|
| 56 |
+
r, c = self.shape
|
| 57 |
+
if r.is_Integer and c.is_Integer:
|
| 58 |
+
m = min(r, c)
|
| 59 |
+
elif r.is_Integer and not c.is_Integer:
|
| 60 |
+
m = r
|
| 61 |
+
elif c.is_Integer and not r.is_Integer:
|
| 62 |
+
m = c
|
| 63 |
+
elif r == c:
|
| 64 |
+
m = r
|
| 65 |
+
else:
|
| 66 |
+
try:
|
| 67 |
+
m = min(r, c)
|
| 68 |
+
except TypeError:
|
| 69 |
+
m = None
|
| 70 |
+
return m
|
| 71 |
+
|
| 72 |
+
def _entry(self, i, j, **kwargs):
|
| 73 |
+
if self.diagonal_length is not None:
|
| 74 |
+
if Ge(i, self.diagonal_length) is S.true:
|
| 75 |
+
return S.Zero
|
| 76 |
+
elif Ge(j, self.diagonal_length) is S.true:
|
| 77 |
+
return S.Zero
|
| 78 |
+
eq = Eq(i, j)
|
| 79 |
+
if eq is S.true:
|
| 80 |
+
return self.arg[i, i]
|
| 81 |
+
elif eq is S.false:
|
| 82 |
+
return S.Zero
|
| 83 |
+
return self.arg[i, j]*KroneckerDelta(i, j)
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
class DiagonalOf(MatrixExpr):
|
| 87 |
+
"""DiagonalOf(M) will create a matrix expression that
|
| 88 |
+
is equivalent to the diagonal of `M`, represented as
|
| 89 |
+
a single column matrix.
|
| 90 |
+
|
| 91 |
+
Examples
|
| 92 |
+
========
|
| 93 |
+
|
| 94 |
+
>>> from sympy import MatrixSymbol, DiagonalOf, Symbol
|
| 95 |
+
>>> n = Symbol('n', integer=True)
|
| 96 |
+
>>> m = Symbol('m', integer=True)
|
| 97 |
+
>>> x = MatrixSymbol('x', 2, 3)
|
| 98 |
+
>>> diag = DiagonalOf(x)
|
| 99 |
+
>>> diag.shape
|
| 100 |
+
(2, 1)
|
| 101 |
+
|
| 102 |
+
The diagonal can be addressed like a matrix or vector and will
|
| 103 |
+
return the corresponding element of the original matrix:
|
| 104 |
+
|
| 105 |
+
>>> diag[1, 0] == diag[1] == x[1, 1]
|
| 106 |
+
True
|
| 107 |
+
|
| 108 |
+
The length of the diagonal -- the lesser of the two dimensions of `M` --
|
| 109 |
+
is accessed through the `diagonal_length` property:
|
| 110 |
+
|
| 111 |
+
>>> diag.diagonal_length
|
| 112 |
+
2
|
| 113 |
+
>>> DiagonalOf(MatrixSymbol('x', n + 1, n)).diagonal_length
|
| 114 |
+
n
|
| 115 |
+
|
| 116 |
+
When only one of the dimensions is symbolic the other will be
|
| 117 |
+
treated as though it is smaller:
|
| 118 |
+
|
| 119 |
+
>>> dtall = DiagonalOf(MatrixSymbol('x', n, 3))
|
| 120 |
+
>>> dtall.diagonal_length
|
| 121 |
+
3
|
| 122 |
+
|
| 123 |
+
When the size of the diagonal is not known, a value of None will
|
| 124 |
+
be returned:
|
| 125 |
+
|
| 126 |
+
>>> DiagonalOf(MatrixSymbol('x', n, m)).diagonal_length is None
|
| 127 |
+
True
|
| 128 |
+
|
| 129 |
+
"""
|
| 130 |
+
arg = property(lambda self: self.args[0])
|
| 131 |
+
@property
|
| 132 |
+
def shape(self):
|
| 133 |
+
r, c = self.arg.shape
|
| 134 |
+
if r.is_Integer and c.is_Integer:
|
| 135 |
+
m = min(r, c)
|
| 136 |
+
elif r.is_Integer and not c.is_Integer:
|
| 137 |
+
m = r
|
| 138 |
+
elif c.is_Integer and not r.is_Integer:
|
| 139 |
+
m = c
|
| 140 |
+
elif r == c:
|
| 141 |
+
m = r
|
| 142 |
+
else:
|
| 143 |
+
try:
|
| 144 |
+
m = min(r, c)
|
| 145 |
+
except TypeError:
|
| 146 |
+
m = None
|
| 147 |
+
return m, S.One
|
| 148 |
+
|
| 149 |
+
@property
|
| 150 |
+
def diagonal_length(self):
|
| 151 |
+
return self.shape[0]
|
| 152 |
+
|
| 153 |
+
def _entry(self, i, j, **kwargs):
|
| 154 |
+
return self.arg._entry(i, i, **kwargs)
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
class DiagMatrix(MatrixExpr):
|
| 158 |
+
"""
|
| 159 |
+
Turn a vector into a diagonal matrix.
|
| 160 |
+
"""
|
| 161 |
+
def __new__(cls, vector):
|
| 162 |
+
vector = _sympify(vector)
|
| 163 |
+
obj = MatrixExpr.__new__(cls, vector)
|
| 164 |
+
shape = vector.shape
|
| 165 |
+
dim = shape[1] if shape[0] == 1 else shape[0]
|
| 166 |
+
if vector.shape[0] != 1:
|
| 167 |
+
obj._iscolumn = True
|
| 168 |
+
else:
|
| 169 |
+
obj._iscolumn = False
|
| 170 |
+
obj._shape = (dim, dim)
|
| 171 |
+
obj._vector = vector
|
| 172 |
+
return obj
|
| 173 |
+
|
| 174 |
+
@property
|
| 175 |
+
def shape(self):
|
| 176 |
+
return self._shape
|
| 177 |
+
|
| 178 |
+
def _entry(self, i, j, **kwargs):
|
| 179 |
+
if self._iscolumn:
|
| 180 |
+
result = self._vector._entry(i, 0, **kwargs)
|
| 181 |
+
else:
|
| 182 |
+
result = self._vector._entry(0, j, **kwargs)
|
| 183 |
+
if i != j:
|
| 184 |
+
result *= KroneckerDelta(i, j)
|
| 185 |
+
return result
|
| 186 |
+
|
| 187 |
+
def _eval_transpose(self):
|
| 188 |
+
return self
|
| 189 |
+
|
| 190 |
+
def as_explicit(self):
|
| 191 |
+
from sympy.matrices.dense import diag
|
| 192 |
+
return diag(*list(self._vector.as_explicit()))
|
| 193 |
+
|
| 194 |
+
def doit(self, **hints):
|
| 195 |
+
from sympy.assumptions import ask, Q
|
| 196 |
+
from sympy.matrices.expressions.matmul import MatMul
|
| 197 |
+
from sympy.matrices.expressions.transpose import Transpose
|
| 198 |
+
from sympy.matrices.dense import eye
|
| 199 |
+
from sympy.matrices.matrices import MatrixBase
|
| 200 |
+
vector = self._vector
|
| 201 |
+
# This accounts for shape (1, 1) and identity matrices, among others:
|
| 202 |
+
if ask(Q.diagonal(vector)):
|
| 203 |
+
return vector
|
| 204 |
+
if isinstance(vector, MatrixBase):
|
| 205 |
+
ret = eye(max(vector.shape))
|
| 206 |
+
for i in range(ret.shape[0]):
|
| 207 |
+
ret[i, i] = vector[i]
|
| 208 |
+
return type(vector)(ret)
|
| 209 |
+
if vector.is_MatMul:
|
| 210 |
+
matrices = [arg for arg in vector.args if arg.is_Matrix]
|
| 211 |
+
scalars = [arg for arg in vector.args if arg not in matrices]
|
| 212 |
+
if scalars:
|
| 213 |
+
return Mul.fromiter(scalars)*DiagMatrix(MatMul.fromiter(matrices).doit()).doit()
|
| 214 |
+
if isinstance(vector, Transpose):
|
| 215 |
+
vector = vector.arg
|
| 216 |
+
return DiagMatrix(vector)
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
def diagonalize_vector(vector):
|
| 220 |
+
return DiagMatrix(vector).doit()
|
venv/lib/python3.10/site-packages/sympy/matrices/expressions/dotproduct.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.core import Basic, Expr
|
| 2 |
+
from sympy.core.sympify import _sympify
|
| 3 |
+
from sympy.matrices.expressions.transpose import transpose
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class DotProduct(Expr):
|
| 7 |
+
"""
|
| 8 |
+
Dot product of vector matrices
|
| 9 |
+
|
| 10 |
+
The input should be two 1 x n or n x 1 matrices. The output represents the
|
| 11 |
+
scalar dotproduct.
|
| 12 |
+
|
| 13 |
+
This is similar to using MatrixElement and MatMul, except DotProduct does
|
| 14 |
+
not require that one vector to be a row vector and the other vector to be
|
| 15 |
+
a column vector.
|
| 16 |
+
|
| 17 |
+
>>> from sympy import MatrixSymbol, DotProduct
|
| 18 |
+
>>> A = MatrixSymbol('A', 1, 3)
|
| 19 |
+
>>> B = MatrixSymbol('B', 1, 3)
|
| 20 |
+
>>> DotProduct(A, B)
|
| 21 |
+
DotProduct(A, B)
|
| 22 |
+
>>> DotProduct(A, B).doit()
|
| 23 |
+
A[0, 0]*B[0, 0] + A[0, 1]*B[0, 1] + A[0, 2]*B[0, 2]
|
| 24 |
+
"""
|
| 25 |
+
|
| 26 |
+
def __new__(cls, arg1, arg2):
|
| 27 |
+
arg1, arg2 = _sympify((arg1, arg2))
|
| 28 |
+
|
| 29 |
+
if not arg1.is_Matrix:
|
| 30 |
+
raise TypeError("Argument 1 of DotProduct is not a matrix")
|
| 31 |
+
if not arg2.is_Matrix:
|
| 32 |
+
raise TypeError("Argument 2 of DotProduct is not a matrix")
|
| 33 |
+
if not (1 in arg1.shape):
|
| 34 |
+
raise TypeError("Argument 1 of DotProduct is not a vector")
|
| 35 |
+
if not (1 in arg2.shape):
|
| 36 |
+
raise TypeError("Argument 2 of DotProduct is not a vector")
|
| 37 |
+
|
| 38 |
+
if set(arg1.shape) != set(arg2.shape):
|
| 39 |
+
raise TypeError("DotProduct arguments are not the same length")
|
| 40 |
+
|
| 41 |
+
return Basic.__new__(cls, arg1, arg2)
|
| 42 |
+
|
| 43 |
+
def doit(self, expand=False, **hints):
|
| 44 |
+
if self.args[0].shape == self.args[1].shape:
|
| 45 |
+
if self.args[0].shape[0] == 1:
|
| 46 |
+
mul = self.args[0]*transpose(self.args[1])
|
| 47 |
+
else:
|
| 48 |
+
mul = transpose(self.args[0])*self.args[1]
|
| 49 |
+
else:
|
| 50 |
+
if self.args[0].shape[0] == 1:
|
| 51 |
+
mul = self.args[0]*self.args[1]
|
| 52 |
+
else:
|
| 53 |
+
mul = transpose(self.args[0])*transpose(self.args[1])
|
| 54 |
+
|
| 55 |
+
return mul[0]
|
venv/lib/python3.10/site-packages/sympy/matrices/expressions/factorizations.py
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.matrices.expressions import MatrixExpr
|
| 2 |
+
from sympy.assumptions.ask import Q
|
| 3 |
+
|
| 4 |
+
class Factorization(MatrixExpr):
|
| 5 |
+
arg = property(lambda self: self.args[0])
|
| 6 |
+
shape = property(lambda self: self.arg.shape) # type: ignore
|
| 7 |
+
|
| 8 |
+
class LofLU(Factorization):
|
| 9 |
+
@property
|
| 10 |
+
def predicates(self):
|
| 11 |
+
return (Q.lower_triangular,)
|
| 12 |
+
class UofLU(Factorization):
|
| 13 |
+
@property
|
| 14 |
+
def predicates(self):
|
| 15 |
+
return (Q.upper_triangular,)
|
| 16 |
+
|
| 17 |
+
class LofCholesky(LofLU): pass
|
| 18 |
+
class UofCholesky(UofLU): pass
|
| 19 |
+
|
| 20 |
+
class QofQR(Factorization):
|
| 21 |
+
@property
|
| 22 |
+
def predicates(self):
|
| 23 |
+
return (Q.orthogonal,)
|
| 24 |
+
class RofQR(Factorization):
|
| 25 |
+
@property
|
| 26 |
+
def predicates(self):
|
| 27 |
+
return (Q.upper_triangular,)
|
| 28 |
+
|
| 29 |
+
class EigenVectors(Factorization):
|
| 30 |
+
@property
|
| 31 |
+
def predicates(self):
|
| 32 |
+
return (Q.orthogonal,)
|
| 33 |
+
class EigenValues(Factorization):
|
| 34 |
+
@property
|
| 35 |
+
def predicates(self):
|
| 36 |
+
return (Q.diagonal,)
|
| 37 |
+
|
| 38 |
+
class UofSVD(Factorization):
|
| 39 |
+
@property
|
| 40 |
+
def predicates(self):
|
| 41 |
+
return (Q.orthogonal,)
|
| 42 |
+
class SofSVD(Factorization):
|
| 43 |
+
@property
|
| 44 |
+
def predicates(self):
|
| 45 |
+
return (Q.diagonal,)
|
| 46 |
+
class VofSVD(Factorization):
|
| 47 |
+
@property
|
| 48 |
+
def predicates(self):
|
| 49 |
+
return (Q.orthogonal,)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def lu(expr):
|
| 53 |
+
return LofLU(expr), UofLU(expr)
|
| 54 |
+
|
| 55 |
+
def qr(expr):
|
| 56 |
+
return QofQR(expr), RofQR(expr)
|
| 57 |
+
|
| 58 |
+
def eig(expr):
|
| 59 |
+
return EigenValues(expr), EigenVectors(expr)
|
| 60 |
+
|
| 61 |
+
def svd(expr):
|
| 62 |
+
return UofSVD(expr), SofSVD(expr), VofSVD(expr)
|
venv/lib/python3.10/site-packages/sympy/matrices/expressions/fourier.py
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.core.sympify import _sympify
|
| 2 |
+
from sympy.matrices.expressions import MatrixExpr
|
| 3 |
+
from sympy.core.numbers import I
|
| 4 |
+
from sympy.core.singleton import S
|
| 5 |
+
from sympy.functions.elementary.exponential import exp
|
| 6 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class DFT(MatrixExpr):
|
| 10 |
+
r"""
|
| 11 |
+
Returns a discrete Fourier transform matrix. The matrix is scaled
|
| 12 |
+
with :math:`\frac{1}{\sqrt{n}}` so that it is unitary.
|
| 13 |
+
|
| 14 |
+
Parameters
|
| 15 |
+
==========
|
| 16 |
+
|
| 17 |
+
n : integer or Symbol
|
| 18 |
+
Size of the transform.
|
| 19 |
+
|
| 20 |
+
Examples
|
| 21 |
+
========
|
| 22 |
+
|
| 23 |
+
>>> from sympy.abc import n
|
| 24 |
+
>>> from sympy.matrices.expressions.fourier import DFT
|
| 25 |
+
>>> DFT(3)
|
| 26 |
+
DFT(3)
|
| 27 |
+
>>> DFT(3).as_explicit()
|
| 28 |
+
Matrix([
|
| 29 |
+
[sqrt(3)/3, sqrt(3)/3, sqrt(3)/3],
|
| 30 |
+
[sqrt(3)/3, sqrt(3)*exp(-2*I*pi/3)/3, sqrt(3)*exp(2*I*pi/3)/3],
|
| 31 |
+
[sqrt(3)/3, sqrt(3)*exp(2*I*pi/3)/3, sqrt(3)*exp(-2*I*pi/3)/3]])
|
| 32 |
+
>>> DFT(n).shape
|
| 33 |
+
(n, n)
|
| 34 |
+
|
| 35 |
+
References
|
| 36 |
+
==========
|
| 37 |
+
|
| 38 |
+
.. [1] https://en.wikipedia.org/wiki/DFT_matrix
|
| 39 |
+
|
| 40 |
+
"""
|
| 41 |
+
|
| 42 |
+
def __new__(cls, n):
|
| 43 |
+
n = _sympify(n)
|
| 44 |
+
cls._check_dim(n)
|
| 45 |
+
|
| 46 |
+
obj = super().__new__(cls, n)
|
| 47 |
+
return obj
|
| 48 |
+
|
| 49 |
+
n = property(lambda self: self.args[0]) # type: ignore
|
| 50 |
+
shape = property(lambda self: (self.n, self.n)) # type: ignore
|
| 51 |
+
|
| 52 |
+
def _entry(self, i, j, **kwargs):
|
| 53 |
+
w = exp(-2*S.Pi*I/self.n)
|
| 54 |
+
return w**(i*j) / sqrt(self.n)
|
| 55 |
+
|
| 56 |
+
def _eval_inverse(self):
|
| 57 |
+
return IDFT(self.n)
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
class IDFT(DFT):
|
| 61 |
+
r"""
|
| 62 |
+
Returns an inverse discrete Fourier transform matrix. The matrix is scaled
|
| 63 |
+
with :math:`\frac{1}{\sqrt{n}}` so that it is unitary.
|
| 64 |
+
|
| 65 |
+
Parameters
|
| 66 |
+
==========
|
| 67 |
+
|
| 68 |
+
n : integer or Symbol
|
| 69 |
+
Size of the transform
|
| 70 |
+
|
| 71 |
+
Examples
|
| 72 |
+
========
|
| 73 |
+
|
| 74 |
+
>>> from sympy.matrices.expressions.fourier import DFT, IDFT
|
| 75 |
+
>>> IDFT(3)
|
| 76 |
+
IDFT(3)
|
| 77 |
+
>>> IDFT(4)*DFT(4)
|
| 78 |
+
I
|
| 79 |
+
|
| 80 |
+
See Also
|
| 81 |
+
========
|
| 82 |
+
|
| 83 |
+
DFT
|
| 84 |
+
|
| 85 |
+
"""
|
| 86 |
+
def _entry(self, i, j, **kwargs):
|
| 87 |
+
w = exp(-2*S.Pi*I/self.n)
|
| 88 |
+
return w**(-i*j) / sqrt(self.n)
|
| 89 |
+
|
| 90 |
+
def _eval_inverse(self):
|
| 91 |
+
return DFT(self.n)
|
venv/lib/python3.10/site-packages/sympy/matrices/expressions/funcmatrix.py
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .matexpr import MatrixExpr
|
| 2 |
+
from sympy.core.function import FunctionClass, Lambda
|
| 3 |
+
from sympy.core.symbol import Dummy
|
| 4 |
+
from sympy.core.sympify import _sympify, sympify
|
| 5 |
+
from sympy.matrices import Matrix
|
| 6 |
+
from sympy.functions.elementary.complexes import re, im
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class FunctionMatrix(MatrixExpr):
|
| 10 |
+
"""Represents a matrix using a function (``Lambda``) which gives
|
| 11 |
+
outputs according to the coordinates of each matrix entries.
|
| 12 |
+
|
| 13 |
+
Parameters
|
| 14 |
+
==========
|
| 15 |
+
|
| 16 |
+
rows : nonnegative integer. Can be symbolic.
|
| 17 |
+
|
| 18 |
+
cols : nonnegative integer. Can be symbolic.
|
| 19 |
+
|
| 20 |
+
lamda : Function, Lambda or str
|
| 21 |
+
If it is a SymPy ``Function`` or ``Lambda`` instance,
|
| 22 |
+
it should be able to accept two arguments which represents the
|
| 23 |
+
matrix coordinates.
|
| 24 |
+
|
| 25 |
+
If it is a pure string containing Python ``lambda`` semantics,
|
| 26 |
+
it is interpreted by the SymPy parser and casted into a SymPy
|
| 27 |
+
``Lambda`` instance.
|
| 28 |
+
|
| 29 |
+
Examples
|
| 30 |
+
========
|
| 31 |
+
|
| 32 |
+
Creating a ``FunctionMatrix`` from ``Lambda``:
|
| 33 |
+
|
| 34 |
+
>>> from sympy import FunctionMatrix, symbols, Lambda, MatPow
|
| 35 |
+
>>> i, j, n, m = symbols('i,j,n,m')
|
| 36 |
+
>>> FunctionMatrix(n, m, Lambda((i, j), i + j))
|
| 37 |
+
FunctionMatrix(n, m, Lambda((i, j), i + j))
|
| 38 |
+
|
| 39 |
+
Creating a ``FunctionMatrix`` from a SymPy function:
|
| 40 |
+
|
| 41 |
+
>>> from sympy import KroneckerDelta
|
| 42 |
+
>>> X = FunctionMatrix(3, 3, KroneckerDelta)
|
| 43 |
+
>>> X.as_explicit()
|
| 44 |
+
Matrix([
|
| 45 |
+
[1, 0, 0],
|
| 46 |
+
[0, 1, 0],
|
| 47 |
+
[0, 0, 1]])
|
| 48 |
+
|
| 49 |
+
Creating a ``FunctionMatrix`` from a SymPy undefined function:
|
| 50 |
+
|
| 51 |
+
>>> from sympy import Function
|
| 52 |
+
>>> f = Function('f')
|
| 53 |
+
>>> X = FunctionMatrix(3, 3, f)
|
| 54 |
+
>>> X.as_explicit()
|
| 55 |
+
Matrix([
|
| 56 |
+
[f(0, 0), f(0, 1), f(0, 2)],
|
| 57 |
+
[f(1, 0), f(1, 1), f(1, 2)],
|
| 58 |
+
[f(2, 0), f(2, 1), f(2, 2)]])
|
| 59 |
+
|
| 60 |
+
Creating a ``FunctionMatrix`` from Python ``lambda``:
|
| 61 |
+
|
| 62 |
+
>>> FunctionMatrix(n, m, 'lambda i, j: i + j')
|
| 63 |
+
FunctionMatrix(n, m, Lambda((i, j), i + j))
|
| 64 |
+
|
| 65 |
+
Example of lazy evaluation of matrix product:
|
| 66 |
+
|
| 67 |
+
>>> Y = FunctionMatrix(1000, 1000, Lambda((i, j), i + j))
|
| 68 |
+
>>> isinstance(Y*Y, MatPow) # this is an expression object
|
| 69 |
+
True
|
| 70 |
+
>>> (Y**2)[10,10] # So this is evaluated lazily
|
| 71 |
+
342923500
|
| 72 |
+
|
| 73 |
+
Notes
|
| 74 |
+
=====
|
| 75 |
+
|
| 76 |
+
This class provides an alternative way to represent an extremely
|
| 77 |
+
dense matrix with entries in some form of a sequence, in a most
|
| 78 |
+
sparse way.
|
| 79 |
+
"""
|
| 80 |
+
def __new__(cls, rows, cols, lamda):
|
| 81 |
+
rows, cols = _sympify(rows), _sympify(cols)
|
| 82 |
+
cls._check_dim(rows)
|
| 83 |
+
cls._check_dim(cols)
|
| 84 |
+
|
| 85 |
+
lamda = sympify(lamda)
|
| 86 |
+
if not isinstance(lamda, (FunctionClass, Lambda)):
|
| 87 |
+
raise ValueError(
|
| 88 |
+
"{} should be compatible with SymPy function classes."
|
| 89 |
+
.format(lamda))
|
| 90 |
+
|
| 91 |
+
if 2 not in lamda.nargs:
|
| 92 |
+
raise ValueError(
|
| 93 |
+
'{} should be able to accept 2 arguments.'.format(lamda))
|
| 94 |
+
|
| 95 |
+
if not isinstance(lamda, Lambda):
|
| 96 |
+
i, j = Dummy('i'), Dummy('j')
|
| 97 |
+
lamda = Lambda((i, j), lamda(i, j))
|
| 98 |
+
|
| 99 |
+
return super().__new__(cls, rows, cols, lamda)
|
| 100 |
+
|
| 101 |
+
@property
|
| 102 |
+
def shape(self):
|
| 103 |
+
return self.args[0:2]
|
| 104 |
+
|
| 105 |
+
@property
|
| 106 |
+
def lamda(self):
|
| 107 |
+
return self.args[2]
|
| 108 |
+
|
| 109 |
+
def _entry(self, i, j, **kwargs):
|
| 110 |
+
return self.lamda(i, j)
|
| 111 |
+
|
| 112 |
+
def _eval_trace(self):
|
| 113 |
+
from sympy.matrices.expressions.trace import Trace
|
| 114 |
+
from sympy.concrete.summations import Sum
|
| 115 |
+
return Trace(self).rewrite(Sum).doit()
|
| 116 |
+
|
| 117 |
+
def _eval_as_real_imag(self):
|
| 118 |
+
return (re(Matrix(self)), im(Matrix(self)))
|
venv/lib/python3.10/site-packages/sympy/matrices/expressions/hadamard.py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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from collections import Counter
|
| 2 |
+
|
| 3 |
+
from sympy.core import Mul, sympify
|
| 4 |
+
from sympy.core.add import Add
|
| 5 |
+
from sympy.core.expr import ExprBuilder
|
| 6 |
+
from sympy.core.sorting import default_sort_key
|
| 7 |
+
from sympy.functions.elementary.exponential import log
|
| 8 |
+
from sympy.matrices.expressions.matexpr import MatrixExpr
|
| 9 |
+
from sympy.matrices.expressions._shape import validate_matadd_integer as validate
|
| 10 |
+
from sympy.matrices.expressions.special import ZeroMatrix, OneMatrix
|
| 11 |
+
from sympy.strategies import (
|
| 12 |
+
unpack, flatten, condition, exhaust, rm_id, sort
|
| 13 |
+
)
|
| 14 |
+
from sympy.utilities.exceptions import sympy_deprecation_warning
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def hadamard_product(*matrices):
|
| 18 |
+
"""
|
| 19 |
+
Return the elementwise (aka Hadamard) product of matrices.
|
| 20 |
+
|
| 21 |
+
Examples
|
| 22 |
+
========
|
| 23 |
+
|
| 24 |
+
>>> from sympy import hadamard_product, MatrixSymbol
|
| 25 |
+
>>> A = MatrixSymbol('A', 2, 3)
|
| 26 |
+
>>> B = MatrixSymbol('B', 2, 3)
|
| 27 |
+
>>> hadamard_product(A)
|
| 28 |
+
A
|
| 29 |
+
>>> hadamard_product(A, B)
|
| 30 |
+
HadamardProduct(A, B)
|
| 31 |
+
>>> hadamard_product(A, B)[0, 1]
|
| 32 |
+
A[0, 1]*B[0, 1]
|
| 33 |
+
"""
|
| 34 |
+
if not matrices:
|
| 35 |
+
raise TypeError("Empty Hadamard product is undefined")
|
| 36 |
+
if len(matrices) == 1:
|
| 37 |
+
return matrices[0]
|
| 38 |
+
return HadamardProduct(*matrices).doit()
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class HadamardProduct(MatrixExpr):
|
| 42 |
+
"""
|
| 43 |
+
Elementwise product of matrix expressions
|
| 44 |
+
|
| 45 |
+
Examples
|
| 46 |
+
========
|
| 47 |
+
|
| 48 |
+
Hadamard product for matrix symbols:
|
| 49 |
+
|
| 50 |
+
>>> from sympy import hadamard_product, HadamardProduct, MatrixSymbol
|
| 51 |
+
>>> A = MatrixSymbol('A', 5, 5)
|
| 52 |
+
>>> B = MatrixSymbol('B', 5, 5)
|
| 53 |
+
>>> isinstance(hadamard_product(A, B), HadamardProduct)
|
| 54 |
+
True
|
| 55 |
+
|
| 56 |
+
Notes
|
| 57 |
+
=====
|
| 58 |
+
|
| 59 |
+
This is a symbolic object that simply stores its argument without
|
| 60 |
+
evaluating it. To actually compute the product, use the function
|
| 61 |
+
``hadamard_product()`` or ``HadamardProduct.doit``
|
| 62 |
+
"""
|
| 63 |
+
is_HadamardProduct = True
|
| 64 |
+
|
| 65 |
+
def __new__(cls, *args, evaluate=False, check=None):
|
| 66 |
+
args = list(map(sympify, args))
|
| 67 |
+
if len(args) == 0:
|
| 68 |
+
# We currently don't have a way to support one-matrices of generic dimensions:
|
| 69 |
+
raise ValueError("HadamardProduct needs at least one argument")
|
| 70 |
+
|
| 71 |
+
if not all(isinstance(arg, MatrixExpr) for arg in args):
|
| 72 |
+
raise TypeError("Mix of Matrix and Scalar symbols")
|
| 73 |
+
|
| 74 |
+
if check is not None:
|
| 75 |
+
sympy_deprecation_warning(
|
| 76 |
+
"Passing check to HadamardProduct is deprecated and the check argument will be removed in a future version.",
|
| 77 |
+
deprecated_since_version="1.11",
|
| 78 |
+
active_deprecations_target='remove-check-argument-from-matrix-operations')
|
| 79 |
+
|
| 80 |
+
if check is not False:
|
| 81 |
+
validate(*args)
|
| 82 |
+
|
| 83 |
+
obj = super().__new__(cls, *args)
|
| 84 |
+
if evaluate:
|
| 85 |
+
obj = obj.doit(deep=False)
|
| 86 |
+
return obj
|
| 87 |
+
|
| 88 |
+
@property
|
| 89 |
+
def shape(self):
|
| 90 |
+
return self.args[0].shape
|
| 91 |
+
|
| 92 |
+
def _entry(self, i, j, **kwargs):
|
| 93 |
+
return Mul(*[arg._entry(i, j, **kwargs) for arg in self.args])
|
| 94 |
+
|
| 95 |
+
def _eval_transpose(self):
|
| 96 |
+
from sympy.matrices.expressions.transpose import transpose
|
| 97 |
+
return HadamardProduct(*list(map(transpose, self.args)))
|
| 98 |
+
|
| 99 |
+
def doit(self, **hints):
|
| 100 |
+
expr = self.func(*(i.doit(**hints) for i in self.args))
|
| 101 |
+
# Check for explicit matrices:
|
| 102 |
+
from sympy.matrices.matrices import MatrixBase
|
| 103 |
+
from sympy.matrices.immutable import ImmutableMatrix
|
| 104 |
+
|
| 105 |
+
explicit = [i for i in expr.args if isinstance(i, MatrixBase)]
|
| 106 |
+
if explicit:
|
| 107 |
+
remainder = [i for i in expr.args if i not in explicit]
|
| 108 |
+
expl_mat = ImmutableMatrix([
|
| 109 |
+
Mul.fromiter(i) for i in zip(*explicit)
|
| 110 |
+
]).reshape(*self.shape)
|
| 111 |
+
expr = HadamardProduct(*([expl_mat] + remainder))
|
| 112 |
+
|
| 113 |
+
return canonicalize(expr)
|
| 114 |
+
|
| 115 |
+
def _eval_derivative(self, x):
|
| 116 |
+
terms = []
|
| 117 |
+
args = list(self.args)
|
| 118 |
+
for i in range(len(args)):
|
| 119 |
+
factors = args[:i] + [args[i].diff(x)] + args[i+1:]
|
| 120 |
+
terms.append(hadamard_product(*factors))
|
| 121 |
+
return Add.fromiter(terms)
|
| 122 |
+
|
| 123 |
+
def _eval_derivative_matrix_lines(self, x):
|
| 124 |
+
from sympy.tensor.array.expressions.array_expressions import ArrayDiagonal
|
| 125 |
+
from sympy.tensor.array.expressions.array_expressions import ArrayTensorProduct
|
| 126 |
+
from sympy.matrices.expressions.matexpr import _make_matrix
|
| 127 |
+
|
| 128 |
+
with_x_ind = [i for i, arg in enumerate(self.args) if arg.has(x)]
|
| 129 |
+
lines = []
|
| 130 |
+
for ind in with_x_ind:
|
| 131 |
+
left_args = self.args[:ind]
|
| 132 |
+
right_args = self.args[ind+1:]
|
| 133 |
+
|
| 134 |
+
d = self.args[ind]._eval_derivative_matrix_lines(x)
|
| 135 |
+
hadam = hadamard_product(*(right_args + left_args))
|
| 136 |
+
diagonal = [(0, 2), (3, 4)]
|
| 137 |
+
diagonal = [e for j, e in enumerate(diagonal) if self.shape[j] != 1]
|
| 138 |
+
for i in d:
|
| 139 |
+
l1 = i._lines[i._first_line_index]
|
| 140 |
+
l2 = i._lines[i._second_line_index]
|
| 141 |
+
subexpr = ExprBuilder(
|
| 142 |
+
ArrayDiagonal,
|
| 143 |
+
[
|
| 144 |
+
ExprBuilder(
|
| 145 |
+
ArrayTensorProduct,
|
| 146 |
+
[
|
| 147 |
+
ExprBuilder(_make_matrix, [l1]),
|
| 148 |
+
hadam,
|
| 149 |
+
ExprBuilder(_make_matrix, [l2]),
|
| 150 |
+
]
|
| 151 |
+
),
|
| 152 |
+
*diagonal],
|
| 153 |
+
|
| 154 |
+
)
|
| 155 |
+
i._first_pointer_parent = subexpr.args[0].args[0].args
|
| 156 |
+
i._first_pointer_index = 0
|
| 157 |
+
i._second_pointer_parent = subexpr.args[0].args[2].args
|
| 158 |
+
i._second_pointer_index = 0
|
| 159 |
+
i._lines = [subexpr]
|
| 160 |
+
lines.append(i)
|
| 161 |
+
|
| 162 |
+
return lines
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
# TODO Implement algorithm for rewriting Hadamard product as diagonal matrix
|
| 166 |
+
# if matmul identy matrix is multiplied.
|
| 167 |
+
def canonicalize(x):
|
| 168 |
+
"""Canonicalize the Hadamard product ``x`` with mathematical properties.
|
| 169 |
+
|
| 170 |
+
Examples
|
| 171 |
+
========
|
| 172 |
+
|
| 173 |
+
>>> from sympy import MatrixSymbol, HadamardProduct
|
| 174 |
+
>>> from sympy import OneMatrix, ZeroMatrix
|
| 175 |
+
>>> from sympy.matrices.expressions.hadamard import canonicalize
|
| 176 |
+
>>> from sympy import init_printing
|
| 177 |
+
>>> init_printing(use_unicode=False)
|
| 178 |
+
|
| 179 |
+
>>> A = MatrixSymbol('A', 2, 2)
|
| 180 |
+
>>> B = MatrixSymbol('B', 2, 2)
|
| 181 |
+
>>> C = MatrixSymbol('C', 2, 2)
|
| 182 |
+
|
| 183 |
+
Hadamard product associativity:
|
| 184 |
+
|
| 185 |
+
>>> X = HadamardProduct(A, HadamardProduct(B, C))
|
| 186 |
+
>>> X
|
| 187 |
+
A.*(B.*C)
|
| 188 |
+
>>> canonicalize(X)
|
| 189 |
+
A.*B.*C
|
| 190 |
+
|
| 191 |
+
Hadamard product commutativity:
|
| 192 |
+
|
| 193 |
+
>>> X = HadamardProduct(A, B)
|
| 194 |
+
>>> Y = HadamardProduct(B, A)
|
| 195 |
+
>>> X
|
| 196 |
+
A.*B
|
| 197 |
+
>>> Y
|
| 198 |
+
B.*A
|
| 199 |
+
>>> canonicalize(X)
|
| 200 |
+
A.*B
|
| 201 |
+
>>> canonicalize(Y)
|
| 202 |
+
A.*B
|
| 203 |
+
|
| 204 |
+
Hadamard product identity:
|
| 205 |
+
|
| 206 |
+
>>> X = HadamardProduct(A, OneMatrix(2, 2))
|
| 207 |
+
>>> X
|
| 208 |
+
A.*1
|
| 209 |
+
>>> canonicalize(X)
|
| 210 |
+
A
|
| 211 |
+
|
| 212 |
+
Absorbing element of Hadamard product:
|
| 213 |
+
|
| 214 |
+
>>> X = HadamardProduct(A, ZeroMatrix(2, 2))
|
| 215 |
+
>>> X
|
| 216 |
+
A.*0
|
| 217 |
+
>>> canonicalize(X)
|
| 218 |
+
0
|
| 219 |
+
|
| 220 |
+
Rewriting to Hadamard Power
|
| 221 |
+
|
| 222 |
+
>>> X = HadamardProduct(A, A, A)
|
| 223 |
+
>>> X
|
| 224 |
+
A.*A.*A
|
| 225 |
+
>>> canonicalize(X)
|
| 226 |
+
.3
|
| 227 |
+
A
|
| 228 |
+
|
| 229 |
+
Notes
|
| 230 |
+
=====
|
| 231 |
+
|
| 232 |
+
As the Hadamard product is associative, nested products can be flattened.
|
| 233 |
+
|
| 234 |
+
The Hadamard product is commutative so that factors can be sorted for
|
| 235 |
+
canonical form.
|
| 236 |
+
|
| 237 |
+
A matrix of only ones is an identity for Hadamard product,
|
| 238 |
+
so every matrices of only ones can be removed.
|
| 239 |
+
|
| 240 |
+
Any zero matrix will make the whole product a zero matrix.
|
| 241 |
+
|
| 242 |
+
Duplicate elements can be collected and rewritten as HadamardPower
|
| 243 |
+
|
| 244 |
+
References
|
| 245 |
+
==========
|
| 246 |
+
|
| 247 |
+
.. [1] https://en.wikipedia.org/wiki/Hadamard_product_(matrices)
|
| 248 |
+
"""
|
| 249 |
+
# Associativity
|
| 250 |
+
rule = condition(
|
| 251 |
+
lambda x: isinstance(x, HadamardProduct),
|
| 252 |
+
flatten
|
| 253 |
+
)
|
| 254 |
+
fun = exhaust(rule)
|
| 255 |
+
x = fun(x)
|
| 256 |
+
|
| 257 |
+
# Identity
|
| 258 |
+
fun = condition(
|
| 259 |
+
lambda x: isinstance(x, HadamardProduct),
|
| 260 |
+
rm_id(lambda x: isinstance(x, OneMatrix))
|
| 261 |
+
)
|
| 262 |
+
x = fun(x)
|
| 263 |
+
|
| 264 |
+
# Absorbing by Zero Matrix
|
| 265 |
+
def absorb(x):
|
| 266 |
+
if any(isinstance(c, ZeroMatrix) for c in x.args):
|
| 267 |
+
return ZeroMatrix(*x.shape)
|
| 268 |
+
else:
|
| 269 |
+
return x
|
| 270 |
+
fun = condition(
|
| 271 |
+
lambda x: isinstance(x, HadamardProduct),
|
| 272 |
+
absorb
|
| 273 |
+
)
|
| 274 |
+
x = fun(x)
|
| 275 |
+
|
| 276 |
+
# Rewriting with HadamardPower
|
| 277 |
+
if isinstance(x, HadamardProduct):
|
| 278 |
+
tally = Counter(x.args)
|
| 279 |
+
|
| 280 |
+
new_arg = []
|
| 281 |
+
for base, exp in tally.items():
|
| 282 |
+
if exp == 1:
|
| 283 |
+
new_arg.append(base)
|
| 284 |
+
else:
|
| 285 |
+
new_arg.append(HadamardPower(base, exp))
|
| 286 |
+
|
| 287 |
+
x = HadamardProduct(*new_arg)
|
| 288 |
+
|
| 289 |
+
# Commutativity
|
| 290 |
+
fun = condition(
|
| 291 |
+
lambda x: isinstance(x, HadamardProduct),
|
| 292 |
+
sort(default_sort_key)
|
| 293 |
+
)
|
| 294 |
+
x = fun(x)
|
| 295 |
+
|
| 296 |
+
# Unpacking
|
| 297 |
+
x = unpack(x)
|
| 298 |
+
return x
|
| 299 |
+
|
| 300 |
+
|
| 301 |
+
def hadamard_power(base, exp):
|
| 302 |
+
base = sympify(base)
|
| 303 |
+
exp = sympify(exp)
|
| 304 |
+
if exp == 1:
|
| 305 |
+
return base
|
| 306 |
+
if not base.is_Matrix:
|
| 307 |
+
return base**exp
|
| 308 |
+
if exp.is_Matrix:
|
| 309 |
+
raise ValueError("cannot raise expression to a matrix")
|
| 310 |
+
return HadamardPower(base, exp)
|
| 311 |
+
|
| 312 |
+
|
| 313 |
+
class HadamardPower(MatrixExpr):
|
| 314 |
+
r"""
|
| 315 |
+
Elementwise power of matrix expressions
|
| 316 |
+
|
| 317 |
+
Parameters
|
| 318 |
+
==========
|
| 319 |
+
|
| 320 |
+
base : scalar or matrix
|
| 321 |
+
|
| 322 |
+
exp : scalar or matrix
|
| 323 |
+
|
| 324 |
+
Notes
|
| 325 |
+
=====
|
| 326 |
+
|
| 327 |
+
There are four definitions for the hadamard power which can be used.
|
| 328 |
+
Let's consider `A, B` as `(m, n)` matrices, and `a, b` as scalars.
|
| 329 |
+
|
| 330 |
+
Matrix raised to a scalar exponent:
|
| 331 |
+
|
| 332 |
+
.. math::
|
| 333 |
+
A^{\circ b} = \begin{bmatrix}
|
| 334 |
+
A_{0, 0}^b & A_{0, 1}^b & \cdots & A_{0, n-1}^b \\
|
| 335 |
+
A_{1, 0}^b & A_{1, 1}^b & \cdots & A_{1, n-1}^b \\
|
| 336 |
+
\vdots & \vdots & \ddots & \vdots \\
|
| 337 |
+
A_{m-1, 0}^b & A_{m-1, 1}^b & \cdots & A_{m-1, n-1}^b
|
| 338 |
+
\end{bmatrix}
|
| 339 |
+
|
| 340 |
+
Scalar raised to a matrix exponent:
|
| 341 |
+
|
| 342 |
+
.. math::
|
| 343 |
+
a^{\circ B} = \begin{bmatrix}
|
| 344 |
+
a^{B_{0, 0}} & a^{B_{0, 1}} & \cdots & a^{B_{0, n-1}} \\
|
| 345 |
+
a^{B_{1, 0}} & a^{B_{1, 1}} & \cdots & a^{B_{1, n-1}} \\
|
| 346 |
+
\vdots & \vdots & \ddots & \vdots \\
|
| 347 |
+
a^{B_{m-1, 0}} & a^{B_{m-1, 1}} & \cdots & a^{B_{m-1, n-1}}
|
| 348 |
+
\end{bmatrix}
|
| 349 |
+
|
| 350 |
+
Matrix raised to a matrix exponent:
|
| 351 |
+
|
| 352 |
+
.. math::
|
| 353 |
+
A^{\circ B} = \begin{bmatrix}
|
| 354 |
+
A_{0, 0}^{B_{0, 0}} & A_{0, 1}^{B_{0, 1}} &
|
| 355 |
+
\cdots & A_{0, n-1}^{B_{0, n-1}} \\
|
| 356 |
+
A_{1, 0}^{B_{1, 0}} & A_{1, 1}^{B_{1, 1}} &
|
| 357 |
+
\cdots & A_{1, n-1}^{B_{1, n-1}} \\
|
| 358 |
+
\vdots & \vdots &
|
| 359 |
+
\ddots & \vdots \\
|
| 360 |
+
A_{m-1, 0}^{B_{m-1, 0}} & A_{m-1, 1}^{B_{m-1, 1}} &
|
| 361 |
+
\cdots & A_{m-1, n-1}^{B_{m-1, n-1}}
|
| 362 |
+
\end{bmatrix}
|
| 363 |
+
|
| 364 |
+
Scalar raised to a scalar exponent:
|
| 365 |
+
|
| 366 |
+
.. math::
|
| 367 |
+
a^{\circ b} = a^b
|
| 368 |
+
"""
|
| 369 |
+
|
| 370 |
+
def __new__(cls, base, exp):
|
| 371 |
+
base = sympify(base)
|
| 372 |
+
exp = sympify(exp)
|
| 373 |
+
|
| 374 |
+
if base.is_scalar and exp.is_scalar:
|
| 375 |
+
return base ** exp
|
| 376 |
+
|
| 377 |
+
if isinstance(base, MatrixExpr) and isinstance(exp, MatrixExpr):
|
| 378 |
+
validate(base, exp)
|
| 379 |
+
|
| 380 |
+
obj = super().__new__(cls, base, exp)
|
| 381 |
+
return obj
|
| 382 |
+
|
| 383 |
+
@property
|
| 384 |
+
def base(self):
|
| 385 |
+
return self._args[0]
|
| 386 |
+
|
| 387 |
+
@property
|
| 388 |
+
def exp(self):
|
| 389 |
+
return self._args[1]
|
| 390 |
+
|
| 391 |
+
@property
|
| 392 |
+
def shape(self):
|
| 393 |
+
if self.base.is_Matrix:
|
| 394 |
+
return self.base.shape
|
| 395 |
+
return self.exp.shape
|
| 396 |
+
|
| 397 |
+
def _entry(self, i, j, **kwargs):
|
| 398 |
+
base = self.base
|
| 399 |
+
exp = self.exp
|
| 400 |
+
|
| 401 |
+
if base.is_Matrix:
|
| 402 |
+
a = base._entry(i, j, **kwargs)
|
| 403 |
+
elif base.is_scalar:
|
| 404 |
+
a = base
|
| 405 |
+
else:
|
| 406 |
+
raise ValueError(
|
| 407 |
+
'The base {} must be a scalar or a matrix.'.format(base))
|
| 408 |
+
|
| 409 |
+
if exp.is_Matrix:
|
| 410 |
+
b = exp._entry(i, j, **kwargs)
|
| 411 |
+
elif exp.is_scalar:
|
| 412 |
+
b = exp
|
| 413 |
+
else:
|
| 414 |
+
raise ValueError(
|
| 415 |
+
'The exponent {} must be a scalar or a matrix.'.format(exp))
|
| 416 |
+
|
| 417 |
+
return a ** b
|
| 418 |
+
|
| 419 |
+
def _eval_transpose(self):
|
| 420 |
+
from sympy.matrices.expressions.transpose import transpose
|
| 421 |
+
return HadamardPower(transpose(self.base), self.exp)
|
| 422 |
+
|
| 423 |
+
def _eval_derivative(self, x):
|
| 424 |
+
dexp = self.exp.diff(x)
|
| 425 |
+
logbase = self.base.applyfunc(log)
|
| 426 |
+
dlbase = logbase.diff(x)
|
| 427 |
+
return hadamard_product(
|
| 428 |
+
dexp*logbase + self.exp*dlbase,
|
| 429 |
+
self
|
| 430 |
+
)
|
| 431 |
+
|
| 432 |
+
def _eval_derivative_matrix_lines(self, x):
|
| 433 |
+
from sympy.tensor.array.expressions.array_expressions import ArrayTensorProduct
|
| 434 |
+
from sympy.tensor.array.expressions.array_expressions import ArrayDiagonal
|
| 435 |
+
from sympy.matrices.expressions.matexpr import _make_matrix
|
| 436 |
+
|
| 437 |
+
lr = self.base._eval_derivative_matrix_lines(x)
|
| 438 |
+
for i in lr:
|
| 439 |
+
diagonal = [(1, 2), (3, 4)]
|
| 440 |
+
diagonal = [e for j, e in enumerate(diagonal) if self.base.shape[j] != 1]
|
| 441 |
+
l1 = i._lines[i._first_line_index]
|
| 442 |
+
l2 = i._lines[i._second_line_index]
|
| 443 |
+
subexpr = ExprBuilder(
|
| 444 |
+
ArrayDiagonal,
|
| 445 |
+
[
|
| 446 |
+
ExprBuilder(
|
| 447 |
+
ArrayTensorProduct,
|
| 448 |
+
[
|
| 449 |
+
ExprBuilder(_make_matrix, [l1]),
|
| 450 |
+
self.exp*hadamard_power(self.base, self.exp-1),
|
| 451 |
+
ExprBuilder(_make_matrix, [l2]),
|
| 452 |
+
]
|
| 453 |
+
),
|
| 454 |
+
*diagonal],
|
| 455 |
+
validator=ArrayDiagonal._validate
|
| 456 |
+
)
|
| 457 |
+
i._first_pointer_parent = subexpr.args[0].args[0].args
|
| 458 |
+
i._first_pointer_index = 0
|
| 459 |
+
i._first_line_index = 0
|
| 460 |
+
i._second_pointer_parent = subexpr.args[0].args[2].args
|
| 461 |
+
i._second_pointer_index = 0
|
| 462 |
+
i._second_line_index = 0
|
| 463 |
+
i._lines = [subexpr]
|
| 464 |
+
return lr
|