Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- llmeval-env/lib/python3.10/site-packages/sympy/matrices/__init__.py +71 -0
- llmeval-env/lib/python3.10/site-packages/sympy/matrices/benchmarks/__init__.py +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/matrices/benchmarks/__pycache__/__init__.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/matrices/benchmarks/__pycache__/bench_matrix.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/matrices/benchmarks/bench_matrix.py +21 -0
- llmeval-env/lib/python3.10/site-packages/sympy/matrices/common.py +3227 -0
- llmeval-env/lib/python3.10/site-packages/sympy/matrices/decompositions.py +1629 -0
- llmeval-env/lib/python3.10/site-packages/sympy/matrices/dense.py +1090 -0
- llmeval-env/lib/python3.10/site-packages/sympy/matrices/expressions/__init__.py +62 -0
- llmeval-env/lib/python3.10/site-packages/sympy/matrices/expressions/_shape.py +102 -0
- llmeval-env/lib/python3.10/site-packages/sympy/matrices/expressions/adjoint.py +61 -0
- llmeval-env/lib/python3.10/site-packages/sympy/matrices/expressions/applyfunc.py +204 -0
- llmeval-env/lib/python3.10/site-packages/sympy/matrices/expressions/blockmatrix.py +979 -0
- llmeval-env/lib/python3.10/site-packages/sympy/matrices/expressions/companion.py +56 -0
- llmeval-env/lib/python3.10/site-packages/sympy/matrices/expressions/determinant.py +141 -0
- llmeval-env/lib/python3.10/site-packages/sympy/matrices/expressions/diagonal.py +220 -0
- llmeval-env/lib/python3.10/site-packages/sympy/matrices/expressions/dotproduct.py +55 -0
- llmeval-env/lib/python3.10/site-packages/sympy/matrices/expressions/factorizations.py +62 -0
- llmeval-env/lib/python3.10/site-packages/sympy/matrices/expressions/fourier.py +91 -0
- llmeval-env/lib/python3.10/site-packages/sympy/matrices/expressions/funcmatrix.py +118 -0
- llmeval-env/lib/python3.10/site-packages/sympy/matrices/expressions/hadamard.py +464 -0
- llmeval-env/lib/python3.10/site-packages/sympy/matrices/expressions/inverse.py +103 -0
- llmeval-env/lib/python3.10/site-packages/sympy/matrices/expressions/matadd.py +155 -0
- llmeval-env/lib/python3.10/site-packages/sympy/matrices/expressions/matexpr.py +885 -0
- llmeval-env/lib/python3.10/site-packages/sympy/matrices/expressions/matmul.py +498 -0
- llmeval-env/lib/python3.10/site-packages/sympy/matrices/expressions/matpow.py +142 -0
- llmeval-env/lib/python3.10/site-packages/sympy/matrices/expressions/permutation.py +303 -0
- llmeval-env/lib/python3.10/site-packages/sympy/matrices/expressions/sets.py +67 -0
- llmeval-env/lib/python3.10/site-packages/sympy/matrices/expressions/slice.py +114 -0
- llmeval-env/lib/python3.10/site-packages/sympy/matrices/expressions/special.py +299 -0
- llmeval-env/lib/python3.10/site-packages/sympy/matrices/expressions/tests/__init__.py +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/matrices/expressions/tests/test_adjoint.py +34 -0
- llmeval-env/lib/python3.10/site-packages/sympy/matrices/expressions/tests/test_applyfunc.py +118 -0
- llmeval-env/lib/python3.10/site-packages/sympy/matrices/expressions/tests/test_blockmatrix.py +445 -0
- llmeval-env/lib/python3.10/site-packages/sympy/matrices/expressions/tests/test_companion.py +48 -0
- llmeval-env/lib/python3.10/site-packages/sympy/matrices/expressions/tests/test_derivatives.py +477 -0
- llmeval-env/lib/python3.10/site-packages/sympy/matrices/expressions/tests/test_determinant.py +62 -0
- llmeval-env/lib/python3.10/site-packages/sympy/matrices/expressions/tests/test_diagonal.py +156 -0
- llmeval-env/lib/python3.10/site-packages/sympy/matrices/expressions/tests/test_dotproduct.py +35 -0
- llmeval-env/lib/python3.10/site-packages/sympy/matrices/expressions/tests/test_factorizations.py +29 -0
- llmeval-env/lib/python3.10/site-packages/sympy/matrices/expressions/tests/test_fourier.py +44 -0
- llmeval-env/lib/python3.10/site-packages/sympy/matrices/expressions/tests/test_funcmatrix.py +56 -0
- llmeval-env/lib/python3.10/site-packages/sympy/matrices/expressions/tests/test_hadamard.py +141 -0
- llmeval-env/lib/python3.10/site-packages/sympy/matrices/expressions/tests/test_indexing.py +299 -0
- llmeval-env/lib/python3.10/site-packages/sympy/matrices/expressions/tests/test_inverse.py +62 -0
- llmeval-env/lib/python3.10/site-packages/sympy/matrices/expressions/tests/test_kronecker.py +150 -0
- llmeval-env/lib/python3.10/site-packages/sympy/matrices/expressions/tests/test_matadd.py +58 -0
- llmeval-env/lib/python3.10/site-packages/sympy/matrices/expressions/tests/test_matexpr.py +567 -0
- llmeval-env/lib/python3.10/site-packages/sympy/matrices/expressions/tests/test_matmul.py +186 -0
- llmeval-env/lib/python3.10/site-packages/sympy/matrices/expressions/tests/test_matpow.py +217 -0
llmeval-env/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 |
+
'dotprodsimp',
|
71 |
+
]
|
llmeval-env/lib/python3.10/site-packages/sympy/matrices/benchmarks/__init__.py
ADDED
File without changes
|
llmeval-env/lib/python3.10/site-packages/sympy/matrices/benchmarks/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (198 Bytes). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/matrices/benchmarks/__pycache__/bench_matrix.cpython-310.pyc
ADDED
Binary file (906 Bytes). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/matrices/benchmarks/bench_matrix.py
ADDED
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.core.numbers import Integer
|
2 |
+
from sympy.matrices.dense import (eye, zeros)
|
3 |
+
|
4 |
+
i3 = Integer(3)
|
5 |
+
M = eye(100)
|
6 |
+
|
7 |
+
|
8 |
+
def timeit_Matrix__getitem_ii():
|
9 |
+
M[3, 3]
|
10 |
+
|
11 |
+
|
12 |
+
def timeit_Matrix__getitem_II():
|
13 |
+
M[i3, i3]
|
14 |
+
|
15 |
+
|
16 |
+
def timeit_Matrix__getslice():
|
17 |
+
M[:, :]
|
18 |
+
|
19 |
+
|
20 |
+
def timeit_Matrix_zeronm():
|
21 |
+
zeros(100, 100)
|
llmeval-env/lib/python3.10/site-packages/sympy/matrices/common.py
ADDED
@@ -0,0 +1,3227 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
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__))
|
llmeval-env/lib/python3.10/site-packages/sympy/matrices/decompositions.py
ADDED
@@ -0,0 +1,1629 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
|
llmeval-env/lib/python3.10/site-packages/sympy/matrices/dense.py
ADDED
@@ -0,0 +1,1090 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import random
|
2 |
+
|
3 |
+
from sympy.core.basic import Basic
|
4 |
+
from sympy.core.singleton import S
|
5 |
+
from sympy.core.symbol import Symbol
|
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)
|
llmeval-env/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 |
+
]
|
llmeval-env/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)
|
llmeval-env/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)
|
llmeval-env/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())
|
llmeval-env/lib/python3.10/site-packages/sympy/matrices/expressions/blockmatrix.py
ADDED
@@ -0,0 +1,979 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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])
|
llmeval-env/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])
|
llmeval-env/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
|
llmeval-env/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()
|
llmeval-env/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]
|
llmeval-env/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)
|
llmeval-env/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)
|
llmeval-env/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)))
|
llmeval-env/lib/python3.10/site-packages/sympy/matrices/expressions/hadamard.py
ADDED
@@ -0,0 +1,464 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
|
llmeval-env/lib/python3.10/site-packages/sympy/matrices/expressions/inverse.py
ADDED
@@ -0,0 +1,103 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.core.sympify import _sympify
|
2 |
+
from sympy.core import S, Basic
|
3 |
+
|
4 |
+
from sympy.matrices.common import NonSquareMatrixError
|
5 |
+
from sympy.matrices.expressions.matpow import MatPow
|
6 |
+
|
7 |
+
|
8 |
+
class Inverse(MatPow):
|
9 |
+
"""
|
10 |
+
The multiplicative inverse of a matrix expression
|
11 |
+
|
12 |
+
This is a symbolic object that simply stores its argument without
|
13 |
+
evaluating it. To actually compute the inverse, use the ``.inverse()``
|
14 |
+
method of matrices.
|
15 |
+
|
16 |
+
Examples
|
17 |
+
========
|
18 |
+
|
19 |
+
>>> from sympy import MatrixSymbol, Inverse
|
20 |
+
>>> A = MatrixSymbol('A', 3, 3)
|
21 |
+
>>> B = MatrixSymbol('B', 3, 3)
|
22 |
+
>>> Inverse(A)
|
23 |
+
A**(-1)
|
24 |
+
>>> A.inverse() == Inverse(A)
|
25 |
+
True
|
26 |
+
>>> (A*B).inverse()
|
27 |
+
B**(-1)*A**(-1)
|
28 |
+
>>> Inverse(A*B)
|
29 |
+
(A*B)**(-1)
|
30 |
+
|
31 |
+
"""
|
32 |
+
is_Inverse = True
|
33 |
+
exp = S.NegativeOne
|
34 |
+
|
35 |
+
def __new__(cls, mat, exp=S.NegativeOne):
|
36 |
+
# exp is there to make it consistent with
|
37 |
+
# inverse.func(*inverse.args) == inverse
|
38 |
+
mat = _sympify(mat)
|
39 |
+
exp = _sympify(exp)
|
40 |
+
if not mat.is_Matrix:
|
41 |
+
raise TypeError("mat should be a matrix")
|
42 |
+
if mat.is_square is False:
|
43 |
+
raise NonSquareMatrixError("Inverse of non-square matrix %s" % mat)
|
44 |
+
return Basic.__new__(cls, mat, exp)
|
45 |
+
|
46 |
+
@property
|
47 |
+
def arg(self):
|
48 |
+
return self.args[0]
|
49 |
+
|
50 |
+
@property
|
51 |
+
def shape(self):
|
52 |
+
return self.arg.shape
|
53 |
+
|
54 |
+
def _eval_inverse(self):
|
55 |
+
return self.arg
|
56 |
+
|
57 |
+
def _eval_determinant(self):
|
58 |
+
from sympy.matrices.expressions.determinant import det
|
59 |
+
return 1/det(self.arg)
|
60 |
+
|
61 |
+
def doit(self, **hints):
|
62 |
+
if 'inv_expand' in hints and hints['inv_expand'] == False:
|
63 |
+
return self
|
64 |
+
|
65 |
+
arg = self.arg
|
66 |
+
if hints.get('deep', True):
|
67 |
+
arg = arg.doit(**hints)
|
68 |
+
|
69 |
+
return arg.inverse()
|
70 |
+
|
71 |
+
def _eval_derivative_matrix_lines(self, x):
|
72 |
+
arg = self.args[0]
|
73 |
+
lines = arg._eval_derivative_matrix_lines(x)
|
74 |
+
for line in lines:
|
75 |
+
line.first_pointer *= -self.T
|
76 |
+
line.second_pointer *= self
|
77 |
+
return lines
|
78 |
+
|
79 |
+
|
80 |
+
from sympy.assumptions.ask import ask, Q
|
81 |
+
from sympy.assumptions.refine import handlers_dict
|
82 |
+
|
83 |
+
|
84 |
+
def refine_Inverse(expr, assumptions):
|
85 |
+
"""
|
86 |
+
>>> from sympy import MatrixSymbol, Q, assuming, refine
|
87 |
+
>>> X = MatrixSymbol('X', 2, 2)
|
88 |
+
>>> X.I
|
89 |
+
X**(-1)
|
90 |
+
>>> with assuming(Q.orthogonal(X)):
|
91 |
+
... print(refine(X.I))
|
92 |
+
X.T
|
93 |
+
"""
|
94 |
+
if ask(Q.orthogonal(expr), assumptions):
|
95 |
+
return expr.arg.T
|
96 |
+
elif ask(Q.unitary(expr), assumptions):
|
97 |
+
return expr.arg.conjugate()
|
98 |
+
elif ask(Q.singular(expr), assumptions):
|
99 |
+
raise ValueError("Inverse of singular matrix %s" % expr.arg)
|
100 |
+
|
101 |
+
return expr
|
102 |
+
|
103 |
+
handlers_dict['Inverse'] = refine_Inverse
|
llmeval-env/lib/python3.10/site-packages/sympy/matrices/expressions/matadd.py
ADDED
@@ -0,0 +1,155 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from functools import reduce
|
2 |
+
import operator
|
3 |
+
|
4 |
+
from sympy.core import Basic, sympify
|
5 |
+
from sympy.core.add import add, Add, _could_extract_minus_sign
|
6 |
+
from sympy.core.sorting import default_sort_key
|
7 |
+
from sympy.functions import adjoint
|
8 |
+
from sympy.matrices.matrices import MatrixBase
|
9 |
+
from sympy.matrices.expressions.transpose import transpose
|
10 |
+
from sympy.strategies import (rm_id, unpack, flatten, sort, condition,
|
11 |
+
exhaust, do_one, glom)
|
12 |
+
from sympy.matrices.expressions.matexpr import MatrixExpr
|
13 |
+
from sympy.matrices.expressions.special import ZeroMatrix, GenericZeroMatrix
|
14 |
+
from sympy.matrices.expressions._shape import validate_matadd_integer as validate
|
15 |
+
from sympy.utilities.iterables import sift
|
16 |
+
from sympy.utilities.exceptions import sympy_deprecation_warning
|
17 |
+
|
18 |
+
# XXX: MatAdd should perhaps not subclass directly from Add
|
19 |
+
class MatAdd(MatrixExpr, Add):
|
20 |
+
"""A Sum of Matrix Expressions
|
21 |
+
|
22 |
+
MatAdd inherits from and operates like SymPy Add
|
23 |
+
|
24 |
+
Examples
|
25 |
+
========
|
26 |
+
|
27 |
+
>>> from sympy import MatAdd, MatrixSymbol
|
28 |
+
>>> A = MatrixSymbol('A', 5, 5)
|
29 |
+
>>> B = MatrixSymbol('B', 5, 5)
|
30 |
+
>>> C = MatrixSymbol('C', 5, 5)
|
31 |
+
>>> MatAdd(A, B, C)
|
32 |
+
A + B + C
|
33 |
+
"""
|
34 |
+
is_MatAdd = True
|
35 |
+
|
36 |
+
identity = GenericZeroMatrix()
|
37 |
+
|
38 |
+
def __new__(cls, *args, evaluate=False, check=None, _sympify=True):
|
39 |
+
if not args:
|
40 |
+
return cls.identity
|
41 |
+
|
42 |
+
# This must be removed aggressively in the constructor to avoid
|
43 |
+
# TypeErrors from GenericZeroMatrix().shape
|
44 |
+
args = list(filter(lambda i: cls.identity != i, args))
|
45 |
+
if _sympify:
|
46 |
+
args = list(map(sympify, args))
|
47 |
+
|
48 |
+
if not all(isinstance(arg, MatrixExpr) for arg in args):
|
49 |
+
raise TypeError("Mix of Matrix and Scalar symbols")
|
50 |
+
|
51 |
+
obj = Basic.__new__(cls, *args)
|
52 |
+
|
53 |
+
if check is not None:
|
54 |
+
sympy_deprecation_warning(
|
55 |
+
"Passing check to MatAdd is deprecated and the check argument will be removed in a future version.",
|
56 |
+
deprecated_since_version="1.11",
|
57 |
+
active_deprecations_target='remove-check-argument-from-matrix-operations')
|
58 |
+
|
59 |
+
if check is not False:
|
60 |
+
validate(*args)
|
61 |
+
|
62 |
+
if evaluate:
|
63 |
+
obj = cls._evaluate(obj)
|
64 |
+
|
65 |
+
return obj
|
66 |
+
|
67 |
+
@classmethod
|
68 |
+
def _evaluate(cls, expr):
|
69 |
+
return canonicalize(expr)
|
70 |
+
|
71 |
+
@property
|
72 |
+
def shape(self):
|
73 |
+
return self.args[0].shape
|
74 |
+
|
75 |
+
def could_extract_minus_sign(self):
|
76 |
+
return _could_extract_minus_sign(self)
|
77 |
+
|
78 |
+
def expand(self, **kwargs):
|
79 |
+
expanded = super(MatAdd, self).expand(**kwargs)
|
80 |
+
return self._evaluate(expanded)
|
81 |
+
|
82 |
+
def _entry(self, i, j, **kwargs):
|
83 |
+
return Add(*[arg._entry(i, j, **kwargs) for arg in self.args])
|
84 |
+
|
85 |
+
def _eval_transpose(self):
|
86 |
+
return MatAdd(*[transpose(arg) for arg in self.args]).doit()
|
87 |
+
|
88 |
+
def _eval_adjoint(self):
|
89 |
+
return MatAdd(*[adjoint(arg) for arg in self.args]).doit()
|
90 |
+
|
91 |
+
def _eval_trace(self):
|
92 |
+
from .trace import trace
|
93 |
+
return Add(*[trace(arg) for arg in self.args]).doit()
|
94 |
+
|
95 |
+
def doit(self, **hints):
|
96 |
+
deep = hints.get('deep', True)
|
97 |
+
if deep:
|
98 |
+
args = [arg.doit(**hints) for arg in self.args]
|
99 |
+
else:
|
100 |
+
args = self.args
|
101 |
+
return canonicalize(MatAdd(*args))
|
102 |
+
|
103 |
+
def _eval_derivative_matrix_lines(self, x):
|
104 |
+
add_lines = [arg._eval_derivative_matrix_lines(x) for arg in self.args]
|
105 |
+
return [j for i in add_lines for j in i]
|
106 |
+
|
107 |
+
add.register_handlerclass((Add, MatAdd), MatAdd)
|
108 |
+
|
109 |
+
|
110 |
+
factor_of = lambda arg: arg.as_coeff_mmul()[0]
|
111 |
+
matrix_of = lambda arg: unpack(arg.as_coeff_mmul()[1])
|
112 |
+
def combine(cnt, mat):
|
113 |
+
if cnt == 1:
|
114 |
+
return mat
|
115 |
+
else:
|
116 |
+
return cnt * mat
|
117 |
+
|
118 |
+
|
119 |
+
def merge_explicit(matadd):
|
120 |
+
""" Merge explicit MatrixBase arguments
|
121 |
+
|
122 |
+
Examples
|
123 |
+
========
|
124 |
+
|
125 |
+
>>> from sympy import MatrixSymbol, eye, Matrix, MatAdd, pprint
|
126 |
+
>>> from sympy.matrices.expressions.matadd import merge_explicit
|
127 |
+
>>> A = MatrixSymbol('A', 2, 2)
|
128 |
+
>>> B = eye(2)
|
129 |
+
>>> C = Matrix([[1, 2], [3, 4]])
|
130 |
+
>>> X = MatAdd(A, B, C)
|
131 |
+
>>> pprint(X)
|
132 |
+
[1 0] [1 2]
|
133 |
+
A + [ ] + [ ]
|
134 |
+
[0 1] [3 4]
|
135 |
+
>>> pprint(merge_explicit(X))
|
136 |
+
[2 2]
|
137 |
+
A + [ ]
|
138 |
+
[3 5]
|
139 |
+
"""
|
140 |
+
groups = sift(matadd.args, lambda arg: isinstance(arg, MatrixBase))
|
141 |
+
if len(groups[True]) > 1:
|
142 |
+
return MatAdd(*(groups[False] + [reduce(operator.add, groups[True])]))
|
143 |
+
else:
|
144 |
+
return matadd
|
145 |
+
|
146 |
+
|
147 |
+
rules = (rm_id(lambda x: x == 0 or isinstance(x, ZeroMatrix)),
|
148 |
+
unpack,
|
149 |
+
flatten,
|
150 |
+
glom(matrix_of, factor_of, combine),
|
151 |
+
merge_explicit,
|
152 |
+
sort(default_sort_key))
|
153 |
+
|
154 |
+
canonicalize = exhaust(condition(lambda x: isinstance(x, MatAdd),
|
155 |
+
do_one(*rules)))
|
llmeval-env/lib/python3.10/site-packages/sympy/matrices/expressions/matexpr.py
ADDED
@@ -0,0 +1,885 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from __future__ import annotations
|
2 |
+
from functools import wraps
|
3 |
+
|
4 |
+
from sympy.core import S, Integer, Basic, Mul, Add
|
5 |
+
from sympy.core.assumptions import check_assumptions
|
6 |
+
from sympy.core.decorators import call_highest_priority
|
7 |
+
from sympy.core.expr import Expr, ExprBuilder
|
8 |
+
from sympy.core.logic import FuzzyBool
|
9 |
+
from sympy.core.symbol import Str, Dummy, symbols, Symbol
|
10 |
+
from sympy.core.sympify import SympifyError, _sympify
|
11 |
+
from sympy.external.gmpy import SYMPY_INTS
|
12 |
+
from sympy.functions import conjugate, adjoint
|
13 |
+
from sympy.functions.special.tensor_functions import KroneckerDelta
|
14 |
+
from sympy.matrices.common import NonSquareMatrixError
|
15 |
+
from sympy.matrices.matrices import MatrixKind, MatrixBase
|
16 |
+
from sympy.multipledispatch import dispatch
|
17 |
+
from sympy.utilities.misc import filldedent
|
18 |
+
|
19 |
+
|
20 |
+
def _sympifyit(arg, retval=None):
|
21 |
+
# This version of _sympifyit sympifies MutableMatrix objects
|
22 |
+
def deco(func):
|
23 |
+
@wraps(func)
|
24 |
+
def __sympifyit_wrapper(a, b):
|
25 |
+
try:
|
26 |
+
b = _sympify(b)
|
27 |
+
return func(a, b)
|
28 |
+
except SympifyError:
|
29 |
+
return retval
|
30 |
+
|
31 |
+
return __sympifyit_wrapper
|
32 |
+
|
33 |
+
return deco
|
34 |
+
|
35 |
+
|
36 |
+
class MatrixExpr(Expr):
|
37 |
+
"""Superclass for Matrix Expressions
|
38 |
+
|
39 |
+
MatrixExprs represent abstract matrices, linear transformations represented
|
40 |
+
within a particular basis.
|
41 |
+
|
42 |
+
Examples
|
43 |
+
========
|
44 |
+
|
45 |
+
>>> from sympy import MatrixSymbol
|
46 |
+
>>> A = MatrixSymbol('A', 3, 3)
|
47 |
+
>>> y = MatrixSymbol('y', 3, 1)
|
48 |
+
>>> x = (A.T*A).I * A * y
|
49 |
+
|
50 |
+
See Also
|
51 |
+
========
|
52 |
+
|
53 |
+
MatrixSymbol, MatAdd, MatMul, Transpose, Inverse
|
54 |
+
"""
|
55 |
+
__slots__: tuple[str, ...] = ()
|
56 |
+
|
57 |
+
# Should not be considered iterable by the
|
58 |
+
# sympy.utilities.iterables.iterable function. Subclass that actually are
|
59 |
+
# iterable (i.e., explicit matrices) should set this to True.
|
60 |
+
_iterable = False
|
61 |
+
|
62 |
+
_op_priority = 11.0
|
63 |
+
|
64 |
+
is_Matrix: bool = True
|
65 |
+
is_MatrixExpr: bool = True
|
66 |
+
is_Identity: FuzzyBool = None
|
67 |
+
is_Inverse = False
|
68 |
+
is_Transpose = False
|
69 |
+
is_ZeroMatrix = False
|
70 |
+
is_MatAdd = False
|
71 |
+
is_MatMul = False
|
72 |
+
|
73 |
+
is_commutative = False
|
74 |
+
is_number = False
|
75 |
+
is_symbol = False
|
76 |
+
is_scalar = False
|
77 |
+
|
78 |
+
kind: MatrixKind = MatrixKind()
|
79 |
+
|
80 |
+
def __new__(cls, *args, **kwargs):
|
81 |
+
args = map(_sympify, args)
|
82 |
+
return Basic.__new__(cls, *args, **kwargs)
|
83 |
+
|
84 |
+
# The following is adapted from the core Expr object
|
85 |
+
|
86 |
+
@property
|
87 |
+
def shape(self) -> tuple[Expr, Expr]:
|
88 |
+
raise NotImplementedError
|
89 |
+
|
90 |
+
@property
|
91 |
+
def _add_handler(self):
|
92 |
+
return MatAdd
|
93 |
+
|
94 |
+
@property
|
95 |
+
def _mul_handler(self):
|
96 |
+
return MatMul
|
97 |
+
|
98 |
+
def __neg__(self):
|
99 |
+
return MatMul(S.NegativeOne, self).doit()
|
100 |
+
|
101 |
+
def __abs__(self):
|
102 |
+
raise NotImplementedError
|
103 |
+
|
104 |
+
@_sympifyit('other', NotImplemented)
|
105 |
+
@call_highest_priority('__radd__')
|
106 |
+
def __add__(self, other):
|
107 |
+
return MatAdd(self, other).doit()
|
108 |
+
|
109 |
+
@_sympifyit('other', NotImplemented)
|
110 |
+
@call_highest_priority('__add__')
|
111 |
+
def __radd__(self, other):
|
112 |
+
return MatAdd(other, self).doit()
|
113 |
+
|
114 |
+
@_sympifyit('other', NotImplemented)
|
115 |
+
@call_highest_priority('__rsub__')
|
116 |
+
def __sub__(self, other):
|
117 |
+
return MatAdd(self, -other).doit()
|
118 |
+
|
119 |
+
@_sympifyit('other', NotImplemented)
|
120 |
+
@call_highest_priority('__sub__')
|
121 |
+
def __rsub__(self, other):
|
122 |
+
return MatAdd(other, -self).doit()
|
123 |
+
|
124 |
+
@_sympifyit('other', NotImplemented)
|
125 |
+
@call_highest_priority('__rmul__')
|
126 |
+
def __mul__(self, other):
|
127 |
+
return MatMul(self, other).doit()
|
128 |
+
|
129 |
+
@_sympifyit('other', NotImplemented)
|
130 |
+
@call_highest_priority('__rmul__')
|
131 |
+
def __matmul__(self, other):
|
132 |
+
return MatMul(self, other).doit()
|
133 |
+
|
134 |
+
@_sympifyit('other', NotImplemented)
|
135 |
+
@call_highest_priority('__mul__')
|
136 |
+
def __rmul__(self, other):
|
137 |
+
return MatMul(other, self).doit()
|
138 |
+
|
139 |
+
@_sympifyit('other', NotImplemented)
|
140 |
+
@call_highest_priority('__mul__')
|
141 |
+
def __rmatmul__(self, other):
|
142 |
+
return MatMul(other, self).doit()
|
143 |
+
|
144 |
+
@_sympifyit('other', NotImplemented)
|
145 |
+
@call_highest_priority('__rpow__')
|
146 |
+
def __pow__(self, other):
|
147 |
+
return MatPow(self, other).doit()
|
148 |
+
|
149 |
+
@_sympifyit('other', NotImplemented)
|
150 |
+
@call_highest_priority('__pow__')
|
151 |
+
def __rpow__(self, other):
|
152 |
+
raise NotImplementedError("Matrix Power not defined")
|
153 |
+
|
154 |
+
@_sympifyit('other', NotImplemented)
|
155 |
+
@call_highest_priority('__rtruediv__')
|
156 |
+
def __truediv__(self, other):
|
157 |
+
return self * other**S.NegativeOne
|
158 |
+
|
159 |
+
@_sympifyit('other', NotImplemented)
|
160 |
+
@call_highest_priority('__truediv__')
|
161 |
+
def __rtruediv__(self, other):
|
162 |
+
raise NotImplementedError()
|
163 |
+
#return MatMul(other, Pow(self, S.NegativeOne))
|
164 |
+
|
165 |
+
@property
|
166 |
+
def rows(self):
|
167 |
+
return self.shape[0]
|
168 |
+
|
169 |
+
@property
|
170 |
+
def cols(self):
|
171 |
+
return self.shape[1]
|
172 |
+
|
173 |
+
@property
|
174 |
+
def is_square(self) -> bool | None:
|
175 |
+
rows, cols = self.shape
|
176 |
+
if isinstance(rows, Integer) and isinstance(cols, Integer):
|
177 |
+
return rows == cols
|
178 |
+
if rows == cols:
|
179 |
+
return True
|
180 |
+
return None
|
181 |
+
|
182 |
+
def _eval_conjugate(self):
|
183 |
+
from sympy.matrices.expressions.adjoint import Adjoint
|
184 |
+
return Adjoint(Transpose(self))
|
185 |
+
|
186 |
+
def as_real_imag(self, deep=True, **hints):
|
187 |
+
return self._eval_as_real_imag()
|
188 |
+
|
189 |
+
def _eval_as_real_imag(self):
|
190 |
+
real = S.Half * (self + self._eval_conjugate())
|
191 |
+
im = (self - self._eval_conjugate())/(2*S.ImaginaryUnit)
|
192 |
+
return (real, im)
|
193 |
+
|
194 |
+
def _eval_inverse(self):
|
195 |
+
return Inverse(self)
|
196 |
+
|
197 |
+
def _eval_determinant(self):
|
198 |
+
return Determinant(self)
|
199 |
+
|
200 |
+
def _eval_transpose(self):
|
201 |
+
return Transpose(self)
|
202 |
+
|
203 |
+
def _eval_power(self, exp):
|
204 |
+
"""
|
205 |
+
Override this in sub-classes to implement simplification of powers. The cases where the exponent
|
206 |
+
is -1, 0, 1 are already covered in MatPow.doit(), so implementations can exclude these cases.
|
207 |
+
"""
|
208 |
+
return MatPow(self, exp)
|
209 |
+
|
210 |
+
def _eval_simplify(self, **kwargs):
|
211 |
+
if self.is_Atom:
|
212 |
+
return self
|
213 |
+
else:
|
214 |
+
from sympy.simplify import simplify
|
215 |
+
return self.func(*[simplify(x, **kwargs) for x in self.args])
|
216 |
+
|
217 |
+
def _eval_adjoint(self):
|
218 |
+
from sympy.matrices.expressions.adjoint import Adjoint
|
219 |
+
return Adjoint(self)
|
220 |
+
|
221 |
+
def _eval_derivative_n_times(self, x, n):
|
222 |
+
return Basic._eval_derivative_n_times(self, x, n)
|
223 |
+
|
224 |
+
def _eval_derivative(self, x):
|
225 |
+
# `x` is a scalar:
|
226 |
+
if self.has(x):
|
227 |
+
# See if there are other methods using it:
|
228 |
+
return super()._eval_derivative(x)
|
229 |
+
else:
|
230 |
+
return ZeroMatrix(*self.shape)
|
231 |
+
|
232 |
+
@classmethod
|
233 |
+
def _check_dim(cls, dim):
|
234 |
+
"""Helper function to check invalid matrix dimensions"""
|
235 |
+
ok = check_assumptions(dim, integer=True, nonnegative=True)
|
236 |
+
if ok is False:
|
237 |
+
raise ValueError(
|
238 |
+
"The dimension specification {} should be "
|
239 |
+
"a nonnegative integer.".format(dim))
|
240 |
+
|
241 |
+
|
242 |
+
def _entry(self, i, j, **kwargs):
|
243 |
+
raise NotImplementedError(
|
244 |
+
"Indexing not implemented for %s" % self.__class__.__name__)
|
245 |
+
|
246 |
+
def adjoint(self):
|
247 |
+
return adjoint(self)
|
248 |
+
|
249 |
+
def as_coeff_Mul(self, rational=False):
|
250 |
+
"""Efficiently extract the coefficient of a product."""
|
251 |
+
return S.One, self
|
252 |
+
|
253 |
+
def conjugate(self):
|
254 |
+
return conjugate(self)
|
255 |
+
|
256 |
+
def transpose(self):
|
257 |
+
from sympy.matrices.expressions.transpose import transpose
|
258 |
+
return transpose(self)
|
259 |
+
|
260 |
+
@property
|
261 |
+
def T(self):
|
262 |
+
'''Matrix transposition'''
|
263 |
+
return self.transpose()
|
264 |
+
|
265 |
+
def inverse(self):
|
266 |
+
if self.is_square is False:
|
267 |
+
raise NonSquareMatrixError('Inverse of non-square matrix')
|
268 |
+
return self._eval_inverse()
|
269 |
+
|
270 |
+
def inv(self):
|
271 |
+
return self.inverse()
|
272 |
+
|
273 |
+
def det(self):
|
274 |
+
from sympy.matrices.expressions.determinant import det
|
275 |
+
return det(self)
|
276 |
+
|
277 |
+
@property
|
278 |
+
def I(self):
|
279 |
+
return self.inverse()
|
280 |
+
|
281 |
+
def valid_index(self, i, j):
|
282 |
+
def is_valid(idx):
|
283 |
+
return isinstance(idx, (int, Integer, Symbol, Expr))
|
284 |
+
return (is_valid(i) and is_valid(j) and
|
285 |
+
(self.rows is None or
|
286 |
+
(i >= -self.rows) != False and (i < self.rows) != False) and
|
287 |
+
(j >= -self.cols) != False and (j < self.cols) != False)
|
288 |
+
|
289 |
+
def __getitem__(self, key):
|
290 |
+
if not isinstance(key, tuple) and isinstance(key, slice):
|
291 |
+
from sympy.matrices.expressions.slice import MatrixSlice
|
292 |
+
return MatrixSlice(self, key, (0, None, 1))
|
293 |
+
if isinstance(key, tuple) and len(key) == 2:
|
294 |
+
i, j = key
|
295 |
+
if isinstance(i, slice) or isinstance(j, slice):
|
296 |
+
from sympy.matrices.expressions.slice import MatrixSlice
|
297 |
+
return MatrixSlice(self, i, j)
|
298 |
+
i, j = _sympify(i), _sympify(j)
|
299 |
+
if self.valid_index(i, j) != False:
|
300 |
+
return self._entry(i, j)
|
301 |
+
else:
|
302 |
+
raise IndexError("Invalid indices (%s, %s)" % (i, j))
|
303 |
+
elif isinstance(key, (SYMPY_INTS, Integer)):
|
304 |
+
# row-wise decomposition of matrix
|
305 |
+
rows, cols = self.shape
|
306 |
+
# allow single indexing if number of columns is known
|
307 |
+
if not isinstance(cols, Integer):
|
308 |
+
raise IndexError(filldedent('''
|
309 |
+
Single indexing is only supported when the number
|
310 |
+
of columns is known.'''))
|
311 |
+
key = _sympify(key)
|
312 |
+
i = key // cols
|
313 |
+
j = key % cols
|
314 |
+
if self.valid_index(i, j) != False:
|
315 |
+
return self._entry(i, j)
|
316 |
+
else:
|
317 |
+
raise IndexError("Invalid index %s" % key)
|
318 |
+
elif isinstance(key, (Symbol, Expr)):
|
319 |
+
raise IndexError(filldedent('''
|
320 |
+
Only integers may be used when addressing the matrix
|
321 |
+
with a single index.'''))
|
322 |
+
raise IndexError("Invalid index, wanted %s[i,j]" % self)
|
323 |
+
|
324 |
+
def _is_shape_symbolic(self) -> bool:
|
325 |
+
return (not isinstance(self.rows, (SYMPY_INTS, Integer))
|
326 |
+
or not isinstance(self.cols, (SYMPY_INTS, Integer)))
|
327 |
+
|
328 |
+
def as_explicit(self):
|
329 |
+
"""
|
330 |
+
Returns a dense Matrix with elements represented explicitly
|
331 |
+
|
332 |
+
Returns an object of type ImmutableDenseMatrix.
|
333 |
+
|
334 |
+
Examples
|
335 |
+
========
|
336 |
+
|
337 |
+
>>> from sympy import Identity
|
338 |
+
>>> I = Identity(3)
|
339 |
+
>>> I
|
340 |
+
I
|
341 |
+
>>> I.as_explicit()
|
342 |
+
Matrix([
|
343 |
+
[1, 0, 0],
|
344 |
+
[0, 1, 0],
|
345 |
+
[0, 0, 1]])
|
346 |
+
|
347 |
+
See Also
|
348 |
+
========
|
349 |
+
as_mutable: returns mutable Matrix type
|
350 |
+
|
351 |
+
"""
|
352 |
+
if self._is_shape_symbolic():
|
353 |
+
raise ValueError(
|
354 |
+
'Matrix with symbolic shape '
|
355 |
+
'cannot be represented explicitly.')
|
356 |
+
from sympy.matrices.immutable import ImmutableDenseMatrix
|
357 |
+
return ImmutableDenseMatrix([[self[i, j]
|
358 |
+
for j in range(self.cols)]
|
359 |
+
for i in range(self.rows)])
|
360 |
+
|
361 |
+
def as_mutable(self):
|
362 |
+
"""
|
363 |
+
Returns a dense, mutable matrix with elements represented explicitly
|
364 |
+
|
365 |
+
Examples
|
366 |
+
========
|
367 |
+
|
368 |
+
>>> from sympy import Identity
|
369 |
+
>>> I = Identity(3)
|
370 |
+
>>> I
|
371 |
+
I
|
372 |
+
>>> I.shape
|
373 |
+
(3, 3)
|
374 |
+
>>> I.as_mutable()
|
375 |
+
Matrix([
|
376 |
+
[1, 0, 0],
|
377 |
+
[0, 1, 0],
|
378 |
+
[0, 0, 1]])
|
379 |
+
|
380 |
+
See Also
|
381 |
+
========
|
382 |
+
as_explicit: returns ImmutableDenseMatrix
|
383 |
+
"""
|
384 |
+
return self.as_explicit().as_mutable()
|
385 |
+
|
386 |
+
def __array__(self):
|
387 |
+
from numpy import empty
|
388 |
+
a = empty(self.shape, dtype=object)
|
389 |
+
for i in range(self.rows):
|
390 |
+
for j in range(self.cols):
|
391 |
+
a[i, j] = self[i, j]
|
392 |
+
return a
|
393 |
+
|
394 |
+
def equals(self, other):
|
395 |
+
"""
|
396 |
+
Test elementwise equality between matrices, potentially of different
|
397 |
+
types
|
398 |
+
|
399 |
+
>>> from sympy import Identity, eye
|
400 |
+
>>> Identity(3).equals(eye(3))
|
401 |
+
True
|
402 |
+
"""
|
403 |
+
return self.as_explicit().equals(other)
|
404 |
+
|
405 |
+
def canonicalize(self):
|
406 |
+
return self
|
407 |
+
|
408 |
+
def as_coeff_mmul(self):
|
409 |
+
return S.One, MatMul(self)
|
410 |
+
|
411 |
+
@staticmethod
|
412 |
+
def from_index_summation(expr, first_index=None, last_index=None, dimensions=None):
|
413 |
+
r"""
|
414 |
+
Parse expression of matrices with explicitly summed indices into a
|
415 |
+
matrix expression without indices, if possible.
|
416 |
+
|
417 |
+
This transformation expressed in mathematical notation:
|
418 |
+
|
419 |
+
`\sum_{j=0}^{N-1} A_{i,j} B_{j,k} \Longrightarrow \mathbf{A}\cdot \mathbf{B}`
|
420 |
+
|
421 |
+
Optional parameter ``first_index``: specify which free index to use as
|
422 |
+
the index starting the expression.
|
423 |
+
|
424 |
+
Examples
|
425 |
+
========
|
426 |
+
|
427 |
+
>>> from sympy import MatrixSymbol, MatrixExpr, Sum
|
428 |
+
>>> from sympy.abc import i, j, k, l, N
|
429 |
+
>>> A = MatrixSymbol("A", N, N)
|
430 |
+
>>> B = MatrixSymbol("B", N, N)
|
431 |
+
>>> expr = Sum(A[i, j]*B[j, k], (j, 0, N-1))
|
432 |
+
>>> MatrixExpr.from_index_summation(expr)
|
433 |
+
A*B
|
434 |
+
|
435 |
+
Transposition is detected:
|
436 |
+
|
437 |
+
>>> expr = Sum(A[j, i]*B[j, k], (j, 0, N-1))
|
438 |
+
>>> MatrixExpr.from_index_summation(expr)
|
439 |
+
A.T*B
|
440 |
+
|
441 |
+
Detect the trace:
|
442 |
+
|
443 |
+
>>> expr = Sum(A[i, i], (i, 0, N-1))
|
444 |
+
>>> MatrixExpr.from_index_summation(expr)
|
445 |
+
Trace(A)
|
446 |
+
|
447 |
+
More complicated expressions:
|
448 |
+
|
449 |
+
>>> expr = Sum(A[i, j]*B[k, j]*A[l, k], (j, 0, N-1), (k, 0, N-1))
|
450 |
+
>>> MatrixExpr.from_index_summation(expr)
|
451 |
+
A*B.T*A.T
|
452 |
+
"""
|
453 |
+
from sympy.tensor.array.expressions.from_indexed_to_array import convert_indexed_to_array
|
454 |
+
from sympy.tensor.array.expressions.from_array_to_matrix import convert_array_to_matrix
|
455 |
+
first_indices = []
|
456 |
+
if first_index is not None:
|
457 |
+
first_indices.append(first_index)
|
458 |
+
if last_index is not None:
|
459 |
+
first_indices.append(last_index)
|
460 |
+
arr = convert_indexed_to_array(expr, first_indices=first_indices)
|
461 |
+
return convert_array_to_matrix(arr)
|
462 |
+
|
463 |
+
def applyfunc(self, func):
|
464 |
+
from .applyfunc import ElementwiseApplyFunction
|
465 |
+
return ElementwiseApplyFunction(func, self)
|
466 |
+
|
467 |
+
|
468 |
+
@dispatch(MatrixExpr, Expr)
|
469 |
+
def _eval_is_eq(lhs, rhs): # noqa:F811
|
470 |
+
return False
|
471 |
+
|
472 |
+
@dispatch(MatrixExpr, MatrixExpr) # type: ignore
|
473 |
+
def _eval_is_eq(lhs, rhs): # noqa:F811
|
474 |
+
if lhs.shape != rhs.shape:
|
475 |
+
return False
|
476 |
+
if (lhs - rhs).is_ZeroMatrix:
|
477 |
+
return True
|
478 |
+
|
479 |
+
def get_postprocessor(cls):
|
480 |
+
def _postprocessor(expr):
|
481 |
+
# To avoid circular imports, we can't have MatMul/MatAdd on the top level
|
482 |
+
mat_class = {Mul: MatMul, Add: MatAdd}[cls]
|
483 |
+
nonmatrices = []
|
484 |
+
matrices = []
|
485 |
+
for term in expr.args:
|
486 |
+
if isinstance(term, MatrixExpr):
|
487 |
+
matrices.append(term)
|
488 |
+
else:
|
489 |
+
nonmatrices.append(term)
|
490 |
+
|
491 |
+
if not matrices:
|
492 |
+
return cls._from_args(nonmatrices)
|
493 |
+
|
494 |
+
if nonmatrices:
|
495 |
+
if cls == Mul:
|
496 |
+
for i in range(len(matrices)):
|
497 |
+
if not matrices[i].is_MatrixExpr:
|
498 |
+
# If one of the matrices explicit, absorb the scalar into it
|
499 |
+
# (doit will combine all explicit matrices into one, so it
|
500 |
+
# doesn't matter which)
|
501 |
+
matrices[i] = matrices[i].__mul__(cls._from_args(nonmatrices))
|
502 |
+
nonmatrices = []
|
503 |
+
break
|
504 |
+
|
505 |
+
else:
|
506 |
+
# Maintain the ability to create Add(scalar, matrix) without
|
507 |
+
# raising an exception. That way different algorithms can
|
508 |
+
# replace matrix expressions with non-commutative symbols to
|
509 |
+
# manipulate them like non-commutative scalars.
|
510 |
+
return cls._from_args(nonmatrices + [mat_class(*matrices).doit(deep=False)])
|
511 |
+
|
512 |
+
if mat_class == MatAdd:
|
513 |
+
return mat_class(*matrices).doit(deep=False)
|
514 |
+
return mat_class(cls._from_args(nonmatrices), *matrices).doit(deep=False)
|
515 |
+
return _postprocessor
|
516 |
+
|
517 |
+
|
518 |
+
Basic._constructor_postprocessor_mapping[MatrixExpr] = {
|
519 |
+
"Mul": [get_postprocessor(Mul)],
|
520 |
+
"Add": [get_postprocessor(Add)],
|
521 |
+
}
|
522 |
+
|
523 |
+
|
524 |
+
def _matrix_derivative(expr, x, old_algorithm=False):
|
525 |
+
|
526 |
+
if isinstance(expr, MatrixBase) or isinstance(x, MatrixBase):
|
527 |
+
# Do not use array expressions for explicit matrices:
|
528 |
+
old_algorithm = True
|
529 |
+
|
530 |
+
if old_algorithm:
|
531 |
+
return _matrix_derivative_old_algorithm(expr, x)
|
532 |
+
|
533 |
+
from sympy.tensor.array.expressions.from_matrix_to_array import convert_matrix_to_array
|
534 |
+
from sympy.tensor.array.expressions.arrayexpr_derivatives import array_derive
|
535 |
+
from sympy.tensor.array.expressions.from_array_to_matrix import convert_array_to_matrix
|
536 |
+
|
537 |
+
array_expr = convert_matrix_to_array(expr)
|
538 |
+
diff_array_expr = array_derive(array_expr, x)
|
539 |
+
diff_matrix_expr = convert_array_to_matrix(diff_array_expr)
|
540 |
+
return diff_matrix_expr
|
541 |
+
|
542 |
+
|
543 |
+
def _matrix_derivative_old_algorithm(expr, x):
|
544 |
+
from sympy.tensor.array.array_derivatives import ArrayDerivative
|
545 |
+
lines = expr._eval_derivative_matrix_lines(x)
|
546 |
+
|
547 |
+
parts = [i.build() for i in lines]
|
548 |
+
|
549 |
+
from sympy.tensor.array.expressions.from_array_to_matrix import convert_array_to_matrix
|
550 |
+
|
551 |
+
parts = [[convert_array_to_matrix(j) for j in i] for i in parts]
|
552 |
+
|
553 |
+
def _get_shape(elem):
|
554 |
+
if isinstance(elem, MatrixExpr):
|
555 |
+
return elem.shape
|
556 |
+
return 1, 1
|
557 |
+
|
558 |
+
def get_rank(parts):
|
559 |
+
return sum([j not in (1, None) for i in parts for j in _get_shape(i)])
|
560 |
+
|
561 |
+
ranks = [get_rank(i) for i in parts]
|
562 |
+
rank = ranks[0]
|
563 |
+
|
564 |
+
def contract_one_dims(parts):
|
565 |
+
if len(parts) == 1:
|
566 |
+
return parts[0]
|
567 |
+
else:
|
568 |
+
p1, p2 = parts[:2]
|
569 |
+
if p2.is_Matrix:
|
570 |
+
p2 = p2.T
|
571 |
+
if p1 == Identity(1):
|
572 |
+
pbase = p2
|
573 |
+
elif p2 == Identity(1):
|
574 |
+
pbase = p1
|
575 |
+
else:
|
576 |
+
pbase = p1*p2
|
577 |
+
if len(parts) == 2:
|
578 |
+
return pbase
|
579 |
+
else: # len(parts) > 2
|
580 |
+
if pbase.is_Matrix:
|
581 |
+
raise ValueError("")
|
582 |
+
return pbase*Mul.fromiter(parts[2:])
|
583 |
+
|
584 |
+
if rank <= 2:
|
585 |
+
return Add.fromiter([contract_one_dims(i) for i in parts])
|
586 |
+
|
587 |
+
return ArrayDerivative(expr, x)
|
588 |
+
|
589 |
+
|
590 |
+
class MatrixElement(Expr):
|
591 |
+
parent = property(lambda self: self.args[0])
|
592 |
+
i = property(lambda self: self.args[1])
|
593 |
+
j = property(lambda self: self.args[2])
|
594 |
+
_diff_wrt = True
|
595 |
+
is_symbol = True
|
596 |
+
is_commutative = True
|
597 |
+
|
598 |
+
def __new__(cls, name, n, m):
|
599 |
+
n, m = map(_sympify, (n, m))
|
600 |
+
from sympy.matrices.matrices import MatrixBase
|
601 |
+
if isinstance(name, str):
|
602 |
+
name = Symbol(name)
|
603 |
+
else:
|
604 |
+
if isinstance(name, MatrixBase):
|
605 |
+
if n.is_Integer and m.is_Integer:
|
606 |
+
return name[n, m]
|
607 |
+
name = _sympify(name) # change mutable into immutable
|
608 |
+
else:
|
609 |
+
name = _sympify(name)
|
610 |
+
if not isinstance(name.kind, MatrixKind):
|
611 |
+
raise TypeError("First argument of MatrixElement should be a matrix")
|
612 |
+
if not getattr(name, 'valid_index', lambda n, m: True)(n, m):
|
613 |
+
raise IndexError('indices out of range')
|
614 |
+
obj = Expr.__new__(cls, name, n, m)
|
615 |
+
return obj
|
616 |
+
|
617 |
+
@property
|
618 |
+
def symbol(self):
|
619 |
+
return self.args[0]
|
620 |
+
|
621 |
+
def doit(self, **hints):
|
622 |
+
deep = hints.get('deep', True)
|
623 |
+
if deep:
|
624 |
+
args = [arg.doit(**hints) for arg in self.args]
|
625 |
+
else:
|
626 |
+
args = self.args
|
627 |
+
return args[0][args[1], args[2]]
|
628 |
+
|
629 |
+
@property
|
630 |
+
def indices(self):
|
631 |
+
return self.args[1:]
|
632 |
+
|
633 |
+
def _eval_derivative(self, v):
|
634 |
+
|
635 |
+
if not isinstance(v, MatrixElement):
|
636 |
+
from sympy.matrices.matrices import MatrixBase
|
637 |
+
if isinstance(self.parent, MatrixBase):
|
638 |
+
return self.parent.diff(v)[self.i, self.j]
|
639 |
+
return S.Zero
|
640 |
+
|
641 |
+
M = self.args[0]
|
642 |
+
|
643 |
+
m, n = self.parent.shape
|
644 |
+
|
645 |
+
if M == v.args[0]:
|
646 |
+
return KroneckerDelta(self.args[1], v.args[1], (0, m-1)) * \
|
647 |
+
KroneckerDelta(self.args[2], v.args[2], (0, n-1))
|
648 |
+
|
649 |
+
if isinstance(M, Inverse):
|
650 |
+
from sympy.concrete.summations import Sum
|
651 |
+
i, j = self.args[1:]
|
652 |
+
i1, i2 = symbols("z1, z2", cls=Dummy)
|
653 |
+
Y = M.args[0]
|
654 |
+
r1, r2 = Y.shape
|
655 |
+
return -Sum(M[i, i1]*Y[i1, i2].diff(v)*M[i2, j], (i1, 0, r1-1), (i2, 0, r2-1))
|
656 |
+
|
657 |
+
if self.has(v.args[0]):
|
658 |
+
return None
|
659 |
+
|
660 |
+
return S.Zero
|
661 |
+
|
662 |
+
|
663 |
+
class MatrixSymbol(MatrixExpr):
|
664 |
+
"""Symbolic representation of a Matrix object
|
665 |
+
|
666 |
+
Creates a SymPy Symbol to represent a Matrix. This matrix has a shape and
|
667 |
+
can be included in Matrix Expressions
|
668 |
+
|
669 |
+
Examples
|
670 |
+
========
|
671 |
+
|
672 |
+
>>> from sympy import MatrixSymbol, Identity
|
673 |
+
>>> A = MatrixSymbol('A', 3, 4) # A 3 by 4 Matrix
|
674 |
+
>>> B = MatrixSymbol('B', 4, 3) # A 4 by 3 Matrix
|
675 |
+
>>> A.shape
|
676 |
+
(3, 4)
|
677 |
+
>>> 2*A*B + Identity(3)
|
678 |
+
I + 2*A*B
|
679 |
+
"""
|
680 |
+
is_commutative = False
|
681 |
+
is_symbol = True
|
682 |
+
_diff_wrt = True
|
683 |
+
|
684 |
+
def __new__(cls, name, n, m):
|
685 |
+
n, m = _sympify(n), _sympify(m)
|
686 |
+
|
687 |
+
cls._check_dim(m)
|
688 |
+
cls._check_dim(n)
|
689 |
+
|
690 |
+
if isinstance(name, str):
|
691 |
+
name = Str(name)
|
692 |
+
obj = Basic.__new__(cls, name, n, m)
|
693 |
+
return obj
|
694 |
+
|
695 |
+
@property
|
696 |
+
def shape(self):
|
697 |
+
return self.args[1], self.args[2]
|
698 |
+
|
699 |
+
@property
|
700 |
+
def name(self):
|
701 |
+
return self.args[0].name
|
702 |
+
|
703 |
+
def _entry(self, i, j, **kwargs):
|
704 |
+
return MatrixElement(self, i, j)
|
705 |
+
|
706 |
+
@property
|
707 |
+
def free_symbols(self):
|
708 |
+
return {self}
|
709 |
+
|
710 |
+
def _eval_simplify(self, **kwargs):
|
711 |
+
return self
|
712 |
+
|
713 |
+
def _eval_derivative(self, x):
|
714 |
+
# x is a scalar:
|
715 |
+
return ZeroMatrix(self.shape[0], self.shape[1])
|
716 |
+
|
717 |
+
def _eval_derivative_matrix_lines(self, x):
|
718 |
+
if self != x:
|
719 |
+
first = ZeroMatrix(x.shape[0], self.shape[0]) if self.shape[0] != 1 else S.Zero
|
720 |
+
second = ZeroMatrix(x.shape[1], self.shape[1]) if self.shape[1] != 1 else S.Zero
|
721 |
+
return [_LeftRightArgs(
|
722 |
+
[first, second],
|
723 |
+
)]
|
724 |
+
else:
|
725 |
+
first = Identity(self.shape[0]) if self.shape[0] != 1 else S.One
|
726 |
+
second = Identity(self.shape[1]) if self.shape[1] != 1 else S.One
|
727 |
+
return [_LeftRightArgs(
|
728 |
+
[first, second],
|
729 |
+
)]
|
730 |
+
|
731 |
+
|
732 |
+
def matrix_symbols(expr):
|
733 |
+
return [sym for sym in expr.free_symbols if sym.is_Matrix]
|
734 |
+
|
735 |
+
|
736 |
+
class _LeftRightArgs:
|
737 |
+
r"""
|
738 |
+
Helper class to compute matrix derivatives.
|
739 |
+
|
740 |
+
The logic: when an expression is derived by a matrix `X_{mn}`, two lines of
|
741 |
+
matrix multiplications are created: the one contracted to `m` (first line),
|
742 |
+
and the one contracted to `n` (second line).
|
743 |
+
|
744 |
+
Transposition flips the side by which new matrices are connected to the
|
745 |
+
lines.
|
746 |
+
|
747 |
+
The trace connects the end of the two lines.
|
748 |
+
"""
|
749 |
+
|
750 |
+
def __init__(self, lines, higher=S.One):
|
751 |
+
self._lines = list(lines)
|
752 |
+
self._first_pointer_parent = self._lines
|
753 |
+
self._first_pointer_index = 0
|
754 |
+
self._first_line_index = 0
|
755 |
+
self._second_pointer_parent = self._lines
|
756 |
+
self._second_pointer_index = 1
|
757 |
+
self._second_line_index = 1
|
758 |
+
self.higher = higher
|
759 |
+
|
760 |
+
@property
|
761 |
+
def first_pointer(self):
|
762 |
+
return self._first_pointer_parent[self._first_pointer_index]
|
763 |
+
|
764 |
+
@first_pointer.setter
|
765 |
+
def first_pointer(self, value):
|
766 |
+
self._first_pointer_parent[self._first_pointer_index] = value
|
767 |
+
|
768 |
+
@property
|
769 |
+
def second_pointer(self):
|
770 |
+
return self._second_pointer_parent[self._second_pointer_index]
|
771 |
+
|
772 |
+
@second_pointer.setter
|
773 |
+
def second_pointer(self, value):
|
774 |
+
self._second_pointer_parent[self._second_pointer_index] = value
|
775 |
+
|
776 |
+
def __repr__(self):
|
777 |
+
built = [self._build(i) for i in self._lines]
|
778 |
+
return "_LeftRightArgs(lines=%s, higher=%s)" % (
|
779 |
+
built,
|
780 |
+
self.higher,
|
781 |
+
)
|
782 |
+
|
783 |
+
def transpose(self):
|
784 |
+
self._first_pointer_parent, self._second_pointer_parent = self._second_pointer_parent, self._first_pointer_parent
|
785 |
+
self._first_pointer_index, self._second_pointer_index = self._second_pointer_index, self._first_pointer_index
|
786 |
+
self._first_line_index, self._second_line_index = self._second_line_index, self._first_line_index
|
787 |
+
return self
|
788 |
+
|
789 |
+
@staticmethod
|
790 |
+
def _build(expr):
|
791 |
+
if isinstance(expr, ExprBuilder):
|
792 |
+
return expr.build()
|
793 |
+
if isinstance(expr, list):
|
794 |
+
if len(expr) == 1:
|
795 |
+
return expr[0]
|
796 |
+
else:
|
797 |
+
return expr[0](*[_LeftRightArgs._build(i) for i in expr[1]])
|
798 |
+
else:
|
799 |
+
return expr
|
800 |
+
|
801 |
+
def build(self):
|
802 |
+
data = [self._build(i) for i in self._lines]
|
803 |
+
if self.higher != 1:
|
804 |
+
data += [self._build(self.higher)]
|
805 |
+
data = list(data)
|
806 |
+
return data
|
807 |
+
|
808 |
+
def matrix_form(self):
|
809 |
+
if self.first != 1 and self.higher != 1:
|
810 |
+
raise ValueError("higher dimensional array cannot be represented")
|
811 |
+
|
812 |
+
def _get_shape(elem):
|
813 |
+
if isinstance(elem, MatrixExpr):
|
814 |
+
return elem.shape
|
815 |
+
return (None, None)
|
816 |
+
|
817 |
+
if _get_shape(self.first)[1] != _get_shape(self.second)[1]:
|
818 |
+
# Remove one-dimensional identity matrices:
|
819 |
+
# (this is needed by `a.diff(a)` where `a` is a vector)
|
820 |
+
if _get_shape(self.second) == (1, 1):
|
821 |
+
return self.first*self.second[0, 0]
|
822 |
+
if _get_shape(self.first) == (1, 1):
|
823 |
+
return self.first[1, 1]*self.second.T
|
824 |
+
raise ValueError("incompatible shapes")
|
825 |
+
if self.first != 1:
|
826 |
+
return self.first*self.second.T
|
827 |
+
else:
|
828 |
+
return self.higher
|
829 |
+
|
830 |
+
def rank(self):
|
831 |
+
"""
|
832 |
+
Number of dimensions different from trivial (warning: not related to
|
833 |
+
matrix rank).
|
834 |
+
"""
|
835 |
+
rank = 0
|
836 |
+
if self.first != 1:
|
837 |
+
rank += sum([i != 1 for i in self.first.shape])
|
838 |
+
if self.second != 1:
|
839 |
+
rank += sum([i != 1 for i in self.second.shape])
|
840 |
+
if self.higher != 1:
|
841 |
+
rank += 2
|
842 |
+
return rank
|
843 |
+
|
844 |
+
def _multiply_pointer(self, pointer, other):
|
845 |
+
from ...tensor.array.expressions.array_expressions import ArrayTensorProduct
|
846 |
+
from ...tensor.array.expressions.array_expressions import ArrayContraction
|
847 |
+
|
848 |
+
subexpr = ExprBuilder(
|
849 |
+
ArrayContraction,
|
850 |
+
[
|
851 |
+
ExprBuilder(
|
852 |
+
ArrayTensorProduct,
|
853 |
+
[
|
854 |
+
pointer,
|
855 |
+
other
|
856 |
+
]
|
857 |
+
),
|
858 |
+
(1, 2)
|
859 |
+
],
|
860 |
+
validator=ArrayContraction._validate
|
861 |
+
)
|
862 |
+
|
863 |
+
return subexpr
|
864 |
+
|
865 |
+
def append_first(self, other):
|
866 |
+
self.first_pointer *= other
|
867 |
+
|
868 |
+
def append_second(self, other):
|
869 |
+
self.second_pointer *= other
|
870 |
+
|
871 |
+
|
872 |
+
def _make_matrix(x):
|
873 |
+
from sympy.matrices.immutable import ImmutableDenseMatrix
|
874 |
+
if isinstance(x, MatrixExpr):
|
875 |
+
return x
|
876 |
+
return ImmutableDenseMatrix([[x]])
|
877 |
+
|
878 |
+
|
879 |
+
from .matmul import MatMul
|
880 |
+
from .matadd import MatAdd
|
881 |
+
from .matpow import MatPow
|
882 |
+
from .transpose import Transpose
|
883 |
+
from .inverse import Inverse
|
884 |
+
from .special import ZeroMatrix, Identity
|
885 |
+
from .determinant import Determinant
|
llmeval-env/lib/python3.10/site-packages/sympy/matrices/expressions/matmul.py
ADDED
@@ -0,0 +1,498 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.assumptions.ask import ask, Q
|
2 |
+
from sympy.assumptions.refine import handlers_dict
|
3 |
+
from sympy.core import Basic, sympify, S
|
4 |
+
from sympy.core.mul import mul, Mul
|
5 |
+
from sympy.core.numbers import Number, Integer
|
6 |
+
from sympy.core.symbol import Dummy
|
7 |
+
from sympy.functions import adjoint
|
8 |
+
from sympy.strategies import (rm_id, unpack, typed, flatten, exhaust,
|
9 |
+
do_one, new)
|
10 |
+
from sympy.matrices.common import NonInvertibleMatrixError
|
11 |
+
from sympy.matrices.matrices import MatrixBase
|
12 |
+
from sympy.utilities.exceptions import sympy_deprecation_warning
|
13 |
+
from sympy.matrices.expressions._shape import validate_matmul_integer as validate
|
14 |
+
|
15 |
+
from .inverse import Inverse
|
16 |
+
from .matexpr import MatrixExpr
|
17 |
+
from .matpow import MatPow
|
18 |
+
from .transpose import transpose
|
19 |
+
from .permutation import PermutationMatrix
|
20 |
+
from .special import ZeroMatrix, Identity, GenericIdentity, OneMatrix
|
21 |
+
|
22 |
+
|
23 |
+
# XXX: MatMul should perhaps not subclass directly from Mul
|
24 |
+
class MatMul(MatrixExpr, Mul):
|
25 |
+
"""
|
26 |
+
A product of matrix expressions
|
27 |
+
|
28 |
+
Examples
|
29 |
+
========
|
30 |
+
|
31 |
+
>>> from sympy import MatMul, MatrixSymbol
|
32 |
+
>>> A = MatrixSymbol('A', 5, 4)
|
33 |
+
>>> B = MatrixSymbol('B', 4, 3)
|
34 |
+
>>> C = MatrixSymbol('C', 3, 6)
|
35 |
+
>>> MatMul(A, B, C)
|
36 |
+
A*B*C
|
37 |
+
"""
|
38 |
+
is_MatMul = True
|
39 |
+
|
40 |
+
identity = GenericIdentity()
|
41 |
+
|
42 |
+
def __new__(cls, *args, evaluate=False, check=None, _sympify=True):
|
43 |
+
if not args:
|
44 |
+
return cls.identity
|
45 |
+
|
46 |
+
# This must be removed aggressively in the constructor to avoid
|
47 |
+
# TypeErrors from GenericIdentity().shape
|
48 |
+
args = list(filter(lambda i: cls.identity != i, args))
|
49 |
+
if _sympify:
|
50 |
+
args = list(map(sympify, args))
|
51 |
+
obj = Basic.__new__(cls, *args)
|
52 |
+
factor, matrices = obj.as_coeff_matrices()
|
53 |
+
|
54 |
+
if check is not None:
|
55 |
+
sympy_deprecation_warning(
|
56 |
+
"Passing check to MatMul is deprecated and the check argument will be removed in a future version.",
|
57 |
+
deprecated_since_version="1.11",
|
58 |
+
active_deprecations_target='remove-check-argument-from-matrix-operations')
|
59 |
+
|
60 |
+
if check is not False:
|
61 |
+
validate(*matrices)
|
62 |
+
|
63 |
+
if not matrices:
|
64 |
+
# Should it be
|
65 |
+
#
|
66 |
+
# return Basic.__neq__(cls, factor, GenericIdentity()) ?
|
67 |
+
return factor
|
68 |
+
|
69 |
+
if evaluate:
|
70 |
+
return cls._evaluate(obj)
|
71 |
+
|
72 |
+
return obj
|
73 |
+
|
74 |
+
@classmethod
|
75 |
+
def _evaluate(cls, expr):
|
76 |
+
return canonicalize(expr)
|
77 |
+
|
78 |
+
@property
|
79 |
+
def shape(self):
|
80 |
+
matrices = [arg for arg in self.args if arg.is_Matrix]
|
81 |
+
return (matrices[0].rows, matrices[-1].cols)
|
82 |
+
|
83 |
+
def _entry(self, i, j, expand=True, **kwargs):
|
84 |
+
# Avoid cyclic imports
|
85 |
+
from sympy.concrete.summations import Sum
|
86 |
+
from sympy.matrices.immutable import ImmutableMatrix
|
87 |
+
|
88 |
+
coeff, matrices = self.as_coeff_matrices()
|
89 |
+
|
90 |
+
if len(matrices) == 1: # situation like 2*X, matmul is just X
|
91 |
+
return coeff * matrices[0][i, j]
|
92 |
+
|
93 |
+
indices = [None]*(len(matrices) + 1)
|
94 |
+
ind_ranges = [None]*(len(matrices) - 1)
|
95 |
+
indices[0] = i
|
96 |
+
indices[-1] = j
|
97 |
+
|
98 |
+
def f():
|
99 |
+
counter = 1
|
100 |
+
while True:
|
101 |
+
yield Dummy("i_%i" % counter)
|
102 |
+
counter += 1
|
103 |
+
|
104 |
+
dummy_generator = kwargs.get("dummy_generator", f())
|
105 |
+
|
106 |
+
for i in range(1, len(matrices)):
|
107 |
+
indices[i] = next(dummy_generator)
|
108 |
+
|
109 |
+
for i, arg in enumerate(matrices[:-1]):
|
110 |
+
ind_ranges[i] = arg.shape[1] - 1
|
111 |
+
matrices = [arg._entry(indices[i], indices[i+1], dummy_generator=dummy_generator) for i, arg in enumerate(matrices)]
|
112 |
+
expr_in_sum = Mul.fromiter(matrices)
|
113 |
+
if any(v.has(ImmutableMatrix) for v in matrices):
|
114 |
+
expand = True
|
115 |
+
result = coeff*Sum(
|
116 |
+
expr_in_sum,
|
117 |
+
*zip(indices[1:-1], [0]*len(ind_ranges), ind_ranges)
|
118 |
+
)
|
119 |
+
|
120 |
+
# Don't waste time in result.doit() if the sum bounds are symbolic
|
121 |
+
if not any(isinstance(v, (Integer, int)) for v in ind_ranges):
|
122 |
+
expand = False
|
123 |
+
return result.doit() if expand else result
|
124 |
+
|
125 |
+
def as_coeff_matrices(self):
|
126 |
+
scalars = [x for x in self.args if not x.is_Matrix]
|
127 |
+
matrices = [x for x in self.args if x.is_Matrix]
|
128 |
+
coeff = Mul(*scalars)
|
129 |
+
if coeff.is_commutative is False:
|
130 |
+
raise NotImplementedError("noncommutative scalars in MatMul are not supported.")
|
131 |
+
|
132 |
+
return coeff, matrices
|
133 |
+
|
134 |
+
def as_coeff_mmul(self):
|
135 |
+
coeff, matrices = self.as_coeff_matrices()
|
136 |
+
return coeff, MatMul(*matrices)
|
137 |
+
|
138 |
+
def expand(self, **kwargs):
|
139 |
+
expanded = super(MatMul, self).expand(**kwargs)
|
140 |
+
return self._evaluate(expanded)
|
141 |
+
|
142 |
+
def _eval_transpose(self):
|
143 |
+
"""Transposition of matrix multiplication.
|
144 |
+
|
145 |
+
Notes
|
146 |
+
=====
|
147 |
+
|
148 |
+
The following rules are applied.
|
149 |
+
|
150 |
+
Transposition for matrix multiplied with another matrix:
|
151 |
+
`\\left(A B\\right)^{T} = B^{T} A^{T}`
|
152 |
+
|
153 |
+
Transposition for matrix multiplied with scalar:
|
154 |
+
`\\left(c A\\right)^{T} = c A^{T}`
|
155 |
+
|
156 |
+
References
|
157 |
+
==========
|
158 |
+
|
159 |
+
.. [1] https://en.wikipedia.org/wiki/Transpose
|
160 |
+
"""
|
161 |
+
coeff, matrices = self.as_coeff_matrices()
|
162 |
+
return MatMul(
|
163 |
+
coeff, *[transpose(arg) for arg in matrices[::-1]]).doit()
|
164 |
+
|
165 |
+
def _eval_adjoint(self):
|
166 |
+
return MatMul(*[adjoint(arg) for arg in self.args[::-1]]).doit()
|
167 |
+
|
168 |
+
def _eval_trace(self):
|
169 |
+
factor, mmul = self.as_coeff_mmul()
|
170 |
+
if factor != 1:
|
171 |
+
from .trace import trace
|
172 |
+
return factor * trace(mmul.doit())
|
173 |
+
else:
|
174 |
+
raise NotImplementedError("Can't simplify any further")
|
175 |
+
|
176 |
+
def _eval_determinant(self):
|
177 |
+
from sympy.matrices.expressions.determinant import Determinant
|
178 |
+
factor, matrices = self.as_coeff_matrices()
|
179 |
+
square_matrices = only_squares(*matrices)
|
180 |
+
return factor**self.rows * Mul(*list(map(Determinant, square_matrices)))
|
181 |
+
|
182 |
+
def _eval_inverse(self):
|
183 |
+
if all(arg.is_square for arg in self.args if isinstance(arg, MatrixExpr)):
|
184 |
+
return MatMul(*(
|
185 |
+
arg.inverse() if isinstance(arg, MatrixExpr) else arg**-1
|
186 |
+
for arg in self.args[::-1]
|
187 |
+
)
|
188 |
+
).doit()
|
189 |
+
return Inverse(self)
|
190 |
+
|
191 |
+
def doit(self, **hints):
|
192 |
+
deep = hints.get('deep', True)
|
193 |
+
if deep:
|
194 |
+
args = tuple(arg.doit(**hints) for arg in self.args)
|
195 |
+
else:
|
196 |
+
args = self.args
|
197 |
+
|
198 |
+
# treat scalar*MatrixSymbol or scalar*MatPow separately
|
199 |
+
expr = canonicalize(MatMul(*args))
|
200 |
+
return expr
|
201 |
+
|
202 |
+
# Needed for partial compatibility with Mul
|
203 |
+
def args_cnc(self, cset=False, warn=True, **kwargs):
|
204 |
+
coeff_c = [x for x in self.args if x.is_commutative]
|
205 |
+
coeff_nc = [x for x in self.args if not x.is_commutative]
|
206 |
+
if cset:
|
207 |
+
clen = len(coeff_c)
|
208 |
+
coeff_c = set(coeff_c)
|
209 |
+
if clen and warn and len(coeff_c) != clen:
|
210 |
+
raise ValueError('repeated commutative arguments: %s' %
|
211 |
+
[ci for ci in coeff_c if list(self.args).count(ci) > 1])
|
212 |
+
return [coeff_c, coeff_nc]
|
213 |
+
|
214 |
+
def _eval_derivative_matrix_lines(self, x):
|
215 |
+
from .transpose import Transpose
|
216 |
+
with_x_ind = [i for i, arg in enumerate(self.args) if arg.has(x)]
|
217 |
+
lines = []
|
218 |
+
for ind in with_x_ind:
|
219 |
+
left_args = self.args[:ind]
|
220 |
+
right_args = self.args[ind+1:]
|
221 |
+
|
222 |
+
if right_args:
|
223 |
+
right_mat = MatMul.fromiter(right_args)
|
224 |
+
else:
|
225 |
+
right_mat = Identity(self.shape[1])
|
226 |
+
if left_args:
|
227 |
+
left_rev = MatMul.fromiter([Transpose(i).doit() if i.is_Matrix else i for i in reversed(left_args)])
|
228 |
+
else:
|
229 |
+
left_rev = Identity(self.shape[0])
|
230 |
+
|
231 |
+
d = self.args[ind]._eval_derivative_matrix_lines(x)
|
232 |
+
for i in d:
|
233 |
+
i.append_first(left_rev)
|
234 |
+
i.append_second(right_mat)
|
235 |
+
lines.append(i)
|
236 |
+
|
237 |
+
return lines
|
238 |
+
|
239 |
+
mul.register_handlerclass((Mul, MatMul), MatMul)
|
240 |
+
|
241 |
+
|
242 |
+
# Rules
|
243 |
+
def newmul(*args):
|
244 |
+
if args[0] == 1:
|
245 |
+
args = args[1:]
|
246 |
+
return new(MatMul, *args)
|
247 |
+
|
248 |
+
def any_zeros(mul):
|
249 |
+
if any(arg.is_zero or (arg.is_Matrix and arg.is_ZeroMatrix)
|
250 |
+
for arg in mul.args):
|
251 |
+
matrices = [arg for arg in mul.args if arg.is_Matrix]
|
252 |
+
return ZeroMatrix(matrices[0].rows, matrices[-1].cols)
|
253 |
+
return mul
|
254 |
+
|
255 |
+
def merge_explicit(matmul):
|
256 |
+
""" Merge explicit MatrixBase arguments
|
257 |
+
|
258 |
+
>>> from sympy import MatrixSymbol, Matrix, MatMul, pprint
|
259 |
+
>>> from sympy.matrices.expressions.matmul import merge_explicit
|
260 |
+
>>> A = MatrixSymbol('A', 2, 2)
|
261 |
+
>>> B = Matrix([[1, 1], [1, 1]])
|
262 |
+
>>> C = Matrix([[1, 2], [3, 4]])
|
263 |
+
>>> X = MatMul(A, B, C)
|
264 |
+
>>> pprint(X)
|
265 |
+
[1 1] [1 2]
|
266 |
+
A*[ ]*[ ]
|
267 |
+
[1 1] [3 4]
|
268 |
+
>>> pprint(merge_explicit(X))
|
269 |
+
[4 6]
|
270 |
+
A*[ ]
|
271 |
+
[4 6]
|
272 |
+
|
273 |
+
>>> X = MatMul(B, A, C)
|
274 |
+
>>> pprint(X)
|
275 |
+
[1 1] [1 2]
|
276 |
+
[ ]*A*[ ]
|
277 |
+
[1 1] [3 4]
|
278 |
+
>>> pprint(merge_explicit(X))
|
279 |
+
[1 1] [1 2]
|
280 |
+
[ ]*A*[ ]
|
281 |
+
[1 1] [3 4]
|
282 |
+
"""
|
283 |
+
if not any(isinstance(arg, MatrixBase) for arg in matmul.args):
|
284 |
+
return matmul
|
285 |
+
newargs = []
|
286 |
+
last = matmul.args[0]
|
287 |
+
for arg in matmul.args[1:]:
|
288 |
+
if isinstance(arg, (MatrixBase, Number)) and isinstance(last, (MatrixBase, Number)):
|
289 |
+
last = last * arg
|
290 |
+
else:
|
291 |
+
newargs.append(last)
|
292 |
+
last = arg
|
293 |
+
newargs.append(last)
|
294 |
+
|
295 |
+
return MatMul(*newargs)
|
296 |
+
|
297 |
+
def remove_ids(mul):
|
298 |
+
""" Remove Identities from a MatMul
|
299 |
+
|
300 |
+
This is a modified version of sympy.strategies.rm_id.
|
301 |
+
This is necesssary because MatMul may contain both MatrixExprs and Exprs
|
302 |
+
as args.
|
303 |
+
|
304 |
+
See Also
|
305 |
+
========
|
306 |
+
|
307 |
+
sympy.strategies.rm_id
|
308 |
+
"""
|
309 |
+
# Separate Exprs from MatrixExprs in args
|
310 |
+
factor, mmul = mul.as_coeff_mmul()
|
311 |
+
# Apply standard rm_id for MatMuls
|
312 |
+
result = rm_id(lambda x: x.is_Identity is True)(mmul)
|
313 |
+
if result != mmul:
|
314 |
+
return newmul(factor, *result.args) # Recombine and return
|
315 |
+
else:
|
316 |
+
return mul
|
317 |
+
|
318 |
+
def factor_in_front(mul):
|
319 |
+
factor, matrices = mul.as_coeff_matrices()
|
320 |
+
if factor != 1:
|
321 |
+
return newmul(factor, *matrices)
|
322 |
+
return mul
|
323 |
+
|
324 |
+
def combine_powers(mul):
|
325 |
+
r"""Combine consecutive powers with the same base into one, e.g.
|
326 |
+
$$A \times A^2 \Rightarrow A^3$$
|
327 |
+
|
328 |
+
This also cancels out the possible matrix inverses using the
|
329 |
+
knowledgebase of :class:`~.Inverse`, e.g.,
|
330 |
+
$$ Y \times X \times X^{-1} \Rightarrow Y $$
|
331 |
+
"""
|
332 |
+
factor, args = mul.as_coeff_matrices()
|
333 |
+
new_args = [args[0]]
|
334 |
+
|
335 |
+
for i in range(1, len(args)):
|
336 |
+
A = new_args[-1]
|
337 |
+
B = args[i]
|
338 |
+
|
339 |
+
if isinstance(B, Inverse) and isinstance(B.arg, MatMul):
|
340 |
+
Bargs = B.arg.args
|
341 |
+
l = len(Bargs)
|
342 |
+
if list(Bargs) == new_args[-l:]:
|
343 |
+
new_args = new_args[:-l] + [Identity(B.shape[0])]
|
344 |
+
continue
|
345 |
+
|
346 |
+
if isinstance(A, Inverse) and isinstance(A.arg, MatMul):
|
347 |
+
Aargs = A.arg.args
|
348 |
+
l = len(Aargs)
|
349 |
+
if list(Aargs) == args[i:i+l]:
|
350 |
+
identity = Identity(A.shape[0])
|
351 |
+
new_args[-1] = identity
|
352 |
+
for j in range(i, i+l):
|
353 |
+
args[j] = identity
|
354 |
+
continue
|
355 |
+
|
356 |
+
if A.is_square == False or B.is_square == False:
|
357 |
+
new_args.append(B)
|
358 |
+
continue
|
359 |
+
|
360 |
+
if isinstance(A, MatPow):
|
361 |
+
A_base, A_exp = A.args
|
362 |
+
else:
|
363 |
+
A_base, A_exp = A, S.One
|
364 |
+
|
365 |
+
if isinstance(B, MatPow):
|
366 |
+
B_base, B_exp = B.args
|
367 |
+
else:
|
368 |
+
B_base, B_exp = B, S.One
|
369 |
+
|
370 |
+
if A_base == B_base:
|
371 |
+
new_exp = A_exp + B_exp
|
372 |
+
new_args[-1] = MatPow(A_base, new_exp).doit(deep=False)
|
373 |
+
continue
|
374 |
+
elif not isinstance(B_base, MatrixBase):
|
375 |
+
try:
|
376 |
+
B_base_inv = B_base.inverse()
|
377 |
+
except NonInvertibleMatrixError:
|
378 |
+
B_base_inv = None
|
379 |
+
if B_base_inv is not None and A_base == B_base_inv:
|
380 |
+
new_exp = A_exp - B_exp
|
381 |
+
new_args[-1] = MatPow(A_base, new_exp).doit(deep=False)
|
382 |
+
continue
|
383 |
+
new_args.append(B)
|
384 |
+
|
385 |
+
return newmul(factor, *new_args)
|
386 |
+
|
387 |
+
def combine_permutations(mul):
|
388 |
+
"""Refine products of permutation matrices as the products of cycles.
|
389 |
+
"""
|
390 |
+
args = mul.args
|
391 |
+
l = len(args)
|
392 |
+
if l < 2:
|
393 |
+
return mul
|
394 |
+
|
395 |
+
result = [args[0]]
|
396 |
+
for i in range(1, l):
|
397 |
+
A = result[-1]
|
398 |
+
B = args[i]
|
399 |
+
if isinstance(A, PermutationMatrix) and \
|
400 |
+
isinstance(B, PermutationMatrix):
|
401 |
+
cycle_1 = A.args[0]
|
402 |
+
cycle_2 = B.args[0]
|
403 |
+
result[-1] = PermutationMatrix(cycle_1 * cycle_2)
|
404 |
+
else:
|
405 |
+
result.append(B)
|
406 |
+
|
407 |
+
return MatMul(*result)
|
408 |
+
|
409 |
+
def combine_one_matrices(mul):
|
410 |
+
"""
|
411 |
+
Combine products of OneMatrix
|
412 |
+
|
413 |
+
e.g. OneMatrix(2, 3) * OneMatrix(3, 4) -> 3 * OneMatrix(2, 4)
|
414 |
+
"""
|
415 |
+
factor, args = mul.as_coeff_matrices()
|
416 |
+
new_args = [args[0]]
|
417 |
+
|
418 |
+
for B in args[1:]:
|
419 |
+
A = new_args[-1]
|
420 |
+
if not isinstance(A, OneMatrix) or not isinstance(B, OneMatrix):
|
421 |
+
new_args.append(B)
|
422 |
+
continue
|
423 |
+
new_args.pop()
|
424 |
+
new_args.append(OneMatrix(A.shape[0], B.shape[1]))
|
425 |
+
factor *= A.shape[1]
|
426 |
+
|
427 |
+
return newmul(factor, *new_args)
|
428 |
+
|
429 |
+
def distribute_monom(mul):
|
430 |
+
"""
|
431 |
+
Simplify MatMul expressions but distributing
|
432 |
+
rational term to MatMul.
|
433 |
+
|
434 |
+
e.g. 2*(A+B) -> 2*A + 2*B
|
435 |
+
"""
|
436 |
+
args = mul.args
|
437 |
+
if len(args) == 2:
|
438 |
+
from .matadd import MatAdd
|
439 |
+
if args[0].is_MatAdd and args[1].is_Rational:
|
440 |
+
return MatAdd(*[MatMul(mat, args[1]).doit() for mat in args[0].args])
|
441 |
+
if args[1].is_MatAdd and args[0].is_Rational:
|
442 |
+
return MatAdd(*[MatMul(args[0], mat).doit() for mat in args[1].args])
|
443 |
+
return mul
|
444 |
+
|
445 |
+
rules = (
|
446 |
+
distribute_monom, any_zeros, remove_ids, combine_one_matrices, combine_powers, unpack, rm_id(lambda x: x == 1),
|
447 |
+
merge_explicit, factor_in_front, flatten, combine_permutations)
|
448 |
+
|
449 |
+
canonicalize = exhaust(typed({MatMul: do_one(*rules)}))
|
450 |
+
|
451 |
+
def only_squares(*matrices):
|
452 |
+
"""factor matrices only if they are square"""
|
453 |
+
if matrices[0].rows != matrices[-1].cols:
|
454 |
+
raise RuntimeError("Invalid matrices being multiplied")
|
455 |
+
out = []
|
456 |
+
start = 0
|
457 |
+
for i, M in enumerate(matrices):
|
458 |
+
if M.cols == matrices[start].rows:
|
459 |
+
out.append(MatMul(*matrices[start:i+1]).doit())
|
460 |
+
start = i+1
|
461 |
+
return out
|
462 |
+
|
463 |
+
|
464 |
+
def refine_MatMul(expr, assumptions):
|
465 |
+
"""
|
466 |
+
>>> from sympy import MatrixSymbol, Q, assuming, refine
|
467 |
+
>>> X = MatrixSymbol('X', 2, 2)
|
468 |
+
>>> expr = X * X.T
|
469 |
+
>>> print(expr)
|
470 |
+
X*X.T
|
471 |
+
>>> with assuming(Q.orthogonal(X)):
|
472 |
+
... print(refine(expr))
|
473 |
+
I
|
474 |
+
"""
|
475 |
+
newargs = []
|
476 |
+
exprargs = []
|
477 |
+
|
478 |
+
for args in expr.args:
|
479 |
+
if args.is_Matrix:
|
480 |
+
exprargs.append(args)
|
481 |
+
else:
|
482 |
+
newargs.append(args)
|
483 |
+
|
484 |
+
last = exprargs[0]
|
485 |
+
for arg in exprargs[1:]:
|
486 |
+
if arg == last.T and ask(Q.orthogonal(arg), assumptions):
|
487 |
+
last = Identity(arg.shape[0])
|
488 |
+
elif arg == last.conjugate() and ask(Q.unitary(arg), assumptions):
|
489 |
+
last = Identity(arg.shape[0])
|
490 |
+
else:
|
491 |
+
newargs.append(last)
|
492 |
+
last = arg
|
493 |
+
newargs.append(last)
|
494 |
+
|
495 |
+
return MatMul(*newargs)
|
496 |
+
|
497 |
+
|
498 |
+
handlers_dict['MatMul'] = refine_MatMul
|
llmeval-env/lib/python3.10/site-packages/sympy/matrices/expressions/matpow.py
ADDED
@@ -0,0 +1,142 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from .matexpr import MatrixExpr
|
2 |
+
from .special import Identity
|
3 |
+
from sympy.core import S
|
4 |
+
from sympy.core.expr import ExprBuilder
|
5 |
+
from sympy.core.cache import cacheit
|
6 |
+
from sympy.core.power import Pow
|
7 |
+
from sympy.core.sympify import _sympify
|
8 |
+
from sympy.matrices import MatrixBase
|
9 |
+
from sympy.matrices.common import NonSquareMatrixError
|
10 |
+
|
11 |
+
|
12 |
+
class MatPow(MatrixExpr):
|
13 |
+
def __new__(cls, base, exp, evaluate=False, **options):
|
14 |
+
base = _sympify(base)
|
15 |
+
if not base.is_Matrix:
|
16 |
+
raise TypeError("MatPow base should be a matrix")
|
17 |
+
|
18 |
+
if base.is_square is False:
|
19 |
+
raise NonSquareMatrixError("Power of non-square matrix %s" % base)
|
20 |
+
|
21 |
+
exp = _sympify(exp)
|
22 |
+
obj = super().__new__(cls, base, exp)
|
23 |
+
|
24 |
+
if evaluate:
|
25 |
+
obj = obj.doit(deep=False)
|
26 |
+
|
27 |
+
return obj
|
28 |
+
|
29 |
+
@property
|
30 |
+
def base(self):
|
31 |
+
return self.args[0]
|
32 |
+
|
33 |
+
@property
|
34 |
+
def exp(self):
|
35 |
+
return self.args[1]
|
36 |
+
|
37 |
+
@property
|
38 |
+
def shape(self):
|
39 |
+
return self.base.shape
|
40 |
+
|
41 |
+
@cacheit
|
42 |
+
def _get_explicit_matrix(self):
|
43 |
+
return self.base.as_explicit()**self.exp
|
44 |
+
|
45 |
+
def _entry(self, i, j, **kwargs):
|
46 |
+
from sympy.matrices.expressions import MatMul
|
47 |
+
A = self.doit()
|
48 |
+
if isinstance(A, MatPow):
|
49 |
+
# We still have a MatPow, make an explicit MatMul out of it.
|
50 |
+
if A.exp.is_Integer and A.exp.is_positive:
|
51 |
+
A = MatMul(*[A.base for k in range(A.exp)])
|
52 |
+
elif not self._is_shape_symbolic():
|
53 |
+
return A._get_explicit_matrix()[i, j]
|
54 |
+
else:
|
55 |
+
# Leave the expression unevaluated:
|
56 |
+
from sympy.matrices.expressions.matexpr import MatrixElement
|
57 |
+
return MatrixElement(self, i, j)
|
58 |
+
return A[i, j]
|
59 |
+
|
60 |
+
def doit(self, **hints):
|
61 |
+
if hints.get('deep', True):
|
62 |
+
base, exp = (arg.doit(**hints) for arg in self.args)
|
63 |
+
else:
|
64 |
+
base, exp = self.args
|
65 |
+
|
66 |
+
# combine all powers, e.g. (A ** 2) ** 3 -> A ** 6
|
67 |
+
while isinstance(base, MatPow):
|
68 |
+
exp *= base.args[1]
|
69 |
+
base = base.args[0]
|
70 |
+
|
71 |
+
if isinstance(base, MatrixBase):
|
72 |
+
# Delegate
|
73 |
+
return base ** exp
|
74 |
+
|
75 |
+
# Handle simple cases so that _eval_power() in MatrixExpr sub-classes can ignore them
|
76 |
+
if exp == S.One:
|
77 |
+
return base
|
78 |
+
if exp == S.Zero:
|
79 |
+
return Identity(base.rows)
|
80 |
+
if exp == S.NegativeOne:
|
81 |
+
from sympy.matrices.expressions import Inverse
|
82 |
+
return Inverse(base).doit(**hints)
|
83 |
+
|
84 |
+
eval_power = getattr(base, '_eval_power', None)
|
85 |
+
if eval_power is not None:
|
86 |
+
return eval_power(exp)
|
87 |
+
|
88 |
+
return MatPow(base, exp)
|
89 |
+
|
90 |
+
def _eval_transpose(self):
|
91 |
+
base, exp = self.args
|
92 |
+
return MatPow(base.T, exp)
|
93 |
+
|
94 |
+
def _eval_derivative(self, x):
|
95 |
+
return Pow._eval_derivative(self, x)
|
96 |
+
|
97 |
+
def _eval_derivative_matrix_lines(self, x):
|
98 |
+
from sympy.tensor.array.expressions.array_expressions import ArrayContraction
|
99 |
+
from ...tensor.array.expressions.array_expressions import ArrayTensorProduct
|
100 |
+
from .matmul import MatMul
|
101 |
+
from .inverse import Inverse
|
102 |
+
exp = self.exp
|
103 |
+
if self.base.shape == (1, 1) and not exp.has(x):
|
104 |
+
lr = self.base._eval_derivative_matrix_lines(x)
|
105 |
+
for i in lr:
|
106 |
+
subexpr = ExprBuilder(
|
107 |
+
ArrayContraction,
|
108 |
+
[
|
109 |
+
ExprBuilder(
|
110 |
+
ArrayTensorProduct,
|
111 |
+
[
|
112 |
+
Identity(1),
|
113 |
+
i._lines[0],
|
114 |
+
exp*self.base**(exp-1),
|
115 |
+
i._lines[1],
|
116 |
+
Identity(1),
|
117 |
+
]
|
118 |
+
),
|
119 |
+
(0, 3, 4), (5, 7, 8)
|
120 |
+
],
|
121 |
+
validator=ArrayContraction._validate
|
122 |
+
)
|
123 |
+
i._first_pointer_parent = subexpr.args[0].args
|
124 |
+
i._first_pointer_index = 0
|
125 |
+
i._second_pointer_parent = subexpr.args[0].args
|
126 |
+
i._second_pointer_index = 4
|
127 |
+
i._lines = [subexpr]
|
128 |
+
return lr
|
129 |
+
if (exp > 0) == True:
|
130 |
+
newexpr = MatMul.fromiter([self.base for i in range(exp)])
|
131 |
+
elif (exp == -1) == True:
|
132 |
+
return Inverse(self.base)._eval_derivative_matrix_lines(x)
|
133 |
+
elif (exp < 0) == True:
|
134 |
+
newexpr = MatMul.fromiter([Inverse(self.base) for i in range(-exp)])
|
135 |
+
elif (exp == 0) == True:
|
136 |
+
return self.doit()._eval_derivative_matrix_lines(x)
|
137 |
+
else:
|
138 |
+
raise NotImplementedError("cannot evaluate %s derived by %s" % (self, x))
|
139 |
+
return newexpr._eval_derivative_matrix_lines(x)
|
140 |
+
|
141 |
+
def _eval_inverse(self):
|
142 |
+
return MatPow(self.base, -self.exp)
|
llmeval-env/lib/python3.10/site-packages/sympy/matrices/expressions/permutation.py
ADDED
@@ -0,0 +1,303 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.core import S
|
2 |
+
from sympy.core.sympify import _sympify
|
3 |
+
from sympy.functions import KroneckerDelta
|
4 |
+
|
5 |
+
from .matexpr import MatrixExpr
|
6 |
+
from .special import ZeroMatrix, Identity, OneMatrix
|
7 |
+
|
8 |
+
|
9 |
+
class PermutationMatrix(MatrixExpr):
|
10 |
+
"""A Permutation Matrix
|
11 |
+
|
12 |
+
Parameters
|
13 |
+
==========
|
14 |
+
|
15 |
+
perm : Permutation
|
16 |
+
The permutation the matrix uses.
|
17 |
+
|
18 |
+
The size of the permutation determines the matrix size.
|
19 |
+
|
20 |
+
See the documentation of
|
21 |
+
:class:`sympy.combinatorics.permutations.Permutation` for
|
22 |
+
the further information of how to create a permutation object.
|
23 |
+
|
24 |
+
Examples
|
25 |
+
========
|
26 |
+
|
27 |
+
>>> from sympy import Matrix, PermutationMatrix
|
28 |
+
>>> from sympy.combinatorics import Permutation
|
29 |
+
|
30 |
+
Creating a permutation matrix:
|
31 |
+
|
32 |
+
>>> p = Permutation(1, 2, 0)
|
33 |
+
>>> P = PermutationMatrix(p)
|
34 |
+
>>> P = P.as_explicit()
|
35 |
+
>>> P
|
36 |
+
Matrix([
|
37 |
+
[0, 1, 0],
|
38 |
+
[0, 0, 1],
|
39 |
+
[1, 0, 0]])
|
40 |
+
|
41 |
+
Permuting a matrix row and column:
|
42 |
+
|
43 |
+
>>> M = Matrix([0, 1, 2])
|
44 |
+
>>> Matrix(P*M)
|
45 |
+
Matrix([
|
46 |
+
[1],
|
47 |
+
[2],
|
48 |
+
[0]])
|
49 |
+
|
50 |
+
>>> Matrix(M.T*P)
|
51 |
+
Matrix([[2, 0, 1]])
|
52 |
+
|
53 |
+
See Also
|
54 |
+
========
|
55 |
+
|
56 |
+
sympy.combinatorics.permutations.Permutation
|
57 |
+
"""
|
58 |
+
|
59 |
+
def __new__(cls, perm):
|
60 |
+
from sympy.combinatorics.permutations import Permutation
|
61 |
+
|
62 |
+
perm = _sympify(perm)
|
63 |
+
if not isinstance(perm, Permutation):
|
64 |
+
raise ValueError(
|
65 |
+
"{} must be a SymPy Permutation instance.".format(perm))
|
66 |
+
|
67 |
+
return super().__new__(cls, perm)
|
68 |
+
|
69 |
+
@property
|
70 |
+
def shape(self):
|
71 |
+
size = self.args[0].size
|
72 |
+
return (size, size)
|
73 |
+
|
74 |
+
@property
|
75 |
+
def is_Identity(self):
|
76 |
+
return self.args[0].is_Identity
|
77 |
+
|
78 |
+
def doit(self, **hints):
|
79 |
+
if self.is_Identity:
|
80 |
+
return Identity(self.rows)
|
81 |
+
return self
|
82 |
+
|
83 |
+
def _entry(self, i, j, **kwargs):
|
84 |
+
perm = self.args[0]
|
85 |
+
return KroneckerDelta(perm.apply(i), j)
|
86 |
+
|
87 |
+
def _eval_power(self, exp):
|
88 |
+
return PermutationMatrix(self.args[0] ** exp).doit()
|
89 |
+
|
90 |
+
def _eval_inverse(self):
|
91 |
+
return PermutationMatrix(self.args[0] ** -1)
|
92 |
+
|
93 |
+
_eval_transpose = _eval_adjoint = _eval_inverse
|
94 |
+
|
95 |
+
def _eval_determinant(self):
|
96 |
+
sign = self.args[0].signature()
|
97 |
+
if sign == 1:
|
98 |
+
return S.One
|
99 |
+
elif sign == -1:
|
100 |
+
return S.NegativeOne
|
101 |
+
raise NotImplementedError
|
102 |
+
|
103 |
+
def _eval_rewrite_as_BlockDiagMatrix(self, *args, **kwargs):
|
104 |
+
from sympy.combinatorics.permutations import Permutation
|
105 |
+
from .blockmatrix import BlockDiagMatrix
|
106 |
+
|
107 |
+
perm = self.args[0]
|
108 |
+
full_cyclic_form = perm.full_cyclic_form
|
109 |
+
|
110 |
+
cycles_picks = []
|
111 |
+
|
112 |
+
# Stage 1. Decompose the cycles into the blockable form.
|
113 |
+
a, b, c = 0, 0, 0
|
114 |
+
flag = False
|
115 |
+
for cycle in full_cyclic_form:
|
116 |
+
l = len(cycle)
|
117 |
+
m = max(cycle)
|
118 |
+
|
119 |
+
if not flag:
|
120 |
+
if m + 1 > a + l:
|
121 |
+
flag = True
|
122 |
+
temp = [cycle]
|
123 |
+
b = m
|
124 |
+
c = l
|
125 |
+
else:
|
126 |
+
cycles_picks.append([cycle])
|
127 |
+
a += l
|
128 |
+
|
129 |
+
else:
|
130 |
+
if m > b:
|
131 |
+
if m + 1 == a + c + l:
|
132 |
+
temp.append(cycle)
|
133 |
+
cycles_picks.append(temp)
|
134 |
+
flag = False
|
135 |
+
a = m+1
|
136 |
+
else:
|
137 |
+
b = m
|
138 |
+
temp.append(cycle)
|
139 |
+
c += l
|
140 |
+
else:
|
141 |
+
if b + 1 == a + c + l:
|
142 |
+
temp.append(cycle)
|
143 |
+
cycles_picks.append(temp)
|
144 |
+
flag = False
|
145 |
+
a = b+1
|
146 |
+
else:
|
147 |
+
temp.append(cycle)
|
148 |
+
c += l
|
149 |
+
|
150 |
+
# Stage 2. Normalize each decomposed cycles and build matrix.
|
151 |
+
p = 0
|
152 |
+
args = []
|
153 |
+
for pick in cycles_picks:
|
154 |
+
new_cycles = []
|
155 |
+
l = 0
|
156 |
+
for cycle in pick:
|
157 |
+
new_cycle = [i - p for i in cycle]
|
158 |
+
new_cycles.append(new_cycle)
|
159 |
+
l += len(cycle)
|
160 |
+
p += l
|
161 |
+
perm = Permutation(new_cycles)
|
162 |
+
mat = PermutationMatrix(perm)
|
163 |
+
args.append(mat)
|
164 |
+
|
165 |
+
return BlockDiagMatrix(*args)
|
166 |
+
|
167 |
+
|
168 |
+
class MatrixPermute(MatrixExpr):
|
169 |
+
r"""Symbolic representation for permuting matrix rows or columns.
|
170 |
+
|
171 |
+
Parameters
|
172 |
+
==========
|
173 |
+
|
174 |
+
perm : Permutation, PermutationMatrix
|
175 |
+
The permutation to use for permuting the matrix.
|
176 |
+
The permutation can be resized to the suitable one,
|
177 |
+
|
178 |
+
axis : 0 or 1
|
179 |
+
The axis to permute alongside.
|
180 |
+
If `0`, it will permute the matrix rows.
|
181 |
+
If `1`, it will permute the matrix columns.
|
182 |
+
|
183 |
+
Notes
|
184 |
+
=====
|
185 |
+
|
186 |
+
This follows the same notation used in
|
187 |
+
:meth:`sympy.matrices.common.MatrixCommon.permute`.
|
188 |
+
|
189 |
+
Examples
|
190 |
+
========
|
191 |
+
|
192 |
+
>>> from sympy import Matrix, MatrixPermute
|
193 |
+
>>> from sympy.combinatorics import Permutation
|
194 |
+
|
195 |
+
Permuting the matrix rows:
|
196 |
+
|
197 |
+
>>> p = Permutation(1, 2, 0)
|
198 |
+
>>> A = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
|
199 |
+
>>> B = MatrixPermute(A, p, axis=0)
|
200 |
+
>>> B.as_explicit()
|
201 |
+
Matrix([
|
202 |
+
[4, 5, 6],
|
203 |
+
[7, 8, 9],
|
204 |
+
[1, 2, 3]])
|
205 |
+
|
206 |
+
Permuting the matrix columns:
|
207 |
+
|
208 |
+
>>> B = MatrixPermute(A, p, axis=1)
|
209 |
+
>>> B.as_explicit()
|
210 |
+
Matrix([
|
211 |
+
[2, 3, 1],
|
212 |
+
[5, 6, 4],
|
213 |
+
[8, 9, 7]])
|
214 |
+
|
215 |
+
See Also
|
216 |
+
========
|
217 |
+
|
218 |
+
sympy.matrices.common.MatrixCommon.permute
|
219 |
+
"""
|
220 |
+
def __new__(cls, mat, perm, axis=S.Zero):
|
221 |
+
from sympy.combinatorics.permutations import Permutation
|
222 |
+
|
223 |
+
mat = _sympify(mat)
|
224 |
+
if not mat.is_Matrix:
|
225 |
+
raise ValueError(
|
226 |
+
"{} must be a SymPy matrix instance.".format(perm))
|
227 |
+
|
228 |
+
perm = _sympify(perm)
|
229 |
+
if isinstance(perm, PermutationMatrix):
|
230 |
+
perm = perm.args[0]
|
231 |
+
|
232 |
+
if not isinstance(perm, Permutation):
|
233 |
+
raise ValueError(
|
234 |
+
"{} must be a SymPy Permutation or a PermutationMatrix " \
|
235 |
+
"instance".format(perm))
|
236 |
+
|
237 |
+
axis = _sympify(axis)
|
238 |
+
if axis not in (0, 1):
|
239 |
+
raise ValueError("The axis must be 0 or 1.")
|
240 |
+
|
241 |
+
mat_size = mat.shape[axis]
|
242 |
+
if mat_size != perm.size:
|
243 |
+
try:
|
244 |
+
perm = perm.resize(mat_size)
|
245 |
+
except ValueError:
|
246 |
+
raise ValueError(
|
247 |
+
"Size does not match between the permutation {} "
|
248 |
+
"and the matrix {} threaded over the axis {} "
|
249 |
+
"and cannot be converted."
|
250 |
+
.format(perm, mat, axis))
|
251 |
+
|
252 |
+
return super().__new__(cls, mat, perm, axis)
|
253 |
+
|
254 |
+
def doit(self, deep=True, **hints):
|
255 |
+
mat, perm, axis = self.args
|
256 |
+
|
257 |
+
if deep:
|
258 |
+
mat = mat.doit(deep=deep, **hints)
|
259 |
+
perm = perm.doit(deep=deep, **hints)
|
260 |
+
|
261 |
+
if perm.is_Identity:
|
262 |
+
return mat
|
263 |
+
|
264 |
+
if mat.is_Identity:
|
265 |
+
if axis is S.Zero:
|
266 |
+
return PermutationMatrix(perm)
|
267 |
+
elif axis is S.One:
|
268 |
+
return PermutationMatrix(perm**-1)
|
269 |
+
|
270 |
+
if isinstance(mat, (ZeroMatrix, OneMatrix)):
|
271 |
+
return mat
|
272 |
+
|
273 |
+
if isinstance(mat, MatrixPermute) and mat.args[2] == axis:
|
274 |
+
return MatrixPermute(mat.args[0], perm * mat.args[1], axis)
|
275 |
+
|
276 |
+
return self
|
277 |
+
|
278 |
+
@property
|
279 |
+
def shape(self):
|
280 |
+
return self.args[0].shape
|
281 |
+
|
282 |
+
def _entry(self, i, j, **kwargs):
|
283 |
+
mat, perm, axis = self.args
|
284 |
+
|
285 |
+
if axis == 0:
|
286 |
+
return mat[perm.apply(i), j]
|
287 |
+
elif axis == 1:
|
288 |
+
return mat[i, perm.apply(j)]
|
289 |
+
|
290 |
+
def _eval_rewrite_as_MatMul(self, *args, **kwargs):
|
291 |
+
from .matmul import MatMul
|
292 |
+
|
293 |
+
mat, perm, axis = self.args
|
294 |
+
|
295 |
+
deep = kwargs.get("deep", True)
|
296 |
+
|
297 |
+
if deep:
|
298 |
+
mat = mat.rewrite(MatMul)
|
299 |
+
|
300 |
+
if axis == 0:
|
301 |
+
return MatMul(PermutationMatrix(perm), mat)
|
302 |
+
elif axis == 1:
|
303 |
+
return MatMul(mat, PermutationMatrix(perm**-1))
|
llmeval-env/lib/python3.10/site-packages/sympy/matrices/expressions/sets.py
ADDED
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.core.assumptions import check_assumptions
|
2 |
+
from sympy.core.logic import fuzzy_and
|
3 |
+
from sympy.core.sympify import _sympify
|
4 |
+
from sympy.matrices.common import MatrixKind
|
5 |
+
from sympy.sets.sets import Set, SetKind
|
6 |
+
from sympy.core.kind import NumberKind
|
7 |
+
from .matexpr import MatrixExpr
|
8 |
+
|
9 |
+
|
10 |
+
class MatrixSet(Set):
|
11 |
+
"""
|
12 |
+
MatrixSet represents the set of matrices with ``shape = (n, m)`` over the
|
13 |
+
given set.
|
14 |
+
|
15 |
+
Examples
|
16 |
+
========
|
17 |
+
|
18 |
+
>>> from sympy.matrices import MatrixSet
|
19 |
+
>>> from sympy import S, I, Matrix
|
20 |
+
>>> M = MatrixSet(2, 2, set=S.Reals)
|
21 |
+
>>> X = Matrix([[1, 2], [3, 4]])
|
22 |
+
>>> X in M
|
23 |
+
True
|
24 |
+
>>> X = Matrix([[1, 2], [I, 4]])
|
25 |
+
>>> X in M
|
26 |
+
False
|
27 |
+
|
28 |
+
"""
|
29 |
+
is_empty = False
|
30 |
+
|
31 |
+
def __new__(cls, n, m, set):
|
32 |
+
n, m, set = _sympify(n), _sympify(m), _sympify(set)
|
33 |
+
cls._check_dim(n)
|
34 |
+
cls._check_dim(m)
|
35 |
+
if not isinstance(set, Set):
|
36 |
+
raise TypeError("{} should be an instance of Set.".format(set))
|
37 |
+
return Set.__new__(cls, n, m, set)
|
38 |
+
|
39 |
+
@property
|
40 |
+
def shape(self):
|
41 |
+
return self.args[:2]
|
42 |
+
|
43 |
+
@property
|
44 |
+
def set(self):
|
45 |
+
return self.args[2]
|
46 |
+
|
47 |
+
def _contains(self, other):
|
48 |
+
if not isinstance(other, MatrixExpr):
|
49 |
+
raise TypeError("{} should be an instance of MatrixExpr.".format(other))
|
50 |
+
if other.shape != self.shape:
|
51 |
+
are_symbolic = any(_sympify(x).is_Symbol for x in other.shape + self.shape)
|
52 |
+
if are_symbolic:
|
53 |
+
return None
|
54 |
+
return False
|
55 |
+
return fuzzy_and(self.set.contains(x) for x in other)
|
56 |
+
|
57 |
+
@classmethod
|
58 |
+
def _check_dim(cls, dim):
|
59 |
+
"""Helper function to check invalid matrix dimensions"""
|
60 |
+
ok = check_assumptions(dim, integer=True, nonnegative=True)
|
61 |
+
if ok is False:
|
62 |
+
raise ValueError(
|
63 |
+
"The dimension specification {} should be "
|
64 |
+
"a nonnegative integer.".format(dim))
|
65 |
+
|
66 |
+
def _kind(self):
|
67 |
+
return SetKind(MatrixKind(NumberKind))
|
llmeval-env/lib/python3.10/site-packages/sympy/matrices/expressions/slice.py
ADDED
@@ -0,0 +1,114 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.matrices.expressions.matexpr import MatrixExpr
|
2 |
+
from sympy.core.basic import Basic
|
3 |
+
from sympy.core.containers import Tuple
|
4 |
+
from sympy.functions.elementary.integers import floor
|
5 |
+
|
6 |
+
def normalize(i, parentsize):
|
7 |
+
if isinstance(i, slice):
|
8 |
+
i = (i.start, i.stop, i.step)
|
9 |
+
if not isinstance(i, (tuple, list, Tuple)):
|
10 |
+
if (i < 0) == True:
|
11 |
+
i += parentsize
|
12 |
+
i = (i, i+1, 1)
|
13 |
+
i = list(i)
|
14 |
+
if len(i) == 2:
|
15 |
+
i.append(1)
|
16 |
+
start, stop, step = i
|
17 |
+
start = start or 0
|
18 |
+
if stop is None:
|
19 |
+
stop = parentsize
|
20 |
+
if (start < 0) == True:
|
21 |
+
start += parentsize
|
22 |
+
if (stop < 0) == True:
|
23 |
+
stop += parentsize
|
24 |
+
step = step or 1
|
25 |
+
|
26 |
+
if ((stop - start) * step < 1) == True:
|
27 |
+
raise IndexError()
|
28 |
+
|
29 |
+
return (start, stop, step)
|
30 |
+
|
31 |
+
class MatrixSlice(MatrixExpr):
|
32 |
+
""" A MatrixSlice of a Matrix Expression
|
33 |
+
|
34 |
+
Examples
|
35 |
+
========
|
36 |
+
|
37 |
+
>>> from sympy import MatrixSlice, ImmutableMatrix
|
38 |
+
>>> M = ImmutableMatrix(4, 4, range(16))
|
39 |
+
>>> M
|
40 |
+
Matrix([
|
41 |
+
[ 0, 1, 2, 3],
|
42 |
+
[ 4, 5, 6, 7],
|
43 |
+
[ 8, 9, 10, 11],
|
44 |
+
[12, 13, 14, 15]])
|
45 |
+
|
46 |
+
>>> B = MatrixSlice(M, (0, 2), (2, 4))
|
47 |
+
>>> ImmutableMatrix(B)
|
48 |
+
Matrix([
|
49 |
+
[2, 3],
|
50 |
+
[6, 7]])
|
51 |
+
"""
|
52 |
+
parent = property(lambda self: self.args[0])
|
53 |
+
rowslice = property(lambda self: self.args[1])
|
54 |
+
colslice = property(lambda self: self.args[2])
|
55 |
+
|
56 |
+
def __new__(cls, parent, rowslice, colslice):
|
57 |
+
rowslice = normalize(rowslice, parent.shape[0])
|
58 |
+
colslice = normalize(colslice, parent.shape[1])
|
59 |
+
if not (len(rowslice) == len(colslice) == 3):
|
60 |
+
raise IndexError()
|
61 |
+
if ((0 > rowslice[0]) == True or
|
62 |
+
(parent.shape[0] < rowslice[1]) == True or
|
63 |
+
(0 > colslice[0]) == True or
|
64 |
+
(parent.shape[1] < colslice[1]) == True):
|
65 |
+
raise IndexError()
|
66 |
+
if isinstance(parent, MatrixSlice):
|
67 |
+
return mat_slice_of_slice(parent, rowslice, colslice)
|
68 |
+
return Basic.__new__(cls, parent, Tuple(*rowslice), Tuple(*colslice))
|
69 |
+
|
70 |
+
@property
|
71 |
+
def shape(self):
|
72 |
+
rows = self.rowslice[1] - self.rowslice[0]
|
73 |
+
rows = rows if self.rowslice[2] == 1 else floor(rows/self.rowslice[2])
|
74 |
+
cols = self.colslice[1] - self.colslice[0]
|
75 |
+
cols = cols if self.colslice[2] == 1 else floor(cols/self.colslice[2])
|
76 |
+
return rows, cols
|
77 |
+
|
78 |
+
def _entry(self, i, j, **kwargs):
|
79 |
+
return self.parent._entry(i*self.rowslice[2] + self.rowslice[0],
|
80 |
+
j*self.colslice[2] + self.colslice[0],
|
81 |
+
**kwargs)
|
82 |
+
|
83 |
+
@property
|
84 |
+
def on_diag(self):
|
85 |
+
return self.rowslice == self.colslice
|
86 |
+
|
87 |
+
|
88 |
+
def slice_of_slice(s, t):
|
89 |
+
start1, stop1, step1 = s
|
90 |
+
start2, stop2, step2 = t
|
91 |
+
|
92 |
+
start = start1 + start2*step1
|
93 |
+
step = step1 * step2
|
94 |
+
stop = start1 + step1*stop2
|
95 |
+
|
96 |
+
if stop > stop1:
|
97 |
+
raise IndexError()
|
98 |
+
|
99 |
+
return start, stop, step
|
100 |
+
|
101 |
+
|
102 |
+
def mat_slice_of_slice(parent, rowslice, colslice):
|
103 |
+
""" Collapse nested matrix slices
|
104 |
+
|
105 |
+
>>> from sympy import MatrixSymbol
|
106 |
+
>>> X = MatrixSymbol('X', 10, 10)
|
107 |
+
>>> X[:, 1:5][5:8, :]
|
108 |
+
X[5:8, 1:5]
|
109 |
+
>>> X[1:9:2, 2:6][1:3, 2]
|
110 |
+
X[3:7:2, 4:5]
|
111 |
+
"""
|
112 |
+
row = slice_of_slice(parent.rowslice, rowslice)
|
113 |
+
col = slice_of_slice(parent.colslice, colslice)
|
114 |
+
return MatrixSlice(parent.parent, row, col)
|
llmeval-env/lib/python3.10/site-packages/sympy/matrices/expressions/special.py
ADDED
@@ -0,0 +1,299 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.assumptions.ask import ask, Q
|
2 |
+
from sympy.core.relational import Eq
|
3 |
+
from sympy.core.singleton import S
|
4 |
+
from sympy.core.sympify import _sympify
|
5 |
+
from sympy.functions.special.tensor_functions import KroneckerDelta
|
6 |
+
from sympy.matrices.common import NonInvertibleMatrixError
|
7 |
+
from .matexpr import MatrixExpr
|
8 |
+
|
9 |
+
|
10 |
+
class ZeroMatrix(MatrixExpr):
|
11 |
+
"""The Matrix Zero 0 - additive identity
|
12 |
+
|
13 |
+
Examples
|
14 |
+
========
|
15 |
+
|
16 |
+
>>> from sympy import MatrixSymbol, ZeroMatrix
|
17 |
+
>>> A = MatrixSymbol('A', 3, 5)
|
18 |
+
>>> Z = ZeroMatrix(3, 5)
|
19 |
+
>>> A + Z
|
20 |
+
A
|
21 |
+
>>> Z*A.T
|
22 |
+
0
|
23 |
+
"""
|
24 |
+
is_ZeroMatrix = True
|
25 |
+
|
26 |
+
def __new__(cls, m, n):
|
27 |
+
m, n = _sympify(m), _sympify(n)
|
28 |
+
cls._check_dim(m)
|
29 |
+
cls._check_dim(n)
|
30 |
+
|
31 |
+
return super().__new__(cls, m, n)
|
32 |
+
|
33 |
+
@property
|
34 |
+
def shape(self):
|
35 |
+
return (self.args[0], self.args[1])
|
36 |
+
|
37 |
+
def _eval_power(self, exp):
|
38 |
+
# exp = -1, 0, 1 are already handled at this stage
|
39 |
+
if (exp < 0) == True:
|
40 |
+
raise NonInvertibleMatrixError("Matrix det == 0; not invertible")
|
41 |
+
return self
|
42 |
+
|
43 |
+
def _eval_transpose(self):
|
44 |
+
return ZeroMatrix(self.cols, self.rows)
|
45 |
+
|
46 |
+
def _eval_adjoint(self):
|
47 |
+
return ZeroMatrix(self.cols, self.rows)
|
48 |
+
|
49 |
+
def _eval_trace(self):
|
50 |
+
return S.Zero
|
51 |
+
|
52 |
+
def _eval_determinant(self):
|
53 |
+
return S.Zero
|
54 |
+
|
55 |
+
def _eval_inverse(self):
|
56 |
+
raise NonInvertibleMatrixError("Matrix det == 0; not invertible.")
|
57 |
+
|
58 |
+
def _eval_as_real_imag(self):
|
59 |
+
return (self, self)
|
60 |
+
|
61 |
+
def _eval_conjugate(self):
|
62 |
+
return self
|
63 |
+
|
64 |
+
def _entry(self, i, j, **kwargs):
|
65 |
+
return S.Zero
|
66 |
+
|
67 |
+
|
68 |
+
class GenericZeroMatrix(ZeroMatrix):
|
69 |
+
"""
|
70 |
+
A zero matrix without a specified shape
|
71 |
+
|
72 |
+
This exists primarily so MatAdd() with no arguments can return something
|
73 |
+
meaningful.
|
74 |
+
"""
|
75 |
+
def __new__(cls):
|
76 |
+
# super(ZeroMatrix, cls) instead of super(GenericZeroMatrix, cls)
|
77 |
+
# because ZeroMatrix.__new__ doesn't have the same signature
|
78 |
+
return super(ZeroMatrix, cls).__new__(cls)
|
79 |
+
|
80 |
+
@property
|
81 |
+
def rows(self):
|
82 |
+
raise TypeError("GenericZeroMatrix does not have a specified shape")
|
83 |
+
|
84 |
+
@property
|
85 |
+
def cols(self):
|
86 |
+
raise TypeError("GenericZeroMatrix does not have a specified shape")
|
87 |
+
|
88 |
+
@property
|
89 |
+
def shape(self):
|
90 |
+
raise TypeError("GenericZeroMatrix does not have a specified shape")
|
91 |
+
|
92 |
+
# Avoid Matrix.__eq__ which might call .shape
|
93 |
+
def __eq__(self, other):
|
94 |
+
return isinstance(other, GenericZeroMatrix)
|
95 |
+
|
96 |
+
def __ne__(self, other):
|
97 |
+
return not (self == other)
|
98 |
+
|
99 |
+
def __hash__(self):
|
100 |
+
return super().__hash__()
|
101 |
+
|
102 |
+
|
103 |
+
|
104 |
+
class Identity(MatrixExpr):
|
105 |
+
"""The Matrix Identity I - multiplicative identity
|
106 |
+
|
107 |
+
Examples
|
108 |
+
========
|
109 |
+
|
110 |
+
>>> from sympy import Identity, MatrixSymbol
|
111 |
+
>>> A = MatrixSymbol('A', 3, 5)
|
112 |
+
>>> I = Identity(3)
|
113 |
+
>>> I*A
|
114 |
+
A
|
115 |
+
"""
|
116 |
+
|
117 |
+
is_Identity = True
|
118 |
+
|
119 |
+
def __new__(cls, n):
|
120 |
+
n = _sympify(n)
|
121 |
+
cls._check_dim(n)
|
122 |
+
|
123 |
+
return super().__new__(cls, n)
|
124 |
+
|
125 |
+
@property
|
126 |
+
def rows(self):
|
127 |
+
return self.args[0]
|
128 |
+
|
129 |
+
@property
|
130 |
+
def cols(self):
|
131 |
+
return self.args[0]
|
132 |
+
|
133 |
+
@property
|
134 |
+
def shape(self):
|
135 |
+
return (self.args[0], self.args[0])
|
136 |
+
|
137 |
+
@property
|
138 |
+
def is_square(self):
|
139 |
+
return True
|
140 |
+
|
141 |
+
def _eval_transpose(self):
|
142 |
+
return self
|
143 |
+
|
144 |
+
def _eval_trace(self):
|
145 |
+
return self.rows
|
146 |
+
|
147 |
+
def _eval_inverse(self):
|
148 |
+
return self
|
149 |
+
|
150 |
+
def _eval_as_real_imag(self):
|
151 |
+
return (self, ZeroMatrix(*self.shape))
|
152 |
+
|
153 |
+
def _eval_conjugate(self):
|
154 |
+
return self
|
155 |
+
|
156 |
+
def _eval_adjoint(self):
|
157 |
+
return self
|
158 |
+
|
159 |
+
def _entry(self, i, j, **kwargs):
|
160 |
+
eq = Eq(i, j)
|
161 |
+
if eq is S.true:
|
162 |
+
return S.One
|
163 |
+
elif eq is S.false:
|
164 |
+
return S.Zero
|
165 |
+
return KroneckerDelta(i, j, (0, self.cols-1))
|
166 |
+
|
167 |
+
def _eval_determinant(self):
|
168 |
+
return S.One
|
169 |
+
|
170 |
+
def _eval_power(self, exp):
|
171 |
+
return self
|
172 |
+
|
173 |
+
|
174 |
+
class GenericIdentity(Identity):
|
175 |
+
"""
|
176 |
+
An identity matrix without a specified shape
|
177 |
+
|
178 |
+
This exists primarily so MatMul() with no arguments can return something
|
179 |
+
meaningful.
|
180 |
+
"""
|
181 |
+
def __new__(cls):
|
182 |
+
# super(Identity, cls) instead of super(GenericIdentity, cls) because
|
183 |
+
# Identity.__new__ doesn't have the same signature
|
184 |
+
return super(Identity, cls).__new__(cls)
|
185 |
+
|
186 |
+
@property
|
187 |
+
def rows(self):
|
188 |
+
raise TypeError("GenericIdentity does not have a specified shape")
|
189 |
+
|
190 |
+
@property
|
191 |
+
def cols(self):
|
192 |
+
raise TypeError("GenericIdentity does not have a specified shape")
|
193 |
+
|
194 |
+
@property
|
195 |
+
def shape(self):
|
196 |
+
raise TypeError("GenericIdentity does not have a specified shape")
|
197 |
+
|
198 |
+
@property
|
199 |
+
def is_square(self):
|
200 |
+
return True
|
201 |
+
|
202 |
+
# Avoid Matrix.__eq__ which might call .shape
|
203 |
+
def __eq__(self, other):
|
204 |
+
return isinstance(other, GenericIdentity)
|
205 |
+
|
206 |
+
def __ne__(self, other):
|
207 |
+
return not (self == other)
|
208 |
+
|
209 |
+
def __hash__(self):
|
210 |
+
return super().__hash__()
|
211 |
+
|
212 |
+
|
213 |
+
class OneMatrix(MatrixExpr):
|
214 |
+
"""
|
215 |
+
Matrix whose all entries are ones.
|
216 |
+
"""
|
217 |
+
def __new__(cls, m, n, evaluate=False):
|
218 |
+
m, n = _sympify(m), _sympify(n)
|
219 |
+
cls._check_dim(m)
|
220 |
+
cls._check_dim(n)
|
221 |
+
|
222 |
+
if evaluate:
|
223 |
+
condition = Eq(m, 1) & Eq(n, 1)
|
224 |
+
if condition == True:
|
225 |
+
return Identity(1)
|
226 |
+
|
227 |
+
obj = super().__new__(cls, m, n)
|
228 |
+
return obj
|
229 |
+
|
230 |
+
@property
|
231 |
+
def shape(self):
|
232 |
+
return self._args
|
233 |
+
|
234 |
+
@property
|
235 |
+
def is_Identity(self):
|
236 |
+
return self._is_1x1() == True
|
237 |
+
|
238 |
+
def as_explicit(self):
|
239 |
+
from sympy.matrices.immutable import ImmutableDenseMatrix
|
240 |
+
return ImmutableDenseMatrix.ones(*self.shape)
|
241 |
+
|
242 |
+
def doit(self, **hints):
|
243 |
+
args = self.args
|
244 |
+
if hints.get('deep', True):
|
245 |
+
args = [a.doit(**hints) for a in args]
|
246 |
+
return self.func(*args, evaluate=True)
|
247 |
+
|
248 |
+
def _eval_power(self, exp):
|
249 |
+
# exp = -1, 0, 1 are already handled at this stage
|
250 |
+
if self._is_1x1() == True:
|
251 |
+
return Identity(1)
|
252 |
+
if (exp < 0) == True:
|
253 |
+
raise NonInvertibleMatrixError("Matrix det == 0; not invertible")
|
254 |
+
if ask(Q.integer(exp)):
|
255 |
+
return self.shape[0] ** (exp - 1) * OneMatrix(*self.shape)
|
256 |
+
return super()._eval_power(exp)
|
257 |
+
|
258 |
+
def _eval_transpose(self):
|
259 |
+
return OneMatrix(self.cols, self.rows)
|
260 |
+
|
261 |
+
def _eval_adjoint(self):
|
262 |
+
return OneMatrix(self.cols, self.rows)
|
263 |
+
|
264 |
+
def _eval_trace(self):
|
265 |
+
return S.One*self.rows
|
266 |
+
|
267 |
+
def _is_1x1(self):
|
268 |
+
"""Returns true if the matrix is known to be 1x1"""
|
269 |
+
shape = self.shape
|
270 |
+
return Eq(shape[0], 1) & Eq(shape[1], 1)
|
271 |
+
|
272 |
+
def _eval_determinant(self):
|
273 |
+
condition = self._is_1x1()
|
274 |
+
if condition == True:
|
275 |
+
return S.One
|
276 |
+
elif condition == False:
|
277 |
+
return S.Zero
|
278 |
+
else:
|
279 |
+
from sympy.matrices.expressions.determinant import Determinant
|
280 |
+
return Determinant(self)
|
281 |
+
|
282 |
+
def _eval_inverse(self):
|
283 |
+
condition = self._is_1x1()
|
284 |
+
if condition == True:
|
285 |
+
return Identity(1)
|
286 |
+
elif condition == False:
|
287 |
+
raise NonInvertibleMatrixError("Matrix det == 0; not invertible.")
|
288 |
+
else:
|
289 |
+
from .inverse import Inverse
|
290 |
+
return Inverse(self)
|
291 |
+
|
292 |
+
def _eval_as_real_imag(self):
|
293 |
+
return (self, ZeroMatrix(*self.shape))
|
294 |
+
|
295 |
+
def _eval_conjugate(self):
|
296 |
+
return self
|
297 |
+
|
298 |
+
def _entry(self, i, j, **kwargs):
|
299 |
+
return S.One
|
llmeval-env/lib/python3.10/site-packages/sympy/matrices/expressions/tests/__init__.py
ADDED
File without changes
|
llmeval-env/lib/python3.10/site-packages/sympy/matrices/expressions/tests/test_adjoint.py
ADDED
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.core import symbols, S
|
2 |
+
from sympy.functions import adjoint, conjugate, transpose
|
3 |
+
from sympy.matrices.expressions import MatrixSymbol, Adjoint, trace, Transpose
|
4 |
+
from sympy.matrices import eye, Matrix
|
5 |
+
|
6 |
+
n, m, l, k, p = symbols('n m l k p', integer=True)
|
7 |
+
A = MatrixSymbol('A', n, m)
|
8 |
+
B = MatrixSymbol('B', m, l)
|
9 |
+
C = MatrixSymbol('C', n, n)
|
10 |
+
|
11 |
+
|
12 |
+
def test_adjoint():
|
13 |
+
Sq = MatrixSymbol('Sq', n, n)
|
14 |
+
|
15 |
+
assert Adjoint(A).shape == (m, n)
|
16 |
+
assert Adjoint(A*B).shape == (l, n)
|
17 |
+
assert adjoint(Adjoint(A)) == A
|
18 |
+
assert isinstance(Adjoint(Adjoint(A)), Adjoint)
|
19 |
+
|
20 |
+
assert conjugate(Adjoint(A)) == Transpose(A)
|
21 |
+
assert transpose(Adjoint(A)) == Adjoint(Transpose(A))
|
22 |
+
|
23 |
+
assert Adjoint(eye(3)).doit() == eye(3)
|
24 |
+
|
25 |
+
assert Adjoint(S(5)).doit() == S(5)
|
26 |
+
|
27 |
+
assert Adjoint(Matrix([[1, 2], [3, 4]])).doit() == Matrix([[1, 3], [2, 4]])
|
28 |
+
|
29 |
+
assert adjoint(trace(Sq)) == conjugate(trace(Sq))
|
30 |
+
assert trace(adjoint(Sq)) == conjugate(trace(Sq))
|
31 |
+
|
32 |
+
assert Adjoint(Sq)[0, 1] == conjugate(Sq[1, 0])
|
33 |
+
|
34 |
+
assert Adjoint(A*B).doit() == Adjoint(B) * Adjoint(A)
|
llmeval-env/lib/python3.10/site-packages/sympy/matrices/expressions/tests/test_applyfunc.py
ADDED
@@ -0,0 +1,118 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.core.symbol import symbols, Dummy
|
2 |
+
from sympy.matrices.expressions.applyfunc import ElementwiseApplyFunction
|
3 |
+
from sympy.core.function import Lambda
|
4 |
+
from sympy.functions.elementary.exponential import exp
|
5 |
+
from sympy.functions.elementary.trigonometric import sin
|
6 |
+
from sympy.matrices.dense import Matrix
|
7 |
+
from sympy.matrices.expressions.matexpr import MatrixSymbol
|
8 |
+
from sympy.matrices.expressions.matmul import MatMul
|
9 |
+
from sympy.simplify.simplify import simplify
|
10 |
+
|
11 |
+
|
12 |
+
X = MatrixSymbol("X", 3, 3)
|
13 |
+
Y = MatrixSymbol("Y", 3, 3)
|
14 |
+
|
15 |
+
k = symbols("k")
|
16 |
+
Xk = MatrixSymbol("X", k, k)
|
17 |
+
|
18 |
+
Xd = X.as_explicit()
|
19 |
+
|
20 |
+
x, y, z, t = symbols("x y z t")
|
21 |
+
|
22 |
+
|
23 |
+
def test_applyfunc_matrix():
|
24 |
+
x = Dummy('x')
|
25 |
+
double = Lambda(x, x**2)
|
26 |
+
|
27 |
+
expr = ElementwiseApplyFunction(double, Xd)
|
28 |
+
assert isinstance(expr, ElementwiseApplyFunction)
|
29 |
+
assert expr.doit() == Xd.applyfunc(lambda x: x**2)
|
30 |
+
assert expr.shape == (3, 3)
|
31 |
+
assert expr.func(*expr.args) == expr
|
32 |
+
assert simplify(expr) == expr
|
33 |
+
assert expr[0, 0] == double(Xd[0, 0])
|
34 |
+
|
35 |
+
expr = ElementwiseApplyFunction(double, X)
|
36 |
+
assert isinstance(expr, ElementwiseApplyFunction)
|
37 |
+
assert isinstance(expr.doit(), ElementwiseApplyFunction)
|
38 |
+
assert expr == X.applyfunc(double)
|
39 |
+
assert expr.func(*expr.args) == expr
|
40 |
+
|
41 |
+
expr = ElementwiseApplyFunction(exp, X*Y)
|
42 |
+
assert expr.expr == X*Y
|
43 |
+
assert expr.function.dummy_eq(Lambda(x, exp(x)))
|
44 |
+
assert expr.dummy_eq((X*Y).applyfunc(exp))
|
45 |
+
assert expr.func(*expr.args) == expr
|
46 |
+
|
47 |
+
assert isinstance(X*expr, MatMul)
|
48 |
+
assert (X*expr).shape == (3, 3)
|
49 |
+
Z = MatrixSymbol("Z", 2, 3)
|
50 |
+
assert (Z*expr).shape == (2, 3)
|
51 |
+
|
52 |
+
expr = ElementwiseApplyFunction(exp, Z.T)*ElementwiseApplyFunction(exp, Z)
|
53 |
+
assert expr.shape == (3, 3)
|
54 |
+
expr = ElementwiseApplyFunction(exp, Z)*ElementwiseApplyFunction(exp, Z.T)
|
55 |
+
assert expr.shape == (2, 2)
|
56 |
+
|
57 |
+
M = Matrix([[x, y], [z, t]])
|
58 |
+
expr = ElementwiseApplyFunction(sin, M)
|
59 |
+
assert isinstance(expr, ElementwiseApplyFunction)
|
60 |
+
assert expr.function.dummy_eq(Lambda(x, sin(x)))
|
61 |
+
assert expr.expr == M
|
62 |
+
assert expr.doit() == M.applyfunc(sin)
|
63 |
+
assert expr.doit() == Matrix([[sin(x), sin(y)], [sin(z), sin(t)]])
|
64 |
+
assert expr.func(*expr.args) == expr
|
65 |
+
|
66 |
+
expr = ElementwiseApplyFunction(double, Xk)
|
67 |
+
assert expr.doit() == expr
|
68 |
+
assert expr.subs(k, 2).shape == (2, 2)
|
69 |
+
assert (expr*expr).shape == (k, k)
|
70 |
+
M = MatrixSymbol("M", k, t)
|
71 |
+
expr2 = M.T*expr*M
|
72 |
+
assert isinstance(expr2, MatMul)
|
73 |
+
assert expr2.args[1] == expr
|
74 |
+
assert expr2.shape == (t, t)
|
75 |
+
expr3 = expr*M
|
76 |
+
assert expr3.shape == (k, t)
|
77 |
+
|
78 |
+
expr1 = ElementwiseApplyFunction(lambda x: x+1, Xk)
|
79 |
+
expr2 = ElementwiseApplyFunction(lambda x: x, Xk)
|
80 |
+
assert expr1 != expr2
|
81 |
+
|
82 |
+
|
83 |
+
def test_applyfunc_entry():
|
84 |
+
|
85 |
+
af = X.applyfunc(sin)
|
86 |
+
assert af[0, 0] == sin(X[0, 0])
|
87 |
+
|
88 |
+
af = Xd.applyfunc(sin)
|
89 |
+
assert af[0, 0] == sin(X[0, 0])
|
90 |
+
|
91 |
+
|
92 |
+
def test_applyfunc_as_explicit():
|
93 |
+
|
94 |
+
af = X.applyfunc(sin)
|
95 |
+
assert af.as_explicit() == Matrix([
|
96 |
+
[sin(X[0, 0]), sin(X[0, 1]), sin(X[0, 2])],
|
97 |
+
[sin(X[1, 0]), sin(X[1, 1]), sin(X[1, 2])],
|
98 |
+
[sin(X[2, 0]), sin(X[2, 1]), sin(X[2, 2])],
|
99 |
+
])
|
100 |
+
|
101 |
+
|
102 |
+
def test_applyfunc_transpose():
|
103 |
+
|
104 |
+
af = Xk.applyfunc(sin)
|
105 |
+
assert af.T.dummy_eq(Xk.T.applyfunc(sin))
|
106 |
+
|
107 |
+
|
108 |
+
def test_applyfunc_shape_11_matrices():
|
109 |
+
M = MatrixSymbol("M", 1, 1)
|
110 |
+
|
111 |
+
double = Lambda(x, x*2)
|
112 |
+
|
113 |
+
expr = M.applyfunc(sin)
|
114 |
+
assert isinstance(expr, ElementwiseApplyFunction)
|
115 |
+
|
116 |
+
expr = M.applyfunc(double)
|
117 |
+
assert isinstance(expr, MatMul)
|
118 |
+
assert expr == 2*M
|
llmeval-env/lib/python3.10/site-packages/sympy/matrices/expressions/tests/test_blockmatrix.py
ADDED
@@ -0,0 +1,445 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.matrices.expressions.trace import Trace
|
2 |
+
from sympy.testing.pytest import raises, slow
|
3 |
+
from sympy.matrices.expressions.blockmatrix import (
|
4 |
+
block_collapse, bc_matmul, bc_block_plus_ident, BlockDiagMatrix,
|
5 |
+
BlockMatrix, bc_dist, bc_matadd, bc_transpose, bc_inverse,
|
6 |
+
blockcut, reblock_2x2, deblock)
|
7 |
+
from sympy.matrices.expressions import (MatrixSymbol, Identity,
|
8 |
+
Inverse, trace, Transpose, det, ZeroMatrix, OneMatrix)
|
9 |
+
from sympy.matrices.common import NonInvertibleMatrixError
|
10 |
+
from sympy.matrices import (
|
11 |
+
Matrix, ImmutableMatrix, ImmutableSparseMatrix)
|
12 |
+
from sympy.core import Tuple, symbols, Expr, S
|
13 |
+
from sympy.functions import transpose, im, re
|
14 |
+
|
15 |
+
i, j, k, l, m, n, p = symbols('i:n, p', integer=True)
|
16 |
+
A = MatrixSymbol('A', n, n)
|
17 |
+
B = MatrixSymbol('B', n, n)
|
18 |
+
C = MatrixSymbol('C', n, n)
|
19 |
+
D = MatrixSymbol('D', n, n)
|
20 |
+
G = MatrixSymbol('G', n, n)
|
21 |
+
H = MatrixSymbol('H', n, n)
|
22 |
+
b1 = BlockMatrix([[G, H]])
|
23 |
+
b2 = BlockMatrix([[G], [H]])
|
24 |
+
|
25 |
+
def test_bc_matmul():
|
26 |
+
assert bc_matmul(H*b1*b2*G) == BlockMatrix([[(H*G*G + H*H*H)*G]])
|
27 |
+
|
28 |
+
def test_bc_matadd():
|
29 |
+
assert bc_matadd(BlockMatrix([[G, H]]) + BlockMatrix([[H, H]])) == \
|
30 |
+
BlockMatrix([[G+H, H+H]])
|
31 |
+
|
32 |
+
def test_bc_transpose():
|
33 |
+
assert bc_transpose(Transpose(BlockMatrix([[A, B], [C, D]]))) == \
|
34 |
+
BlockMatrix([[A.T, C.T], [B.T, D.T]])
|
35 |
+
|
36 |
+
def test_bc_dist_diag():
|
37 |
+
A = MatrixSymbol('A', n, n)
|
38 |
+
B = MatrixSymbol('B', m, m)
|
39 |
+
C = MatrixSymbol('C', l, l)
|
40 |
+
X = BlockDiagMatrix(A, B, C)
|
41 |
+
|
42 |
+
assert bc_dist(X+X).equals(BlockDiagMatrix(2*A, 2*B, 2*C))
|
43 |
+
|
44 |
+
def test_block_plus_ident():
|
45 |
+
A = MatrixSymbol('A', n, n)
|
46 |
+
B = MatrixSymbol('B', n, m)
|
47 |
+
C = MatrixSymbol('C', m, n)
|
48 |
+
D = MatrixSymbol('D', m, m)
|
49 |
+
X = BlockMatrix([[A, B], [C, D]])
|
50 |
+
Z = MatrixSymbol('Z', n + m, n + m)
|
51 |
+
assert bc_block_plus_ident(X + Identity(m + n) + Z) == \
|
52 |
+
BlockDiagMatrix(Identity(n), Identity(m)) + X + Z
|
53 |
+
|
54 |
+
def test_BlockMatrix():
|
55 |
+
A = MatrixSymbol('A', n, m)
|
56 |
+
B = MatrixSymbol('B', n, k)
|
57 |
+
C = MatrixSymbol('C', l, m)
|
58 |
+
D = MatrixSymbol('D', l, k)
|
59 |
+
M = MatrixSymbol('M', m + k, p)
|
60 |
+
N = MatrixSymbol('N', l + n, k + m)
|
61 |
+
X = BlockMatrix(Matrix([[A, B], [C, D]]))
|
62 |
+
|
63 |
+
assert X.__class__(*X.args) == X
|
64 |
+
|
65 |
+
# block_collapse does nothing on normal inputs
|
66 |
+
E = MatrixSymbol('E', n, m)
|
67 |
+
assert block_collapse(A + 2*E) == A + 2*E
|
68 |
+
F = MatrixSymbol('F', m, m)
|
69 |
+
assert block_collapse(E.T*A*F) == E.T*A*F
|
70 |
+
|
71 |
+
assert X.shape == (l + n, k + m)
|
72 |
+
assert X.blockshape == (2, 2)
|
73 |
+
assert transpose(X) == BlockMatrix(Matrix([[A.T, C.T], [B.T, D.T]]))
|
74 |
+
assert transpose(X).shape == X.shape[::-1]
|
75 |
+
|
76 |
+
# Test that BlockMatrices and MatrixSymbols can still mix
|
77 |
+
assert (X*M).is_MatMul
|
78 |
+
assert X._blockmul(M).is_MatMul
|
79 |
+
assert (X*M).shape == (n + l, p)
|
80 |
+
assert (X + N).is_MatAdd
|
81 |
+
assert X._blockadd(N).is_MatAdd
|
82 |
+
assert (X + N).shape == X.shape
|
83 |
+
|
84 |
+
E = MatrixSymbol('E', m, 1)
|
85 |
+
F = MatrixSymbol('F', k, 1)
|
86 |
+
|
87 |
+
Y = BlockMatrix(Matrix([[E], [F]]))
|
88 |
+
|
89 |
+
assert (X*Y).shape == (l + n, 1)
|
90 |
+
assert block_collapse(X*Y).blocks[0, 0] == A*E + B*F
|
91 |
+
assert block_collapse(X*Y).blocks[1, 0] == C*E + D*F
|
92 |
+
|
93 |
+
# block_collapse passes down into container objects, transposes, and inverse
|
94 |
+
assert block_collapse(transpose(X*Y)) == transpose(block_collapse(X*Y))
|
95 |
+
assert block_collapse(Tuple(X*Y, 2*X)) == (
|
96 |
+
block_collapse(X*Y), block_collapse(2*X))
|
97 |
+
|
98 |
+
# Make sure that MatrixSymbols will enter 1x1 BlockMatrix if it simplifies
|
99 |
+
Ab = BlockMatrix([[A]])
|
100 |
+
Z = MatrixSymbol('Z', *A.shape)
|
101 |
+
assert block_collapse(Ab + Z) == A + Z
|
102 |
+
|
103 |
+
def test_block_collapse_explicit_matrices():
|
104 |
+
A = Matrix([[1, 2], [3, 4]])
|
105 |
+
assert block_collapse(BlockMatrix([[A]])) == A
|
106 |
+
|
107 |
+
A = ImmutableSparseMatrix([[1, 2], [3, 4]])
|
108 |
+
assert block_collapse(BlockMatrix([[A]])) == A
|
109 |
+
|
110 |
+
def test_issue_17624():
|
111 |
+
a = MatrixSymbol("a", 2, 2)
|
112 |
+
z = ZeroMatrix(2, 2)
|
113 |
+
b = BlockMatrix([[a, z], [z, z]])
|
114 |
+
assert block_collapse(b * b) == BlockMatrix([[a**2, z], [z, z]])
|
115 |
+
assert block_collapse(b * b * b) == BlockMatrix([[a**3, z], [z, z]])
|
116 |
+
|
117 |
+
def test_issue_18618():
|
118 |
+
A = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
|
119 |
+
assert A == Matrix(BlockDiagMatrix(A))
|
120 |
+
|
121 |
+
def test_BlockMatrix_trace():
|
122 |
+
A, B, C, D = [MatrixSymbol(s, 3, 3) for s in 'ABCD']
|
123 |
+
X = BlockMatrix([[A, B], [C, D]])
|
124 |
+
assert trace(X) == trace(A) + trace(D)
|
125 |
+
assert trace(BlockMatrix([ZeroMatrix(n, n)])) == 0
|
126 |
+
|
127 |
+
def test_BlockMatrix_Determinant():
|
128 |
+
A, B, C, D = [MatrixSymbol(s, 3, 3) for s in 'ABCD']
|
129 |
+
X = BlockMatrix([[A, B], [C, D]])
|
130 |
+
from sympy.assumptions.ask import Q
|
131 |
+
from sympy.assumptions.assume import assuming
|
132 |
+
with assuming(Q.invertible(A)):
|
133 |
+
assert det(X) == det(A) * det(X.schur('A'))
|
134 |
+
|
135 |
+
assert isinstance(det(X), Expr)
|
136 |
+
assert det(BlockMatrix([A])) == det(A)
|
137 |
+
assert det(BlockMatrix([ZeroMatrix(n, n)])) == 0
|
138 |
+
|
139 |
+
def test_squareBlockMatrix():
|
140 |
+
A = MatrixSymbol('A', n, n)
|
141 |
+
B = MatrixSymbol('B', n, m)
|
142 |
+
C = MatrixSymbol('C', m, n)
|
143 |
+
D = MatrixSymbol('D', m, m)
|
144 |
+
X = BlockMatrix([[A, B], [C, D]])
|
145 |
+
Y = BlockMatrix([[A]])
|
146 |
+
|
147 |
+
assert X.is_square
|
148 |
+
|
149 |
+
Q = X + Identity(m + n)
|
150 |
+
assert (block_collapse(Q) ==
|
151 |
+
BlockMatrix([[A + Identity(n), B], [C, D + Identity(m)]]))
|
152 |
+
|
153 |
+
assert (X + MatrixSymbol('Q', n + m, n + m)).is_MatAdd
|
154 |
+
assert (X * MatrixSymbol('Q', n + m, n + m)).is_MatMul
|
155 |
+
|
156 |
+
assert block_collapse(Y.I) == A.I
|
157 |
+
|
158 |
+
assert isinstance(X.inverse(), Inverse)
|
159 |
+
|
160 |
+
assert not X.is_Identity
|
161 |
+
|
162 |
+
Z = BlockMatrix([[Identity(n), B], [C, D]])
|
163 |
+
assert not Z.is_Identity
|
164 |
+
|
165 |
+
|
166 |
+
def test_BlockMatrix_2x2_inverse_symbolic():
|
167 |
+
A = MatrixSymbol('A', n, m)
|
168 |
+
B = MatrixSymbol('B', n, k - m)
|
169 |
+
C = MatrixSymbol('C', k - n, m)
|
170 |
+
D = MatrixSymbol('D', k - n, k - m)
|
171 |
+
X = BlockMatrix([[A, B], [C, D]])
|
172 |
+
assert X.is_square and X.shape == (k, k)
|
173 |
+
assert isinstance(block_collapse(X.I), Inverse) # Can't invert when none of the blocks is square
|
174 |
+
|
175 |
+
# test code path where only A is invertible
|
176 |
+
A = MatrixSymbol('A', n, n)
|
177 |
+
B = MatrixSymbol('B', n, m)
|
178 |
+
C = MatrixSymbol('C', m, n)
|
179 |
+
D = ZeroMatrix(m, m)
|
180 |
+
X = BlockMatrix([[A, B], [C, D]])
|
181 |
+
assert block_collapse(X.inverse()) == BlockMatrix([
|
182 |
+
[A.I + A.I * B * X.schur('A').I * C * A.I, -A.I * B * X.schur('A').I],
|
183 |
+
[-X.schur('A').I * C * A.I, X.schur('A').I],
|
184 |
+
])
|
185 |
+
|
186 |
+
# test code path where only B is invertible
|
187 |
+
A = MatrixSymbol('A', n, m)
|
188 |
+
B = MatrixSymbol('B', n, n)
|
189 |
+
C = ZeroMatrix(m, m)
|
190 |
+
D = MatrixSymbol('D', m, n)
|
191 |
+
X = BlockMatrix([[A, B], [C, D]])
|
192 |
+
assert block_collapse(X.inverse()) == BlockMatrix([
|
193 |
+
[-X.schur('B').I * D * B.I, X.schur('B').I],
|
194 |
+
[B.I + B.I * A * X.schur('B').I * D * B.I, -B.I * A * X.schur('B').I],
|
195 |
+
])
|
196 |
+
|
197 |
+
# test code path where only C is invertible
|
198 |
+
A = MatrixSymbol('A', n, m)
|
199 |
+
B = ZeroMatrix(n, n)
|
200 |
+
C = MatrixSymbol('C', m, m)
|
201 |
+
D = MatrixSymbol('D', m, n)
|
202 |
+
X = BlockMatrix([[A, B], [C, D]])
|
203 |
+
assert block_collapse(X.inverse()) == BlockMatrix([
|
204 |
+
[-C.I * D * X.schur('C').I, C.I + C.I * D * X.schur('C').I * A * C.I],
|
205 |
+
[X.schur('C').I, -X.schur('C').I * A * C.I],
|
206 |
+
])
|
207 |
+
|
208 |
+
# test code path where only D is invertible
|
209 |
+
A = ZeroMatrix(n, n)
|
210 |
+
B = MatrixSymbol('B', n, m)
|
211 |
+
C = MatrixSymbol('C', m, n)
|
212 |
+
D = MatrixSymbol('D', m, m)
|
213 |
+
X = BlockMatrix([[A, B], [C, D]])
|
214 |
+
assert block_collapse(X.inverse()) == BlockMatrix([
|
215 |
+
[X.schur('D').I, -X.schur('D').I * B * D.I],
|
216 |
+
[-D.I * C * X.schur('D').I, D.I + D.I * C * X.schur('D').I * B * D.I],
|
217 |
+
])
|
218 |
+
|
219 |
+
|
220 |
+
def test_BlockMatrix_2x2_inverse_numeric():
|
221 |
+
"""Test 2x2 block matrix inversion numerically for all 4 formulas"""
|
222 |
+
M = Matrix([[1, 2], [3, 4]])
|
223 |
+
# rank deficient matrices that have full rank when two of them combined
|
224 |
+
D1 = Matrix([[1, 2], [2, 4]])
|
225 |
+
D2 = Matrix([[1, 3], [3, 9]])
|
226 |
+
D3 = Matrix([[1, 4], [4, 16]])
|
227 |
+
assert D1.rank() == D2.rank() == D3.rank() == 1
|
228 |
+
assert (D1 + D2).rank() == (D2 + D3).rank() == (D3 + D1).rank() == 2
|
229 |
+
|
230 |
+
# Only A is invertible
|
231 |
+
K = BlockMatrix([[M, D1], [D2, D3]])
|
232 |
+
assert block_collapse(K.inv()).as_explicit() == K.as_explicit().inv()
|
233 |
+
# Only B is invertible
|
234 |
+
K = BlockMatrix([[D1, M], [D2, D3]])
|
235 |
+
assert block_collapse(K.inv()).as_explicit() == K.as_explicit().inv()
|
236 |
+
# Only C is invertible
|
237 |
+
K = BlockMatrix([[D1, D2], [M, D3]])
|
238 |
+
assert block_collapse(K.inv()).as_explicit() == K.as_explicit().inv()
|
239 |
+
# Only D is invertible
|
240 |
+
K = BlockMatrix([[D1, D2], [D3, M]])
|
241 |
+
assert block_collapse(K.inv()).as_explicit() == K.as_explicit().inv()
|
242 |
+
|
243 |
+
|
244 |
+
@slow
|
245 |
+
def test_BlockMatrix_3x3_symbolic():
|
246 |
+
# Only test one of these, instead of all permutations, because it's slow
|
247 |
+
rowblocksizes = (n, m, k)
|
248 |
+
colblocksizes = (m, k, n)
|
249 |
+
K = BlockMatrix([
|
250 |
+
[MatrixSymbol('M%s%s' % (rows, cols), rows, cols) for cols in colblocksizes]
|
251 |
+
for rows in rowblocksizes
|
252 |
+
])
|
253 |
+
collapse = block_collapse(K.I)
|
254 |
+
assert isinstance(collapse, BlockMatrix)
|
255 |
+
|
256 |
+
|
257 |
+
def test_BlockDiagMatrix():
|
258 |
+
A = MatrixSymbol('A', n, n)
|
259 |
+
B = MatrixSymbol('B', m, m)
|
260 |
+
C = MatrixSymbol('C', l, l)
|
261 |
+
M = MatrixSymbol('M', n + m + l, n + m + l)
|
262 |
+
|
263 |
+
X = BlockDiagMatrix(A, B, C)
|
264 |
+
Y = BlockDiagMatrix(A, 2*B, 3*C)
|
265 |
+
|
266 |
+
assert X.blocks[1, 1] == B
|
267 |
+
assert X.shape == (n + m + l, n + m + l)
|
268 |
+
assert all(X.blocks[i, j].is_ZeroMatrix if i != j else X.blocks[i, j] in [A, B, C]
|
269 |
+
for i in range(3) for j in range(3))
|
270 |
+
assert X.__class__(*X.args) == X
|
271 |
+
assert X.get_diag_blocks() == (A, B, C)
|
272 |
+
|
273 |
+
assert isinstance(block_collapse(X.I * X), Identity)
|
274 |
+
|
275 |
+
assert bc_matmul(X*X) == BlockDiagMatrix(A*A, B*B, C*C)
|
276 |
+
assert block_collapse(X*X) == BlockDiagMatrix(A*A, B*B, C*C)
|
277 |
+
#XXX: should be == ??
|
278 |
+
assert block_collapse(X + X).equals(BlockDiagMatrix(2*A, 2*B, 2*C))
|
279 |
+
assert block_collapse(X*Y) == BlockDiagMatrix(A*A, 2*B*B, 3*C*C)
|
280 |
+
assert block_collapse(X + Y) == BlockDiagMatrix(2*A, 3*B, 4*C)
|
281 |
+
|
282 |
+
# Ensure that BlockDiagMatrices can still interact with normal MatrixExprs
|
283 |
+
assert (X*(2*M)).is_MatMul
|
284 |
+
assert (X + (2*M)).is_MatAdd
|
285 |
+
|
286 |
+
assert (X._blockmul(M)).is_MatMul
|
287 |
+
assert (X._blockadd(M)).is_MatAdd
|
288 |
+
|
289 |
+
def test_BlockDiagMatrix_nonsquare():
|
290 |
+
A = MatrixSymbol('A', n, m)
|
291 |
+
B = MatrixSymbol('B', k, l)
|
292 |
+
X = BlockDiagMatrix(A, B)
|
293 |
+
assert X.shape == (n + k, m + l)
|
294 |
+
assert X.shape == (n + k, m + l)
|
295 |
+
assert X.rowblocksizes == [n, k]
|
296 |
+
assert X.colblocksizes == [m, l]
|
297 |
+
C = MatrixSymbol('C', n, m)
|
298 |
+
D = MatrixSymbol('D', k, l)
|
299 |
+
Y = BlockDiagMatrix(C, D)
|
300 |
+
assert block_collapse(X + Y) == BlockDiagMatrix(A + C, B + D)
|
301 |
+
assert block_collapse(X * Y.T) == BlockDiagMatrix(A * C.T, B * D.T)
|
302 |
+
raises(NonInvertibleMatrixError, lambda: BlockDiagMatrix(A, C.T).inverse())
|
303 |
+
|
304 |
+
def test_BlockDiagMatrix_determinant():
|
305 |
+
A = MatrixSymbol('A', n, n)
|
306 |
+
B = MatrixSymbol('B', m, m)
|
307 |
+
assert det(BlockDiagMatrix()) == 1
|
308 |
+
assert det(BlockDiagMatrix(A)) == det(A)
|
309 |
+
assert det(BlockDiagMatrix(A, B)) == det(A) * det(B)
|
310 |
+
|
311 |
+
# non-square blocks
|
312 |
+
C = MatrixSymbol('C', m, n)
|
313 |
+
D = MatrixSymbol('D', n, m)
|
314 |
+
assert det(BlockDiagMatrix(C, D)) == 0
|
315 |
+
|
316 |
+
def test_BlockDiagMatrix_trace():
|
317 |
+
assert trace(BlockDiagMatrix()) == 0
|
318 |
+
assert trace(BlockDiagMatrix(ZeroMatrix(n, n))) == 0
|
319 |
+
A = MatrixSymbol('A', n, n)
|
320 |
+
assert trace(BlockDiagMatrix(A)) == trace(A)
|
321 |
+
B = MatrixSymbol('B', m, m)
|
322 |
+
assert trace(BlockDiagMatrix(A, B)) == trace(A) + trace(B)
|
323 |
+
|
324 |
+
# non-square blocks
|
325 |
+
C = MatrixSymbol('C', m, n)
|
326 |
+
D = MatrixSymbol('D', n, m)
|
327 |
+
assert isinstance(trace(BlockDiagMatrix(C, D)), Trace)
|
328 |
+
|
329 |
+
def test_BlockDiagMatrix_transpose():
|
330 |
+
A = MatrixSymbol('A', n, m)
|
331 |
+
B = MatrixSymbol('B', k, l)
|
332 |
+
assert transpose(BlockDiagMatrix()) == BlockDiagMatrix()
|
333 |
+
assert transpose(BlockDiagMatrix(A)) == BlockDiagMatrix(A.T)
|
334 |
+
assert transpose(BlockDiagMatrix(A, B)) == BlockDiagMatrix(A.T, B.T)
|
335 |
+
|
336 |
+
def test_issue_2460():
|
337 |
+
bdm1 = BlockDiagMatrix(Matrix([i]), Matrix([j]))
|
338 |
+
bdm2 = BlockDiagMatrix(Matrix([k]), Matrix([l]))
|
339 |
+
assert block_collapse(bdm1 + bdm2) == BlockDiagMatrix(Matrix([i + k]), Matrix([j + l]))
|
340 |
+
|
341 |
+
def test_blockcut():
|
342 |
+
A = MatrixSymbol('A', n, m)
|
343 |
+
B = blockcut(A, (n/2, n/2), (m/2, m/2))
|
344 |
+
assert B == BlockMatrix([[A[:n/2, :m/2], A[:n/2, m/2:]],
|
345 |
+
[A[n/2:, :m/2], A[n/2:, m/2:]]])
|
346 |
+
|
347 |
+
M = ImmutableMatrix(4, 4, range(16))
|
348 |
+
B = blockcut(M, (2, 2), (2, 2))
|
349 |
+
assert M == ImmutableMatrix(B)
|
350 |
+
|
351 |
+
B = blockcut(M, (1, 3), (2, 2))
|
352 |
+
assert ImmutableMatrix(B.blocks[0, 1]) == ImmutableMatrix([[2, 3]])
|
353 |
+
|
354 |
+
def test_reblock_2x2():
|
355 |
+
B = BlockMatrix([[MatrixSymbol('A_%d%d'%(i,j), 2, 2)
|
356 |
+
for j in range(3)]
|
357 |
+
for i in range(3)])
|
358 |
+
assert B.blocks.shape == (3, 3)
|
359 |
+
|
360 |
+
BB = reblock_2x2(B)
|
361 |
+
assert BB.blocks.shape == (2, 2)
|
362 |
+
|
363 |
+
assert B.shape == BB.shape
|
364 |
+
assert B.as_explicit() == BB.as_explicit()
|
365 |
+
|
366 |
+
def test_deblock():
|
367 |
+
B = BlockMatrix([[MatrixSymbol('A_%d%d'%(i,j), n, n)
|
368 |
+
for j in range(4)]
|
369 |
+
for i in range(4)])
|
370 |
+
|
371 |
+
assert deblock(reblock_2x2(B)) == B
|
372 |
+
|
373 |
+
def test_block_collapse_type():
|
374 |
+
bm1 = BlockDiagMatrix(ImmutableMatrix([1]), ImmutableMatrix([2]))
|
375 |
+
bm2 = BlockDiagMatrix(ImmutableMatrix([3]), ImmutableMatrix([4]))
|
376 |
+
|
377 |
+
assert bm1.T.__class__ == BlockDiagMatrix
|
378 |
+
assert block_collapse(bm1 - bm2).__class__ == BlockDiagMatrix
|
379 |
+
assert block_collapse(Inverse(bm1)).__class__ == BlockDiagMatrix
|
380 |
+
assert block_collapse(Transpose(bm1)).__class__ == BlockDiagMatrix
|
381 |
+
assert bc_transpose(Transpose(bm1)).__class__ == BlockDiagMatrix
|
382 |
+
assert bc_inverse(Inverse(bm1)).__class__ == BlockDiagMatrix
|
383 |
+
|
384 |
+
def test_invalid_block_matrix():
|
385 |
+
raises(ValueError, lambda: BlockMatrix([
|
386 |
+
[Identity(2), Identity(5)],
|
387 |
+
]))
|
388 |
+
raises(ValueError, lambda: BlockMatrix([
|
389 |
+
[Identity(n), Identity(m)],
|
390 |
+
]))
|
391 |
+
raises(ValueError, lambda: BlockMatrix([
|
392 |
+
[ZeroMatrix(n, n), ZeroMatrix(n, n)],
|
393 |
+
[ZeroMatrix(n, n - 1), ZeroMatrix(n, n + 1)],
|
394 |
+
]))
|
395 |
+
raises(ValueError, lambda: BlockMatrix([
|
396 |
+
[ZeroMatrix(n - 1, n), ZeroMatrix(n, n)],
|
397 |
+
[ZeroMatrix(n + 1, n), ZeroMatrix(n, n)],
|
398 |
+
]))
|
399 |
+
|
400 |
+
def test_block_lu_decomposition():
|
401 |
+
A = MatrixSymbol('A', n, n)
|
402 |
+
B = MatrixSymbol('B', n, m)
|
403 |
+
C = MatrixSymbol('C', m, n)
|
404 |
+
D = MatrixSymbol('D', m, m)
|
405 |
+
X = BlockMatrix([[A, B], [C, D]])
|
406 |
+
|
407 |
+
#LDU decomposition
|
408 |
+
L, D, U = X.LDUdecomposition()
|
409 |
+
assert block_collapse(L*D*U) == X
|
410 |
+
|
411 |
+
#UDL decomposition
|
412 |
+
U, D, L = X.UDLdecomposition()
|
413 |
+
assert block_collapse(U*D*L) == X
|
414 |
+
|
415 |
+
#LU decomposition
|
416 |
+
L, U = X.LUdecomposition()
|
417 |
+
assert block_collapse(L*U) == X
|
418 |
+
|
419 |
+
def test_issue_21866():
|
420 |
+
n = 10
|
421 |
+
I = Identity(n)
|
422 |
+
O = ZeroMatrix(n, n)
|
423 |
+
A = BlockMatrix([[ I, O, O, O ],
|
424 |
+
[ O, I, O, O ],
|
425 |
+
[ O, O, I, O ],
|
426 |
+
[ I, O, O, I ]])
|
427 |
+
Ainv = block_collapse(A.inv())
|
428 |
+
AinvT = BlockMatrix([[ I, O, O, O ],
|
429 |
+
[ O, I, O, O ],
|
430 |
+
[ O, O, I, O ],
|
431 |
+
[ -I, O, O, I ]])
|
432 |
+
assert Ainv == AinvT
|
433 |
+
|
434 |
+
|
435 |
+
def test_adjoint_and_special_matrices():
|
436 |
+
A = Identity(3)
|
437 |
+
B = OneMatrix(3, 2)
|
438 |
+
C = ZeroMatrix(2, 3)
|
439 |
+
D = Identity(2)
|
440 |
+
X = BlockMatrix([[A, B], [C, D]])
|
441 |
+
X2 = BlockMatrix([[A, S.ImaginaryUnit*B], [C, D]])
|
442 |
+
assert X.adjoint() == BlockMatrix([[A, ZeroMatrix(3, 2)], [OneMatrix(2, 3), D]])
|
443 |
+
assert re(X) == X
|
444 |
+
assert X2.adjoint() == BlockMatrix([[A, ZeroMatrix(3, 2)], [-S.ImaginaryUnit*OneMatrix(2, 3), D]])
|
445 |
+
assert im(X2) == BlockMatrix([[ZeroMatrix(3, 3), OneMatrix(3, 2)], [ZeroMatrix(2, 3), ZeroMatrix(2, 2)]])
|
llmeval-env/lib/python3.10/site-packages/sympy/matrices/expressions/tests/test_companion.py
ADDED
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.core.expr import unchanged
|
2 |
+
from sympy.core.symbol import Symbol, symbols
|
3 |
+
from sympy.matrices.immutable import ImmutableDenseMatrix
|
4 |
+
from sympy.matrices.expressions.companion import CompanionMatrix
|
5 |
+
from sympy.polys.polytools import Poly
|
6 |
+
from sympy.testing.pytest import raises
|
7 |
+
|
8 |
+
|
9 |
+
def test_creation():
|
10 |
+
x = Symbol('x')
|
11 |
+
y = Symbol('y')
|
12 |
+
raises(ValueError, lambda: CompanionMatrix(1))
|
13 |
+
raises(ValueError, lambda: CompanionMatrix(Poly([1], x)))
|
14 |
+
raises(ValueError, lambda: CompanionMatrix(Poly([2, 1], x)))
|
15 |
+
raises(ValueError, lambda: CompanionMatrix(Poly(x*y, [x, y])))
|
16 |
+
assert unchanged(CompanionMatrix, Poly([1, 2, 3], x))
|
17 |
+
|
18 |
+
|
19 |
+
def test_shape():
|
20 |
+
c0, c1, c2 = symbols('c0:3')
|
21 |
+
x = Symbol('x')
|
22 |
+
assert CompanionMatrix(Poly([1, c0], x)).shape == (1, 1)
|
23 |
+
assert CompanionMatrix(Poly([1, c1, c0], x)).shape == (2, 2)
|
24 |
+
assert CompanionMatrix(Poly([1, c2, c1, c0], x)).shape == (3, 3)
|
25 |
+
|
26 |
+
|
27 |
+
def test_entry():
|
28 |
+
c0, c1, c2 = symbols('c0:3')
|
29 |
+
x = Symbol('x')
|
30 |
+
A = CompanionMatrix(Poly([1, c2, c1, c0], x))
|
31 |
+
assert A[0, 0] == 0
|
32 |
+
assert A[1, 0] == 1
|
33 |
+
assert A[1, 1] == 0
|
34 |
+
assert A[2, 1] == 1
|
35 |
+
assert A[0, 2] == -c0
|
36 |
+
assert A[1, 2] == -c1
|
37 |
+
assert A[2, 2] == -c2
|
38 |
+
|
39 |
+
|
40 |
+
def test_as_explicit():
|
41 |
+
c0, c1, c2 = symbols('c0:3')
|
42 |
+
x = Symbol('x')
|
43 |
+
assert CompanionMatrix(Poly([1, c0], x)).as_explicit() == \
|
44 |
+
ImmutableDenseMatrix([-c0])
|
45 |
+
assert CompanionMatrix(Poly([1, c1, c0], x)).as_explicit() == \
|
46 |
+
ImmutableDenseMatrix([[0, -c0], [1, -c1]])
|
47 |
+
assert CompanionMatrix(Poly([1, c2, c1, c0], x)).as_explicit() == \
|
48 |
+
ImmutableDenseMatrix([[0, 0, -c0], [1, 0, -c1], [0, 1, -c2]])
|
llmeval-env/lib/python3.10/site-packages/sympy/matrices/expressions/tests/test_derivatives.py
ADDED
@@ -0,0 +1,477 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Some examples have been taken from:
|
3 |
+
|
4 |
+
http://www.math.uwaterloo.ca/~hwolkowi//matrixcookbook.pdf
|
5 |
+
"""
|
6 |
+
from sympy import KroneckerProduct
|
7 |
+
from sympy.combinatorics import Permutation
|
8 |
+
from sympy.concrete.summations import Sum
|
9 |
+
from sympy.core.numbers import Rational
|
10 |
+
from sympy.core.singleton import S
|
11 |
+
from sympy.core.symbol import symbols
|
12 |
+
from sympy.functions.elementary.exponential import (exp, log)
|
13 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
14 |
+
from sympy.functions.elementary.trigonometric import (cos, sin, tan)
|
15 |
+
from sympy.functions.special.tensor_functions import KroneckerDelta
|
16 |
+
from sympy.matrices.expressions.determinant import Determinant
|
17 |
+
from sympy.matrices.expressions.diagonal import DiagMatrix
|
18 |
+
from sympy.matrices.expressions.hadamard import (HadamardPower, HadamardProduct, hadamard_product)
|
19 |
+
from sympy.matrices.expressions.inverse import Inverse
|
20 |
+
from sympy.matrices.expressions.matexpr import MatrixSymbol
|
21 |
+
from sympy.matrices.expressions.special import OneMatrix
|
22 |
+
from sympy.matrices.expressions.trace import Trace
|
23 |
+
from sympy.matrices.expressions.matadd import MatAdd
|
24 |
+
from sympy.matrices.expressions.matmul import MatMul
|
25 |
+
from sympy.matrices.expressions.special import (Identity, ZeroMatrix)
|
26 |
+
from sympy.tensor.array.array_derivatives import ArrayDerivative
|
27 |
+
from sympy.matrices.expressions import hadamard_power
|
28 |
+
from sympy.tensor.array.expressions.array_expressions import ArrayAdd, ArrayTensorProduct, PermuteDims
|
29 |
+
|
30 |
+
i, j, k = symbols("i j k")
|
31 |
+
m, n = symbols("m n")
|
32 |
+
|
33 |
+
X = MatrixSymbol("X", k, k)
|
34 |
+
x = MatrixSymbol("x", k, 1)
|
35 |
+
y = MatrixSymbol("y", k, 1)
|
36 |
+
|
37 |
+
A = MatrixSymbol("A", k, k)
|
38 |
+
B = MatrixSymbol("B", k, k)
|
39 |
+
C = MatrixSymbol("C", k, k)
|
40 |
+
D = MatrixSymbol("D", k, k)
|
41 |
+
|
42 |
+
a = MatrixSymbol("a", k, 1)
|
43 |
+
b = MatrixSymbol("b", k, 1)
|
44 |
+
c = MatrixSymbol("c", k, 1)
|
45 |
+
d = MatrixSymbol("d", k, 1)
|
46 |
+
|
47 |
+
|
48 |
+
KDelta = lambda i, j: KroneckerDelta(i, j, (0, k-1))
|
49 |
+
|
50 |
+
|
51 |
+
def _check_derivative_with_explicit_matrix(expr, x, diffexpr, dim=2):
|
52 |
+
# TODO: this is commented because it slows down the tests.
|
53 |
+
return
|
54 |
+
|
55 |
+
expr = expr.xreplace({k: dim})
|
56 |
+
x = x.xreplace({k: dim})
|
57 |
+
diffexpr = diffexpr.xreplace({k: dim})
|
58 |
+
|
59 |
+
expr = expr.as_explicit()
|
60 |
+
x = x.as_explicit()
|
61 |
+
diffexpr = diffexpr.as_explicit()
|
62 |
+
|
63 |
+
assert expr.diff(x).reshape(*diffexpr.shape).tomatrix() == diffexpr
|
64 |
+
|
65 |
+
|
66 |
+
def test_matrix_derivative_by_scalar():
|
67 |
+
assert A.diff(i) == ZeroMatrix(k, k)
|
68 |
+
assert (A*(X + B)*c).diff(i) == ZeroMatrix(k, 1)
|
69 |
+
assert x.diff(i) == ZeroMatrix(k, 1)
|
70 |
+
assert (x.T*y).diff(i) == ZeroMatrix(1, 1)
|
71 |
+
assert (x*x.T).diff(i) == ZeroMatrix(k, k)
|
72 |
+
assert (x + y).diff(i) == ZeroMatrix(k, 1)
|
73 |
+
assert hadamard_power(x, 2).diff(i) == ZeroMatrix(k, 1)
|
74 |
+
assert hadamard_power(x, i).diff(i).dummy_eq(
|
75 |
+
HadamardProduct(x.applyfunc(log), HadamardPower(x, i)))
|
76 |
+
assert hadamard_product(x, y).diff(i) == ZeroMatrix(k, 1)
|
77 |
+
assert hadamard_product(i*OneMatrix(k, 1), x, y).diff(i) == hadamard_product(x, y)
|
78 |
+
assert (i*x).diff(i) == x
|
79 |
+
assert (sin(i)*A*B*x).diff(i) == cos(i)*A*B*x
|
80 |
+
assert x.applyfunc(sin).diff(i) == ZeroMatrix(k, 1)
|
81 |
+
assert Trace(i**2*X).diff(i) == 2*i*Trace(X)
|
82 |
+
|
83 |
+
mu = symbols("mu")
|
84 |
+
expr = (2*mu*x)
|
85 |
+
assert expr.diff(x) == 2*mu*Identity(k)
|
86 |
+
|
87 |
+
|
88 |
+
def test_one_matrix():
|
89 |
+
assert MatMul(x.T, OneMatrix(k, 1)).diff(x) == OneMatrix(k, 1)
|
90 |
+
|
91 |
+
|
92 |
+
def test_matrix_derivative_non_matrix_result():
|
93 |
+
# This is a 4-dimensional array:
|
94 |
+
I = Identity(k)
|
95 |
+
AdA = PermuteDims(ArrayTensorProduct(I, I), Permutation(3)(1, 2))
|
96 |
+
assert A.diff(A) == AdA
|
97 |
+
assert A.T.diff(A) == PermuteDims(ArrayTensorProduct(I, I), Permutation(3)(1, 2, 3))
|
98 |
+
assert (2*A).diff(A) == PermuteDims(ArrayTensorProduct(2*I, I), Permutation(3)(1, 2))
|
99 |
+
assert MatAdd(A, A).diff(A) == ArrayAdd(AdA, AdA)
|
100 |
+
assert (A + B).diff(A) == AdA
|
101 |
+
|
102 |
+
|
103 |
+
def test_matrix_derivative_trivial_cases():
|
104 |
+
# Cookbook example 33:
|
105 |
+
# TODO: find a way to represent a four-dimensional zero-array:
|
106 |
+
assert X.diff(A) == ArrayDerivative(X, A)
|
107 |
+
|
108 |
+
|
109 |
+
def test_matrix_derivative_with_inverse():
|
110 |
+
|
111 |
+
# Cookbook example 61:
|
112 |
+
expr = a.T*Inverse(X)*b
|
113 |
+
assert expr.diff(X) == -Inverse(X).T*a*b.T*Inverse(X).T
|
114 |
+
|
115 |
+
# Cookbook example 62:
|
116 |
+
expr = Determinant(Inverse(X))
|
117 |
+
# Not implemented yet:
|
118 |
+
# assert expr.diff(X) == -Determinant(X.inv())*(X.inv()).T
|
119 |
+
|
120 |
+
# Cookbook example 63:
|
121 |
+
expr = Trace(A*Inverse(X)*B)
|
122 |
+
assert expr.diff(X) == -(X**(-1)*B*A*X**(-1)).T
|
123 |
+
|
124 |
+
# Cookbook example 64:
|
125 |
+
expr = Trace(Inverse(X + A))
|
126 |
+
assert expr.diff(X) == -(Inverse(X + A)).T**2
|
127 |
+
|
128 |
+
|
129 |
+
def test_matrix_derivative_vectors_and_scalars():
|
130 |
+
|
131 |
+
assert x.diff(x) == Identity(k)
|
132 |
+
assert x[i, 0].diff(x[m, 0]).doit() == KDelta(m, i)
|
133 |
+
|
134 |
+
assert x.T.diff(x) == Identity(k)
|
135 |
+
|
136 |
+
# Cookbook example 69:
|
137 |
+
expr = x.T*a
|
138 |
+
assert expr.diff(x) == a
|
139 |
+
assert expr[0, 0].diff(x[m, 0]).doit() == a[m, 0]
|
140 |
+
expr = a.T*x
|
141 |
+
assert expr.diff(x) == a
|
142 |
+
|
143 |
+
# Cookbook example 70:
|
144 |
+
expr = a.T*X*b
|
145 |
+
assert expr.diff(X) == a*b.T
|
146 |
+
|
147 |
+
# Cookbook example 71:
|
148 |
+
expr = a.T*X.T*b
|
149 |
+
assert expr.diff(X) == b*a.T
|
150 |
+
|
151 |
+
# Cookbook example 72:
|
152 |
+
expr = a.T*X*a
|
153 |
+
assert expr.diff(X) == a*a.T
|
154 |
+
expr = a.T*X.T*a
|
155 |
+
assert expr.diff(X) == a*a.T
|
156 |
+
|
157 |
+
# Cookbook example 77:
|
158 |
+
expr = b.T*X.T*X*c
|
159 |
+
assert expr.diff(X) == X*b*c.T + X*c*b.T
|
160 |
+
|
161 |
+
# Cookbook example 78:
|
162 |
+
expr = (B*x + b).T*C*(D*x + d)
|
163 |
+
assert expr.diff(x) == B.T*C*(D*x + d) + D.T*C.T*(B*x + b)
|
164 |
+
|
165 |
+
# Cookbook example 81:
|
166 |
+
expr = x.T*B*x
|
167 |
+
assert expr.diff(x) == B*x + B.T*x
|
168 |
+
|
169 |
+
# Cookbook example 82:
|
170 |
+
expr = b.T*X.T*D*X*c
|
171 |
+
assert expr.diff(X) == D.T*X*b*c.T + D*X*c*b.T
|
172 |
+
|
173 |
+
# Cookbook example 83:
|
174 |
+
expr = (X*b + c).T*D*(X*b + c)
|
175 |
+
assert expr.diff(X) == D*(X*b + c)*b.T + D.T*(X*b + c)*b.T
|
176 |
+
assert str(expr[0, 0].diff(X[m, n]).doit()) == \
|
177 |
+
'b[n, 0]*Sum((c[_i_1, 0] + Sum(X[_i_1, _i_3]*b[_i_3, 0], (_i_3, 0, k - 1)))*D[_i_1, m], (_i_1, 0, k - 1)) + Sum((c[_i_2, 0] + Sum(X[_i_2, _i_4]*b[_i_4, 0], (_i_4, 0, k - 1)))*D[m, _i_2]*b[n, 0], (_i_2, 0, k - 1))'
|
178 |
+
|
179 |
+
# See https://github.com/sympy/sympy/issues/16504#issuecomment-1018339957
|
180 |
+
expr = x*x.T*x
|
181 |
+
I = Identity(k)
|
182 |
+
assert expr.diff(x) == KroneckerProduct(I, x.T*x) + 2*x*x.T
|
183 |
+
|
184 |
+
|
185 |
+
def test_matrix_derivatives_of_traces():
|
186 |
+
|
187 |
+
expr = Trace(A)*A
|
188 |
+
I = Identity(k)
|
189 |
+
assert expr.diff(A) == ArrayAdd(ArrayTensorProduct(I, A), PermuteDims(ArrayTensorProduct(Trace(A)*I, I), Permutation(3)(1, 2)))
|
190 |
+
assert expr[i, j].diff(A[m, n]).doit() == (
|
191 |
+
KDelta(i, m)*KDelta(j, n)*Trace(A) +
|
192 |
+
KDelta(m, n)*A[i, j]
|
193 |
+
)
|
194 |
+
|
195 |
+
## First order:
|
196 |
+
|
197 |
+
# Cookbook example 99:
|
198 |
+
expr = Trace(X)
|
199 |
+
assert expr.diff(X) == Identity(k)
|
200 |
+
assert expr.rewrite(Sum).diff(X[m, n]).doit() == KDelta(m, n)
|
201 |
+
|
202 |
+
# Cookbook example 100:
|
203 |
+
expr = Trace(X*A)
|
204 |
+
assert expr.diff(X) == A.T
|
205 |
+
assert expr.rewrite(Sum).diff(X[m, n]).doit() == A[n, m]
|
206 |
+
|
207 |
+
# Cookbook example 101:
|
208 |
+
expr = Trace(A*X*B)
|
209 |
+
assert expr.diff(X) == A.T*B.T
|
210 |
+
assert expr.rewrite(Sum).diff(X[m, n]).doit().dummy_eq((A.T*B.T)[m, n])
|
211 |
+
|
212 |
+
# Cookbook example 102:
|
213 |
+
expr = Trace(A*X.T*B)
|
214 |
+
assert expr.diff(X) == B*A
|
215 |
+
|
216 |
+
# Cookbook example 103:
|
217 |
+
expr = Trace(X.T*A)
|
218 |
+
assert expr.diff(X) == A
|
219 |
+
|
220 |
+
# Cookbook example 104:
|
221 |
+
expr = Trace(A*X.T)
|
222 |
+
assert expr.diff(X) == A
|
223 |
+
|
224 |
+
# Cookbook example 105:
|
225 |
+
# TODO: TensorProduct is not supported
|
226 |
+
#expr = Trace(TensorProduct(A, X))
|
227 |
+
#assert expr.diff(X) == Trace(A)*Identity(k)
|
228 |
+
|
229 |
+
## Second order:
|
230 |
+
|
231 |
+
# Cookbook example 106:
|
232 |
+
expr = Trace(X**2)
|
233 |
+
assert expr.diff(X) == 2*X.T
|
234 |
+
|
235 |
+
# Cookbook example 107:
|
236 |
+
expr = Trace(X**2*B)
|
237 |
+
assert expr.diff(X) == (X*B + B*X).T
|
238 |
+
expr = Trace(MatMul(X, X, B))
|
239 |
+
assert expr.diff(X) == (X*B + B*X).T
|
240 |
+
|
241 |
+
# Cookbook example 108:
|
242 |
+
expr = Trace(X.T*B*X)
|
243 |
+
assert expr.diff(X) == B*X + B.T*X
|
244 |
+
|
245 |
+
# Cookbook example 109:
|
246 |
+
expr = Trace(B*X*X.T)
|
247 |
+
assert expr.diff(X) == B*X + B.T*X
|
248 |
+
|
249 |
+
# Cookbook example 110:
|
250 |
+
expr = Trace(X*X.T*B)
|
251 |
+
assert expr.diff(X) == B*X + B.T*X
|
252 |
+
|
253 |
+
# Cookbook example 111:
|
254 |
+
expr = Trace(X*B*X.T)
|
255 |
+
assert expr.diff(X) == X*B.T + X*B
|
256 |
+
|
257 |
+
# Cookbook example 112:
|
258 |
+
expr = Trace(B*X.T*X)
|
259 |
+
assert expr.diff(X) == X*B.T + X*B
|
260 |
+
|
261 |
+
# Cookbook example 113:
|
262 |
+
expr = Trace(X.T*X*B)
|
263 |
+
assert expr.diff(X) == X*B.T + X*B
|
264 |
+
|
265 |
+
# Cookbook example 114:
|
266 |
+
expr = Trace(A*X*B*X)
|
267 |
+
assert expr.diff(X) == A.T*X.T*B.T + B.T*X.T*A.T
|
268 |
+
|
269 |
+
# Cookbook example 115:
|
270 |
+
expr = Trace(X.T*X)
|
271 |
+
assert expr.diff(X) == 2*X
|
272 |
+
expr = Trace(X*X.T)
|
273 |
+
assert expr.diff(X) == 2*X
|
274 |
+
|
275 |
+
# Cookbook example 116:
|
276 |
+
expr = Trace(B.T*X.T*C*X*B)
|
277 |
+
assert expr.diff(X) == C.T*X*B*B.T + C*X*B*B.T
|
278 |
+
|
279 |
+
# Cookbook example 117:
|
280 |
+
expr = Trace(X.T*B*X*C)
|
281 |
+
assert expr.diff(X) == B*X*C + B.T*X*C.T
|
282 |
+
|
283 |
+
# Cookbook example 118:
|
284 |
+
expr = Trace(A*X*B*X.T*C)
|
285 |
+
assert expr.diff(X) == A.T*C.T*X*B.T + C*A*X*B
|
286 |
+
|
287 |
+
# Cookbook example 119:
|
288 |
+
expr = Trace((A*X*B + C)*(A*X*B + C).T)
|
289 |
+
assert expr.diff(X) == 2*A.T*(A*X*B + C)*B.T
|
290 |
+
|
291 |
+
# Cookbook example 120:
|
292 |
+
# TODO: no support for TensorProduct.
|
293 |
+
# expr = Trace(TensorProduct(X, X))
|
294 |
+
# expr = Trace(X)*Trace(X)
|
295 |
+
# expr.diff(X) == 2*Trace(X)*Identity(k)
|
296 |
+
|
297 |
+
# Higher Order
|
298 |
+
|
299 |
+
# Cookbook example 121:
|
300 |
+
expr = Trace(X**k)
|
301 |
+
#assert expr.diff(X) == k*(X**(k-1)).T
|
302 |
+
|
303 |
+
# Cookbook example 122:
|
304 |
+
expr = Trace(A*X**k)
|
305 |
+
#assert expr.diff(X) == # Needs indices
|
306 |
+
|
307 |
+
# Cookbook example 123:
|
308 |
+
expr = Trace(B.T*X.T*C*X*X.T*C*X*B)
|
309 |
+
assert expr.diff(X) == C*X*X.T*C*X*B*B.T + C.T*X*B*B.T*X.T*C.T*X + C*X*B*B.T*X.T*C*X + C.T*X*X.T*C.T*X*B*B.T
|
310 |
+
|
311 |
+
# Other
|
312 |
+
|
313 |
+
# Cookbook example 124:
|
314 |
+
expr = Trace(A*X**(-1)*B)
|
315 |
+
assert expr.diff(X) == -Inverse(X).T*A.T*B.T*Inverse(X).T
|
316 |
+
|
317 |
+
# Cookbook example 125:
|
318 |
+
expr = Trace(Inverse(X.T*C*X)*A)
|
319 |
+
# Warning: result in the cookbook is equivalent if B and C are symmetric:
|
320 |
+
assert expr.diff(X) == - X.inv().T*A.T*X.inv()*C.inv().T*X.inv().T - X.inv().T*A*X.inv()*C.inv()*X.inv().T
|
321 |
+
|
322 |
+
# Cookbook example 126:
|
323 |
+
expr = Trace((X.T*C*X).inv()*(X.T*B*X))
|
324 |
+
assert expr.diff(X) == -2*C*X*(X.T*C*X).inv()*X.T*B*X*(X.T*C*X).inv() + 2*B*X*(X.T*C*X).inv()
|
325 |
+
|
326 |
+
# Cookbook example 127:
|
327 |
+
expr = Trace((A + X.T*C*X).inv()*(X.T*B*X))
|
328 |
+
# Warning: result in the cookbook is equivalent if B and C are symmetric:
|
329 |
+
assert expr.diff(X) == B*X*Inverse(A + X.T*C*X) - C*X*Inverse(A + X.T*C*X)*X.T*B*X*Inverse(A + X.T*C*X) - C.T*X*Inverse(A.T + (C*X).T*X)*X.T*B.T*X*Inverse(A.T + (C*X).T*X) + B.T*X*Inverse(A.T + (C*X).T*X)
|
330 |
+
|
331 |
+
|
332 |
+
def test_derivatives_of_complicated_matrix_expr():
|
333 |
+
expr = a.T*(A*X*(X.T*B + X*A) + B.T*X.T*(a*b.T*(X*D*X.T + X*(X.T*B + A*X)*D*B - X.T*C.T*A)*B + B*(X*D.T + B*A*X*A.T - 3*X*D))*B + 42*X*B*X.T*A.T*(X + X.T))*b
|
334 |
+
result = (B*(B*A*X*A.T - 3*X*D + X*D.T) + a*b.T*(X*(A*X + X.T*B)*D*B + X*D*X.T - X.T*C.T*A)*B)*B*b*a.T*B.T + B**2*b*a.T*B.T*X.T*a*b.T*X*D + 42*A*X*B.T*X.T*a*b.T + B*D*B**3*b*a.T*B.T*X.T*a*b.T*X + B*b*a.T*A*X + a*b.T*(42*X + 42*X.T)*A*X*B.T + b*a.T*X*B*a*b.T*B.T**2*X*D.T + b*a.T*X*B*a*b.T*B.T**3*D.T*(B.T*X + X.T*A.T) + 42*b*a.T*X*B*X.T*A.T + A.T*(42*X + 42*X.T)*b*a.T*X*B + A.T*B.T**2*X*B*a*b.T*B.T*A + A.T*a*b.T*(A.T*X.T + B.T*X) + A.T*X.T*b*a.T*X*B*a*b.T*B.T**3*D.T + B.T*X*B*a*b.T*B.T*D - 3*B.T*X*B*a*b.T*B.T*D.T - C.T*A*B**2*b*a.T*B.T*X.T*a*b.T + X.T*A.T*a*b.T*A.T
|
335 |
+
assert expr.diff(X) == result
|
336 |
+
|
337 |
+
|
338 |
+
def test_mixed_deriv_mixed_expressions():
|
339 |
+
|
340 |
+
expr = 3*Trace(A)
|
341 |
+
assert expr.diff(A) == 3*Identity(k)
|
342 |
+
|
343 |
+
expr = k
|
344 |
+
deriv = expr.diff(A)
|
345 |
+
assert isinstance(deriv, ZeroMatrix)
|
346 |
+
assert deriv == ZeroMatrix(k, k)
|
347 |
+
|
348 |
+
expr = Trace(A)**2
|
349 |
+
assert expr.diff(A) == (2*Trace(A))*Identity(k)
|
350 |
+
|
351 |
+
expr = Trace(A)*A
|
352 |
+
I = Identity(k)
|
353 |
+
assert expr.diff(A) == ArrayAdd(ArrayTensorProduct(I, A), PermuteDims(ArrayTensorProduct(Trace(A)*I, I), Permutation(3)(1, 2)))
|
354 |
+
|
355 |
+
expr = Trace(Trace(A)*A)
|
356 |
+
assert expr.diff(A) == (2*Trace(A))*Identity(k)
|
357 |
+
|
358 |
+
expr = Trace(Trace(Trace(A)*A)*A)
|
359 |
+
assert expr.diff(A) == (3*Trace(A)**2)*Identity(k)
|
360 |
+
|
361 |
+
|
362 |
+
def test_derivatives_matrix_norms():
|
363 |
+
|
364 |
+
expr = x.T*y
|
365 |
+
assert expr.diff(x) == y
|
366 |
+
assert expr[0, 0].diff(x[m, 0]).doit() == y[m, 0]
|
367 |
+
|
368 |
+
expr = (x.T*y)**S.Half
|
369 |
+
assert expr.diff(x) == y/(2*sqrt(x.T*y))
|
370 |
+
|
371 |
+
expr = (x.T*x)**S.Half
|
372 |
+
assert expr.diff(x) == x*(x.T*x)**Rational(-1, 2)
|
373 |
+
|
374 |
+
expr = (c.T*a*x.T*b)**S.Half
|
375 |
+
assert expr.diff(x) == b*a.T*c/sqrt(c.T*a*x.T*b)/2
|
376 |
+
|
377 |
+
expr = (c.T*a*x.T*b)**Rational(1, 3)
|
378 |
+
assert expr.diff(x) == b*a.T*c*(c.T*a*x.T*b)**Rational(-2, 3)/3
|
379 |
+
|
380 |
+
expr = (a.T*X*b)**S.Half
|
381 |
+
assert expr.diff(X) == a/(2*sqrt(a.T*X*b))*b.T
|
382 |
+
|
383 |
+
expr = d.T*x*(a.T*X*b)**S.Half*y.T*c
|
384 |
+
assert expr.diff(X) == a/(2*sqrt(a.T*X*b))*x.T*d*y.T*c*b.T
|
385 |
+
|
386 |
+
|
387 |
+
def test_derivatives_elementwise_applyfunc():
|
388 |
+
|
389 |
+
expr = x.applyfunc(tan)
|
390 |
+
assert expr.diff(x).dummy_eq(
|
391 |
+
DiagMatrix(x.applyfunc(lambda x: tan(x)**2 + 1)))
|
392 |
+
assert expr[i, 0].diff(x[m, 0]).doit() == (tan(x[i, 0])**2 + 1)*KDelta(i, m)
|
393 |
+
_check_derivative_with_explicit_matrix(expr, x, expr.diff(x))
|
394 |
+
|
395 |
+
expr = (i**2*x).applyfunc(sin)
|
396 |
+
assert expr.diff(i).dummy_eq(
|
397 |
+
HadamardProduct((2*i)*x, (i**2*x).applyfunc(cos)))
|
398 |
+
assert expr[i, 0].diff(i).doit() == 2*i*x[i, 0]*cos(i**2*x[i, 0])
|
399 |
+
_check_derivative_with_explicit_matrix(expr, i, expr.diff(i))
|
400 |
+
|
401 |
+
expr = (log(i)*A*B).applyfunc(sin)
|
402 |
+
assert expr.diff(i).dummy_eq(
|
403 |
+
HadamardProduct(A*B/i, (log(i)*A*B).applyfunc(cos)))
|
404 |
+
_check_derivative_with_explicit_matrix(expr, i, expr.diff(i))
|
405 |
+
|
406 |
+
expr = A*x.applyfunc(exp)
|
407 |
+
# TODO: restore this result (currently returning the transpose):
|
408 |
+
# assert expr.diff(x).dummy_eq(DiagMatrix(x.applyfunc(exp))*A.T)
|
409 |
+
_check_derivative_with_explicit_matrix(expr, x, expr.diff(x))
|
410 |
+
|
411 |
+
expr = x.T*A*x + k*y.applyfunc(sin).T*x
|
412 |
+
assert expr.diff(x).dummy_eq(A.T*x + A*x + k*y.applyfunc(sin))
|
413 |
+
_check_derivative_with_explicit_matrix(expr, x, expr.diff(x))
|
414 |
+
|
415 |
+
expr = x.applyfunc(sin).T*y
|
416 |
+
# TODO: restore (currently returning the transpose):
|
417 |
+
# assert expr.diff(x).dummy_eq(DiagMatrix(x.applyfunc(cos))*y)
|
418 |
+
_check_derivative_with_explicit_matrix(expr, x, expr.diff(x))
|
419 |
+
|
420 |
+
expr = (a.T * X * b).applyfunc(sin)
|
421 |
+
assert expr.diff(X).dummy_eq(a*(a.T*X*b).applyfunc(cos)*b.T)
|
422 |
+
_check_derivative_with_explicit_matrix(expr, X, expr.diff(X))
|
423 |
+
|
424 |
+
expr = a.T * X.applyfunc(sin) * b
|
425 |
+
assert expr.diff(X).dummy_eq(
|
426 |
+
DiagMatrix(a)*X.applyfunc(cos)*DiagMatrix(b))
|
427 |
+
_check_derivative_with_explicit_matrix(expr, X, expr.diff(X))
|
428 |
+
|
429 |
+
expr = a.T * (A*X*B).applyfunc(sin) * b
|
430 |
+
assert expr.diff(X).dummy_eq(
|
431 |
+
A.T*DiagMatrix(a)*(A*X*B).applyfunc(cos)*DiagMatrix(b)*B.T)
|
432 |
+
_check_derivative_with_explicit_matrix(expr, X, expr.diff(X))
|
433 |
+
|
434 |
+
expr = a.T * (A*X*b).applyfunc(sin) * b.T
|
435 |
+
# TODO: not implemented
|
436 |
+
#assert expr.diff(X) == ...
|
437 |
+
#_check_derivative_with_explicit_matrix(expr, X, expr.diff(X))
|
438 |
+
|
439 |
+
expr = a.T*A*X.applyfunc(sin)*B*b
|
440 |
+
assert expr.diff(X).dummy_eq(
|
441 |
+
HadamardProduct(A.T * a * b.T * B.T, X.applyfunc(cos)))
|
442 |
+
|
443 |
+
expr = a.T * (A*X.applyfunc(sin)*B).applyfunc(log) * b
|
444 |
+
# TODO: wrong
|
445 |
+
# assert expr.diff(X) == A.T*DiagMatrix(a)*(A*X.applyfunc(sin)*B).applyfunc(Lambda(k, 1/k))*DiagMatrix(b)*B.T
|
446 |
+
|
447 |
+
expr = a.T * (X.applyfunc(sin)).applyfunc(log) * b
|
448 |
+
# TODO: wrong
|
449 |
+
# assert expr.diff(X) == DiagMatrix(a)*X.applyfunc(sin).applyfunc(Lambda(k, 1/k))*DiagMatrix(b)
|
450 |
+
|
451 |
+
|
452 |
+
def test_derivatives_of_hadamard_expressions():
|
453 |
+
|
454 |
+
# Hadamard Product
|
455 |
+
|
456 |
+
expr = hadamard_product(a, x, b)
|
457 |
+
assert expr.diff(x) == DiagMatrix(hadamard_product(b, a))
|
458 |
+
|
459 |
+
expr = a.T*hadamard_product(A, X, B)*b
|
460 |
+
assert expr.diff(X) == HadamardProduct(a*b.T, A, B)
|
461 |
+
|
462 |
+
# Hadamard Power
|
463 |
+
|
464 |
+
expr = hadamard_power(x, 2)
|
465 |
+
assert expr.diff(x).doit() == 2*DiagMatrix(x)
|
466 |
+
|
467 |
+
expr = hadamard_power(x.T, 2)
|
468 |
+
assert expr.diff(x).doit() == 2*DiagMatrix(x)
|
469 |
+
|
470 |
+
expr = hadamard_power(x, S.Half)
|
471 |
+
assert expr.diff(x) == S.Half*DiagMatrix(hadamard_power(x, Rational(-1, 2)))
|
472 |
+
|
473 |
+
expr = hadamard_power(a.T*X*b, 2)
|
474 |
+
assert expr.diff(X) == 2*a*a.T*X*b*b.T
|
475 |
+
|
476 |
+
expr = hadamard_power(a.T*X*b, S.Half)
|
477 |
+
assert expr.diff(X) == a/(2*sqrt(a.T*X*b))*b.T
|
llmeval-env/lib/python3.10/site-packages/sympy/matrices/expressions/tests/test_determinant.py
ADDED
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.core import S, symbols
|
2 |
+
from sympy.matrices import eye, ones, Matrix, ShapeError
|
3 |
+
from sympy.matrices.expressions import (
|
4 |
+
Identity, MatrixExpr, MatrixSymbol, Determinant,
|
5 |
+
det, per, ZeroMatrix, Transpose,
|
6 |
+
Permanent
|
7 |
+
)
|
8 |
+
from sympy.matrices.expressions.special import OneMatrix
|
9 |
+
from sympy.testing.pytest import raises
|
10 |
+
from sympy.assumptions.ask import Q
|
11 |
+
from sympy.assumptions.refine import refine
|
12 |
+
|
13 |
+
n = symbols('n', integer=True)
|
14 |
+
A = MatrixSymbol('A', n, n)
|
15 |
+
B = MatrixSymbol('B', n, n)
|
16 |
+
C = MatrixSymbol('C', 3, 4)
|
17 |
+
|
18 |
+
|
19 |
+
def test_det():
|
20 |
+
assert isinstance(Determinant(A), Determinant)
|
21 |
+
assert not isinstance(Determinant(A), MatrixExpr)
|
22 |
+
raises(ShapeError, lambda: Determinant(C))
|
23 |
+
assert det(eye(3)) == 1
|
24 |
+
assert det(Matrix(3, 3, [1, 3, 2, 4, 1, 3, 2, 5, 2])) == 17
|
25 |
+
_ = A / det(A) # Make sure this is possible
|
26 |
+
|
27 |
+
raises(TypeError, lambda: Determinant(S.One))
|
28 |
+
|
29 |
+
assert Determinant(A).arg is A
|
30 |
+
|
31 |
+
def test_eval_determinant():
|
32 |
+
assert det(Identity(n)) == 1
|
33 |
+
assert det(ZeroMatrix(n, n)) == 0
|
34 |
+
assert det(OneMatrix(n, n)) == Determinant(OneMatrix(n, n))
|
35 |
+
assert det(OneMatrix(1, 1)) == 1
|
36 |
+
assert det(OneMatrix(2, 2)) == 0
|
37 |
+
assert det(Transpose(A)) == det(A)
|
38 |
+
|
39 |
+
|
40 |
+
def test_refine():
|
41 |
+
assert refine(det(A), Q.orthogonal(A)) == 1
|
42 |
+
assert refine(det(A), Q.singular(A)) == 0
|
43 |
+
assert refine(det(A), Q.unit_triangular(A)) == 1
|
44 |
+
assert refine(det(A), Q.normal(A)) == det(A)
|
45 |
+
|
46 |
+
|
47 |
+
def test_commutative():
|
48 |
+
det_a = Determinant(A)
|
49 |
+
det_b = Determinant(B)
|
50 |
+
assert det_a.is_commutative
|
51 |
+
assert det_b.is_commutative
|
52 |
+
assert det_a * det_b == det_b * det_a
|
53 |
+
|
54 |
+
def test_permanent():
|
55 |
+
assert isinstance(Permanent(A), Permanent)
|
56 |
+
assert not isinstance(Permanent(A), MatrixExpr)
|
57 |
+
assert isinstance(Permanent(C), Permanent)
|
58 |
+
assert Permanent(ones(3, 3)).doit() == 6
|
59 |
+
_ = C / per(C)
|
60 |
+
assert per(Matrix(3, 3, [1, 3, 2, 4, 1, 3, 2, 5, 2])) == 103
|
61 |
+
raises(TypeError, lambda: Permanent(S.One))
|
62 |
+
assert Permanent(A).arg is A
|
llmeval-env/lib/python3.10/site-packages/sympy/matrices/expressions/tests/test_diagonal.py
ADDED
@@ -0,0 +1,156 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.matrices.expressions import MatrixSymbol
|
2 |
+
from sympy.matrices.expressions.diagonal import DiagonalMatrix, DiagonalOf, DiagMatrix, diagonalize_vector
|
3 |
+
from sympy.assumptions.ask import (Q, ask)
|
4 |
+
from sympy.core.symbol import Symbol
|
5 |
+
from sympy.functions.special.tensor_functions import KroneckerDelta
|
6 |
+
from sympy.matrices.dense import Matrix
|
7 |
+
from sympy.matrices.expressions.matmul import MatMul
|
8 |
+
from sympy.matrices.expressions.special import Identity
|
9 |
+
from sympy.testing.pytest import raises
|
10 |
+
|
11 |
+
|
12 |
+
n = Symbol('n')
|
13 |
+
m = Symbol('m')
|
14 |
+
|
15 |
+
|
16 |
+
def test_DiagonalMatrix():
|
17 |
+
x = MatrixSymbol('x', n, m)
|
18 |
+
D = DiagonalMatrix(x)
|
19 |
+
assert D.diagonal_length is None
|
20 |
+
assert D.shape == (n, m)
|
21 |
+
|
22 |
+
x = MatrixSymbol('x', n, n)
|
23 |
+
D = DiagonalMatrix(x)
|
24 |
+
assert D.diagonal_length == n
|
25 |
+
assert D.shape == (n, n)
|
26 |
+
assert D[1, 2] == 0
|
27 |
+
assert D[1, 1] == x[1, 1]
|
28 |
+
i = Symbol('i')
|
29 |
+
j = Symbol('j')
|
30 |
+
x = MatrixSymbol('x', 3, 3)
|
31 |
+
ij = DiagonalMatrix(x)[i, j]
|
32 |
+
assert ij != 0
|
33 |
+
assert ij.subs({i:0, j:0}) == x[0, 0]
|
34 |
+
assert ij.subs({i:0, j:1}) == 0
|
35 |
+
assert ij.subs({i:1, j:1}) == x[1, 1]
|
36 |
+
assert ask(Q.diagonal(D)) # affirm that D is diagonal
|
37 |
+
|
38 |
+
x = MatrixSymbol('x', n, 3)
|
39 |
+
D = DiagonalMatrix(x)
|
40 |
+
assert D.diagonal_length == 3
|
41 |
+
assert D.shape == (n, 3)
|
42 |
+
assert D[2, m] == KroneckerDelta(2, m)*x[2, m]
|
43 |
+
assert D[3, m] == 0
|
44 |
+
raises(IndexError, lambda: D[m, 3])
|
45 |
+
|
46 |
+
x = MatrixSymbol('x', 3, n)
|
47 |
+
D = DiagonalMatrix(x)
|
48 |
+
assert D.diagonal_length == 3
|
49 |
+
assert D.shape == (3, n)
|
50 |
+
assert D[m, 2] == KroneckerDelta(m, 2)*x[m, 2]
|
51 |
+
assert D[m, 3] == 0
|
52 |
+
raises(IndexError, lambda: D[3, m])
|
53 |
+
|
54 |
+
x = MatrixSymbol('x', n, m)
|
55 |
+
D = DiagonalMatrix(x)
|
56 |
+
assert D.diagonal_length is None
|
57 |
+
assert D.shape == (n, m)
|
58 |
+
assert D[m, 4] != 0
|
59 |
+
|
60 |
+
x = MatrixSymbol('x', 3, 4)
|
61 |
+
assert [DiagonalMatrix(x)[i] for i in range(12)] == [
|
62 |
+
x[0, 0], 0, 0, 0, 0, x[1, 1], 0, 0, 0, 0, x[2, 2], 0]
|
63 |
+
|
64 |
+
# shape is retained, issue 12427
|
65 |
+
assert (
|
66 |
+
DiagonalMatrix(MatrixSymbol('x', 3, 4))*
|
67 |
+
DiagonalMatrix(MatrixSymbol('x', 4, 2))).shape == (3, 2)
|
68 |
+
|
69 |
+
|
70 |
+
def test_DiagonalOf():
|
71 |
+
x = MatrixSymbol('x', n, n)
|
72 |
+
d = DiagonalOf(x)
|
73 |
+
assert d.shape == (n, 1)
|
74 |
+
assert d.diagonal_length == n
|
75 |
+
assert d[2, 0] == d[2] == x[2, 2]
|
76 |
+
|
77 |
+
x = MatrixSymbol('x', n, m)
|
78 |
+
d = DiagonalOf(x)
|
79 |
+
assert d.shape == (None, 1)
|
80 |
+
assert d.diagonal_length is None
|
81 |
+
assert d[2, 0] == d[2] == x[2, 2]
|
82 |
+
|
83 |
+
d = DiagonalOf(MatrixSymbol('x', 4, 3))
|
84 |
+
assert d.shape == (3, 1)
|
85 |
+
d = DiagonalOf(MatrixSymbol('x', n, 3))
|
86 |
+
assert d.shape == (3, 1)
|
87 |
+
d = DiagonalOf(MatrixSymbol('x', 3, n))
|
88 |
+
assert d.shape == (3, 1)
|
89 |
+
x = MatrixSymbol('x', n, m)
|
90 |
+
assert [DiagonalOf(x)[i] for i in range(4)] ==[
|
91 |
+
x[0, 0], x[1, 1], x[2, 2], x[3, 3]]
|
92 |
+
|
93 |
+
|
94 |
+
def test_DiagMatrix():
|
95 |
+
x = MatrixSymbol('x', n, 1)
|
96 |
+
d = DiagMatrix(x)
|
97 |
+
assert d.shape == (n, n)
|
98 |
+
assert d[0, 1] == 0
|
99 |
+
assert d[0, 0] == x[0, 0]
|
100 |
+
|
101 |
+
a = MatrixSymbol('a', 1, 1)
|
102 |
+
d = diagonalize_vector(a)
|
103 |
+
assert isinstance(d, MatrixSymbol)
|
104 |
+
assert a == d
|
105 |
+
assert diagonalize_vector(Identity(3)) == Identity(3)
|
106 |
+
assert DiagMatrix(Identity(3)).doit() == Identity(3)
|
107 |
+
assert isinstance(DiagMatrix(Identity(3)), DiagMatrix)
|
108 |
+
|
109 |
+
# A diagonal matrix is equal to its transpose:
|
110 |
+
assert DiagMatrix(x).T == DiagMatrix(x)
|
111 |
+
assert diagonalize_vector(x.T) == DiagMatrix(x)
|
112 |
+
|
113 |
+
dx = DiagMatrix(x)
|
114 |
+
assert dx[0, 0] == x[0, 0]
|
115 |
+
assert dx[1, 1] == x[1, 0]
|
116 |
+
assert dx[0, 1] == 0
|
117 |
+
assert dx[0, m] == x[0, 0]*KroneckerDelta(0, m)
|
118 |
+
|
119 |
+
z = MatrixSymbol('z', 1, n)
|
120 |
+
dz = DiagMatrix(z)
|
121 |
+
assert dz[0, 0] == z[0, 0]
|
122 |
+
assert dz[1, 1] == z[0, 1]
|
123 |
+
assert dz[0, 1] == 0
|
124 |
+
assert dz[0, m] == z[0, m]*KroneckerDelta(0, m)
|
125 |
+
|
126 |
+
v = MatrixSymbol('v', 3, 1)
|
127 |
+
dv = DiagMatrix(v)
|
128 |
+
assert dv.as_explicit() == Matrix([
|
129 |
+
[v[0, 0], 0, 0],
|
130 |
+
[0, v[1, 0], 0],
|
131 |
+
[0, 0, v[2, 0]],
|
132 |
+
])
|
133 |
+
|
134 |
+
v = MatrixSymbol('v', 1, 3)
|
135 |
+
dv = DiagMatrix(v)
|
136 |
+
assert dv.as_explicit() == Matrix([
|
137 |
+
[v[0, 0], 0, 0],
|
138 |
+
[0, v[0, 1], 0],
|
139 |
+
[0, 0, v[0, 2]],
|
140 |
+
])
|
141 |
+
|
142 |
+
dv = DiagMatrix(3*v)
|
143 |
+
assert dv.args == (3*v,)
|
144 |
+
assert dv.doit() == 3*DiagMatrix(v)
|
145 |
+
assert isinstance(dv.doit(), MatMul)
|
146 |
+
|
147 |
+
a = MatrixSymbol("a", 3, 1).as_explicit()
|
148 |
+
expr = DiagMatrix(a)
|
149 |
+
result = Matrix([
|
150 |
+
[a[0, 0], 0, 0],
|
151 |
+
[0, a[1, 0], 0],
|
152 |
+
[0, 0, a[2, 0]],
|
153 |
+
])
|
154 |
+
assert expr.doit() == result
|
155 |
+
expr = DiagMatrix(a.T)
|
156 |
+
assert expr.doit() == result
|
llmeval-env/lib/python3.10/site-packages/sympy/matrices/expressions/tests/test_dotproduct.py
ADDED
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.core.expr import unchanged
|
2 |
+
from sympy.core.mul import Mul
|
3 |
+
from sympy.matrices import Matrix
|
4 |
+
from sympy.matrices.expressions.matexpr import MatrixSymbol
|
5 |
+
from sympy.matrices.expressions.dotproduct import DotProduct
|
6 |
+
from sympy.testing.pytest import raises
|
7 |
+
|
8 |
+
|
9 |
+
A = Matrix(3, 1, [1, 2, 3])
|
10 |
+
B = Matrix(3, 1, [1, 3, 5])
|
11 |
+
C = Matrix(4, 1, [1, 2, 4, 5])
|
12 |
+
D = Matrix(2, 2, [1, 2, 3, 4])
|
13 |
+
|
14 |
+
def test_docproduct():
|
15 |
+
assert DotProduct(A, B).doit() == 22
|
16 |
+
assert DotProduct(A.T, B).doit() == 22
|
17 |
+
assert DotProduct(A, B.T).doit() == 22
|
18 |
+
assert DotProduct(A.T, B.T).doit() == 22
|
19 |
+
|
20 |
+
raises(TypeError, lambda: DotProduct(1, A))
|
21 |
+
raises(TypeError, lambda: DotProduct(A, 1))
|
22 |
+
raises(TypeError, lambda: DotProduct(A, D))
|
23 |
+
raises(TypeError, lambda: DotProduct(D, A))
|
24 |
+
|
25 |
+
raises(TypeError, lambda: DotProduct(B, C).doit())
|
26 |
+
|
27 |
+
def test_dotproduct_symbolic():
|
28 |
+
A = MatrixSymbol('A', 3, 1)
|
29 |
+
B = MatrixSymbol('B', 3, 1)
|
30 |
+
|
31 |
+
dot = DotProduct(A, B)
|
32 |
+
assert dot.is_scalar == True
|
33 |
+
assert unchanged(Mul, 2, dot)
|
34 |
+
# XXX Fix forced evaluation for arithmetics with matrix expressions
|
35 |
+
assert dot * A == (A[0, 0]*B[0, 0] + A[1, 0]*B[1, 0] + A[2, 0]*B[2, 0])*A
|
llmeval-env/lib/python3.10/site-packages/sympy/matrices/expressions/tests/test_factorizations.py
ADDED
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.matrices.expressions.factorizations import lu, LofCholesky, qr, svd
|
2 |
+
from sympy.assumptions.ask import (Q, ask)
|
3 |
+
from sympy.core.symbol import Symbol
|
4 |
+
from sympy.matrices.expressions.matexpr import MatrixSymbol
|
5 |
+
|
6 |
+
n = Symbol('n')
|
7 |
+
X = MatrixSymbol('X', n, n)
|
8 |
+
|
9 |
+
def test_LU():
|
10 |
+
L, U = lu(X)
|
11 |
+
assert L.shape == U.shape == X.shape
|
12 |
+
assert ask(Q.lower_triangular(L))
|
13 |
+
assert ask(Q.upper_triangular(U))
|
14 |
+
|
15 |
+
def test_Cholesky():
|
16 |
+
LofCholesky(X)
|
17 |
+
|
18 |
+
def test_QR():
|
19 |
+
Q_, R = qr(X)
|
20 |
+
assert Q_.shape == R.shape == X.shape
|
21 |
+
assert ask(Q.orthogonal(Q_))
|
22 |
+
assert ask(Q.upper_triangular(R))
|
23 |
+
|
24 |
+
def test_svd():
|
25 |
+
U, S, V = svd(X)
|
26 |
+
assert U.shape == S.shape == V.shape == X.shape
|
27 |
+
assert ask(Q.orthogonal(U))
|
28 |
+
assert ask(Q.orthogonal(V))
|
29 |
+
assert ask(Q.diagonal(S))
|
llmeval-env/lib/python3.10/site-packages/sympy/matrices/expressions/tests/test_fourier.py
ADDED
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.assumptions.ask import (Q, ask)
|
2 |
+
from sympy.core.numbers import (I, Rational)
|
3 |
+
from sympy.core.singleton import S
|
4 |
+
from sympy.functions.elementary.complexes import Abs
|
5 |
+
from sympy.functions.elementary.exponential import exp
|
6 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
7 |
+
from sympy.simplify.simplify import simplify
|
8 |
+
from sympy.core.symbol import symbols
|
9 |
+
from sympy.matrices.expressions.fourier import DFT, IDFT
|
10 |
+
from sympy.matrices import det, Matrix, Identity
|
11 |
+
from sympy.testing.pytest import raises
|
12 |
+
|
13 |
+
|
14 |
+
def test_dft_creation():
|
15 |
+
assert DFT(2)
|
16 |
+
assert DFT(0)
|
17 |
+
raises(ValueError, lambda: DFT(-1))
|
18 |
+
raises(ValueError, lambda: DFT(2.0))
|
19 |
+
raises(ValueError, lambda: DFT(2 + 1j))
|
20 |
+
|
21 |
+
n = symbols('n')
|
22 |
+
assert DFT(n)
|
23 |
+
n = symbols('n', integer=False)
|
24 |
+
raises(ValueError, lambda: DFT(n))
|
25 |
+
n = symbols('n', negative=True)
|
26 |
+
raises(ValueError, lambda: DFT(n))
|
27 |
+
|
28 |
+
|
29 |
+
def test_dft():
|
30 |
+
n, i, j = symbols('n i j')
|
31 |
+
assert DFT(4).shape == (4, 4)
|
32 |
+
assert ask(Q.unitary(DFT(4)))
|
33 |
+
assert Abs(simplify(det(Matrix(DFT(4))))) == 1
|
34 |
+
assert DFT(n)*IDFT(n) == Identity(n)
|
35 |
+
assert DFT(n)[i, j] == exp(-2*S.Pi*I/n)**(i*j) / sqrt(n)
|
36 |
+
|
37 |
+
|
38 |
+
def test_dft2():
|
39 |
+
assert DFT(1).as_explicit() == Matrix([[1]])
|
40 |
+
assert DFT(2).as_explicit() == 1/sqrt(2)*Matrix([[1,1],[1,-1]])
|
41 |
+
assert DFT(4).as_explicit() == Matrix([[S.Half, S.Half, S.Half, S.Half],
|
42 |
+
[S.Half, -I/2, Rational(-1,2), I/2],
|
43 |
+
[S.Half, Rational(-1,2), S.Half, Rational(-1,2)],
|
44 |
+
[S.Half, I/2, Rational(-1,2), -I/2]])
|
llmeval-env/lib/python3.10/site-packages/sympy/matrices/expressions/tests/test_funcmatrix.py
ADDED
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.core import symbols, Lambda
|
2 |
+
from sympy.functions import KroneckerDelta
|
3 |
+
from sympy.matrices import Matrix
|
4 |
+
from sympy.matrices.expressions import FunctionMatrix, MatrixExpr, Identity
|
5 |
+
from sympy.testing.pytest import raises, warns
|
6 |
+
from sympy.utilities.exceptions import SymPyDeprecationWarning
|
7 |
+
|
8 |
+
|
9 |
+
def test_funcmatrix_creation():
|
10 |
+
i, j, k = symbols('i j k')
|
11 |
+
assert FunctionMatrix(2, 2, Lambda((i, j), 0))
|
12 |
+
assert FunctionMatrix(0, 0, Lambda((i, j), 0))
|
13 |
+
|
14 |
+
raises(ValueError, lambda: FunctionMatrix(-1, 0, Lambda((i, j), 0)))
|
15 |
+
raises(ValueError, lambda: FunctionMatrix(2.0, 0, Lambda((i, j), 0)))
|
16 |
+
raises(ValueError, lambda: FunctionMatrix(2j, 0, Lambda((i, j), 0)))
|
17 |
+
raises(ValueError, lambda: FunctionMatrix(0, -1, Lambda((i, j), 0)))
|
18 |
+
raises(ValueError, lambda: FunctionMatrix(0, 2.0, Lambda((i, j), 0)))
|
19 |
+
raises(ValueError, lambda: FunctionMatrix(0, 2j, Lambda((i, j), 0)))
|
20 |
+
|
21 |
+
raises(ValueError, lambda: FunctionMatrix(2, 2, Lambda(i, 0)))
|
22 |
+
with warns(SymPyDeprecationWarning, test_stacklevel=False):
|
23 |
+
# This raises a deprecation warning from sympify()
|
24 |
+
raises(ValueError, lambda: FunctionMatrix(2, 2, lambda i, j: 0))
|
25 |
+
raises(ValueError, lambda: FunctionMatrix(2, 2, Lambda((i,), 0)))
|
26 |
+
raises(ValueError, lambda: FunctionMatrix(2, 2, Lambda((i, j, k), 0)))
|
27 |
+
raises(ValueError, lambda: FunctionMatrix(2, 2, i+j))
|
28 |
+
assert FunctionMatrix(2, 2, "lambda i, j: 0") == \
|
29 |
+
FunctionMatrix(2, 2, Lambda((i, j), 0))
|
30 |
+
|
31 |
+
m = FunctionMatrix(2, 2, KroneckerDelta)
|
32 |
+
assert m.as_explicit() == Identity(2).as_explicit()
|
33 |
+
assert m.args[2].dummy_eq(Lambda((i, j), KroneckerDelta(i, j)))
|
34 |
+
|
35 |
+
n = symbols('n')
|
36 |
+
assert FunctionMatrix(n, n, Lambda((i, j), 0))
|
37 |
+
n = symbols('n', integer=False)
|
38 |
+
raises(ValueError, lambda: FunctionMatrix(n, n, Lambda((i, j), 0)))
|
39 |
+
n = symbols('n', negative=True)
|
40 |
+
raises(ValueError, lambda: FunctionMatrix(n, n, Lambda((i, j), 0)))
|
41 |
+
|
42 |
+
|
43 |
+
def test_funcmatrix():
|
44 |
+
i, j = symbols('i,j')
|
45 |
+
X = FunctionMatrix(3, 3, Lambda((i, j), i - j))
|
46 |
+
assert X[1, 1] == 0
|
47 |
+
assert X[1, 2] == -1
|
48 |
+
assert X.shape == (3, 3)
|
49 |
+
assert X.rows == X.cols == 3
|
50 |
+
assert Matrix(X) == Matrix(3, 3, lambda i, j: i - j)
|
51 |
+
assert isinstance(X*X + X, MatrixExpr)
|
52 |
+
|
53 |
+
|
54 |
+
def test_replace_issue():
|
55 |
+
X = FunctionMatrix(3, 3, KroneckerDelta)
|
56 |
+
assert X.replace(lambda x: True, lambda x: x) == X
|
llmeval-env/lib/python3.10/site-packages/sympy/matrices/expressions/tests/test_hadamard.py
ADDED
@@ -0,0 +1,141 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.matrices.dense import Matrix, eye
|
2 |
+
from sympy.matrices.common import ShapeError
|
3 |
+
from sympy.matrices.expressions.matadd import MatAdd
|
4 |
+
from sympy.matrices.expressions.special import Identity, OneMatrix, ZeroMatrix
|
5 |
+
from sympy.core import symbols
|
6 |
+
from sympy.testing.pytest import raises, warns_deprecated_sympy
|
7 |
+
|
8 |
+
from sympy.matrices import MatrixSymbol
|
9 |
+
from sympy.matrices.expressions import (HadamardProduct, hadamard_product, HadamardPower, hadamard_power)
|
10 |
+
|
11 |
+
n, m, k = symbols('n,m,k')
|
12 |
+
Z = MatrixSymbol('Z', n, n)
|
13 |
+
A = MatrixSymbol('A', n, m)
|
14 |
+
B = MatrixSymbol('B', n, m)
|
15 |
+
C = MatrixSymbol('C', m, k)
|
16 |
+
|
17 |
+
|
18 |
+
def test_HadamardProduct():
|
19 |
+
assert HadamardProduct(A, B, A).shape == A.shape
|
20 |
+
|
21 |
+
raises(TypeError, lambda: HadamardProduct(A, n))
|
22 |
+
raises(TypeError, lambda: HadamardProduct(A, 1))
|
23 |
+
|
24 |
+
assert HadamardProduct(A, 2*B, -A)[1, 1] == \
|
25 |
+
-2 * A[1, 1] * B[1, 1] * A[1, 1]
|
26 |
+
|
27 |
+
mix = HadamardProduct(Z*A, B)*C
|
28 |
+
assert mix.shape == (n, k)
|
29 |
+
|
30 |
+
assert set(HadamardProduct(A, B, A).T.args) == {A.T, A.T, B.T}
|
31 |
+
|
32 |
+
|
33 |
+
def test_HadamardProduct_isnt_commutative():
|
34 |
+
assert HadamardProduct(A, B) != HadamardProduct(B, A)
|
35 |
+
|
36 |
+
|
37 |
+
def test_mixed_indexing():
|
38 |
+
X = MatrixSymbol('X', 2, 2)
|
39 |
+
Y = MatrixSymbol('Y', 2, 2)
|
40 |
+
Z = MatrixSymbol('Z', 2, 2)
|
41 |
+
|
42 |
+
assert (X*HadamardProduct(Y, Z))[0, 0] == \
|
43 |
+
X[0, 0]*Y[0, 0]*Z[0, 0] + X[0, 1]*Y[1, 0]*Z[1, 0]
|
44 |
+
|
45 |
+
|
46 |
+
def test_canonicalize():
|
47 |
+
X = MatrixSymbol('X', 2, 2)
|
48 |
+
Y = MatrixSymbol('Y', 2, 2)
|
49 |
+
with warns_deprecated_sympy():
|
50 |
+
expr = HadamardProduct(X, check=False)
|
51 |
+
assert isinstance(expr, HadamardProduct)
|
52 |
+
expr2 = expr.doit() # unpack is called
|
53 |
+
assert isinstance(expr2, MatrixSymbol)
|
54 |
+
Z = ZeroMatrix(2, 2)
|
55 |
+
U = OneMatrix(2, 2)
|
56 |
+
assert HadamardProduct(Z, X).doit() == Z
|
57 |
+
assert HadamardProduct(U, X, X, U).doit() == HadamardPower(X, 2)
|
58 |
+
assert HadamardProduct(X, U, Y).doit() == HadamardProduct(X, Y)
|
59 |
+
assert HadamardProduct(X, Z, U, Y).doit() == Z
|
60 |
+
|
61 |
+
|
62 |
+
def test_hadamard():
|
63 |
+
m, n, p = symbols('m, n, p', integer=True)
|
64 |
+
A = MatrixSymbol('A', m, n)
|
65 |
+
B = MatrixSymbol('B', m, n)
|
66 |
+
X = MatrixSymbol('X', m, m)
|
67 |
+
I = Identity(m)
|
68 |
+
|
69 |
+
raises(TypeError, lambda: hadamard_product())
|
70 |
+
assert hadamard_product(A) == A
|
71 |
+
assert isinstance(hadamard_product(A, B), HadamardProduct)
|
72 |
+
assert hadamard_product(A, B).doit() == hadamard_product(A, B)
|
73 |
+
assert hadamard_product(X, I) == HadamardProduct(I, X)
|
74 |
+
assert isinstance(hadamard_product(X, I), HadamardProduct)
|
75 |
+
|
76 |
+
a = MatrixSymbol("a", k, 1)
|
77 |
+
expr = MatAdd(ZeroMatrix(k, 1), OneMatrix(k, 1))
|
78 |
+
expr = HadamardProduct(expr, a)
|
79 |
+
assert expr.doit() == a
|
80 |
+
|
81 |
+
raises(ValueError, lambda: HadamardProduct())
|
82 |
+
|
83 |
+
|
84 |
+
def test_hadamard_product_with_explicit_mat():
|
85 |
+
A = MatrixSymbol("A", 3, 3).as_explicit()
|
86 |
+
B = MatrixSymbol("B", 3, 3).as_explicit()
|
87 |
+
X = MatrixSymbol("X", 3, 3)
|
88 |
+
expr = hadamard_product(A, B)
|
89 |
+
ret = Matrix([i*j for i, j in zip(A, B)]).reshape(3, 3)
|
90 |
+
assert expr == ret
|
91 |
+
expr = hadamard_product(A, X, B)
|
92 |
+
assert expr == HadamardProduct(ret, X)
|
93 |
+
expr = hadamard_product(eye(3), A)
|
94 |
+
assert expr == Matrix([[A[0, 0], 0, 0], [0, A[1, 1], 0], [0, 0, A[2, 2]]])
|
95 |
+
expr = hadamard_product(eye(3), eye(3))
|
96 |
+
assert expr == eye(3)
|
97 |
+
|
98 |
+
|
99 |
+
def test_hadamard_power():
|
100 |
+
m, n, p = symbols('m, n, p', integer=True)
|
101 |
+
A = MatrixSymbol('A', m, n)
|
102 |
+
|
103 |
+
assert hadamard_power(A, 1) == A
|
104 |
+
assert isinstance(hadamard_power(A, 2), HadamardPower)
|
105 |
+
assert hadamard_power(A, n).T == hadamard_power(A.T, n)
|
106 |
+
assert hadamard_power(A, n)[0, 0] == A[0, 0]**n
|
107 |
+
assert hadamard_power(m, n) == m**n
|
108 |
+
raises(ValueError, lambda: hadamard_power(A, A))
|
109 |
+
|
110 |
+
|
111 |
+
def test_hadamard_power_explicit():
|
112 |
+
A = MatrixSymbol('A', 2, 2)
|
113 |
+
B = MatrixSymbol('B', 2, 2)
|
114 |
+
a, b = symbols('a b')
|
115 |
+
|
116 |
+
assert HadamardPower(a, b) == a**b
|
117 |
+
|
118 |
+
assert HadamardPower(a, B).as_explicit() == \
|
119 |
+
Matrix([
|
120 |
+
[a**B[0, 0], a**B[0, 1]],
|
121 |
+
[a**B[1, 0], a**B[1, 1]]])
|
122 |
+
|
123 |
+
assert HadamardPower(A, b).as_explicit() == \
|
124 |
+
Matrix([
|
125 |
+
[A[0, 0]**b, A[0, 1]**b],
|
126 |
+
[A[1, 0]**b, A[1, 1]**b]])
|
127 |
+
|
128 |
+
assert HadamardPower(A, B).as_explicit() == \
|
129 |
+
Matrix([
|
130 |
+
[A[0, 0]**B[0, 0], A[0, 1]**B[0, 1]],
|
131 |
+
[A[1, 0]**B[1, 0], A[1, 1]**B[1, 1]]])
|
132 |
+
|
133 |
+
|
134 |
+
def test_shape_error():
|
135 |
+
A = MatrixSymbol('A', 2, 3)
|
136 |
+
B = MatrixSymbol('B', 3, 3)
|
137 |
+
raises(ShapeError, lambda: HadamardProduct(A, B))
|
138 |
+
raises(ShapeError, lambda: HadamardPower(A, B))
|
139 |
+
A = MatrixSymbol('A', 3, 2)
|
140 |
+
raises(ShapeError, lambda: HadamardProduct(A, B))
|
141 |
+
raises(ShapeError, lambda: HadamardPower(A, B))
|
llmeval-env/lib/python3.10/site-packages/sympy/matrices/expressions/tests/test_indexing.py
ADDED
@@ -0,0 +1,299 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.concrete.summations import Sum
|
2 |
+
from sympy.core.symbol import symbols, Symbol, Dummy
|
3 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
4 |
+
from sympy.functions.special.tensor_functions import KroneckerDelta
|
5 |
+
from sympy.matrices.dense import eye
|
6 |
+
from sympy.matrices.expressions.blockmatrix import BlockMatrix
|
7 |
+
from sympy.matrices.expressions.hadamard import HadamardPower
|
8 |
+
from sympy.matrices.expressions.matexpr import (MatrixSymbol,
|
9 |
+
MatrixExpr, MatrixElement)
|
10 |
+
from sympy.matrices.expressions.matpow import MatPow
|
11 |
+
from sympy.matrices.expressions.special import (ZeroMatrix, Identity,
|
12 |
+
OneMatrix)
|
13 |
+
from sympy.matrices.expressions.trace import Trace, trace
|
14 |
+
from sympy.matrices.immutable import ImmutableMatrix
|
15 |
+
from sympy.tensor.array.expressions.array_expressions import ArrayTensorProduct
|
16 |
+
from sympy.testing.pytest import XFAIL, raises
|
17 |
+
|
18 |
+
k, l, m, n = symbols('k l m n', integer=True)
|
19 |
+
i, j = symbols('i j', integer=True)
|
20 |
+
|
21 |
+
W = MatrixSymbol('W', k, l)
|
22 |
+
X = MatrixSymbol('X', l, m)
|
23 |
+
Y = MatrixSymbol('Y', l, m)
|
24 |
+
Z = MatrixSymbol('Z', m, n)
|
25 |
+
|
26 |
+
X1 = MatrixSymbol('X1', m, m)
|
27 |
+
X2 = MatrixSymbol('X2', m, m)
|
28 |
+
X3 = MatrixSymbol('X3', m, m)
|
29 |
+
X4 = MatrixSymbol('X4', m, m)
|
30 |
+
|
31 |
+
A = MatrixSymbol('A', 2, 2)
|
32 |
+
B = MatrixSymbol('B', 2, 2)
|
33 |
+
x = MatrixSymbol('x', 1, 2)
|
34 |
+
y = MatrixSymbol('x', 2, 1)
|
35 |
+
|
36 |
+
|
37 |
+
def test_symbolic_indexing():
|
38 |
+
x12 = X[1, 2]
|
39 |
+
assert all(s in str(x12) for s in ['1', '2', X.name])
|
40 |
+
# We don't care about the exact form of this. We do want to make sure
|
41 |
+
# that all of these features are present
|
42 |
+
|
43 |
+
|
44 |
+
def test_add_index():
|
45 |
+
assert (X + Y)[i, j] == X[i, j] + Y[i, j]
|
46 |
+
|
47 |
+
|
48 |
+
def test_mul_index():
|
49 |
+
assert (A*y)[0, 0] == A[0, 0]*y[0, 0] + A[0, 1]*y[1, 0]
|
50 |
+
assert (A*B).as_mutable() == (A.as_mutable() * B.as_mutable())
|
51 |
+
X = MatrixSymbol('X', n, m)
|
52 |
+
Y = MatrixSymbol('Y', m, k)
|
53 |
+
|
54 |
+
result = (X*Y)[4,2]
|
55 |
+
expected = Sum(X[4, i]*Y[i, 2], (i, 0, m - 1))
|
56 |
+
assert result.args[0].dummy_eq(expected.args[0], i)
|
57 |
+
assert result.args[1][1:] == expected.args[1][1:]
|
58 |
+
|
59 |
+
|
60 |
+
def test_pow_index():
|
61 |
+
Q = MatPow(A, 2)
|
62 |
+
assert Q[0, 0] == A[0, 0]**2 + A[0, 1]*A[1, 0]
|
63 |
+
n = symbols("n")
|
64 |
+
Q2 = A**n
|
65 |
+
assert Q2[0, 0] == 2*(
|
66 |
+
-sqrt((A[0, 0] + A[1, 1])**2 - 4*A[0, 0]*A[1, 1] +
|
67 |
+
4*A[0, 1]*A[1, 0])/2 + A[0, 0]/2 + A[1, 1]/2
|
68 |
+
)**n * \
|
69 |
+
A[0, 1]*A[1, 0]/(
|
70 |
+
(sqrt(A[0, 0]**2 - 2*A[0, 0]*A[1, 1] + 4*A[0, 1]*A[1, 0] +
|
71 |
+
A[1, 1]**2) + A[0, 0] - A[1, 1])*
|
72 |
+
sqrt(A[0, 0]**2 - 2*A[0, 0]*A[1, 1] + 4*A[0, 1]*A[1, 0] + A[1, 1]**2)
|
73 |
+
) - 2*(
|
74 |
+
sqrt((A[0, 0] + A[1, 1])**2 - 4*A[0, 0]*A[1, 1] +
|
75 |
+
4*A[0, 1]*A[1, 0])/2 + A[0, 0]/2 + A[1, 1]/2
|
76 |
+
)**n * A[0, 1]*A[1, 0]/(
|
77 |
+
(-sqrt(A[0, 0]**2 - 2*A[0, 0]*A[1, 1] + 4*A[0, 1]*A[1, 0] +
|
78 |
+
A[1, 1]**2) + A[0, 0] - A[1, 1])*
|
79 |
+
sqrt(A[0, 0]**2 - 2*A[0, 0]*A[1, 1] + 4*A[0, 1]*A[1, 0] + A[1, 1]**2)
|
80 |
+
)
|
81 |
+
|
82 |
+
|
83 |
+
def test_transpose_index():
|
84 |
+
assert X.T[i, j] == X[j, i]
|
85 |
+
|
86 |
+
|
87 |
+
def test_Identity_index():
|
88 |
+
I = Identity(3)
|
89 |
+
assert I[0, 0] == I[1, 1] == I[2, 2] == 1
|
90 |
+
assert I[1, 0] == I[0, 1] == I[2, 1] == 0
|
91 |
+
assert I[i, 0].delta_range == (0, 2)
|
92 |
+
raises(IndexError, lambda: I[3, 3])
|
93 |
+
|
94 |
+
|
95 |
+
def test_block_index():
|
96 |
+
I = Identity(3)
|
97 |
+
Z = ZeroMatrix(3, 3)
|
98 |
+
B = BlockMatrix([[I, I], [I, I]])
|
99 |
+
e3 = ImmutableMatrix(eye(3))
|
100 |
+
BB = BlockMatrix([[e3, e3], [e3, e3]])
|
101 |
+
assert B[0, 0] == B[3, 0] == B[0, 3] == B[3, 3] == 1
|
102 |
+
assert B[4, 3] == B[5, 1] == 0
|
103 |
+
|
104 |
+
BB = BlockMatrix([[e3, e3], [e3, e3]])
|
105 |
+
assert B.as_explicit() == BB.as_explicit()
|
106 |
+
|
107 |
+
BI = BlockMatrix([[I, Z], [Z, I]])
|
108 |
+
|
109 |
+
assert BI.as_explicit().equals(eye(6))
|
110 |
+
|
111 |
+
|
112 |
+
def test_block_index_symbolic():
|
113 |
+
# Note that these matrices may be zero-sized and indices may be negative, which causes
|
114 |
+
# all naive simplifications given in the comments to be invalid
|
115 |
+
A1 = MatrixSymbol('A1', n, k)
|
116 |
+
A2 = MatrixSymbol('A2', n, l)
|
117 |
+
A3 = MatrixSymbol('A3', m, k)
|
118 |
+
A4 = MatrixSymbol('A4', m, l)
|
119 |
+
A = BlockMatrix([[A1, A2], [A3, A4]])
|
120 |
+
assert A[0, 0] == MatrixElement(A, 0, 0) # Cannot be A1[0, 0]
|
121 |
+
assert A[n - 1, k - 1] == A1[n - 1, k - 1]
|
122 |
+
assert A[n, k] == A4[0, 0]
|
123 |
+
assert A[n + m - 1, 0] == MatrixElement(A, n + m - 1, 0) # Cannot be A3[m - 1, 0]
|
124 |
+
assert A[0, k + l - 1] == MatrixElement(A, 0, k + l - 1) # Cannot be A2[0, l - 1]
|
125 |
+
assert A[n + m - 1, k + l - 1] == MatrixElement(A, n + m - 1, k + l - 1) # Cannot be A4[m - 1, l - 1]
|
126 |
+
assert A[i, j] == MatrixElement(A, i, j)
|
127 |
+
assert A[n + i, k + j] == MatrixElement(A, n + i, k + j) # Cannot be A4[i, j]
|
128 |
+
assert A[n - i - 1, k - j - 1] == MatrixElement(A, n - i - 1, k - j - 1) # Cannot be A1[n - i - 1, k - j - 1]
|
129 |
+
|
130 |
+
|
131 |
+
def test_block_index_symbolic_nonzero():
|
132 |
+
# All invalid simplifications from test_block_index_symbolic() that become valid if all
|
133 |
+
# matrices have nonzero size and all indices are nonnegative
|
134 |
+
k, l, m, n = symbols('k l m n', integer=True, positive=True)
|
135 |
+
i, j = symbols('i j', integer=True, nonnegative=True)
|
136 |
+
A1 = MatrixSymbol('A1', n, k)
|
137 |
+
A2 = MatrixSymbol('A2', n, l)
|
138 |
+
A3 = MatrixSymbol('A3', m, k)
|
139 |
+
A4 = MatrixSymbol('A4', m, l)
|
140 |
+
A = BlockMatrix([[A1, A2], [A3, A4]])
|
141 |
+
assert A[0, 0] == A1[0, 0]
|
142 |
+
assert A[n + m - 1, 0] == A3[m - 1, 0]
|
143 |
+
assert A[0, k + l - 1] == A2[0, l - 1]
|
144 |
+
assert A[n + m - 1, k + l - 1] == A4[m - 1, l - 1]
|
145 |
+
assert A[i, j] == MatrixElement(A, i, j)
|
146 |
+
assert A[n + i, k + j] == A4[i, j]
|
147 |
+
assert A[n - i - 1, k - j - 1] == A1[n - i - 1, k - j - 1]
|
148 |
+
assert A[2 * n, 2 * k] == A4[n, k]
|
149 |
+
|
150 |
+
|
151 |
+
def test_block_index_large():
|
152 |
+
n, m, k = symbols('n m k', integer=True, positive=True)
|
153 |
+
i = symbols('i', integer=True, nonnegative=True)
|
154 |
+
A1 = MatrixSymbol('A1', n, n)
|
155 |
+
A2 = MatrixSymbol('A2', n, m)
|
156 |
+
A3 = MatrixSymbol('A3', n, k)
|
157 |
+
A4 = MatrixSymbol('A4', m, n)
|
158 |
+
A5 = MatrixSymbol('A5', m, m)
|
159 |
+
A6 = MatrixSymbol('A6', m, k)
|
160 |
+
A7 = MatrixSymbol('A7', k, n)
|
161 |
+
A8 = MatrixSymbol('A8', k, m)
|
162 |
+
A9 = MatrixSymbol('A9', k, k)
|
163 |
+
A = BlockMatrix([[A1, A2, A3], [A4, A5, A6], [A7, A8, A9]])
|
164 |
+
assert A[n + i, n + i] == MatrixElement(A, n + i, n + i)
|
165 |
+
|
166 |
+
|
167 |
+
@XFAIL
|
168 |
+
def test_block_index_symbolic_fail():
|
169 |
+
# To make this work, symbolic matrix dimensions would need to be somehow assumed nonnegative
|
170 |
+
# even if the symbols aren't specified as such. Then 2 * n < n would correctly evaluate to
|
171 |
+
# False in BlockMatrix._entry()
|
172 |
+
A1 = MatrixSymbol('A1', n, 1)
|
173 |
+
A2 = MatrixSymbol('A2', m, 1)
|
174 |
+
A = BlockMatrix([[A1], [A2]])
|
175 |
+
assert A[2 * n, 0] == A2[n, 0]
|
176 |
+
|
177 |
+
|
178 |
+
def test_slicing():
|
179 |
+
A.as_explicit()[0, :] # does not raise an error
|
180 |
+
|
181 |
+
|
182 |
+
def test_errors():
|
183 |
+
raises(IndexError, lambda: Identity(2)[1, 2, 3, 4, 5])
|
184 |
+
raises(IndexError, lambda: Identity(2)[[1, 2, 3, 4, 5]])
|
185 |
+
|
186 |
+
|
187 |
+
def test_matrix_expression_to_indices():
|
188 |
+
i, j = symbols("i, j")
|
189 |
+
i1, i2, i3 = symbols("i_1:4")
|
190 |
+
|
191 |
+
def replace_dummies(expr):
|
192 |
+
repl = {i: Symbol(i.name) for i in expr.atoms(Dummy)}
|
193 |
+
return expr.xreplace(repl)
|
194 |
+
|
195 |
+
expr = W*X*Z
|
196 |
+
assert replace_dummies(expr._entry(i, j)) == \
|
197 |
+
Sum(W[i, i1]*X[i1, i2]*Z[i2, j], (i1, 0, l-1), (i2, 0, m-1))
|
198 |
+
assert MatrixExpr.from_index_summation(expr._entry(i, j)) == expr
|
199 |
+
|
200 |
+
expr = Z.T*X.T*W.T
|
201 |
+
assert replace_dummies(expr._entry(i, j)) == \
|
202 |
+
Sum(W[j, i2]*X[i2, i1]*Z[i1, i], (i1, 0, m-1), (i2, 0, l-1))
|
203 |
+
assert MatrixExpr.from_index_summation(expr._entry(i, j), i) == expr
|
204 |
+
|
205 |
+
expr = W*X*Z + W*Y*Z
|
206 |
+
assert replace_dummies(expr._entry(i, j)) == \
|
207 |
+
Sum(W[i, i1]*X[i1, i2]*Z[i2, j], (i1, 0, l-1), (i2, 0, m-1)) +\
|
208 |
+
Sum(W[i, i1]*Y[i1, i2]*Z[i2, j], (i1, 0, l-1), (i2, 0, m-1))
|
209 |
+
assert MatrixExpr.from_index_summation(expr._entry(i, j)) == expr
|
210 |
+
|
211 |
+
expr = 2*W*X*Z + 3*W*Y*Z
|
212 |
+
assert replace_dummies(expr._entry(i, j)) == \
|
213 |
+
2*Sum(W[i, i1]*X[i1, i2]*Z[i2, j], (i1, 0, l-1), (i2, 0, m-1)) +\
|
214 |
+
3*Sum(W[i, i1]*Y[i1, i2]*Z[i2, j], (i1, 0, l-1), (i2, 0, m-1))
|
215 |
+
assert MatrixExpr.from_index_summation(expr._entry(i, j)) == expr
|
216 |
+
|
217 |
+
expr = W*(X + Y)*Z
|
218 |
+
assert replace_dummies(expr._entry(i, j)) == \
|
219 |
+
Sum(W[i, i1]*(X[i1, i2] + Y[i1, i2])*Z[i2, j], (i1, 0, l-1), (i2, 0, m-1))
|
220 |
+
assert MatrixExpr.from_index_summation(expr._entry(i, j)) == expr
|
221 |
+
|
222 |
+
expr = A*B**2*A
|
223 |
+
#assert replace_dummies(expr._entry(i, j)) == \
|
224 |
+
# Sum(A[i, i1]*B[i1, i2]*B[i2, i3]*A[i3, j], (i1, 0, 1), (i2, 0, 1), (i3, 0, 1))
|
225 |
+
|
226 |
+
# Check that different dummies are used in sub-multiplications:
|
227 |
+
expr = (X1*X2 + X2*X1)*X3
|
228 |
+
assert replace_dummies(expr._entry(i, j)) == \
|
229 |
+
Sum((Sum(X1[i, i2] * X2[i2, i1], (i2, 0, m - 1)) + Sum(X1[i3, i1] * X2[i, i3], (i3, 0, m - 1))) * X3[
|
230 |
+
i1, j], (i1, 0, m - 1))
|
231 |
+
|
232 |
+
|
233 |
+
def test_matrix_expression_from_index_summation():
|
234 |
+
from sympy.abc import a,b,c,d
|
235 |
+
A = MatrixSymbol("A", k, k)
|
236 |
+
B = MatrixSymbol("B", k, k)
|
237 |
+
C = MatrixSymbol("C", k, k)
|
238 |
+
w1 = MatrixSymbol("w1", k, 1)
|
239 |
+
|
240 |
+
i0, i1, i2, i3, i4 = symbols("i0:5", cls=Dummy)
|
241 |
+
|
242 |
+
expr = Sum(W[a,b]*X[b,c]*Z[c,d], (b, 0, l-1), (c, 0, m-1))
|
243 |
+
assert MatrixExpr.from_index_summation(expr, a) == W*X*Z
|
244 |
+
expr = Sum(W.T[b,a]*X[b,c]*Z[c,d], (b, 0, l-1), (c, 0, m-1))
|
245 |
+
assert MatrixExpr.from_index_summation(expr, a) == W*X*Z
|
246 |
+
expr = Sum(A[b, a]*B[b, c]*C[c, d], (b, 0, k-1), (c, 0, k-1))
|
247 |
+
assert MatrixSymbol.from_index_summation(expr, a) == A.T*B*C
|
248 |
+
expr = Sum(A[b, a]*B[c, b]*C[c, d], (b, 0, k-1), (c, 0, k-1))
|
249 |
+
assert MatrixSymbol.from_index_summation(expr, a) == A.T*B.T*C
|
250 |
+
expr = Sum(C[c, d]*A[b, a]*B[c, b], (b, 0, k-1), (c, 0, k-1))
|
251 |
+
assert MatrixSymbol.from_index_summation(expr, a) == A.T*B.T*C
|
252 |
+
expr = Sum(A[a, b] + B[a, b], (a, 0, k-1), (b, 0, k-1))
|
253 |
+
assert MatrixExpr.from_index_summation(expr, a) == OneMatrix(1, k)*A*OneMatrix(k, 1) + OneMatrix(1, k)*B*OneMatrix(k, 1)
|
254 |
+
expr = Sum(A[a, b]**2, (a, 0, k - 1), (b, 0, k - 1))
|
255 |
+
assert MatrixExpr.from_index_summation(expr, a) == Trace(A * A.T)
|
256 |
+
expr = Sum(A[a, b]**3, (a, 0, k - 1), (b, 0, k - 1))
|
257 |
+
assert MatrixExpr.from_index_summation(expr, a) == Trace(HadamardPower(A.T, 2) * A)
|
258 |
+
expr = Sum((A[a, b] + B[a, b])*C[b, c], (b, 0, k-1))
|
259 |
+
assert MatrixExpr.from_index_summation(expr, a) == (A+B)*C
|
260 |
+
expr = Sum((A[a, b] + B[b, a])*C[b, c], (b, 0, k-1))
|
261 |
+
assert MatrixExpr.from_index_summation(expr, a) == (A+B.T)*C
|
262 |
+
expr = Sum(A[a, b]*A[b, c]*A[c, d], (b, 0, k-1), (c, 0, k-1))
|
263 |
+
assert MatrixExpr.from_index_summation(expr, a) == A**3
|
264 |
+
expr = Sum(A[a, b]*A[b, c]*B[c, d], (b, 0, k-1), (c, 0, k-1))
|
265 |
+
assert MatrixExpr.from_index_summation(expr, a) == A**2*B
|
266 |
+
|
267 |
+
# Parse the trace of a matrix:
|
268 |
+
|
269 |
+
expr = Sum(A[a, a], (a, 0, k-1))
|
270 |
+
assert MatrixExpr.from_index_summation(expr, None) == trace(A)
|
271 |
+
expr = Sum(A[a, a]*B[b, c]*C[c, d], (a, 0, k-1), (c, 0, k-1))
|
272 |
+
assert MatrixExpr.from_index_summation(expr, b) == trace(A)*B*C
|
273 |
+
|
274 |
+
# Check wrong sum ranges (should raise an exception):
|
275 |
+
|
276 |
+
## Case 1: 0 to m instead of 0 to m-1
|
277 |
+
expr = Sum(W[a,b]*X[b,c]*Z[c,d], (b, 0, l-1), (c, 0, m))
|
278 |
+
raises(ValueError, lambda: MatrixExpr.from_index_summation(expr, a))
|
279 |
+
## Case 2: 1 to m-1 instead of 0 to m-1
|
280 |
+
expr = Sum(W[a,b]*X[b,c]*Z[c,d], (b, 0, l-1), (c, 1, m-1))
|
281 |
+
raises(ValueError, lambda: MatrixExpr.from_index_summation(expr, a))
|
282 |
+
|
283 |
+
# Parse nested sums:
|
284 |
+
expr = Sum(A[a, b]*Sum(B[b, c]*C[c, d], (c, 0, k-1)), (b, 0, k-1))
|
285 |
+
assert MatrixExpr.from_index_summation(expr, a) == A*B*C
|
286 |
+
|
287 |
+
# Test Kronecker delta:
|
288 |
+
expr = Sum(A[a, b]*KroneckerDelta(b, c)*B[c, d], (b, 0, k-1), (c, 0, k-1))
|
289 |
+
assert MatrixExpr.from_index_summation(expr, a) == A*B
|
290 |
+
|
291 |
+
expr = Sum(KroneckerDelta(i1, m)*KroneckerDelta(i2, n)*A[i, i1]*A[j, i2], (i1, 0, k-1), (i2, 0, k-1))
|
292 |
+
assert MatrixExpr.from_index_summation(expr, m) == ArrayTensorProduct(A.T, A)
|
293 |
+
|
294 |
+
# Test numbered indices:
|
295 |
+
expr = Sum(A[i1, i2]*w1[i2, 0], (i2, 0, k-1))
|
296 |
+
assert MatrixExpr.from_index_summation(expr, i1) == MatrixElement(A*w1, i1, 0)
|
297 |
+
|
298 |
+
expr = Sum(A[i1, i2]*B[i2, 0], (i2, 0, k-1))
|
299 |
+
assert MatrixExpr.from_index_summation(expr, i1) == MatrixElement(A*B, i1, 0)
|
llmeval-env/lib/python3.10/site-packages/sympy/matrices/expressions/tests/test_inverse.py
ADDED
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.core import symbols, S
|
2 |
+
from sympy.matrices.expressions import MatrixSymbol, Inverse, MatPow, ZeroMatrix, OneMatrix
|
3 |
+
from sympy.matrices.common import NonInvertibleMatrixError, NonSquareMatrixError
|
4 |
+
from sympy.matrices import eye, Identity
|
5 |
+
from sympy.testing.pytest import raises
|
6 |
+
from sympy.assumptions.ask import Q
|
7 |
+
from sympy.assumptions.refine import refine
|
8 |
+
|
9 |
+
n, m, l = symbols('n m l', integer=True)
|
10 |
+
A = MatrixSymbol('A', n, m)
|
11 |
+
B = MatrixSymbol('B', m, l)
|
12 |
+
C = MatrixSymbol('C', n, n)
|
13 |
+
D = MatrixSymbol('D', n, n)
|
14 |
+
E = MatrixSymbol('E', m, n)
|
15 |
+
|
16 |
+
|
17 |
+
def test_inverse():
|
18 |
+
assert Inverse(C).args == (C, S.NegativeOne)
|
19 |
+
assert Inverse(C).shape == (n, n)
|
20 |
+
assert Inverse(A*E).shape == (n, n)
|
21 |
+
assert Inverse(E*A).shape == (m, m)
|
22 |
+
assert Inverse(C).inverse() == C
|
23 |
+
assert Inverse(Inverse(C)).doit() == C
|
24 |
+
assert isinstance(Inverse(Inverse(C)), Inverse)
|
25 |
+
|
26 |
+
assert Inverse(*Inverse(E*A).args) == Inverse(E*A)
|
27 |
+
|
28 |
+
assert C.inverse().inverse() == C
|
29 |
+
|
30 |
+
assert C.inverse()*C == Identity(C.rows)
|
31 |
+
|
32 |
+
assert Identity(n).inverse() == Identity(n)
|
33 |
+
assert (3*Identity(n)).inverse() == Identity(n)/3
|
34 |
+
|
35 |
+
# Simplifies Muls if possible (i.e. submatrices are square)
|
36 |
+
assert (C*D).inverse() == D.I*C.I
|
37 |
+
# But still works when not possible
|
38 |
+
assert isinstance((A*E).inverse(), Inverse)
|
39 |
+
assert Inverse(C*D).doit(inv_expand=False) == Inverse(C*D)
|
40 |
+
|
41 |
+
assert Inverse(eye(3)).doit() == eye(3)
|
42 |
+
assert Inverse(eye(3)).doit(deep=False) == eye(3)
|
43 |
+
|
44 |
+
assert OneMatrix(1, 1).I == Identity(1)
|
45 |
+
assert isinstance(OneMatrix(n, n).I, Inverse)
|
46 |
+
|
47 |
+
def test_inverse_non_invertible():
|
48 |
+
raises(NonInvertibleMatrixError, lambda: ZeroMatrix(n, n).I)
|
49 |
+
raises(NonInvertibleMatrixError, lambda: OneMatrix(2, 2).I)
|
50 |
+
|
51 |
+
def test_refine():
|
52 |
+
assert refine(C.I, Q.orthogonal(C)) == C.T
|
53 |
+
|
54 |
+
|
55 |
+
def test_inverse_matpow_canonicalization():
|
56 |
+
A = MatrixSymbol('A', 3, 3)
|
57 |
+
assert Inverse(MatPow(A, 3)).doit() == MatPow(Inverse(A), 3).doit()
|
58 |
+
|
59 |
+
|
60 |
+
def test_nonsquare_error():
|
61 |
+
A = MatrixSymbol('A', 3, 4)
|
62 |
+
raises(NonSquareMatrixError, lambda: Inverse(A))
|
llmeval-env/lib/python3.10/site-packages/sympy/matrices/expressions/tests/test_kronecker.py
ADDED
@@ -0,0 +1,150 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.core.mod import Mod
|
2 |
+
from sympy.core.numbers import I
|
3 |
+
from sympy.core.symbol import symbols
|
4 |
+
from sympy.functions.elementary.integers import floor
|
5 |
+
from sympy.matrices.dense import (Matrix, eye)
|
6 |
+
from sympy.matrices import MatrixSymbol, Identity
|
7 |
+
from sympy.matrices.expressions import det, trace
|
8 |
+
|
9 |
+
from sympy.matrices.expressions.kronecker import (KroneckerProduct,
|
10 |
+
kronecker_product,
|
11 |
+
combine_kronecker)
|
12 |
+
|
13 |
+
|
14 |
+
mat1 = Matrix([[1, 2 * I], [1 + I, 3]])
|
15 |
+
mat2 = Matrix([[2 * I, 3], [4 * I, 2]])
|
16 |
+
|
17 |
+
i, j, k, n, m, o, p, x = symbols('i,j,k,n,m,o,p,x')
|
18 |
+
Z = MatrixSymbol('Z', n, n)
|
19 |
+
W = MatrixSymbol('W', m, m)
|
20 |
+
A = MatrixSymbol('A', n, m)
|
21 |
+
B = MatrixSymbol('B', n, m)
|
22 |
+
C = MatrixSymbol('C', m, k)
|
23 |
+
|
24 |
+
|
25 |
+
def test_KroneckerProduct():
|
26 |
+
assert isinstance(KroneckerProduct(A, B), KroneckerProduct)
|
27 |
+
assert KroneckerProduct(A, B).subs(A, C) == KroneckerProduct(C, B)
|
28 |
+
assert KroneckerProduct(A, C).shape == (n*m, m*k)
|
29 |
+
assert (KroneckerProduct(A, C) + KroneckerProduct(-A, C)).is_ZeroMatrix
|
30 |
+
assert (KroneckerProduct(W, Z) * KroneckerProduct(W.I, Z.I)).is_Identity
|
31 |
+
|
32 |
+
|
33 |
+
def test_KroneckerProduct_identity():
|
34 |
+
assert KroneckerProduct(Identity(m), Identity(n)) == Identity(m*n)
|
35 |
+
assert KroneckerProduct(eye(2), eye(3)) == eye(6)
|
36 |
+
|
37 |
+
|
38 |
+
def test_KroneckerProduct_explicit():
|
39 |
+
X = MatrixSymbol('X', 2, 2)
|
40 |
+
Y = MatrixSymbol('Y', 2, 2)
|
41 |
+
kp = KroneckerProduct(X, Y)
|
42 |
+
assert kp.shape == (4, 4)
|
43 |
+
assert kp.as_explicit() == Matrix(
|
44 |
+
[
|
45 |
+
[X[0, 0]*Y[0, 0], X[0, 0]*Y[0, 1], X[0, 1]*Y[0, 0], X[0, 1]*Y[0, 1]],
|
46 |
+
[X[0, 0]*Y[1, 0], X[0, 0]*Y[1, 1], X[0, 1]*Y[1, 0], X[0, 1]*Y[1, 1]],
|
47 |
+
[X[1, 0]*Y[0, 0], X[1, 0]*Y[0, 1], X[1, 1]*Y[0, 0], X[1, 1]*Y[0, 1]],
|
48 |
+
[X[1, 0]*Y[1, 0], X[1, 0]*Y[1, 1], X[1, 1]*Y[1, 0], X[1, 1]*Y[1, 1]]
|
49 |
+
]
|
50 |
+
)
|
51 |
+
|
52 |
+
|
53 |
+
def test_tensor_product_adjoint():
|
54 |
+
assert KroneckerProduct(I*A, B).adjoint() == \
|
55 |
+
-I*KroneckerProduct(A.adjoint(), B.adjoint())
|
56 |
+
assert KroneckerProduct(mat1, mat2).adjoint() == \
|
57 |
+
kronecker_product(mat1.adjoint(), mat2.adjoint())
|
58 |
+
|
59 |
+
|
60 |
+
def test_tensor_product_conjugate():
|
61 |
+
assert KroneckerProduct(I*A, B).conjugate() == \
|
62 |
+
-I*KroneckerProduct(A.conjugate(), B.conjugate())
|
63 |
+
assert KroneckerProduct(mat1, mat2).conjugate() == \
|
64 |
+
kronecker_product(mat1.conjugate(), mat2.conjugate())
|
65 |
+
|
66 |
+
|
67 |
+
def test_tensor_product_transpose():
|
68 |
+
assert KroneckerProduct(I*A, B).transpose() == \
|
69 |
+
I*KroneckerProduct(A.transpose(), B.transpose())
|
70 |
+
assert KroneckerProduct(mat1, mat2).transpose() == \
|
71 |
+
kronecker_product(mat1.transpose(), mat2.transpose())
|
72 |
+
|
73 |
+
|
74 |
+
def test_KroneckerProduct_is_associative():
|
75 |
+
assert kronecker_product(A, kronecker_product(
|
76 |
+
B, C)) == kronecker_product(kronecker_product(A, B), C)
|
77 |
+
assert kronecker_product(A, kronecker_product(
|
78 |
+
B, C)) == KroneckerProduct(A, B, C)
|
79 |
+
|
80 |
+
|
81 |
+
def test_KroneckerProduct_is_bilinear():
|
82 |
+
assert kronecker_product(x*A, B) == x*kronecker_product(A, B)
|
83 |
+
assert kronecker_product(A, x*B) == x*kronecker_product(A, B)
|
84 |
+
|
85 |
+
|
86 |
+
def test_KroneckerProduct_determinant():
|
87 |
+
kp = kronecker_product(W, Z)
|
88 |
+
assert det(kp) == det(W)**n * det(Z)**m
|
89 |
+
|
90 |
+
|
91 |
+
def test_KroneckerProduct_trace():
|
92 |
+
kp = kronecker_product(W, Z)
|
93 |
+
assert trace(kp) == trace(W)*trace(Z)
|
94 |
+
|
95 |
+
|
96 |
+
def test_KroneckerProduct_isnt_commutative():
|
97 |
+
assert KroneckerProduct(A, B) != KroneckerProduct(B, A)
|
98 |
+
assert KroneckerProduct(A, B).is_commutative is False
|
99 |
+
|
100 |
+
|
101 |
+
def test_KroneckerProduct_extracts_commutative_part():
|
102 |
+
assert kronecker_product(x * A, 2 * B) == x * \
|
103 |
+
2 * KroneckerProduct(A, B)
|
104 |
+
|
105 |
+
|
106 |
+
def test_KroneckerProduct_inverse():
|
107 |
+
kp = kronecker_product(W, Z)
|
108 |
+
assert kp.inverse() == kronecker_product(W.inverse(), Z.inverse())
|
109 |
+
|
110 |
+
|
111 |
+
def test_KroneckerProduct_combine_add():
|
112 |
+
kp1 = kronecker_product(A, B)
|
113 |
+
kp2 = kronecker_product(C, W)
|
114 |
+
assert combine_kronecker(kp1*kp2) == kronecker_product(A*C, B*W)
|
115 |
+
|
116 |
+
|
117 |
+
def test_KroneckerProduct_combine_mul():
|
118 |
+
X = MatrixSymbol('X', m, n)
|
119 |
+
Y = MatrixSymbol('Y', m, n)
|
120 |
+
kp1 = kronecker_product(A, X)
|
121 |
+
kp2 = kronecker_product(B, Y)
|
122 |
+
assert combine_kronecker(kp1+kp2) == kronecker_product(A+B, X+Y)
|
123 |
+
|
124 |
+
|
125 |
+
def test_KroneckerProduct_combine_pow():
|
126 |
+
X = MatrixSymbol('X', n, n)
|
127 |
+
Y = MatrixSymbol('Y', n, n)
|
128 |
+
assert combine_kronecker(KroneckerProduct(
|
129 |
+
X, Y)**x) == KroneckerProduct(X**x, Y**x)
|
130 |
+
assert combine_kronecker(x * KroneckerProduct(X, Y)
|
131 |
+
** 2) == x * KroneckerProduct(X**2, Y**2)
|
132 |
+
assert combine_kronecker(
|
133 |
+
x * (KroneckerProduct(X, Y)**2) * KroneckerProduct(A, B)) == x * KroneckerProduct(X**2 * A, Y**2 * B)
|
134 |
+
# cannot simplify because of non-square arguments to kronecker product:
|
135 |
+
assert combine_kronecker(KroneckerProduct(A, B.T) ** m) == KroneckerProduct(A, B.T) ** m
|
136 |
+
|
137 |
+
|
138 |
+
def test_KroneckerProduct_expand():
|
139 |
+
X = MatrixSymbol('X', n, n)
|
140 |
+
Y = MatrixSymbol('Y', n, n)
|
141 |
+
|
142 |
+
assert KroneckerProduct(X + Y, Y + Z).expand(kroneckerproduct=True) == \
|
143 |
+
KroneckerProduct(X, Y) + KroneckerProduct(X, Z) + \
|
144 |
+
KroneckerProduct(Y, Y) + KroneckerProduct(Y, Z)
|
145 |
+
|
146 |
+
def test_KroneckerProduct_entry():
|
147 |
+
A = MatrixSymbol('A', n, m)
|
148 |
+
B = MatrixSymbol('B', o, p)
|
149 |
+
|
150 |
+
assert KroneckerProduct(A, B)._entry(i, j) == A[Mod(floor(i/o), n), Mod(floor(j/p), m)]*B[Mod(i, o), Mod(j, p)]
|
llmeval-env/lib/python3.10/site-packages/sympy/matrices/expressions/tests/test_matadd.py
ADDED
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.matrices.expressions import MatrixSymbol, MatAdd, MatPow, MatMul
|
2 |
+
from sympy.matrices.expressions.special import GenericZeroMatrix, ZeroMatrix
|
3 |
+
from sympy.matrices.common import ShapeError
|
4 |
+
from sympy.matrices import eye, ImmutableMatrix
|
5 |
+
from sympy.core import Add, Basic, S
|
6 |
+
from sympy.core.add import add
|
7 |
+
from sympy.testing.pytest import XFAIL, raises
|
8 |
+
|
9 |
+
X = MatrixSymbol('X', 2, 2)
|
10 |
+
Y = MatrixSymbol('Y', 2, 2)
|
11 |
+
|
12 |
+
def test_evaluate():
|
13 |
+
assert MatAdd(X, X, evaluate=True) == add(X, X, evaluate=True) == MatAdd(X, X).doit()
|
14 |
+
|
15 |
+
def test_sort_key():
|
16 |
+
assert MatAdd(Y, X).doit().args == add(Y, X).doit().args == (X, Y)
|
17 |
+
|
18 |
+
|
19 |
+
def test_matadd_sympify():
|
20 |
+
assert isinstance(MatAdd(eye(1), eye(1)).args[0], Basic)
|
21 |
+
assert isinstance(add(eye(1), eye(1)).args[0], Basic)
|
22 |
+
|
23 |
+
|
24 |
+
def test_matadd_of_matrices():
|
25 |
+
assert MatAdd(eye(2), 4*eye(2), eye(2)).doit() == ImmutableMatrix(6*eye(2))
|
26 |
+
assert add(eye(2), 4*eye(2), eye(2)).doit() == ImmutableMatrix(6*eye(2))
|
27 |
+
|
28 |
+
|
29 |
+
def test_doit_args():
|
30 |
+
A = ImmutableMatrix([[1, 2], [3, 4]])
|
31 |
+
B = ImmutableMatrix([[2, 3], [4, 5]])
|
32 |
+
assert MatAdd(A, MatPow(B, 2)).doit() == A + B**2
|
33 |
+
assert MatAdd(A, MatMul(A, B)).doit() == A + A*B
|
34 |
+
assert (MatAdd(A, X, MatMul(A, B), Y, MatAdd(2*A, B)).doit() ==
|
35 |
+
add(A, X, MatMul(A, B), Y, add(2*A, B)).doit() ==
|
36 |
+
MatAdd(3*A + A*B + B, X, Y))
|
37 |
+
|
38 |
+
|
39 |
+
def test_generic_identity():
|
40 |
+
assert MatAdd.identity == GenericZeroMatrix()
|
41 |
+
assert MatAdd.identity != S.Zero
|
42 |
+
|
43 |
+
|
44 |
+
def test_zero_matrix_add():
|
45 |
+
assert Add(ZeroMatrix(2, 2), ZeroMatrix(2, 2)) == ZeroMatrix(2, 2)
|
46 |
+
|
47 |
+
@XFAIL
|
48 |
+
def test_matrix_Add_with_scalar():
|
49 |
+
raises(TypeError, lambda: Add(0, ZeroMatrix(2, 2)))
|
50 |
+
|
51 |
+
|
52 |
+
def test_shape_error():
|
53 |
+
A = MatrixSymbol('A', 2, 3)
|
54 |
+
B = MatrixSymbol('B', 3, 3)
|
55 |
+
raises(ShapeError, lambda: MatAdd(A, B))
|
56 |
+
|
57 |
+
A = MatrixSymbol('A', 3, 2)
|
58 |
+
raises(ShapeError, lambda: MatAdd(A, B))
|
llmeval-env/lib/python3.10/site-packages/sympy/matrices/expressions/tests/test_matexpr.py
ADDED
@@ -0,0 +1,567 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.concrete.summations import Sum
|
2 |
+
from sympy.core.exprtools import gcd_terms
|
3 |
+
from sympy.core.function import (diff, expand)
|
4 |
+
from sympy.core.relational import Eq
|
5 |
+
from sympy.core.symbol import (Dummy, Symbol, Str)
|
6 |
+
from sympy.functions.special.tensor_functions import KroneckerDelta
|
7 |
+
from sympy.matrices.dense import zeros
|
8 |
+
from sympy.polys.polytools import factor
|
9 |
+
|
10 |
+
from sympy.core import (S, symbols, Add, Mul, SympifyError, Rational,
|
11 |
+
Function)
|
12 |
+
from sympy.functions import sin, cos, tan, sqrt, cbrt, exp
|
13 |
+
from sympy.simplify import simplify
|
14 |
+
from sympy.matrices import (ImmutableMatrix, Inverse, MatAdd, MatMul,
|
15 |
+
MatPow, Matrix, MatrixExpr, MatrixSymbol,
|
16 |
+
SparseMatrix, Transpose, Adjoint, MatrixSet)
|
17 |
+
from sympy.matrices.common import NonSquareMatrixError
|
18 |
+
from sympy.matrices.expressions.determinant import Determinant, det
|
19 |
+
from sympy.matrices.expressions.matexpr import MatrixElement
|
20 |
+
from sympy.matrices.expressions.special import ZeroMatrix, Identity
|
21 |
+
from sympy.testing.pytest import raises, XFAIL
|
22 |
+
|
23 |
+
|
24 |
+
n, m, l, k, p = symbols('n m l k p', integer=True)
|
25 |
+
x = symbols('x')
|
26 |
+
A = MatrixSymbol('A', n, m)
|
27 |
+
B = MatrixSymbol('B', m, l)
|
28 |
+
C = MatrixSymbol('C', n, n)
|
29 |
+
D = MatrixSymbol('D', n, n)
|
30 |
+
E = MatrixSymbol('E', m, n)
|
31 |
+
w = MatrixSymbol('w', n, 1)
|
32 |
+
|
33 |
+
|
34 |
+
def test_matrix_symbol_creation():
|
35 |
+
assert MatrixSymbol('A', 2, 2)
|
36 |
+
assert MatrixSymbol('A', 0, 0)
|
37 |
+
raises(ValueError, lambda: MatrixSymbol('A', -1, 2))
|
38 |
+
raises(ValueError, lambda: MatrixSymbol('A', 2.0, 2))
|
39 |
+
raises(ValueError, lambda: MatrixSymbol('A', 2j, 2))
|
40 |
+
raises(ValueError, lambda: MatrixSymbol('A', 2, -1))
|
41 |
+
raises(ValueError, lambda: MatrixSymbol('A', 2, 2.0))
|
42 |
+
raises(ValueError, lambda: MatrixSymbol('A', 2, 2j))
|
43 |
+
|
44 |
+
n = symbols('n')
|
45 |
+
assert MatrixSymbol('A', n, n)
|
46 |
+
n = symbols('n', integer=False)
|
47 |
+
raises(ValueError, lambda: MatrixSymbol('A', n, n))
|
48 |
+
n = symbols('n', negative=True)
|
49 |
+
raises(ValueError, lambda: MatrixSymbol('A', n, n))
|
50 |
+
|
51 |
+
|
52 |
+
def test_matexpr_properties():
|
53 |
+
assert A.shape == (n, m)
|
54 |
+
assert (A * B).shape == (n, l)
|
55 |
+
assert A[0, 1].indices == (0, 1)
|
56 |
+
assert A[0, 0].symbol == A
|
57 |
+
assert A[0, 0].symbol.name == 'A'
|
58 |
+
|
59 |
+
|
60 |
+
def test_matexpr():
|
61 |
+
assert (x*A).shape == A.shape
|
62 |
+
assert (x*A).__class__ == MatMul
|
63 |
+
assert 2*A - A - A == ZeroMatrix(*A.shape)
|
64 |
+
assert (A*B).shape == (n, l)
|
65 |
+
|
66 |
+
|
67 |
+
def test_matexpr_subs():
|
68 |
+
A = MatrixSymbol('A', n, m)
|
69 |
+
B = MatrixSymbol('B', m, l)
|
70 |
+
C = MatrixSymbol('C', m, l)
|
71 |
+
|
72 |
+
assert A.subs(n, m).shape == (m, m)
|
73 |
+
assert (A*B).subs(B, C) == A*C
|
74 |
+
assert (A*B).subs(l, n).is_square
|
75 |
+
|
76 |
+
W = MatrixSymbol("W", 3, 3)
|
77 |
+
X = MatrixSymbol("X", 2, 2)
|
78 |
+
Y = MatrixSymbol("Y", 1, 2)
|
79 |
+
Z = MatrixSymbol("Z", n, 2)
|
80 |
+
# no restrictions on Symbol replacement
|
81 |
+
assert X.subs(X, Y) == Y
|
82 |
+
# it might be better to just change the name
|
83 |
+
y = Str('y')
|
84 |
+
assert X.subs(Str("X"), y).args == (y, 2, 2)
|
85 |
+
# it's ok to introduce a wider matrix
|
86 |
+
assert X[1, 1].subs(X, W) == W[1, 1]
|
87 |
+
# but for a given MatrixExpression, only change
|
88 |
+
# name if indexing on the new shape is valid.
|
89 |
+
# Here, X is 2,2; Y is 1,2 and Y[1, 1] is out
|
90 |
+
# of range so an error is raised
|
91 |
+
raises(IndexError, lambda: X[1, 1].subs(X, Y))
|
92 |
+
# here, [0, 1] is in range so the subs succeeds
|
93 |
+
assert X[0, 1].subs(X, Y) == Y[0, 1]
|
94 |
+
# and here the size of n will accept any index
|
95 |
+
# in the first position
|
96 |
+
assert W[2, 1].subs(W, Z) == Z[2, 1]
|
97 |
+
# but not in the second position
|
98 |
+
raises(IndexError, lambda: W[2, 2].subs(W, Z))
|
99 |
+
# any matrix should raise if invalid
|
100 |
+
raises(IndexError, lambda: W[2, 2].subs(W, zeros(2)))
|
101 |
+
|
102 |
+
A = SparseMatrix([[1, 2], [3, 4]])
|
103 |
+
B = Matrix([[1, 2], [3, 4]])
|
104 |
+
C, D = MatrixSymbol('C', 2, 2), MatrixSymbol('D', 2, 2)
|
105 |
+
|
106 |
+
assert (C*D).subs({C: A, D: B}) == MatMul(A, B)
|
107 |
+
|
108 |
+
|
109 |
+
def test_addition():
|
110 |
+
A = MatrixSymbol('A', n, m)
|
111 |
+
B = MatrixSymbol('B', n, m)
|
112 |
+
|
113 |
+
assert isinstance(A + B, MatAdd)
|
114 |
+
assert (A + B).shape == A.shape
|
115 |
+
assert isinstance(A - A + 2*B, MatMul)
|
116 |
+
|
117 |
+
raises(TypeError, lambda: A + 1)
|
118 |
+
raises(TypeError, lambda: 5 + A)
|
119 |
+
raises(TypeError, lambda: 5 - A)
|
120 |
+
|
121 |
+
assert A + ZeroMatrix(n, m) - A == ZeroMatrix(n, m)
|
122 |
+
raises(TypeError, lambda: ZeroMatrix(n, m) + S.Zero)
|
123 |
+
|
124 |
+
|
125 |
+
def test_multiplication():
|
126 |
+
A = MatrixSymbol('A', n, m)
|
127 |
+
B = MatrixSymbol('B', m, l)
|
128 |
+
C = MatrixSymbol('C', n, n)
|
129 |
+
|
130 |
+
assert (2*A*B).shape == (n, l)
|
131 |
+
assert (A*0*B) == ZeroMatrix(n, l)
|
132 |
+
assert (2*A).shape == A.shape
|
133 |
+
|
134 |
+
assert A * ZeroMatrix(m, m) * B == ZeroMatrix(n, l)
|
135 |
+
|
136 |
+
assert C * Identity(n) * C.I == Identity(n)
|
137 |
+
|
138 |
+
assert B/2 == S.Half*B
|
139 |
+
raises(NotImplementedError, lambda: 2/B)
|
140 |
+
|
141 |
+
A = MatrixSymbol('A', n, n)
|
142 |
+
B = MatrixSymbol('B', n, n)
|
143 |
+
assert Identity(n) * (A + B) == A + B
|
144 |
+
|
145 |
+
assert A**2*A == A**3
|
146 |
+
assert A**2*(A.I)**3 == A.I
|
147 |
+
assert A**3*(A.I)**2 == A
|
148 |
+
|
149 |
+
|
150 |
+
def test_MatPow():
|
151 |
+
A = MatrixSymbol('A', n, n)
|
152 |
+
|
153 |
+
AA = MatPow(A, 2)
|
154 |
+
assert AA.exp == 2
|
155 |
+
assert AA.base == A
|
156 |
+
assert (A**n).exp == n
|
157 |
+
|
158 |
+
assert A**0 == Identity(n)
|
159 |
+
assert A**1 == A
|
160 |
+
assert A**2 == AA
|
161 |
+
assert A**-1 == Inverse(A)
|
162 |
+
assert (A**-1)**-1 == A
|
163 |
+
assert (A**2)**3 == A**6
|
164 |
+
assert A**S.Half == sqrt(A)
|
165 |
+
assert A**Rational(1, 3) == cbrt(A)
|
166 |
+
raises(NonSquareMatrixError, lambda: MatrixSymbol('B', 3, 2)**2)
|
167 |
+
|
168 |
+
|
169 |
+
def test_MatrixSymbol():
|
170 |
+
n, m, t = symbols('n,m,t')
|
171 |
+
X = MatrixSymbol('X', n, m)
|
172 |
+
assert X.shape == (n, m)
|
173 |
+
raises(TypeError, lambda: MatrixSymbol('X', n, m)(t)) # issue 5855
|
174 |
+
assert X.doit() == X
|
175 |
+
|
176 |
+
|
177 |
+
def test_dense_conversion():
|
178 |
+
X = MatrixSymbol('X', 2, 2)
|
179 |
+
assert ImmutableMatrix(X) == ImmutableMatrix(2, 2, lambda i, j: X[i, j])
|
180 |
+
assert Matrix(X) == Matrix(2, 2, lambda i, j: X[i, j])
|
181 |
+
|
182 |
+
|
183 |
+
def test_free_symbols():
|
184 |
+
assert (C*D).free_symbols == {C, D}
|
185 |
+
|
186 |
+
|
187 |
+
def test_zero_matmul():
|
188 |
+
assert isinstance(S.Zero * MatrixSymbol('X', 2, 2), MatrixExpr)
|
189 |
+
|
190 |
+
|
191 |
+
def test_matadd_simplify():
|
192 |
+
A = MatrixSymbol('A', 1, 1)
|
193 |
+
assert simplify(MatAdd(A, ImmutableMatrix([[sin(x)**2 + cos(x)**2]]))) == \
|
194 |
+
MatAdd(A, Matrix([[1]]))
|
195 |
+
|
196 |
+
|
197 |
+
def test_matmul_simplify():
|
198 |
+
A = MatrixSymbol('A', 1, 1)
|
199 |
+
assert simplify(MatMul(A, ImmutableMatrix([[sin(x)**2 + cos(x)**2]]))) == \
|
200 |
+
MatMul(A, Matrix([[1]]))
|
201 |
+
|
202 |
+
|
203 |
+
def test_invariants():
|
204 |
+
A = MatrixSymbol('A', n, m)
|
205 |
+
B = MatrixSymbol('B', m, l)
|
206 |
+
X = MatrixSymbol('X', n, n)
|
207 |
+
objs = [Identity(n), ZeroMatrix(m, n), A, MatMul(A, B), MatAdd(A, A),
|
208 |
+
Transpose(A), Adjoint(A), Inverse(X), MatPow(X, 2), MatPow(X, -1),
|
209 |
+
MatPow(X, 0)]
|
210 |
+
for obj in objs:
|
211 |
+
assert obj == obj.__class__(*obj.args)
|
212 |
+
|
213 |
+
|
214 |
+
def test_matexpr_indexing():
|
215 |
+
A = MatrixSymbol('A', n, m)
|
216 |
+
A[1, 2]
|
217 |
+
A[l, k]
|
218 |
+
A[l + 1, k + 1]
|
219 |
+
A = MatrixSymbol('A', 2, 1)
|
220 |
+
for i in range(-2, 2):
|
221 |
+
for j in range(-1, 1):
|
222 |
+
A[i, j]
|
223 |
+
|
224 |
+
|
225 |
+
def test_single_indexing():
|
226 |
+
A = MatrixSymbol('A', 2, 3)
|
227 |
+
assert A[1] == A[0, 1]
|
228 |
+
assert A[int(1)] == A[0, 1]
|
229 |
+
assert A[3] == A[1, 0]
|
230 |
+
assert list(A[:2, :2]) == [A[0, 0], A[0, 1], A[1, 0], A[1, 1]]
|
231 |
+
raises(IndexError, lambda: A[6])
|
232 |
+
raises(IndexError, lambda: A[n])
|
233 |
+
B = MatrixSymbol('B', n, m)
|
234 |
+
raises(IndexError, lambda: B[1])
|
235 |
+
B = MatrixSymbol('B', n, 3)
|
236 |
+
assert B[3] == B[1, 0]
|
237 |
+
|
238 |
+
|
239 |
+
def test_MatrixElement_commutative():
|
240 |
+
assert A[0, 1]*A[1, 0] == A[1, 0]*A[0, 1]
|
241 |
+
|
242 |
+
|
243 |
+
def test_MatrixSymbol_determinant():
|
244 |
+
A = MatrixSymbol('A', 4, 4)
|
245 |
+
assert A.as_explicit().det() == A[0, 0]*A[1, 1]*A[2, 2]*A[3, 3] - \
|
246 |
+
A[0, 0]*A[1, 1]*A[2, 3]*A[3, 2] - A[0, 0]*A[1, 2]*A[2, 1]*A[3, 3] + \
|
247 |
+
A[0, 0]*A[1, 2]*A[2, 3]*A[3, 1] + A[0, 0]*A[1, 3]*A[2, 1]*A[3, 2] - \
|
248 |
+
A[0, 0]*A[1, 3]*A[2, 2]*A[3, 1] - A[0, 1]*A[1, 0]*A[2, 2]*A[3, 3] + \
|
249 |
+
A[0, 1]*A[1, 0]*A[2, 3]*A[3, 2] + A[0, 1]*A[1, 2]*A[2, 0]*A[3, 3] - \
|
250 |
+
A[0, 1]*A[1, 2]*A[2, 3]*A[3, 0] - A[0, 1]*A[1, 3]*A[2, 0]*A[3, 2] + \
|
251 |
+
A[0, 1]*A[1, 3]*A[2, 2]*A[3, 0] + A[0, 2]*A[1, 0]*A[2, 1]*A[3, 3] - \
|
252 |
+
A[0, 2]*A[1, 0]*A[2, 3]*A[3, 1] - A[0, 2]*A[1, 1]*A[2, 0]*A[3, 3] + \
|
253 |
+
A[0, 2]*A[1, 1]*A[2, 3]*A[3, 0] + A[0, 2]*A[1, 3]*A[2, 0]*A[3, 1] - \
|
254 |
+
A[0, 2]*A[1, 3]*A[2, 1]*A[3, 0] - A[0, 3]*A[1, 0]*A[2, 1]*A[3, 2] + \
|
255 |
+
A[0, 3]*A[1, 0]*A[2, 2]*A[3, 1] + A[0, 3]*A[1, 1]*A[2, 0]*A[3, 2] - \
|
256 |
+
A[0, 3]*A[1, 1]*A[2, 2]*A[3, 0] - A[0, 3]*A[1, 2]*A[2, 0]*A[3, 1] + \
|
257 |
+
A[0, 3]*A[1, 2]*A[2, 1]*A[3, 0]
|
258 |
+
|
259 |
+
B = MatrixSymbol('B', 4, 4)
|
260 |
+
assert Determinant(A + B).doit() == det(A + B) == (A + B).det()
|
261 |
+
|
262 |
+
|
263 |
+
def test_MatrixElement_diff():
|
264 |
+
assert (A[3, 0]*A[0, 0]).diff(A[0, 0]) == A[3, 0]
|
265 |
+
|
266 |
+
|
267 |
+
def test_MatrixElement_doit():
|
268 |
+
u = MatrixSymbol('u', 2, 1)
|
269 |
+
v = ImmutableMatrix([3, 5])
|
270 |
+
assert u[0, 0].subs(u, v).doit() == v[0, 0]
|
271 |
+
|
272 |
+
|
273 |
+
def test_identity_powers():
|
274 |
+
M = Identity(n)
|
275 |
+
assert MatPow(M, 3).doit() == M**3
|
276 |
+
assert M**n == M
|
277 |
+
assert MatPow(M, 0).doit() == M**2
|
278 |
+
assert M**-2 == M
|
279 |
+
assert MatPow(M, -2).doit() == M**0
|
280 |
+
N = Identity(3)
|
281 |
+
assert MatPow(N, 2).doit() == N**n
|
282 |
+
assert MatPow(N, 3).doit() == N
|
283 |
+
assert MatPow(N, -2).doit() == N**4
|
284 |
+
assert MatPow(N, 2).doit() == N**0
|
285 |
+
|
286 |
+
|
287 |
+
def test_Zero_power():
|
288 |
+
z1 = ZeroMatrix(n, n)
|
289 |
+
assert z1**4 == z1
|
290 |
+
raises(ValueError, lambda:z1**-2)
|
291 |
+
assert z1**0 == Identity(n)
|
292 |
+
assert MatPow(z1, 2).doit() == z1**2
|
293 |
+
raises(ValueError, lambda:MatPow(z1, -2).doit())
|
294 |
+
z2 = ZeroMatrix(3, 3)
|
295 |
+
assert MatPow(z2, 4).doit() == z2**4
|
296 |
+
raises(ValueError, lambda:z2**-3)
|
297 |
+
assert z2**3 == MatPow(z2, 3).doit()
|
298 |
+
assert z2**0 == Identity(3)
|
299 |
+
raises(ValueError, lambda:MatPow(z2, -1).doit())
|
300 |
+
|
301 |
+
|
302 |
+
def test_matrixelement_diff():
|
303 |
+
dexpr = diff((D*w)[k,0], w[p,0])
|
304 |
+
|
305 |
+
assert w[k, p].diff(w[k, p]) == 1
|
306 |
+
assert w[k, p].diff(w[0, 0]) == KroneckerDelta(0, k, (0, n-1))*KroneckerDelta(0, p, (0, 0))
|
307 |
+
_i_1 = Dummy("_i_1")
|
308 |
+
assert dexpr.dummy_eq(Sum(KroneckerDelta(_i_1, p, (0, n-1))*D[k, _i_1], (_i_1, 0, n - 1)))
|
309 |
+
assert dexpr.doit() == D[k, p]
|
310 |
+
|
311 |
+
|
312 |
+
def test_MatrixElement_with_values():
|
313 |
+
x, y, z, w = symbols("x y z w")
|
314 |
+
M = Matrix([[x, y], [z, w]])
|
315 |
+
i, j = symbols("i, j")
|
316 |
+
Mij = M[i, j]
|
317 |
+
assert isinstance(Mij, MatrixElement)
|
318 |
+
Ms = SparseMatrix([[2, 3], [4, 5]])
|
319 |
+
msij = Ms[i, j]
|
320 |
+
assert isinstance(msij, MatrixElement)
|
321 |
+
for oi, oj in [(0, 0), (0, 1), (1, 0), (1, 1)]:
|
322 |
+
assert Mij.subs({i: oi, j: oj}) == M[oi, oj]
|
323 |
+
assert msij.subs({i: oi, j: oj}) == Ms[oi, oj]
|
324 |
+
A = MatrixSymbol("A", 2, 2)
|
325 |
+
assert A[0, 0].subs(A, M) == x
|
326 |
+
assert A[i, j].subs(A, M) == M[i, j]
|
327 |
+
assert M[i, j].subs(M, A) == A[i, j]
|
328 |
+
|
329 |
+
assert isinstance(M[3*i - 2, j], MatrixElement)
|
330 |
+
assert M[3*i - 2, j].subs({i: 1, j: 0}) == M[1, 0]
|
331 |
+
assert isinstance(M[i, 0], MatrixElement)
|
332 |
+
assert M[i, 0].subs(i, 0) == M[0, 0]
|
333 |
+
assert M[0, i].subs(i, 1) == M[0, 1]
|
334 |
+
|
335 |
+
assert M[i, j].diff(x) == Matrix([[1, 0], [0, 0]])[i, j]
|
336 |
+
|
337 |
+
raises(ValueError, lambda: M[i, 2])
|
338 |
+
raises(ValueError, lambda: M[i, -1])
|
339 |
+
raises(ValueError, lambda: M[2, i])
|
340 |
+
raises(ValueError, lambda: M[-1, i])
|
341 |
+
|
342 |
+
|
343 |
+
def test_inv():
|
344 |
+
B = MatrixSymbol('B', 3, 3)
|
345 |
+
assert B.inv() == B**-1
|
346 |
+
|
347 |
+
# https://github.com/sympy/sympy/issues/19162
|
348 |
+
X = MatrixSymbol('X', 1, 1).as_explicit()
|
349 |
+
assert X.inv() == Matrix([[1/X[0, 0]]])
|
350 |
+
|
351 |
+
X = MatrixSymbol('X', 2, 2).as_explicit()
|
352 |
+
detX = X[0, 0]*X[1, 1] - X[0, 1]*X[1, 0]
|
353 |
+
invX = Matrix([[ X[1, 1], -X[0, 1]],
|
354 |
+
[-X[1, 0], X[0, 0]]]) / detX
|
355 |
+
assert X.inv() == invX
|
356 |
+
|
357 |
+
|
358 |
+
@XFAIL
|
359 |
+
def test_factor_expand():
|
360 |
+
A = MatrixSymbol("A", n, n)
|
361 |
+
B = MatrixSymbol("B", n, n)
|
362 |
+
expr1 = (A + B)*(C + D)
|
363 |
+
expr2 = A*C + B*C + A*D + B*D
|
364 |
+
assert expr1 != expr2
|
365 |
+
assert expand(expr1) == expr2
|
366 |
+
assert factor(expr2) == expr1
|
367 |
+
|
368 |
+
expr = B**(-1)*(A**(-1)*B**(-1) - A**(-1)*C*B**(-1))**(-1)*A**(-1)
|
369 |
+
I = Identity(n)
|
370 |
+
# Ideally we get the first, but we at least don't want a wrong answer
|
371 |
+
assert factor(expr) in [I - C, B**-1*(A**-1*(I - C)*B**-1)**-1*A**-1]
|
372 |
+
|
373 |
+
|
374 |
+
def test_issue_2749():
|
375 |
+
A = MatrixSymbol("A", 5, 2)
|
376 |
+
assert (A.T * A).I.as_explicit() == Matrix([[(A.T * A).I[0, 0], (A.T * A).I[0, 1]], \
|
377 |
+
[(A.T * A).I[1, 0], (A.T * A).I[1, 1]]])
|
378 |
+
|
379 |
+
|
380 |
+
def test_issue_2750():
|
381 |
+
x = MatrixSymbol('x', 1, 1)
|
382 |
+
assert (x.T*x).as_explicit()**-1 == Matrix([[x[0, 0]**(-2)]])
|
383 |
+
|
384 |
+
|
385 |
+
def test_issue_7842():
|
386 |
+
A = MatrixSymbol('A', 3, 1)
|
387 |
+
B = MatrixSymbol('B', 2, 1)
|
388 |
+
assert Eq(A, B) == False
|
389 |
+
assert Eq(A[1,0], B[1, 0]).func is Eq
|
390 |
+
A = ZeroMatrix(2, 3)
|
391 |
+
B = ZeroMatrix(2, 3)
|
392 |
+
assert Eq(A, B) == True
|
393 |
+
|
394 |
+
|
395 |
+
def test_issue_21195():
|
396 |
+
t = symbols('t')
|
397 |
+
x = Function('x')(t)
|
398 |
+
dx = x.diff(t)
|
399 |
+
exp1 = cos(x) + cos(x)*dx
|
400 |
+
exp2 = sin(x) + tan(x)*(dx.diff(t))
|
401 |
+
exp3 = sin(x)*sin(t)*(dx.diff(t)).diff(t)
|
402 |
+
A = Matrix([[exp1], [exp2], [exp3]])
|
403 |
+
B = Matrix([[exp1.diff(x)], [exp2.diff(x)], [exp3.diff(x)]])
|
404 |
+
assert A.diff(x) == B
|
405 |
+
|
406 |
+
|
407 |
+
def test_MatMul_postprocessor():
|
408 |
+
z = zeros(2)
|
409 |
+
z1 = ZeroMatrix(2, 2)
|
410 |
+
assert Mul(0, z) == Mul(z, 0) in [z, z1]
|
411 |
+
|
412 |
+
M = Matrix([[1, 2], [3, 4]])
|
413 |
+
Mx = Matrix([[x, 2*x], [3*x, 4*x]])
|
414 |
+
assert Mul(x, M) == Mul(M, x) == Mx
|
415 |
+
|
416 |
+
A = MatrixSymbol("A", 2, 2)
|
417 |
+
assert Mul(A, M) == MatMul(A, M)
|
418 |
+
assert Mul(M, A) == MatMul(M, A)
|
419 |
+
# Scalars should be absorbed into constant matrices
|
420 |
+
a = Mul(x, M, A)
|
421 |
+
b = Mul(M, x, A)
|
422 |
+
c = Mul(M, A, x)
|
423 |
+
assert a == b == c == MatMul(Mx, A)
|
424 |
+
a = Mul(x, A, M)
|
425 |
+
b = Mul(A, x, M)
|
426 |
+
c = Mul(A, M, x)
|
427 |
+
assert a == b == c == MatMul(A, Mx)
|
428 |
+
assert Mul(M, M) == M**2
|
429 |
+
assert Mul(A, M, M) == MatMul(A, M**2)
|
430 |
+
assert Mul(M, M, A) == MatMul(M**2, A)
|
431 |
+
assert Mul(M, A, M) == MatMul(M, A, M)
|
432 |
+
|
433 |
+
assert Mul(A, x, M, M, x) == MatMul(A, Mx**2)
|
434 |
+
|
435 |
+
|
436 |
+
@XFAIL
|
437 |
+
def test_MatAdd_postprocessor_xfail():
|
438 |
+
# This is difficult to get working because of the way that Add processes
|
439 |
+
# its args.
|
440 |
+
z = zeros(2)
|
441 |
+
assert Add(z, S.NaN) == Add(S.NaN, z)
|
442 |
+
|
443 |
+
|
444 |
+
def test_MatAdd_postprocessor():
|
445 |
+
# Some of these are nonsensical, but we do not raise errors for Add
|
446 |
+
# because that breaks algorithms that want to replace matrices with dummy
|
447 |
+
# symbols.
|
448 |
+
|
449 |
+
z = zeros(2)
|
450 |
+
|
451 |
+
assert Add(0, z) == Add(z, 0) == z
|
452 |
+
|
453 |
+
a = Add(S.Infinity, z)
|
454 |
+
assert a == Add(z, S.Infinity)
|
455 |
+
assert isinstance(a, Add)
|
456 |
+
assert a.args == (S.Infinity, z)
|
457 |
+
|
458 |
+
a = Add(S.ComplexInfinity, z)
|
459 |
+
assert a == Add(z, S.ComplexInfinity)
|
460 |
+
assert isinstance(a, Add)
|
461 |
+
assert a.args == (S.ComplexInfinity, z)
|
462 |
+
|
463 |
+
a = Add(z, S.NaN)
|
464 |
+
# assert a == Add(S.NaN, z) # See the XFAIL above
|
465 |
+
assert isinstance(a, Add)
|
466 |
+
assert a.args == (S.NaN, z)
|
467 |
+
|
468 |
+
M = Matrix([[1, 2], [3, 4]])
|
469 |
+
a = Add(x, M)
|
470 |
+
assert a == Add(M, x)
|
471 |
+
assert isinstance(a, Add)
|
472 |
+
assert a.args == (x, M)
|
473 |
+
|
474 |
+
A = MatrixSymbol("A", 2, 2)
|
475 |
+
assert Add(A, M) == Add(M, A) == A + M
|
476 |
+
|
477 |
+
# Scalars should be absorbed into constant matrices (producing an error)
|
478 |
+
a = Add(x, M, A)
|
479 |
+
assert a == Add(M, x, A) == Add(M, A, x) == Add(x, A, M) == Add(A, x, M) == Add(A, M, x)
|
480 |
+
assert isinstance(a, Add)
|
481 |
+
assert a.args == (x, A + M)
|
482 |
+
|
483 |
+
assert Add(M, M) == 2*M
|
484 |
+
assert Add(M, A, M) == Add(M, M, A) == Add(A, M, M) == A + 2*M
|
485 |
+
|
486 |
+
a = Add(A, x, M, M, x)
|
487 |
+
assert isinstance(a, Add)
|
488 |
+
assert a.args == (2*x, A + 2*M)
|
489 |
+
|
490 |
+
|
491 |
+
def test_simplify_matrix_expressions():
|
492 |
+
# Various simplification functions
|
493 |
+
assert type(gcd_terms(C*D + D*C)) == MatAdd
|
494 |
+
a = gcd_terms(2*C*D + 4*D*C)
|
495 |
+
assert type(a) == MatAdd
|
496 |
+
assert a.args == (2*C*D, 4*D*C)
|
497 |
+
|
498 |
+
|
499 |
+
def test_exp():
|
500 |
+
A = MatrixSymbol('A', 2, 2)
|
501 |
+
B = MatrixSymbol('B', 2, 2)
|
502 |
+
expr1 = exp(A)*exp(B)
|
503 |
+
expr2 = exp(B)*exp(A)
|
504 |
+
assert expr1 != expr2
|
505 |
+
assert expr1 - expr2 != 0
|
506 |
+
assert not isinstance(expr1, exp)
|
507 |
+
assert not isinstance(expr2, exp)
|
508 |
+
|
509 |
+
|
510 |
+
def test_invalid_args():
|
511 |
+
raises(SympifyError, lambda: MatrixSymbol(1, 2, 'A'))
|
512 |
+
|
513 |
+
|
514 |
+
def test_matrixsymbol_from_symbol():
|
515 |
+
# The label should be preserved during doit and subs
|
516 |
+
A_label = Symbol('A', complex=True)
|
517 |
+
A = MatrixSymbol(A_label, 2, 2)
|
518 |
+
|
519 |
+
A_1 = A.doit()
|
520 |
+
A_2 = A.subs(2, 3)
|
521 |
+
assert A_1.args == A.args
|
522 |
+
assert A_2.args[0] == A.args[0]
|
523 |
+
|
524 |
+
|
525 |
+
def test_as_explicit():
|
526 |
+
Z = MatrixSymbol('Z', 2, 3)
|
527 |
+
assert Z.as_explicit() == ImmutableMatrix([
|
528 |
+
[Z[0, 0], Z[0, 1], Z[0, 2]],
|
529 |
+
[Z[1, 0], Z[1, 1], Z[1, 2]],
|
530 |
+
])
|
531 |
+
raises(ValueError, lambda: A.as_explicit())
|
532 |
+
|
533 |
+
|
534 |
+
def test_MatrixSet():
|
535 |
+
M = MatrixSet(2, 2, set=S.Reals)
|
536 |
+
assert M.shape == (2, 2)
|
537 |
+
assert M.set == S.Reals
|
538 |
+
X = Matrix([[1, 2], [3, 4]])
|
539 |
+
assert X in M
|
540 |
+
X = ZeroMatrix(2, 2)
|
541 |
+
assert X in M
|
542 |
+
raises(TypeError, lambda: A in M)
|
543 |
+
raises(TypeError, lambda: 1 in M)
|
544 |
+
M = MatrixSet(n, m, set=S.Reals)
|
545 |
+
assert A in M
|
546 |
+
raises(TypeError, lambda: C in M)
|
547 |
+
raises(TypeError, lambda: X in M)
|
548 |
+
M = MatrixSet(2, 2, set={1, 2, 3})
|
549 |
+
X = Matrix([[1, 2], [3, 4]])
|
550 |
+
Y = Matrix([[1, 2]])
|
551 |
+
assert (X in M) == S.false
|
552 |
+
assert (Y in M) == S.false
|
553 |
+
raises(ValueError, lambda: MatrixSet(2, -2, S.Reals))
|
554 |
+
raises(ValueError, lambda: MatrixSet(2.4, -1, S.Reals))
|
555 |
+
raises(TypeError, lambda: MatrixSet(2, 2, (1, 2, 3)))
|
556 |
+
|
557 |
+
|
558 |
+
def test_matrixsymbol_solving():
|
559 |
+
A = MatrixSymbol('A', 2, 2)
|
560 |
+
B = MatrixSymbol('B', 2, 2)
|
561 |
+
Z = ZeroMatrix(2, 2)
|
562 |
+
assert -(-A + B) - A + B == Z
|
563 |
+
assert (-(-A + B) - A + B).simplify() == Z
|
564 |
+
assert (-(-A + B) - A + B).expand() == Z
|
565 |
+
assert (-(-A + B) - A + B - Z).simplify() == Z
|
566 |
+
assert (-(-A + B) - A + B - Z).expand() == Z
|
567 |
+
assert (A*(A + B) + B*(A.T + B.T)).expand() == A**2 + A*B + B*A.T + B*B.T
|
llmeval-env/lib/python3.10/site-packages/sympy/matrices/expressions/tests/test_matmul.py
ADDED
@@ -0,0 +1,186 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.core import I, symbols, Basic, Mul, S
|
2 |
+
from sympy.core.mul import mul
|
3 |
+
from sympy.functions import adjoint, transpose
|
4 |
+
from sympy.matrices.common import ShapeError
|
5 |
+
from sympy.matrices import (Identity, Inverse, Matrix, MatrixSymbol, ZeroMatrix,
|
6 |
+
eye, ImmutableMatrix)
|
7 |
+
from sympy.matrices.expressions import Adjoint, Transpose, det, MatPow
|
8 |
+
from sympy.matrices.expressions.special import GenericIdentity
|
9 |
+
from sympy.matrices.expressions.matmul import (factor_in_front, remove_ids,
|
10 |
+
MatMul, combine_powers, any_zeros, unpack, only_squares)
|
11 |
+
from sympy.strategies import null_safe
|
12 |
+
from sympy.assumptions.ask import Q
|
13 |
+
from sympy.assumptions.refine import refine
|
14 |
+
from sympy.core.symbol import Symbol
|
15 |
+
|
16 |
+
from sympy.testing.pytest import XFAIL, raises
|
17 |
+
|
18 |
+
n, m, l, k = symbols('n m l k', integer=True)
|
19 |
+
x = symbols('x')
|
20 |
+
A = MatrixSymbol('A', n, m)
|
21 |
+
B = MatrixSymbol('B', m, l)
|
22 |
+
C = MatrixSymbol('C', n, n)
|
23 |
+
D = MatrixSymbol('D', n, n)
|
24 |
+
E = MatrixSymbol('E', m, n)
|
25 |
+
|
26 |
+
def test_evaluate():
|
27 |
+
assert MatMul(C, C, evaluate=True) == MatMul(C, C).doit()
|
28 |
+
|
29 |
+
def test_adjoint():
|
30 |
+
assert adjoint(A*B) == Adjoint(B)*Adjoint(A)
|
31 |
+
assert adjoint(2*A*B) == 2*Adjoint(B)*Adjoint(A)
|
32 |
+
assert adjoint(2*I*C) == -2*I*Adjoint(C)
|
33 |
+
|
34 |
+
M = Matrix(2, 2, [1, 2 + I, 3, 4])
|
35 |
+
MA = Matrix(2, 2, [1, 3, 2 - I, 4])
|
36 |
+
assert adjoint(M) == MA
|
37 |
+
assert adjoint(2*M) == 2*MA
|
38 |
+
assert adjoint(MatMul(2, M)) == MatMul(2, MA).doit()
|
39 |
+
|
40 |
+
|
41 |
+
def test_transpose():
|
42 |
+
assert transpose(A*B) == Transpose(B)*Transpose(A)
|
43 |
+
assert transpose(2*A*B) == 2*Transpose(B)*Transpose(A)
|
44 |
+
assert transpose(2*I*C) == 2*I*Transpose(C)
|
45 |
+
|
46 |
+
M = Matrix(2, 2, [1, 2 + I, 3, 4])
|
47 |
+
MT = Matrix(2, 2, [1, 3, 2 + I, 4])
|
48 |
+
assert transpose(M) == MT
|
49 |
+
assert transpose(2*M) == 2*MT
|
50 |
+
assert transpose(x*M) == x*MT
|
51 |
+
assert transpose(MatMul(2, M)) == MatMul(2, MT).doit()
|
52 |
+
|
53 |
+
|
54 |
+
def test_factor_in_front():
|
55 |
+
assert factor_in_front(MatMul(A, 2, B, evaluate=False)) ==\
|
56 |
+
MatMul(2, A, B, evaluate=False)
|
57 |
+
|
58 |
+
|
59 |
+
def test_remove_ids():
|
60 |
+
assert remove_ids(MatMul(A, Identity(m), B, evaluate=False)) == \
|
61 |
+
MatMul(A, B, evaluate=False)
|
62 |
+
assert null_safe(remove_ids)(MatMul(Identity(n), evaluate=False)) == \
|
63 |
+
MatMul(Identity(n), evaluate=False)
|
64 |
+
|
65 |
+
|
66 |
+
def test_combine_powers():
|
67 |
+
assert combine_powers(MatMul(D, Inverse(D), D, evaluate=False)) == \
|
68 |
+
MatMul(Identity(n), D, evaluate=False)
|
69 |
+
assert combine_powers(MatMul(B.T, Inverse(E*A), E, A, B, evaluate=False)) == \
|
70 |
+
MatMul(B.T, Identity(m), B, evaluate=False)
|
71 |
+
assert combine_powers(MatMul(A, E, Inverse(A*E), D, evaluate=False)) == \
|
72 |
+
MatMul(Identity(n), D, evaluate=False)
|
73 |
+
|
74 |
+
|
75 |
+
def test_any_zeros():
|
76 |
+
assert any_zeros(MatMul(A, ZeroMatrix(m, k), evaluate=False)) == \
|
77 |
+
ZeroMatrix(n, k)
|
78 |
+
|
79 |
+
|
80 |
+
def test_unpack():
|
81 |
+
assert unpack(MatMul(A, evaluate=False)) == A
|
82 |
+
x = MatMul(A, B)
|
83 |
+
assert unpack(x) == x
|
84 |
+
|
85 |
+
|
86 |
+
def test_only_squares():
|
87 |
+
assert only_squares(C) == [C]
|
88 |
+
assert only_squares(C, D) == [C, D]
|
89 |
+
assert only_squares(C, A, A.T, D) == [C, A*A.T, D]
|
90 |
+
|
91 |
+
|
92 |
+
def test_determinant():
|
93 |
+
assert det(2*C) == 2**n*det(C)
|
94 |
+
assert det(2*C*D) == 2**n*det(C)*det(D)
|
95 |
+
assert det(3*C*A*A.T*D) == 3**n*det(C)*det(A*A.T)*det(D)
|
96 |
+
|
97 |
+
|
98 |
+
def test_doit():
|
99 |
+
assert MatMul(C, 2, D).args == (C, 2, D)
|
100 |
+
assert MatMul(C, 2, D).doit().args == (2, C, D)
|
101 |
+
assert MatMul(C, Transpose(D*C)).args == (C, Transpose(D*C))
|
102 |
+
assert MatMul(C, Transpose(D*C)).doit(deep=True).args == (C, C.T, D.T)
|
103 |
+
|
104 |
+
|
105 |
+
def test_doit_drills_down():
|
106 |
+
X = ImmutableMatrix([[1, 2], [3, 4]])
|
107 |
+
Y = ImmutableMatrix([[2, 3], [4, 5]])
|
108 |
+
assert MatMul(X, MatPow(Y, 2)).doit() == X*Y**2
|
109 |
+
assert MatMul(C, Transpose(D*C)).doit().args == (C, C.T, D.T)
|
110 |
+
|
111 |
+
|
112 |
+
def test_doit_deep_false_still_canonical():
|
113 |
+
assert (MatMul(C, Transpose(D*C), 2).doit(deep=False).args ==
|
114 |
+
(2, C, Transpose(D*C)))
|
115 |
+
|
116 |
+
|
117 |
+
def test_matmul_scalar_Matrix_doit():
|
118 |
+
# Issue 9053
|
119 |
+
X = Matrix([[1, 2], [3, 4]])
|
120 |
+
assert MatMul(2, X).doit() == 2*X
|
121 |
+
|
122 |
+
|
123 |
+
def test_matmul_sympify():
|
124 |
+
assert isinstance(MatMul(eye(1), eye(1)).args[0], Basic)
|
125 |
+
|
126 |
+
|
127 |
+
def test_collapse_MatrixBase():
|
128 |
+
A = Matrix([[1, 1], [1, 1]])
|
129 |
+
B = Matrix([[1, 2], [3, 4]])
|
130 |
+
assert MatMul(A, B).doit() == ImmutableMatrix([[4, 6], [4, 6]])
|
131 |
+
|
132 |
+
|
133 |
+
def test_refine():
|
134 |
+
assert refine(C*C.T*D, Q.orthogonal(C)).doit() == D
|
135 |
+
|
136 |
+
kC = k*C
|
137 |
+
assert refine(kC*C.T, Q.orthogonal(C)).doit() == k*Identity(n)
|
138 |
+
assert refine(kC* kC.T, Q.orthogonal(C)).doit() == (k**2)*Identity(n)
|
139 |
+
|
140 |
+
def test_matmul_no_matrices():
|
141 |
+
assert MatMul(1) == 1
|
142 |
+
assert MatMul(n, m) == n*m
|
143 |
+
assert not isinstance(MatMul(n, m), MatMul)
|
144 |
+
|
145 |
+
def test_matmul_args_cnc():
|
146 |
+
assert MatMul(n, A, A.T).args_cnc() == [[n], [A, A.T]]
|
147 |
+
assert MatMul(A, A.T).args_cnc() == [[], [A, A.T]]
|
148 |
+
|
149 |
+
@XFAIL
|
150 |
+
def test_matmul_args_cnc_symbols():
|
151 |
+
# Not currently supported
|
152 |
+
a, b = symbols('a b', commutative=False)
|
153 |
+
assert MatMul(n, a, b, A, A.T).args_cnc() == [[n], [a, b, A, A.T]]
|
154 |
+
assert MatMul(n, a, A, b, A.T).args_cnc() == [[n], [a, A, b, A.T]]
|
155 |
+
|
156 |
+
def test_issue_12950():
|
157 |
+
M = Matrix([[Symbol("x")]]) * MatrixSymbol("A", 1, 1)
|
158 |
+
assert MatrixSymbol("A", 1, 1).as_explicit()[0]*Symbol('x') == M.as_explicit()[0]
|
159 |
+
|
160 |
+
def test_construction_with_Mul():
|
161 |
+
assert Mul(C, D) == MatMul(C, D)
|
162 |
+
assert Mul(D, C) == MatMul(D, C)
|
163 |
+
|
164 |
+
def test_construction_with_mul():
|
165 |
+
assert mul(C, D) == MatMul(C, D)
|
166 |
+
assert mul(D, C) == MatMul(D, C)
|
167 |
+
assert mul(C, D) != MatMul(D, C)
|
168 |
+
|
169 |
+
def test_generic_identity():
|
170 |
+
assert MatMul.identity == GenericIdentity()
|
171 |
+
assert MatMul.identity != S.One
|
172 |
+
|
173 |
+
|
174 |
+
def test_issue_23519():
|
175 |
+
N = Symbol("N", integer=True)
|
176 |
+
M1 = MatrixSymbol("M1", N, N)
|
177 |
+
M2 = MatrixSymbol("M2", N, N)
|
178 |
+
I = Identity(N)
|
179 |
+
z = (M2 + 2 * (M2 + I) * M1 + I)
|
180 |
+
assert z.coeff(M1) == 2*I + 2*M2
|
181 |
+
|
182 |
+
|
183 |
+
def test_shape_error():
|
184 |
+
A = MatrixSymbol('A', 2, 2)
|
185 |
+
B = MatrixSymbol('B', 3, 3)
|
186 |
+
raises(ShapeError, lambda: MatMul(A, B))
|
llmeval-env/lib/python3.10/site-packages/sympy/matrices/expressions/tests/test_matpow.py
ADDED
@@ -0,0 +1,217 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
2 |
+
from sympy.simplify.powsimp import powsimp
|
3 |
+
from sympy.testing.pytest import raises
|
4 |
+
from sympy.core.expr import unchanged
|
5 |
+
from sympy.core import symbols, S
|
6 |
+
from sympy.matrices import Identity, MatrixSymbol, ImmutableMatrix, ZeroMatrix, OneMatrix, Matrix
|
7 |
+
from sympy.matrices.common import NonSquareMatrixError
|
8 |
+
from sympy.matrices.expressions import MatPow, MatAdd, MatMul
|
9 |
+
from sympy.matrices.expressions.inverse import Inverse
|
10 |
+
from sympy.matrices.expressions.matexpr import MatrixElement
|
11 |
+
|
12 |
+
n, m, l, k = symbols('n m l k', integer=True)
|
13 |
+
A = MatrixSymbol('A', n, m)
|
14 |
+
B = MatrixSymbol('B', m, l)
|
15 |
+
C = MatrixSymbol('C', n, n)
|
16 |
+
D = MatrixSymbol('D', n, n)
|
17 |
+
E = MatrixSymbol('E', m, n)
|
18 |
+
|
19 |
+
|
20 |
+
def test_entry_matrix():
|
21 |
+
X = ImmutableMatrix([[1, 2], [3, 4]])
|
22 |
+
assert MatPow(X, 0)[0, 0] == 1
|
23 |
+
assert MatPow(X, 0)[0, 1] == 0
|
24 |
+
assert MatPow(X, 1)[0, 0] == 1
|
25 |
+
assert MatPow(X, 1)[0, 1] == 2
|
26 |
+
assert MatPow(X, 2)[0, 0] == 7
|
27 |
+
|
28 |
+
|
29 |
+
def test_entry_symbol():
|
30 |
+
from sympy.concrete import Sum
|
31 |
+
assert MatPow(C, 0)[0, 0] == 1
|
32 |
+
assert MatPow(C, 0)[0, 1] == 0
|
33 |
+
assert MatPow(C, 1)[0, 0] == C[0, 0]
|
34 |
+
assert isinstance(MatPow(C, 2)[0, 0], Sum)
|
35 |
+
assert isinstance(MatPow(C, n)[0, 0], MatrixElement)
|
36 |
+
|
37 |
+
|
38 |
+
def test_as_explicit_symbol():
|
39 |
+
X = MatrixSymbol('X', 2, 2)
|
40 |
+
assert MatPow(X, 0).as_explicit() == ImmutableMatrix(Identity(2))
|
41 |
+
assert MatPow(X, 1).as_explicit() == X.as_explicit()
|
42 |
+
assert MatPow(X, 2).as_explicit() == (X.as_explicit())**2
|
43 |
+
assert MatPow(X, n).as_explicit() == ImmutableMatrix([
|
44 |
+
[(X ** n)[0, 0], (X ** n)[0, 1]],
|
45 |
+
[(X ** n)[1, 0], (X ** n)[1, 1]],
|
46 |
+
])
|
47 |
+
|
48 |
+
a = MatrixSymbol("a", 3, 1)
|
49 |
+
b = MatrixSymbol("b", 3, 1)
|
50 |
+
c = MatrixSymbol("c", 3, 1)
|
51 |
+
|
52 |
+
expr = (a.T*b)**S.Half
|
53 |
+
assert expr.as_explicit() == Matrix([[sqrt(a[0, 0]*b[0, 0] + a[1, 0]*b[1, 0] + a[2, 0]*b[2, 0])]])
|
54 |
+
|
55 |
+
expr = c*(a.T*b)**S.Half
|
56 |
+
m = sqrt(a[0, 0]*b[0, 0] + a[1, 0]*b[1, 0] + a[2, 0]*b[2, 0])
|
57 |
+
assert expr.as_explicit() == Matrix([[c[0, 0]*m], [c[1, 0]*m], [c[2, 0]*m]])
|
58 |
+
|
59 |
+
expr = (a*b.T)**S.Half
|
60 |
+
denom = sqrt(a[0, 0]*b[0, 0] + a[1, 0]*b[1, 0] + a[2, 0]*b[2, 0])
|
61 |
+
expected = (a*b.T).as_explicit()/denom
|
62 |
+
assert expr.as_explicit() == expected
|
63 |
+
|
64 |
+
expr = X**-1
|
65 |
+
det = X[0, 0]*X[1, 1] - X[1, 0]*X[0, 1]
|
66 |
+
expected = Matrix([[X[1, 1], -X[0, 1]], [-X[1, 0], X[0, 0]]])/det
|
67 |
+
assert expr.as_explicit() == expected
|
68 |
+
|
69 |
+
expr = X**m
|
70 |
+
assert expr.as_explicit() == X.as_explicit()**m
|
71 |
+
|
72 |
+
|
73 |
+
def test_as_explicit_matrix():
|
74 |
+
A = ImmutableMatrix([[1, 2], [3, 4]])
|
75 |
+
assert MatPow(A, 0).as_explicit() == ImmutableMatrix(Identity(2))
|
76 |
+
assert MatPow(A, 1).as_explicit() == A
|
77 |
+
assert MatPow(A, 2).as_explicit() == A**2
|
78 |
+
assert MatPow(A, -1).as_explicit() == A.inv()
|
79 |
+
assert MatPow(A, -2).as_explicit() == (A.inv())**2
|
80 |
+
# less expensive than testing on a 2x2
|
81 |
+
A = ImmutableMatrix([4])
|
82 |
+
assert MatPow(A, S.Half).as_explicit() == A**S.Half
|
83 |
+
|
84 |
+
|
85 |
+
def test_doit_symbol():
|
86 |
+
assert MatPow(C, 0).doit() == Identity(n)
|
87 |
+
assert MatPow(C, 1).doit() == C
|
88 |
+
assert MatPow(C, -1).doit() == C.I
|
89 |
+
for r in [2, S.Half, S.Pi, n]:
|
90 |
+
assert MatPow(C, r).doit() == MatPow(C, r)
|
91 |
+
|
92 |
+
|
93 |
+
def test_doit_matrix():
|
94 |
+
X = ImmutableMatrix([[1, 2], [3, 4]])
|
95 |
+
assert MatPow(X, 0).doit() == ImmutableMatrix(Identity(2))
|
96 |
+
assert MatPow(X, 1).doit() == X
|
97 |
+
assert MatPow(X, 2).doit() == X**2
|
98 |
+
assert MatPow(X, -1).doit() == X.inv()
|
99 |
+
assert MatPow(X, -2).doit() == (X.inv())**2
|
100 |
+
# less expensive than testing on a 2x2
|
101 |
+
assert MatPow(ImmutableMatrix([4]), S.Half).doit() == ImmutableMatrix([2])
|
102 |
+
X = ImmutableMatrix([[0, 2], [0, 4]]) # det() == 0
|
103 |
+
raises(ValueError, lambda: MatPow(X,-1).doit())
|
104 |
+
raises(ValueError, lambda: MatPow(X,-2).doit())
|
105 |
+
|
106 |
+
|
107 |
+
def test_nonsquare():
|
108 |
+
A = MatrixSymbol('A', 2, 3)
|
109 |
+
B = ImmutableMatrix([[1, 2, 3], [4, 5, 6]])
|
110 |
+
for r in [-1, 0, 1, 2, S.Half, S.Pi, n]:
|
111 |
+
raises(NonSquareMatrixError, lambda: MatPow(A, r))
|
112 |
+
raises(NonSquareMatrixError, lambda: MatPow(B, r))
|
113 |
+
|
114 |
+
|
115 |
+
def test_doit_equals_pow(): #17179
|
116 |
+
X = ImmutableMatrix ([[1,0],[0,1]])
|
117 |
+
assert MatPow(X, n).doit() == X**n == X
|
118 |
+
|
119 |
+
|
120 |
+
def test_doit_nested_MatrixExpr():
|
121 |
+
X = ImmutableMatrix([[1, 2], [3, 4]])
|
122 |
+
Y = ImmutableMatrix([[2, 3], [4, 5]])
|
123 |
+
assert MatPow(MatMul(X, Y), 2).doit() == (X*Y)**2
|
124 |
+
assert MatPow(MatAdd(X, Y), 2).doit() == (X + Y)**2
|
125 |
+
|
126 |
+
|
127 |
+
def test_identity_power():
|
128 |
+
k = Identity(n)
|
129 |
+
assert MatPow(k, 4).doit() == k
|
130 |
+
assert MatPow(k, n).doit() == k
|
131 |
+
assert MatPow(k, -3).doit() == k
|
132 |
+
assert MatPow(k, 0).doit() == k
|
133 |
+
l = Identity(3)
|
134 |
+
assert MatPow(l, n).doit() == l
|
135 |
+
assert MatPow(l, -1).doit() == l
|
136 |
+
assert MatPow(l, 0).doit() == l
|
137 |
+
|
138 |
+
|
139 |
+
def test_zero_power():
|
140 |
+
z1 = ZeroMatrix(n, n)
|
141 |
+
assert MatPow(z1, 3).doit() == z1
|
142 |
+
raises(ValueError, lambda:MatPow(z1, -1).doit())
|
143 |
+
assert MatPow(z1, 0).doit() == Identity(n)
|
144 |
+
assert MatPow(z1, n).doit() == z1
|
145 |
+
raises(ValueError, lambda:MatPow(z1, -2).doit())
|
146 |
+
z2 = ZeroMatrix(4, 4)
|
147 |
+
assert MatPow(z2, n).doit() == z2
|
148 |
+
raises(ValueError, lambda:MatPow(z2, -3).doit())
|
149 |
+
assert MatPow(z2, 2).doit() == z2
|
150 |
+
assert MatPow(z2, 0).doit() == Identity(4)
|
151 |
+
raises(ValueError, lambda:MatPow(z2, -1).doit())
|
152 |
+
|
153 |
+
|
154 |
+
def test_OneMatrix_power():
|
155 |
+
o = OneMatrix(3, 3)
|
156 |
+
assert o ** 0 == Identity(3)
|
157 |
+
assert o ** 1 == o
|
158 |
+
assert o * o == o ** 2 == 3 * o
|
159 |
+
assert o * o * o == o ** 3 == 9 * o
|
160 |
+
|
161 |
+
o = OneMatrix(n, n)
|
162 |
+
assert o * o == o ** 2 == n * o
|
163 |
+
# powsimp necessary as n ** (n - 2) * n does not produce n ** (n - 1)
|
164 |
+
assert powsimp(o ** (n - 1) * o) == o ** n == n ** (n - 1) * o
|
165 |
+
|
166 |
+
|
167 |
+
def test_transpose_power():
|
168 |
+
from sympy.matrices.expressions.transpose import Transpose as TP
|
169 |
+
|
170 |
+
assert (C*D).T**5 == ((C*D)**5).T == (D.T * C.T)**5
|
171 |
+
assert ((C*D).T**5).T == (C*D)**5
|
172 |
+
|
173 |
+
assert (C.T.I.T)**7 == C**-7
|
174 |
+
assert (C.T**l).T**k == C**(l*k)
|
175 |
+
|
176 |
+
assert ((E.T * A.T)**5).T == (A*E)**5
|
177 |
+
assert ((A*E).T**5).T**7 == (A*E)**35
|
178 |
+
assert TP(TP(C**2 * D**3)**5).doit() == (C**2 * D**3)**5
|
179 |
+
|
180 |
+
assert ((D*C)**-5).T**-5 == ((D*C)**25).T
|
181 |
+
assert (((D*C)**l).T**k).T == (D*C)**(l*k)
|
182 |
+
|
183 |
+
|
184 |
+
def test_Inverse():
|
185 |
+
assert Inverse(MatPow(C, 0)).doit() == Identity(n)
|
186 |
+
assert Inverse(MatPow(C, 1)).doit() == Inverse(C)
|
187 |
+
assert Inverse(MatPow(C, 2)).doit() == MatPow(C, -2)
|
188 |
+
assert Inverse(MatPow(C, -1)).doit() == C
|
189 |
+
|
190 |
+
assert MatPow(Inverse(C), 0).doit() == Identity(n)
|
191 |
+
assert MatPow(Inverse(C), 1).doit() == Inverse(C)
|
192 |
+
assert MatPow(Inverse(C), 2).doit() == MatPow(C, -2)
|
193 |
+
assert MatPow(Inverse(C), -1).doit() == C
|
194 |
+
|
195 |
+
|
196 |
+
def test_combine_powers():
|
197 |
+
assert (C ** 1) ** 1 == C
|
198 |
+
assert (C ** 2) ** 3 == MatPow(C, 6)
|
199 |
+
assert (C ** -2) ** -3 == MatPow(C, 6)
|
200 |
+
assert (C ** -1) ** -1 == C
|
201 |
+
assert (((C ** 2) ** 3) ** 4) ** 5 == MatPow(C, 120)
|
202 |
+
assert (C ** n) ** n == C ** (n ** 2)
|
203 |
+
|
204 |
+
|
205 |
+
def test_unchanged():
|
206 |
+
assert unchanged(MatPow, C, 0)
|
207 |
+
assert unchanged(MatPow, C, 1)
|
208 |
+
assert unchanged(MatPow, Inverse(C), -1)
|
209 |
+
assert unchanged(Inverse, MatPow(C, -1), -1)
|
210 |
+
assert unchanged(MatPow, MatPow(C, -1), -1)
|
211 |
+
assert unchanged(MatPow, MatPow(C, 1), 1)
|
212 |
+
|
213 |
+
|
214 |
+
def test_no_exponentiation():
|
215 |
+
# if this passes, Pow.as_numer_denom should recognize
|
216 |
+
# MatAdd as exponent
|
217 |
+
raises(NotImplementedError, lambda: 3**(-2*C))
|