Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- env-llmeval/lib/python3.10/site-packages/sympy/liealgebras/__pycache__/weyl_group.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/matrices/expressions/__init__.py +62 -0
- env-llmeval/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/__init__.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/_shape.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/adjoint.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/applyfunc.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/blockmatrix.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/companion.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/determinant.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/diagonal.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/dotproduct.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/factorizations.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/fourier.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/funcmatrix.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/hadamard.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/inverse.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/matadd.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/matexpr.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/matmul.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/matpow.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/permutation.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/slice.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/trace.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/transpose.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/matrices/expressions/_shape.py +102 -0
- env-llmeval/lib/python3.10/site-packages/sympy/matrices/expressions/adjoint.py +61 -0
- env-llmeval/lib/python3.10/site-packages/sympy/matrices/expressions/applyfunc.py +204 -0
- env-llmeval/lib/python3.10/site-packages/sympy/matrices/expressions/blockmatrix.py +979 -0
- env-llmeval/lib/python3.10/site-packages/sympy/matrices/expressions/companion.py +56 -0
- env-llmeval/lib/python3.10/site-packages/sympy/matrices/expressions/determinant.py +141 -0
- env-llmeval/lib/python3.10/site-packages/sympy/matrices/expressions/diagonal.py +220 -0
- env-llmeval/lib/python3.10/site-packages/sympy/matrices/expressions/dotproduct.py +55 -0
- env-llmeval/lib/python3.10/site-packages/sympy/matrices/expressions/factorizations.py +62 -0
- env-llmeval/lib/python3.10/site-packages/sympy/matrices/expressions/funcmatrix.py +118 -0
- env-llmeval/lib/python3.10/site-packages/sympy/matrices/expressions/hadamard.py +464 -0
- env-llmeval/lib/python3.10/site-packages/sympy/matrices/expressions/inverse.py +103 -0
- env-llmeval/lib/python3.10/site-packages/sympy/matrices/expressions/matadd.py +155 -0
- env-llmeval/lib/python3.10/site-packages/sympy/matrices/expressions/matexpr.py +885 -0
- env-llmeval/lib/python3.10/site-packages/sympy/matrices/expressions/matmul.py +498 -0
- env-llmeval/lib/python3.10/site-packages/sympy/matrices/expressions/matpow.py +142 -0
- env-llmeval/lib/python3.10/site-packages/sympy/matrices/expressions/permutation.py +303 -0
- env-llmeval/lib/python3.10/site-packages/sympy/matrices/expressions/sets.py +67 -0
- env-llmeval/lib/python3.10/site-packages/sympy/matrices/expressions/slice.py +114 -0
- env-llmeval/lib/python3.10/site-packages/sympy/matrices/expressions/special.py +299 -0
- env-llmeval/lib/python3.10/site-packages/sympy/matrices/expressions/tests/__init__.py +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/matrices/expressions/tests/__pycache__/test_adjoint.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/matrices/expressions/tests/__pycache__/test_applyfunc.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/matrices/expressions/tests/__pycache__/test_diagonal.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/matrices/expressions/tests/__pycache__/test_fourier.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/matrices/expressions/tests/__pycache__/test_indexing.cpython-310.pyc +0 -0
env-llmeval/lib/python3.10/site-packages/sympy/liealgebras/__pycache__/weyl_group.cpython-310.pyc
ADDED
Binary file (10.7 kB). View file
|
|
env-llmeval/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 |
+
]
|
env-llmeval/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (1.78 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/_shape.cpython-310.pyc
ADDED
Binary file (4.26 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/adjoint.cpython-310.pyc
ADDED
Binary file (2.48 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/applyfunc.cpython-310.pyc
ADDED
Binary file (5.52 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/blockmatrix.cpython-310.pyc
ADDED
Binary file (33.8 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/companion.cpython-310.pyc
ADDED
Binary file (2.22 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/determinant.cpython-310.pyc
ADDED
Binary file (3.98 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/diagonal.cpython-310.pyc
ADDED
Binary file (7.07 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/dotproduct.cpython-310.pyc
ADDED
Binary file (2.03 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/factorizations.cpython-310.pyc
ADDED
Binary file (3.39 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/fourier.cpython-310.pyc
ADDED
Binary file (3.08 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/funcmatrix.cpython-310.pyc
ADDED
Binary file (4.24 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/hadamard.cpython-310.pyc
ADDED
Binary file (14.2 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/inverse.cpython-310.pyc
ADDED
Binary file (3.32 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/matadd.cpython-310.pyc
ADDED
Binary file (6.92 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/matexpr.cpython-310.pyc
ADDED
Binary file (29.9 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/matmul.cpython-310.pyc
ADDED
Binary file (16.2 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/matpow.cpython-310.pyc
ADDED
Binary file (4.95 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/permutation.cpython-310.pyc
ADDED
Binary file (7.66 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/slice.cpython-310.pyc
ADDED
Binary file (3.56 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/trace.cpython-310.pyc
ADDED
Binary file (4.86 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/matrices/expressions/__pycache__/transpose.cpython-310.pyc
ADDED
Binary file (3.89 kB). View file
|
|
env-llmeval/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)
|
env-llmeval/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)
|
env-llmeval/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())
|
env-llmeval/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])
|
env-llmeval/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])
|
env-llmeval/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
|
env-llmeval/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()
|
env-llmeval/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]
|
env-llmeval/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)
|
env-llmeval/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)))
|
env-llmeval/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
|
env-llmeval/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
|
env-llmeval/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)))
|
env-llmeval/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
|
env-llmeval/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
|
env-llmeval/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)
|
env-llmeval/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))
|
env-llmeval/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))
|
env-llmeval/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)
|
env-llmeval/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
|
env-llmeval/lib/python3.10/site-packages/sympy/matrices/expressions/tests/__init__.py
ADDED
File without changes
|
env-llmeval/lib/python3.10/site-packages/sympy/matrices/expressions/tests/__pycache__/test_adjoint.cpython-310.pyc
ADDED
Binary file (1.31 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/matrices/expressions/tests/__pycache__/test_applyfunc.cpython-310.pyc
ADDED
Binary file (3.66 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/matrices/expressions/tests/__pycache__/test_diagonal.cpython-310.pyc
ADDED
Binary file (4.38 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/matrices/expressions/tests/__pycache__/test_fourier.cpython-310.pyc
ADDED
Binary file (2.47 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/matrices/expressions/tests/__pycache__/test_indexing.cpython-310.pyc
ADDED
Binary file (12 kB). View file
|
|