jasonfan commited on
Commit
61f7854
·
verified ·
1 Parent(s): c39956c

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/matrices/benchmarks/__init__.py +0 -0
  2. miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/matrices/benchmarks/bench_matrix.py +21 -0
  3. miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/matrices/expressions/__init__.py +62 -0
  4. miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/matrices/expressions/_shape.py +102 -0
  5. miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/matrices/expressions/adjoint.py +60 -0
  6. miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/matrices/expressions/applyfunc.py +204 -0
  7. miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/matrices/expressions/blockmatrix.py +975 -0
  8. miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/matrices/expressions/companion.py +56 -0
  9. miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/matrices/expressions/determinant.py +148 -0
  10. miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/matrices/expressions/diagonal.py +220 -0
  11. miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/matrices/expressions/dotproduct.py +55 -0
  12. miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/matrices/expressions/factorizations.py +62 -0
  13. miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/matrices/expressions/fourier.py +91 -0
  14. miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/matrices/expressions/funcmatrix.py +118 -0
  15. miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/matrices/expressions/hadamard.py +464 -0
  16. miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/matrices/expressions/inverse.py +112 -0
  17. miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/matrices/expressions/kronecker.py +434 -0
  18. miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/matrices/expressions/matadd.py +155 -0
  19. miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/matrices/expressions/matexpr.py +888 -0
  20. miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/matrices/expressions/matmul.py +496 -0
  21. miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/matrices/expressions/matpow.py +150 -0
  22. miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/matrices/expressions/permutation.py +303 -0
  23. miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/matrices/expressions/sets.py +68 -0
  24. miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/matrices/expressions/slice.py +114 -0
  25. miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/matrices/expressions/special.py +299 -0
  26. miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/matrices/expressions/tests/__init__.py +0 -0
  27. miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/matrices/expressions/tests/test_adjoint.py +34 -0
  28. miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/matrices/expressions/tests/test_applyfunc.py +118 -0
  29. miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/matrices/expressions/tests/test_blockmatrix.py +469 -0
  30. miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/matrices/expressions/tests/test_companion.py +48 -0
  31. miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/matrices/expressions/tests/test_derivatives.py +477 -0
  32. miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/matrices/expressions/tests/test_determinant.py +65 -0
  33. miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/matrices/expressions/tests/test_diagonal.py +156 -0
  34. miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/matrices/expressions/tests/test_dotproduct.py +35 -0
  35. miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/matrices/expressions/tests/test_factorizations.py +29 -0
  36. miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/matrices/expressions/tests/test_fourier.py +44 -0
  37. miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/matrices/expressions/tests/test_funcmatrix.py +54 -0
  38. miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/matrices/expressions/tests/test_hadamard.py +141 -0
  39. miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/matrices/expressions/tests/test_indexing.py +299 -0
  40. miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/matrices/expressions/tests/test_inverse.py +69 -0
  41. miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/matrices/expressions/tests/test_kronecker.py +150 -0
  42. miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/matrices/expressions/tests/test_matadd.py +58 -0
  43. miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/matrices/expressions/tests/test_matexpr.py +592 -0
  44. miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/matrices/expressions/tests/test_matmul.py +193 -0
  45. miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/matrices/expressions/tests/test_matpow.py +217 -0
  46. miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/matrices/expressions/tests/test_permutation.py +166 -0
  47. miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/matrices/expressions/tests/test_sets.py +42 -0
  48. miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/matrices/expressions/tests/test_slice.py +65 -0
  49. miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/matrices/expressions/tests/test_special.py +228 -0
  50. miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/matrices/expressions/tests/test_trace.py +116 -0
miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/matrices/benchmarks/__init__.py ADDED
File without changes
miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/matrices/benchmarks/bench_matrix.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.numbers import Integer
2
+ from sympy.matrices.dense import (eye, zeros)
3
+
4
+ i3 = Integer(3)
5
+ M = eye(100)
6
+
7
+
8
+ def timeit_Matrix__getitem_ii():
9
+ M[3, 3]
10
+
11
+
12
+ def timeit_Matrix__getitem_II():
13
+ M[i3, i3]
14
+
15
+
16
+ def timeit_Matrix__getslice():
17
+ M[:, :]
18
+
19
+
20
+ def timeit_Matrix_zeronm():
21
+ zeros(100, 100)
miniconda3/envs/ladir/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
+ ]
miniconda3/envs/ladir/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.exceptions 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)
miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/matrices/expressions/adjoint.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core import Basic
2
+ from sympy.functions import adjoint, conjugate
3
+ from sympy.matrices.expressions.matexpr import MatrixExpr
4
+
5
+
6
+ class Adjoint(MatrixExpr):
7
+ """
8
+ The Hermitian adjoint of a matrix expression.
9
+
10
+ This is a symbolic object that simply stores its argument without
11
+ evaluating it. To actually compute the adjoint, use the ``adjoint()``
12
+ function.
13
+
14
+ Examples
15
+ ========
16
+
17
+ >>> from sympy import MatrixSymbol, Adjoint, adjoint
18
+ >>> A = MatrixSymbol('A', 3, 5)
19
+ >>> B = MatrixSymbol('B', 5, 3)
20
+ >>> Adjoint(A*B)
21
+ Adjoint(A*B)
22
+ >>> adjoint(A*B)
23
+ Adjoint(B)*Adjoint(A)
24
+ >>> adjoint(A*B) == Adjoint(A*B)
25
+ False
26
+ >>> adjoint(A*B) == Adjoint(A*B).doit()
27
+ True
28
+ """
29
+ is_Adjoint = True
30
+
31
+ def doit(self, **hints):
32
+ arg = self.arg
33
+ if hints.get('deep', True) and isinstance(arg, Basic):
34
+ return adjoint(arg.doit(**hints))
35
+ else:
36
+ return adjoint(self.arg)
37
+
38
+ @property
39
+ def arg(self):
40
+ return self.args[0]
41
+
42
+ @property
43
+ def shape(self):
44
+ return self.arg.shape[::-1]
45
+
46
+ def _entry(self, i, j, **kwargs):
47
+ return conjugate(self.arg._entry(j, i, **kwargs))
48
+
49
+ def _eval_adjoint(self):
50
+ return self.arg
51
+
52
+ def _eval_transpose(self):
53
+ return self.arg.conjugate()
54
+
55
+ def _eval_conjugate(self):
56
+ return self.arg.transpose()
57
+
58
+ def _eval_trace(self):
59
+ from sympy.matrices.expressions.trace import Trace
60
+ return conjugate(Trace(self.arg))
miniconda3/envs/ladir/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.matrixbase 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())
miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/matrices/expressions/blockmatrix.py ADDED
@@ -0,0 +1,975 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.elementary.complexes import re, im
5
+ from sympy.strategies import typed, exhaust, condition, do_one, unpack
6
+ from sympy.strategies.traverse import bottom_up
7
+ from sympy.utilities.iterables import is_sequence, sift
8
+ from sympy.utilities.misc import filldedent
9
+
10
+ from sympy.matrices import Matrix, ShapeError
11
+ from sympy.matrices.exceptions import NonInvertibleMatrixError
12
+ from sympy.matrices.expressions.determinant import det, Determinant
13
+ from sympy.matrices.expressions.inverse import Inverse
14
+ from sympy.matrices.expressions.matadd import MatAdd
15
+ from sympy.matrices.expressions.matexpr import MatrixExpr, MatrixElement
16
+ from sympy.matrices.expressions.matmul import MatMul
17
+ from sympy.matrices.expressions.matpow import MatPow
18
+ from sympy.matrices.expressions.slice import MatrixSlice
19
+ from sympy.matrices.expressions.special import ZeroMatrix, Identity
20
+ from sympy.matrices.expressions.trace import trace
21
+ from sympy.matrices.expressions.transpose import Transpose, transpose
22
+
23
+
24
+ class BlockMatrix(MatrixExpr):
25
+ """A BlockMatrix is a Matrix comprised of other matrices.
26
+
27
+ The submatrices are stored in a SymPy Matrix object but accessed as part of
28
+ a Matrix Expression
29
+
30
+ >>> from sympy import (MatrixSymbol, BlockMatrix, symbols,
31
+ ... Identity, ZeroMatrix, block_collapse)
32
+ >>> n,m,l = symbols('n m l')
33
+ >>> X = MatrixSymbol('X', n, n)
34
+ >>> Y = MatrixSymbol('Y', m, m)
35
+ >>> Z = MatrixSymbol('Z', n, m)
36
+ >>> B = BlockMatrix([[X, Z], [ZeroMatrix(m,n), Y]])
37
+ >>> print(B)
38
+ Matrix([
39
+ [X, Z],
40
+ [0, Y]])
41
+
42
+ >>> C = BlockMatrix([[Identity(n), Z]])
43
+ >>> print(C)
44
+ Matrix([[I, Z]])
45
+
46
+ >>> print(block_collapse(C*B))
47
+ Matrix([[X, Z + Z*Y]])
48
+
49
+ Some matrices might be comprised of rows of blocks with
50
+ the matrices in each row having the same height and the
51
+ rows all having the same total number of columns but
52
+ not having the same number of columns for each matrix
53
+ in each row. In this case, the matrix is not a block
54
+ matrix and should be instantiated by Matrix.
55
+
56
+ >>> from sympy import ones, Matrix
57
+ >>> dat = [
58
+ ... [ones(3,2), ones(3,3)*2],
59
+ ... [ones(2,3)*3, ones(2,2)*4]]
60
+ ...
61
+ >>> BlockMatrix(dat)
62
+ Traceback (most recent call last):
63
+ ...
64
+ ValueError:
65
+ Although this matrix is comprised of blocks, the blocks do not fill
66
+ the matrix in a size-symmetric fashion. To create a full matrix from
67
+ these arguments, pass them directly to Matrix.
68
+ >>> Matrix(dat)
69
+ Matrix([
70
+ [1, 1, 2, 2, 2],
71
+ [1, 1, 2, 2, 2],
72
+ [1, 1, 2, 2, 2],
73
+ [3, 3, 3, 4, 4],
74
+ [3, 3, 3, 4, 4]])
75
+
76
+ See Also
77
+ ========
78
+ sympy.matrices.matrixbase.MatrixBase.irregular
79
+ """
80
+ def __new__(cls, *args, **kwargs):
81
+ from sympy.matrices.immutable import ImmutableDenseMatrix
82
+ isMat = lambda i: getattr(i, 'is_Matrix', False)
83
+ if len(args) != 1 or \
84
+ not is_sequence(args[0]) or \
85
+ len({isMat(r) for r in args[0]}) != 1:
86
+ raise ValueError(filldedent('''
87
+ expecting a sequence of 1 or more rows
88
+ containing Matrices.'''))
89
+ rows = args[0] if args else []
90
+ if not isMat(rows):
91
+ if rows and isMat(rows[0]):
92
+ rows = [rows] # rows is not list of lists or []
93
+ # regularity check
94
+ # same number of matrices in each row
95
+ blocky = ok = len({len(r) for r in rows}) == 1
96
+ if ok:
97
+ # same number of rows for each matrix in a row
98
+ for r in rows:
99
+ ok = len({i.rows for i in r}) == 1
100
+ if not ok:
101
+ break
102
+ blocky = ok
103
+ if ok:
104
+ # same number of cols for each matrix in each col
105
+ for c in range(len(rows[0])):
106
+ ok = len({rows[i][c].cols
107
+ for i in range(len(rows))}) == 1
108
+ if not ok:
109
+ break
110
+ if not ok:
111
+ # same total cols in each row
112
+ ok = len({
113
+ sum(i.cols for i in r) for r in rows}) == 1
114
+ if blocky and ok:
115
+ raise ValueError(filldedent('''
116
+ Although this matrix is comprised of blocks,
117
+ the blocks do not fill the matrix in a
118
+ size-symmetric fashion. To create a full matrix
119
+ from these arguments, pass them directly to
120
+ Matrix.'''))
121
+ raise ValueError(filldedent('''
122
+ When there are not the same number of rows in each
123
+ row's matrices or there are not the same number of
124
+ total columns in each row, the matrix is not a
125
+ block matrix. If this matrix is known to consist of
126
+ blocks fully filling a 2-D space then see
127
+ Matrix.irregular.'''))
128
+ mat = ImmutableDenseMatrix(rows, evaluate=False)
129
+ obj = Basic.__new__(cls, mat)
130
+ return obj
131
+
132
+ @property
133
+ def shape(self):
134
+ numrows = numcols = 0
135
+ M = self.blocks
136
+ for i in range(M.shape[0]):
137
+ numrows += M[i, 0].shape[0]
138
+ for i in range(M.shape[1]):
139
+ numcols += M[0, i].shape[1]
140
+ return (numrows, numcols)
141
+
142
+ @property
143
+ def blockshape(self):
144
+ return self.blocks.shape
145
+
146
+ @property
147
+ def blocks(self):
148
+ return self.args[0]
149
+
150
+ @property
151
+ def rowblocksizes(self):
152
+ return [self.blocks[i, 0].rows for i in range(self.blockshape[0])]
153
+
154
+ @property
155
+ def colblocksizes(self):
156
+ return [self.blocks[0, i].cols for i in range(self.blockshape[1])]
157
+
158
+ def structurally_equal(self, other):
159
+ return (isinstance(other, BlockMatrix)
160
+ and self.shape == other.shape
161
+ and self.blockshape == other.blockshape
162
+ and self.rowblocksizes == other.rowblocksizes
163
+ and self.colblocksizes == other.colblocksizes)
164
+
165
+ def _blockmul(self, other):
166
+ if (isinstance(other, BlockMatrix) and
167
+ self.colblocksizes == other.rowblocksizes):
168
+ return BlockMatrix(self.blocks*other.blocks)
169
+
170
+ return self * other
171
+
172
+ def _blockadd(self, other):
173
+ if (isinstance(other, BlockMatrix)
174
+ and self.structurally_equal(other)):
175
+ return BlockMatrix(self.blocks + other.blocks)
176
+
177
+ return self + other
178
+
179
+ def _eval_transpose(self):
180
+ # Flip all the individual matrices
181
+ matrices = [transpose(matrix) for matrix in self.blocks]
182
+ # Make a copy
183
+ M = Matrix(self.blockshape[0], self.blockshape[1], matrices)
184
+ # Transpose the block structure
185
+ M = M.transpose()
186
+ return BlockMatrix(M)
187
+
188
+ def _eval_adjoint(self):
189
+ return BlockMatrix(
190
+ Matrix(self.blockshape[0], self.blockshape[1], self.blocks).adjoint()
191
+ )
192
+
193
+ def _eval_trace(self):
194
+ if self.rowblocksizes == self.colblocksizes:
195
+ blocks = [self.blocks[i, i] for i in range(self.blockshape[0])]
196
+ return Add(*[trace(block) for block in blocks])
197
+
198
+ def _eval_determinant(self):
199
+ if self.blockshape == (1, 1):
200
+ return det(self.blocks[0, 0])
201
+ if self.blockshape == (2, 2):
202
+ [[A, B],
203
+ [C, D]] = self.blocks.tolist()
204
+ if ask(Q.invertible(A)):
205
+ return det(A)*det(D - C*A.I*B)
206
+ elif ask(Q.invertible(D)):
207
+ return det(D)*det(A - B*D.I*C)
208
+ return Determinant(self)
209
+
210
+ def _eval_as_real_imag(self):
211
+ real_matrices = [re(matrix) for matrix in self.blocks]
212
+ real_matrices = Matrix(self.blockshape[0], self.blockshape[1], real_matrices)
213
+
214
+ im_matrices = [im(matrix) for matrix in self.blocks]
215
+ im_matrices = Matrix(self.blockshape[0], self.blockshape[1], im_matrices)
216
+
217
+ return (BlockMatrix(real_matrices), BlockMatrix(im_matrices))
218
+
219
+ def _eval_derivative(self, x):
220
+ return BlockMatrix(self.blocks.diff(x))
221
+
222
+ def transpose(self):
223
+ """Return transpose of matrix.
224
+
225
+ Examples
226
+ ========
227
+
228
+ >>> from sympy import MatrixSymbol, BlockMatrix, ZeroMatrix
229
+ >>> from sympy.abc import m, n
230
+ >>> X = MatrixSymbol('X', n, n)
231
+ >>> Y = MatrixSymbol('Y', m, m)
232
+ >>> Z = MatrixSymbol('Z', n, m)
233
+ >>> B = BlockMatrix([[X, Z], [ZeroMatrix(m,n), Y]])
234
+ >>> B.transpose()
235
+ Matrix([
236
+ [X.T, 0],
237
+ [Z.T, Y.T]])
238
+ >>> _.transpose()
239
+ Matrix([
240
+ [X, Z],
241
+ [0, Y]])
242
+ """
243
+ return self._eval_transpose()
244
+
245
+ def schur(self, mat = 'A', generalized = False):
246
+ """Return the Schur Complement of the 2x2 BlockMatrix
247
+
248
+ Parameters
249
+ ==========
250
+
251
+ mat : String, optional
252
+ The matrix with respect to which the
253
+ Schur Complement is calculated. 'A' is
254
+ used by default
255
+
256
+ generalized : bool, optional
257
+ If True, returns the generalized Schur
258
+ Component which uses Moore-Penrose Inverse
259
+
260
+ Examples
261
+ ========
262
+
263
+ >>> from sympy import symbols, MatrixSymbol, BlockMatrix
264
+ >>> m, n = symbols('m n')
265
+ >>> A = MatrixSymbol('A', n, n)
266
+ >>> B = MatrixSymbol('B', n, m)
267
+ >>> C = MatrixSymbol('C', m, n)
268
+ >>> D = MatrixSymbol('D', m, m)
269
+ >>> X = BlockMatrix([[A, B], [C, D]])
270
+
271
+ The default Schur Complement is evaluated with "A"
272
+
273
+ >>> X.schur()
274
+ -C*A**(-1)*B + D
275
+ >>> X.schur('D')
276
+ A - B*D**(-1)*C
277
+
278
+ Schur complement with non-invertible matrices is not
279
+ defined. Instead, the generalized Schur complement can
280
+ be calculated which uses the Moore-Penrose Inverse. To
281
+ achieve this, `generalized` must be set to `True`
282
+
283
+ >>> X.schur('B', generalized=True)
284
+ C - D*(B.T*B)**(-1)*B.T*A
285
+ >>> X.schur('C', generalized=True)
286
+ -A*(C.T*C)**(-1)*C.T*D + B
287
+
288
+ Returns
289
+ =======
290
+
291
+ M : Matrix
292
+ The Schur Complement Matrix
293
+
294
+ Raises
295
+ ======
296
+
297
+ ShapeError
298
+ If the block matrix is not a 2x2 matrix
299
+
300
+ NonInvertibleMatrixError
301
+ If given matrix is non-invertible
302
+
303
+ References
304
+ ==========
305
+
306
+ .. [1] Wikipedia Article on Schur Component : https://en.wikipedia.org/wiki/Schur_complement
307
+
308
+ See Also
309
+ ========
310
+
311
+ sympy.matrices.matrixbase.MatrixBase.pinv
312
+ """
313
+
314
+ if self.blockshape == (2, 2):
315
+ [[A, B],
316
+ [C, D]] = self.blocks.tolist()
317
+ d={'A' : A, 'B' : B, 'C' : C, 'D' : D}
318
+ try:
319
+ inv = (d[mat].T*d[mat]).inv()*d[mat].T if generalized else d[mat].inv()
320
+ if mat == 'A':
321
+ return D - C * inv * B
322
+ elif mat == 'B':
323
+ return C - D * inv * A
324
+ elif mat == 'C':
325
+ return B - A * inv * D
326
+ elif mat == 'D':
327
+ return A - B * inv * C
328
+ #For matrices where no sub-matrix is square
329
+ return self
330
+ except NonInvertibleMatrixError:
331
+ raise NonInvertibleMatrixError('The given matrix is not invertible. Please set generalized=True \
332
+ to compute the generalized Schur Complement which uses Moore-Penrose Inverse')
333
+ else:
334
+ raise ShapeError('Schur Complement can only be calculated for 2x2 block matrices')
335
+
336
+ def LDUdecomposition(self):
337
+ """Returns the Block LDU decomposition of
338
+ a 2x2 Block Matrix
339
+
340
+ Returns
341
+ =======
342
+
343
+ (L, D, U) : Matrices
344
+ L : Lower Diagonal Matrix
345
+ D : Diagonal Matrix
346
+ U : Upper Diagonal Matrix
347
+
348
+ Examples
349
+ ========
350
+
351
+ >>> from sympy import symbols, MatrixSymbol, BlockMatrix, block_collapse
352
+ >>> m, n = symbols('m n')
353
+ >>> A = MatrixSymbol('A', n, n)
354
+ >>> B = MatrixSymbol('B', n, m)
355
+ >>> C = MatrixSymbol('C', m, n)
356
+ >>> D = MatrixSymbol('D', m, m)
357
+ >>> X = BlockMatrix([[A, B], [C, D]])
358
+ >>> L, D, U = X.LDUdecomposition()
359
+ >>> block_collapse(L*D*U)
360
+ Matrix([
361
+ [A, B],
362
+ [C, D]])
363
+
364
+ Raises
365
+ ======
366
+
367
+ ShapeError
368
+ If the block matrix is not a 2x2 matrix
369
+
370
+ NonInvertibleMatrixError
371
+ If the matrix "A" is non-invertible
372
+
373
+ See Also
374
+ ========
375
+ sympy.matrices.expressions.blockmatrix.BlockMatrix.UDLdecomposition
376
+ sympy.matrices.expressions.blockmatrix.BlockMatrix.LUdecomposition
377
+ """
378
+ if self.blockshape == (2,2):
379
+ [[A, B],
380
+ [C, D]] = self.blocks.tolist()
381
+ try:
382
+ AI = A.I
383
+ except NonInvertibleMatrixError:
384
+ raise NonInvertibleMatrixError('Block LDU decomposition cannot be calculated when\
385
+ "A" is singular')
386
+ Ip = Identity(B.shape[0])
387
+ Iq = Identity(B.shape[1])
388
+ Z = ZeroMatrix(*B.shape)
389
+ L = BlockMatrix([[Ip, Z], [C*AI, Iq]])
390
+ D = BlockDiagMatrix(A, self.schur())
391
+ U = BlockMatrix([[Ip, AI*B],[Z.T, Iq]])
392
+ return L, D, U
393
+ else:
394
+ raise ShapeError("Block LDU decomposition is supported only for 2x2 block matrices")
395
+
396
+ def UDLdecomposition(self):
397
+ """Returns the Block UDL decomposition of
398
+ a 2x2 Block Matrix
399
+
400
+ Returns
401
+ =======
402
+
403
+ (U, D, L) : Matrices
404
+ U : Upper Diagonal Matrix
405
+ D : Diagonal Matrix
406
+ L : Lower Diagonal Matrix
407
+
408
+ Examples
409
+ ========
410
+
411
+ >>> from sympy import symbols, MatrixSymbol, BlockMatrix, block_collapse
412
+ >>> m, n = symbols('m n')
413
+ >>> A = MatrixSymbol('A', n, n)
414
+ >>> B = MatrixSymbol('B', n, m)
415
+ >>> C = MatrixSymbol('C', m, n)
416
+ >>> D = MatrixSymbol('D', m, m)
417
+ >>> X = BlockMatrix([[A, B], [C, D]])
418
+ >>> U, D, L = X.UDLdecomposition()
419
+ >>> block_collapse(U*D*L)
420
+ Matrix([
421
+ [A, B],
422
+ [C, D]])
423
+
424
+ Raises
425
+ ======
426
+
427
+ ShapeError
428
+ If the block matrix is not a 2x2 matrix
429
+
430
+ NonInvertibleMatrixError
431
+ If the matrix "D" is non-invertible
432
+
433
+ See Also
434
+ ========
435
+ sympy.matrices.expressions.blockmatrix.BlockMatrix.LDUdecomposition
436
+ sympy.matrices.expressions.blockmatrix.BlockMatrix.LUdecomposition
437
+ """
438
+ if self.blockshape == (2,2):
439
+ [[A, B],
440
+ [C, D]] = self.blocks.tolist()
441
+ try:
442
+ DI = D.I
443
+ except NonInvertibleMatrixError:
444
+ raise NonInvertibleMatrixError('Block UDL decomposition cannot be calculated when\
445
+ "D" is singular')
446
+ Ip = Identity(A.shape[0])
447
+ Iq = Identity(B.shape[1])
448
+ Z = ZeroMatrix(*B.shape)
449
+ U = BlockMatrix([[Ip, B*DI], [Z.T, Iq]])
450
+ D = BlockDiagMatrix(self.schur('D'), D)
451
+ L = BlockMatrix([[Ip, Z],[DI*C, Iq]])
452
+ return U, D, L
453
+ else:
454
+ raise ShapeError("Block UDL decomposition is supported only for 2x2 block matrices")
455
+
456
+ def LUdecomposition(self):
457
+ """Returns the Block LU decomposition of
458
+ a 2x2 Block Matrix
459
+
460
+ Returns
461
+ =======
462
+
463
+ (L, U) : Matrices
464
+ L : Lower Diagonal Matrix
465
+ U : Upper Diagonal Matrix
466
+
467
+ Examples
468
+ ========
469
+
470
+ >>> from sympy import symbols, MatrixSymbol, BlockMatrix, block_collapse
471
+ >>> m, n = symbols('m n')
472
+ >>> A = MatrixSymbol('A', n, n)
473
+ >>> B = MatrixSymbol('B', n, m)
474
+ >>> C = MatrixSymbol('C', m, n)
475
+ >>> D = MatrixSymbol('D', m, m)
476
+ >>> X = BlockMatrix([[A, B], [C, D]])
477
+ >>> L, U = X.LUdecomposition()
478
+ >>> block_collapse(L*U)
479
+ Matrix([
480
+ [A, B],
481
+ [C, D]])
482
+
483
+ Raises
484
+ ======
485
+
486
+ ShapeError
487
+ If the block matrix is not a 2x2 matrix
488
+
489
+ NonInvertibleMatrixError
490
+ If the matrix "A" is non-invertible
491
+
492
+ See Also
493
+ ========
494
+ sympy.matrices.expressions.blockmatrix.BlockMatrix.UDLdecomposition
495
+ sympy.matrices.expressions.blockmatrix.BlockMatrix.LDUdecomposition
496
+ """
497
+ if self.blockshape == (2,2):
498
+ [[A, B],
499
+ [C, D]] = self.blocks.tolist()
500
+ try:
501
+ A = A**S.Half
502
+ AI = A.I
503
+ except NonInvertibleMatrixError:
504
+ raise NonInvertibleMatrixError('Block LU decomposition cannot be calculated when\
505
+ "A" is singular')
506
+ Z = ZeroMatrix(*B.shape)
507
+ Q = self.schur()**S.Half
508
+ L = BlockMatrix([[A, Z], [C*AI, Q]])
509
+ U = BlockMatrix([[A, AI*B],[Z.T, Q]])
510
+ return L, U
511
+ else:
512
+ raise ShapeError("Block LU decomposition is supported only for 2x2 block matrices")
513
+
514
+ def _entry(self, i, j, **kwargs):
515
+ # Find row entry
516
+ orig_i, orig_j = i, j
517
+ for row_block, numrows in enumerate(self.rowblocksizes):
518
+ cmp = i < numrows
519
+ if cmp == True:
520
+ break
521
+ elif cmp == False:
522
+ i -= numrows
523
+ elif row_block < self.blockshape[0] - 1:
524
+ # Can't tell which block and it's not the last one, return unevaluated
525
+ return MatrixElement(self, orig_i, orig_j)
526
+ for col_block, numcols in enumerate(self.colblocksizes):
527
+ cmp = j < numcols
528
+ if cmp == True:
529
+ break
530
+ elif cmp == False:
531
+ j -= numcols
532
+ elif col_block < self.blockshape[1] - 1:
533
+ return MatrixElement(self, orig_i, orig_j)
534
+ return self.blocks[row_block, col_block][i, j]
535
+
536
+ @property
537
+ def is_Identity(self):
538
+ if self.blockshape[0] != self.blockshape[1]:
539
+ return False
540
+ for i in range(self.blockshape[0]):
541
+ for j in range(self.blockshape[1]):
542
+ if i==j and not self.blocks[i, j].is_Identity:
543
+ return False
544
+ if i!=j and not self.blocks[i, j].is_ZeroMatrix:
545
+ return False
546
+ return True
547
+
548
+ @property
549
+ def is_structurally_symmetric(self):
550
+ return self.rowblocksizes == self.colblocksizes
551
+
552
+ def equals(self, other):
553
+ if self == other:
554
+ return True
555
+ if (isinstance(other, BlockMatrix) and self.blocks == other.blocks):
556
+ return True
557
+ return super().equals(other)
558
+
559
+
560
+ class BlockDiagMatrix(BlockMatrix):
561
+ """A sparse matrix with block matrices along its diagonals
562
+
563
+ Examples
564
+ ========
565
+
566
+ >>> from sympy import MatrixSymbol, BlockDiagMatrix, symbols
567
+ >>> n, m, l = symbols('n m l')
568
+ >>> X = MatrixSymbol('X', n, n)
569
+ >>> Y = MatrixSymbol('Y', m, m)
570
+ >>> BlockDiagMatrix(X, Y)
571
+ Matrix([
572
+ [X, 0],
573
+ [0, Y]])
574
+
575
+ Notes
576
+ =====
577
+
578
+ If you want to get the individual diagonal blocks, use
579
+ :meth:`get_diag_blocks`.
580
+
581
+ See Also
582
+ ========
583
+
584
+ sympy.matrices.dense.diag
585
+ """
586
+ def __new__(cls, *mats):
587
+ return Basic.__new__(BlockDiagMatrix, *[_sympify(m) for m in mats])
588
+
589
+ @property
590
+ def diag(self):
591
+ return self.args
592
+
593
+ @property
594
+ def blocks(self):
595
+ from sympy.matrices.immutable import ImmutableDenseMatrix
596
+ mats = self.args
597
+ data = [[mats[i] if i == j else ZeroMatrix(mats[i].rows, mats[j].cols)
598
+ for j in range(len(mats))]
599
+ for i in range(len(mats))]
600
+ return ImmutableDenseMatrix(data, evaluate=False)
601
+
602
+ @property
603
+ def shape(self):
604
+ return (sum(block.rows for block in self.args),
605
+ sum(block.cols for block in self.args))
606
+
607
+ @property
608
+ def blockshape(self):
609
+ n = len(self.args)
610
+ return (n, n)
611
+
612
+ @property
613
+ def rowblocksizes(self):
614
+ return [block.rows for block in self.args]
615
+
616
+ @property
617
+ def colblocksizes(self):
618
+ return [block.cols for block in self.args]
619
+
620
+ def _all_square_blocks(self):
621
+ """Returns true if all blocks are square"""
622
+ return all(mat.is_square for mat in self.args)
623
+
624
+ def _eval_determinant(self):
625
+ if self._all_square_blocks():
626
+ return Mul(*[det(mat) for mat in self.args])
627
+ # At least one block is non-square. Since the entire matrix must be square we know there must
628
+ # be at least two blocks in this matrix, in which case the entire matrix is necessarily rank-deficient
629
+ return S.Zero
630
+
631
+ def _eval_inverse(self, expand='ignored'):
632
+ if self._all_square_blocks():
633
+ return BlockDiagMatrix(*[mat.inverse() for mat in self.args])
634
+ # See comment in _eval_determinant()
635
+ raise NonInvertibleMatrixError('Matrix det == 0; not invertible.')
636
+
637
+ def _eval_transpose(self):
638
+ return BlockDiagMatrix(*[mat.transpose() for mat in self.args])
639
+
640
+ def _blockmul(self, other):
641
+ if (isinstance(other, BlockDiagMatrix) and
642
+ self.colblocksizes == other.rowblocksizes):
643
+ return BlockDiagMatrix(*[a*b for a, b in zip(self.args, other.args)])
644
+ else:
645
+ return BlockMatrix._blockmul(self, other)
646
+
647
+ def _blockadd(self, other):
648
+ if (isinstance(other, BlockDiagMatrix) and
649
+ self.blockshape == other.blockshape and
650
+ self.rowblocksizes == other.rowblocksizes and
651
+ self.colblocksizes == other.colblocksizes):
652
+ return BlockDiagMatrix(*[a + b for a, b in zip(self.args, other.args)])
653
+ else:
654
+ return BlockMatrix._blockadd(self, other)
655
+
656
+ def get_diag_blocks(self):
657
+ """Return the list of diagonal blocks of the matrix.
658
+
659
+ Examples
660
+ ========
661
+
662
+ >>> from sympy import BlockDiagMatrix, Matrix
663
+
664
+ >>> A = Matrix([[1, 2], [3, 4]])
665
+ >>> B = Matrix([[5, 6], [7, 8]])
666
+ >>> M = BlockDiagMatrix(A, B)
667
+
668
+ How to get diagonal blocks from the block diagonal matrix:
669
+
670
+ >>> diag_blocks = M.get_diag_blocks()
671
+ >>> diag_blocks[0]
672
+ Matrix([
673
+ [1, 2],
674
+ [3, 4]])
675
+ >>> diag_blocks[1]
676
+ Matrix([
677
+ [5, 6],
678
+ [7, 8]])
679
+ """
680
+ return self.args
681
+
682
+
683
+ def block_collapse(expr):
684
+ """Evaluates a block matrix expression
685
+
686
+ >>> from sympy import MatrixSymbol, BlockMatrix, symbols, Identity, ZeroMatrix, block_collapse
687
+ >>> n,m,l = symbols('n m l')
688
+ >>> X = MatrixSymbol('X', n, n)
689
+ >>> Y = MatrixSymbol('Y', m, m)
690
+ >>> Z = MatrixSymbol('Z', n, m)
691
+ >>> B = BlockMatrix([[X, Z], [ZeroMatrix(m, n), Y]])
692
+ >>> print(B)
693
+ Matrix([
694
+ [X, Z],
695
+ [0, Y]])
696
+
697
+ >>> C = BlockMatrix([[Identity(n), Z]])
698
+ >>> print(C)
699
+ Matrix([[I, Z]])
700
+
701
+ >>> print(block_collapse(C*B))
702
+ Matrix([[X, Z + Z*Y]])
703
+ """
704
+ from sympy.strategies.util import expr_fns
705
+
706
+ hasbm = lambda expr: isinstance(expr, MatrixExpr) and expr.has(BlockMatrix)
707
+
708
+ conditioned_rl = condition(
709
+ hasbm,
710
+ typed(
711
+ {MatAdd: do_one(bc_matadd, bc_block_plus_ident),
712
+ MatMul: do_one(bc_matmul, bc_dist),
713
+ MatPow: bc_matmul,
714
+ Transpose: bc_transpose,
715
+ Inverse: bc_inverse,
716
+ BlockMatrix: do_one(bc_unpack, deblock)}
717
+ )
718
+ )
719
+
720
+ rule = exhaust(
721
+ bottom_up(
722
+ exhaust(conditioned_rl),
723
+ fns=expr_fns
724
+ )
725
+ )
726
+
727
+ result = rule(expr)
728
+ doit = getattr(result, 'doit', None)
729
+ if doit is not None:
730
+ return doit()
731
+ else:
732
+ return result
733
+
734
+ def bc_unpack(expr):
735
+ if expr.blockshape == (1, 1):
736
+ return expr.blocks[0, 0]
737
+ return expr
738
+
739
+ def bc_matadd(expr):
740
+ args = sift(expr.args, lambda M: isinstance(M, BlockMatrix))
741
+ blocks = args[True]
742
+ if not blocks:
743
+ return expr
744
+
745
+ nonblocks = args[False]
746
+ block = blocks[0]
747
+ for b in blocks[1:]:
748
+ block = block._blockadd(b)
749
+ if nonblocks:
750
+ return MatAdd(*nonblocks) + block
751
+ else:
752
+ return block
753
+
754
+ def bc_block_plus_ident(expr):
755
+ idents = [arg for arg in expr.args if arg.is_Identity]
756
+ if not idents:
757
+ return expr
758
+
759
+ blocks = [arg for arg in expr.args if isinstance(arg, BlockMatrix)]
760
+ if (blocks and all(b.structurally_equal(blocks[0]) for b in blocks)
761
+ and blocks[0].is_structurally_symmetric):
762
+ block_id = BlockDiagMatrix(*[Identity(k)
763
+ for k in blocks[0].rowblocksizes])
764
+ rest = [arg for arg in expr.args if not arg.is_Identity and not isinstance(arg, BlockMatrix)]
765
+ return MatAdd(block_id * len(idents), *blocks, *rest).doit()
766
+
767
+ return expr
768
+
769
+ def bc_dist(expr):
770
+ """ Turn a*[X, Y] into [a*X, a*Y] """
771
+ factor, mat = expr.as_coeff_mmul()
772
+ if factor == 1:
773
+ return expr
774
+
775
+ unpacked = unpack(mat)
776
+
777
+ if isinstance(unpacked, BlockDiagMatrix):
778
+ B = unpacked.diag
779
+ new_B = [factor * mat for mat in B]
780
+ return BlockDiagMatrix(*new_B)
781
+ elif isinstance(unpacked, BlockMatrix):
782
+ B = unpacked.blocks
783
+ new_B = [
784
+ [factor * B[i, j] for j in range(B.cols)] for i in range(B.rows)]
785
+ return BlockMatrix(new_B)
786
+ return expr
787
+
788
+
789
+ def bc_matmul(expr):
790
+ if isinstance(expr, MatPow):
791
+ if expr.args[1].is_Integer and expr.args[1] > 0:
792
+ factor, matrices = 1, [expr.args[0]]*expr.args[1]
793
+ else:
794
+ return expr
795
+ else:
796
+ factor, matrices = expr.as_coeff_matrices()
797
+
798
+ i = 0
799
+ while (i+1 < len(matrices)):
800
+ A, B = matrices[i:i+2]
801
+ if isinstance(A, BlockMatrix) and isinstance(B, BlockMatrix):
802
+ matrices[i] = A._blockmul(B)
803
+ matrices.pop(i+1)
804
+ elif isinstance(A, BlockMatrix):
805
+ matrices[i] = A._blockmul(BlockMatrix([[B]]))
806
+ matrices.pop(i+1)
807
+ elif isinstance(B, BlockMatrix):
808
+ matrices[i] = BlockMatrix([[A]])._blockmul(B)
809
+ matrices.pop(i+1)
810
+ else:
811
+ i+=1
812
+ return MatMul(factor, *matrices).doit()
813
+
814
+ def bc_transpose(expr):
815
+ collapse = block_collapse(expr.arg)
816
+ return collapse._eval_transpose()
817
+
818
+
819
+ def bc_inverse(expr):
820
+ if isinstance(expr.arg, BlockDiagMatrix):
821
+ return expr.inverse()
822
+
823
+ expr2 = blockinverse_1x1(expr)
824
+ if expr != expr2:
825
+ return expr2
826
+ return blockinverse_2x2(Inverse(reblock_2x2(expr.arg)))
827
+
828
+ def blockinverse_1x1(expr):
829
+ if isinstance(expr.arg, BlockMatrix) and expr.arg.blockshape == (1, 1):
830
+ mat = Matrix([[expr.arg.blocks[0].inverse()]])
831
+ return BlockMatrix(mat)
832
+ return expr
833
+
834
+
835
+ def blockinverse_2x2(expr):
836
+ if isinstance(expr.arg, BlockMatrix) and expr.arg.blockshape == (2, 2):
837
+ # See: Inverses of 2x2 Block Matrices, Tzon-Tzer Lu and Sheng-Hua Shiou
838
+ [[A, B],
839
+ [C, D]] = expr.arg.blocks.tolist()
840
+
841
+ formula = _choose_2x2_inversion_formula(A, B, C, D)
842
+ if formula != None:
843
+ MI = expr.arg.schur(formula).I
844
+ if formula == 'A':
845
+ AI = A.I
846
+ return BlockMatrix([[AI + AI * B * MI * C * AI, -AI * B * MI], [-MI * C * AI, MI]])
847
+ if formula == 'B':
848
+ BI = B.I
849
+ return BlockMatrix([[-MI * D * BI, MI], [BI + BI * A * MI * D * BI, -BI * A * MI]])
850
+ if formula == 'C':
851
+ CI = C.I
852
+ return BlockMatrix([[-CI * D * MI, CI + CI * D * MI * A * CI], [MI, -MI * A * CI]])
853
+ if formula == 'D':
854
+ DI = D.I
855
+ return BlockMatrix([[MI, -MI * B * DI], [-DI * C * MI, DI + DI * C * MI * B * DI]])
856
+
857
+ return expr
858
+
859
+
860
+ def _choose_2x2_inversion_formula(A, B, C, D):
861
+ """
862
+ Assuming [[A, B], [C, D]] would form a valid square block matrix, find
863
+ which of the classical 2x2 block matrix inversion formulas would be
864
+ best suited.
865
+
866
+ Returns 'A', 'B', 'C', 'D' to represent the algorithm involving inversion
867
+ of the given argument or None if the matrix cannot be inverted using
868
+ any of those formulas.
869
+ """
870
+ # Try to find a known invertible matrix. Note that the Schur complement
871
+ # is currently not being considered for this
872
+ A_inv = ask(Q.invertible(A))
873
+ if A_inv == True:
874
+ return 'A'
875
+ B_inv = ask(Q.invertible(B))
876
+ if B_inv == True:
877
+ return 'B'
878
+ C_inv = ask(Q.invertible(C))
879
+ if C_inv == True:
880
+ return 'C'
881
+ D_inv = ask(Q.invertible(D))
882
+ if D_inv == True:
883
+ return 'D'
884
+ # Otherwise try to find a matrix that isn't known to be non-invertible
885
+ if A_inv != False:
886
+ return 'A'
887
+ if B_inv != False:
888
+ return 'B'
889
+ if C_inv != False:
890
+ return 'C'
891
+ if D_inv != False:
892
+ return 'D'
893
+ return None
894
+
895
+
896
+ def deblock(B):
897
+ """ Flatten a BlockMatrix of BlockMatrices """
898
+ if not isinstance(B, BlockMatrix) or not B.blocks.has(BlockMatrix):
899
+ return B
900
+ wrap = lambda x: x if isinstance(x, BlockMatrix) else BlockMatrix([[x]])
901
+ bb = B.blocks.applyfunc(wrap) # everything is a block
902
+
903
+ try:
904
+ MM = Matrix(0, sum(bb[0, i].blocks.shape[1] for i in range(bb.shape[1])), [])
905
+ for row in range(0, bb.shape[0]):
906
+ M = Matrix(bb[row, 0].blocks)
907
+ for col in range(1, bb.shape[1]):
908
+ M = M.row_join(bb[row, col].blocks)
909
+ MM = MM.col_join(M)
910
+
911
+ return BlockMatrix(MM)
912
+ except ShapeError:
913
+ return B
914
+
915
+
916
+ def reblock_2x2(expr):
917
+ """
918
+ Reblock a BlockMatrix so that it has 2x2 blocks of block matrices. If
919
+ possible in such a way that the matrix continues to be invertible using the
920
+ classical 2x2 block inversion formulas.
921
+ """
922
+ if not isinstance(expr, BlockMatrix) or not all(d > 2 for d in expr.blockshape):
923
+ return expr
924
+
925
+ BM = BlockMatrix # for brevity's sake
926
+ rowblocks, colblocks = expr.blockshape
927
+ blocks = expr.blocks
928
+ for i in range(1, rowblocks):
929
+ for j in range(1, colblocks):
930
+ # try to split rows at i and cols at j
931
+ A = bc_unpack(BM(blocks[:i, :j]))
932
+ B = bc_unpack(BM(blocks[:i, j:]))
933
+ C = bc_unpack(BM(blocks[i:, :j]))
934
+ D = bc_unpack(BM(blocks[i:, j:]))
935
+
936
+ formula = _choose_2x2_inversion_formula(A, B, C, D)
937
+ if formula is not None:
938
+ return BlockMatrix([[A, B], [C, D]])
939
+
940
+ # else: nothing worked, just split upper left corner
941
+ return BM([[blocks[0, 0], BM(blocks[0, 1:])],
942
+ [BM(blocks[1:, 0]), BM(blocks[1:, 1:])]])
943
+
944
+
945
+ def bounds(sizes):
946
+ """ Convert sequence of numbers into pairs of low-high pairs
947
+
948
+ >>> from sympy.matrices.expressions.blockmatrix import bounds
949
+ >>> bounds((1, 10, 50))
950
+ [(0, 1), (1, 11), (11, 61)]
951
+ """
952
+ low = 0
953
+ rv = []
954
+ for size in sizes:
955
+ rv.append((low, low + size))
956
+ low += size
957
+ return rv
958
+
959
+ def blockcut(expr, rowsizes, colsizes):
960
+ """ Cut a matrix expression into Blocks
961
+
962
+ >>> from sympy import ImmutableMatrix, blockcut
963
+ >>> M = ImmutableMatrix(4, 4, range(16))
964
+ >>> B = blockcut(M, (1, 3), (1, 3))
965
+ >>> type(B).__name__
966
+ 'BlockMatrix'
967
+ >>> ImmutableMatrix(B.blocks[0, 1])
968
+ Matrix([[1, 2, 3]])
969
+ """
970
+
971
+ rowbounds = bounds(rowsizes)
972
+ colbounds = bounds(colsizes)
973
+ return BlockMatrix([[MatrixSlice(expr, rowbound, colbound)
974
+ for colbound in colbounds]
975
+ for rowbound in rowbounds])
miniconda3/envs/ladir/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])
miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/matrices/expressions/determinant.py ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.exceptions import NonSquareMatrixError
6
+ from sympy.matrices.matrixbase import MatrixBase
7
+
8
+
9
+ class Determinant(Expr):
10
+ """Matrix Determinant
11
+
12
+ Represents the determinant of a matrix expression.
13
+
14
+ Examples
15
+ ========
16
+
17
+ >>> from sympy import MatrixSymbol, Determinant, eye
18
+ >>> A = MatrixSymbol('A', 3, 3)
19
+ >>> Determinant(A)
20
+ Determinant(A)
21
+ >>> Determinant(eye(3)).doit()
22
+ 1
23
+ """
24
+ is_commutative = True
25
+
26
+ def __new__(cls, mat):
27
+ mat = sympify(mat)
28
+ if not mat.is_Matrix:
29
+ raise TypeError("Input to Determinant, %s, not a matrix" % str(mat))
30
+
31
+ if mat.is_square is False:
32
+ raise NonSquareMatrixError("Det of a non-square matrix")
33
+
34
+ return Basic.__new__(cls, mat)
35
+
36
+ @property
37
+ def arg(self):
38
+ return self.args[0]
39
+
40
+ @property
41
+ def kind(self):
42
+ return self.arg.kind.element_kind
43
+
44
+ def doit(self, **hints):
45
+ arg = self.arg
46
+ if hints.get('deep', True):
47
+ arg = arg.doit(**hints)
48
+
49
+ result = arg._eval_determinant()
50
+ if result is not None:
51
+ return result
52
+
53
+ return self
54
+
55
+
56
+ def det(matexpr):
57
+ """ Matrix Determinant
58
+
59
+ Examples
60
+ ========
61
+
62
+ >>> from sympy import MatrixSymbol, det, eye
63
+ >>> A = MatrixSymbol('A', 3, 3)
64
+ >>> det(A)
65
+ Determinant(A)
66
+ >>> det(eye(3))
67
+ 1
68
+ """
69
+
70
+ return Determinant(matexpr).doit()
71
+
72
+ class Permanent(Expr):
73
+ """Matrix Permanent
74
+
75
+ Represents the permanent of a matrix expression.
76
+
77
+ Examples
78
+ ========
79
+
80
+ >>> from sympy import MatrixSymbol, Permanent, ones
81
+ >>> A = MatrixSymbol('A', 3, 3)
82
+ >>> Permanent(A)
83
+ Permanent(A)
84
+ >>> Permanent(ones(3, 3)).doit()
85
+ 6
86
+ """
87
+
88
+ def __new__(cls, mat):
89
+ mat = sympify(mat)
90
+ if not mat.is_Matrix:
91
+ raise TypeError("Input to Permanent, %s, not a matrix" % str(mat))
92
+
93
+ return Basic.__new__(cls, mat)
94
+
95
+ @property
96
+ def arg(self):
97
+ return self.args[0]
98
+
99
+ def doit(self, expand=False, **hints):
100
+ if isinstance(self.arg, MatrixBase):
101
+ return self.arg.per()
102
+ else:
103
+ return self
104
+
105
+ def per(matexpr):
106
+ """ Matrix Permanent
107
+
108
+ Examples
109
+ ========
110
+
111
+ >>> from sympy import MatrixSymbol, Matrix, per, ones
112
+ >>> A = MatrixSymbol('A', 3, 3)
113
+ >>> per(A)
114
+ Permanent(A)
115
+ >>> per(ones(5, 5))
116
+ 120
117
+ >>> M = Matrix([1, 2, 5])
118
+ >>> per(M)
119
+ 8
120
+ """
121
+
122
+ return Permanent(matexpr).doit()
123
+
124
+ from sympy.assumptions.ask import ask, Q
125
+ from sympy.assumptions.refine import handlers_dict
126
+
127
+
128
+ def refine_Determinant(expr, assumptions):
129
+ """
130
+ >>> from sympy import MatrixSymbol, Q, assuming, refine, det
131
+ >>> X = MatrixSymbol('X', 2, 2)
132
+ >>> det(X)
133
+ Determinant(X)
134
+ >>> with assuming(Q.orthogonal(X)):
135
+ ... print(refine(det(X)))
136
+ 1
137
+ """
138
+ if ask(Q.orthogonal(expr.arg), assumptions):
139
+ return S.One
140
+ elif ask(Q.singular(expr.arg), assumptions):
141
+ return S.Zero
142
+ elif ask(Q.unit_triangular(expr.arg), assumptions):
143
+ return S.One
144
+
145
+ return expr
146
+
147
+
148
+ handlers_dict['Determinant'] = refine_Determinant
miniconda3/envs/ladir/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.matrixbase 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()
miniconda3/envs/ladir/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]
miniconda3/envs/ladir/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)
miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/matrices/expressions/fourier.py ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.sympify import _sympify
2
+ from sympy.matrices.expressions import MatrixExpr
3
+ from sympy.core.numbers import I
4
+ from sympy.core.singleton import S
5
+ from sympy.functions.elementary.exponential import exp
6
+ from sympy.functions.elementary.miscellaneous import sqrt
7
+
8
+
9
+ class DFT(MatrixExpr):
10
+ r"""
11
+ Returns a discrete Fourier transform matrix. The matrix is scaled
12
+ with :math:`\frac{1}{\sqrt{n}}` so that it is unitary.
13
+
14
+ Parameters
15
+ ==========
16
+
17
+ n : integer or Symbol
18
+ Size of the transform.
19
+
20
+ Examples
21
+ ========
22
+
23
+ >>> from sympy.abc import n
24
+ >>> from sympy.matrices.expressions.fourier import DFT
25
+ >>> DFT(3)
26
+ DFT(3)
27
+ >>> DFT(3).as_explicit()
28
+ Matrix([
29
+ [sqrt(3)/3, sqrt(3)/3, sqrt(3)/3],
30
+ [sqrt(3)/3, sqrt(3)*exp(-2*I*pi/3)/3, sqrt(3)*exp(2*I*pi/3)/3],
31
+ [sqrt(3)/3, sqrt(3)*exp(2*I*pi/3)/3, sqrt(3)*exp(-2*I*pi/3)/3]])
32
+ >>> DFT(n).shape
33
+ (n, n)
34
+
35
+ References
36
+ ==========
37
+
38
+ .. [1] https://en.wikipedia.org/wiki/DFT_matrix
39
+
40
+ """
41
+
42
+ def __new__(cls, n):
43
+ n = _sympify(n)
44
+ cls._check_dim(n)
45
+
46
+ obj = super().__new__(cls, n)
47
+ return obj
48
+
49
+ n = property(lambda self: self.args[0]) # type: ignore
50
+ shape = property(lambda self: (self.n, self.n)) # type: ignore
51
+
52
+ def _entry(self, i, j, **kwargs):
53
+ w = exp(-2*S.Pi*I/self.n)
54
+ return w**(i*j) / sqrt(self.n)
55
+
56
+ def _eval_inverse(self):
57
+ return IDFT(self.n)
58
+
59
+
60
+ class IDFT(DFT):
61
+ r"""
62
+ Returns an inverse discrete Fourier transform matrix. The matrix is scaled
63
+ with :math:`\frac{1}{\sqrt{n}}` so that it is unitary.
64
+
65
+ Parameters
66
+ ==========
67
+
68
+ n : integer or Symbol
69
+ Size of the transform
70
+
71
+ Examples
72
+ ========
73
+
74
+ >>> from sympy.matrices.expressions.fourier import DFT, IDFT
75
+ >>> IDFT(3)
76
+ IDFT(3)
77
+ >>> IDFT(4)*DFT(4)
78
+ I
79
+
80
+ See Also
81
+ ========
82
+
83
+ DFT
84
+
85
+ """
86
+ def _entry(self, i, j, **kwargs):
87
+ w = exp(-2*S.Pi*I/self.n)
88
+ return w**(-i*j) / sqrt(self.n)
89
+
90
+ def _eval_inverse(self):
91
+ return DFT(self.n)
miniconda3/envs/ladir/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)))
miniconda3/envs/ladir/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.matrixbase 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
miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/matrices/expressions/inverse.py ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.sympify import _sympify
2
+ from sympy.core import S, Basic
3
+
4
+ from sympy.matrices.exceptions 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_transpose(self):
58
+ return Inverse(self.arg.transpose())
59
+
60
+ def _eval_adjoint(self):
61
+ return Inverse(self.arg.adjoint())
62
+
63
+ def _eval_conjugate(self):
64
+ return Inverse(self.arg.conjugate())
65
+
66
+ def _eval_determinant(self):
67
+ from sympy.matrices.expressions.determinant import det
68
+ return 1/det(self.arg)
69
+
70
+ def doit(self, **hints):
71
+ if 'inv_expand' in hints and hints['inv_expand'] == False:
72
+ return self
73
+
74
+ arg = self.arg
75
+ if hints.get('deep', True):
76
+ arg = arg.doit(**hints)
77
+
78
+ return arg.inverse()
79
+
80
+ def _eval_derivative_matrix_lines(self, x):
81
+ arg = self.args[0]
82
+ lines = arg._eval_derivative_matrix_lines(x)
83
+ for line in lines:
84
+ line.first_pointer *= -self.T
85
+ line.second_pointer *= self
86
+ return lines
87
+
88
+
89
+ from sympy.assumptions.ask import ask, Q
90
+ from sympy.assumptions.refine import handlers_dict
91
+
92
+
93
+ def refine_Inverse(expr, assumptions):
94
+ """
95
+ >>> from sympy import MatrixSymbol, Q, assuming, refine
96
+ >>> X = MatrixSymbol('X', 2, 2)
97
+ >>> X.I
98
+ X**(-1)
99
+ >>> with assuming(Q.orthogonal(X)):
100
+ ... print(refine(X.I))
101
+ X.T
102
+ """
103
+ if ask(Q.orthogonal(expr), assumptions):
104
+ return expr.arg.T
105
+ elif ask(Q.unitary(expr), assumptions):
106
+ return expr.arg.conjugate()
107
+ elif ask(Q.singular(expr), assumptions):
108
+ raise ValueError("Inverse of singular matrix %s" % expr.arg)
109
+
110
+ return expr
111
+
112
+ handlers_dict['Inverse'] = refine_Inverse
miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/matrices/expressions/kronecker.py ADDED
@@ -0,0 +1,434 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Implementation of the Kronecker product"""
2
+ from functools import reduce
3
+ from math import prod
4
+
5
+ from sympy.core import Mul, sympify
6
+ from sympy.functions import adjoint
7
+ from sympy.matrices.exceptions import ShapeError
8
+ from sympy.matrices.expressions.matexpr import MatrixExpr
9
+ from sympy.matrices.expressions.transpose import transpose
10
+ from sympy.matrices.expressions.special import Identity
11
+ from sympy.matrices.matrixbase import MatrixBase
12
+ from sympy.strategies import (
13
+ canon, condition, distribute, do_one, exhaust, flatten, typed, unpack)
14
+ from sympy.strategies.traverse import bottom_up
15
+ from sympy.utilities import sift
16
+
17
+ from .matadd import MatAdd
18
+ from .matmul import MatMul
19
+ from .matpow import MatPow
20
+
21
+
22
+ def kronecker_product(*matrices):
23
+ """
24
+ The Kronecker product of two or more arguments.
25
+
26
+ This computes the explicit Kronecker product for subclasses of
27
+ ``MatrixBase`` i.e. explicit matrices. Otherwise, a symbolic
28
+ ``KroneckerProduct`` object is returned.
29
+
30
+
31
+ Examples
32
+ ========
33
+
34
+ For ``MatrixSymbol`` arguments a ``KroneckerProduct`` object is returned.
35
+ Elements of this matrix can be obtained by indexing, or for MatrixSymbols
36
+ with known dimension the explicit matrix can be obtained with
37
+ ``.as_explicit()``
38
+
39
+ >>> from sympy import kronecker_product, MatrixSymbol
40
+ >>> A = MatrixSymbol('A', 2, 2)
41
+ >>> B = MatrixSymbol('B', 2, 2)
42
+ >>> kronecker_product(A)
43
+ A
44
+ >>> kronecker_product(A, B)
45
+ KroneckerProduct(A, B)
46
+ >>> kronecker_product(A, B)[0, 1]
47
+ A[0, 0]*B[0, 1]
48
+ >>> kronecker_product(A, B).as_explicit()
49
+ Matrix([
50
+ [A[0, 0]*B[0, 0], A[0, 0]*B[0, 1], A[0, 1]*B[0, 0], A[0, 1]*B[0, 1]],
51
+ [A[0, 0]*B[1, 0], A[0, 0]*B[1, 1], A[0, 1]*B[1, 0], A[0, 1]*B[1, 1]],
52
+ [A[1, 0]*B[0, 0], A[1, 0]*B[0, 1], A[1, 1]*B[0, 0], A[1, 1]*B[0, 1]],
53
+ [A[1, 0]*B[1, 0], A[1, 0]*B[1, 1], A[1, 1]*B[1, 0], A[1, 1]*B[1, 1]]])
54
+
55
+ For explicit matrices the Kronecker product is returned as a Matrix
56
+
57
+ >>> from sympy import Matrix, kronecker_product
58
+ >>> sigma_x = Matrix([
59
+ ... [0, 1],
60
+ ... [1, 0]])
61
+ ...
62
+ >>> Isigma_y = Matrix([
63
+ ... [0, 1],
64
+ ... [-1, 0]])
65
+ ...
66
+ >>> kronecker_product(sigma_x, Isigma_y)
67
+ Matrix([
68
+ [ 0, 0, 0, 1],
69
+ [ 0, 0, -1, 0],
70
+ [ 0, 1, 0, 0],
71
+ [-1, 0, 0, 0]])
72
+
73
+ See Also
74
+ ========
75
+ KroneckerProduct
76
+
77
+ """
78
+ if not matrices:
79
+ raise TypeError("Empty Kronecker product is undefined")
80
+ if len(matrices) == 1:
81
+ return matrices[0]
82
+ else:
83
+ return KroneckerProduct(*matrices).doit()
84
+
85
+
86
+ class KroneckerProduct(MatrixExpr):
87
+ """
88
+ The Kronecker product of two or more arguments.
89
+
90
+ The Kronecker product is a non-commutative product of matrices.
91
+ Given two matrices of dimension (m, n) and (s, t) it produces a matrix
92
+ of dimension (m s, n t).
93
+
94
+ This is a symbolic object that simply stores its argument without
95
+ evaluating it. To actually compute the product, use the function
96
+ ``kronecker_product()`` or call the ``.doit()`` or ``.as_explicit()``
97
+ methods.
98
+
99
+ >>> from sympy import KroneckerProduct, MatrixSymbol
100
+ >>> A = MatrixSymbol('A', 5, 5)
101
+ >>> B = MatrixSymbol('B', 5, 5)
102
+ >>> isinstance(KroneckerProduct(A, B), KroneckerProduct)
103
+ True
104
+ """
105
+ is_KroneckerProduct = True
106
+
107
+ def __new__(cls, *args, check=True):
108
+ args = list(map(sympify, args))
109
+ if all(a.is_Identity for a in args):
110
+ ret = Identity(prod(a.rows for a in args))
111
+ if all(isinstance(a, MatrixBase) for a in args):
112
+ return ret.as_explicit()
113
+ else:
114
+ return ret
115
+
116
+ if check:
117
+ validate(*args)
118
+ return super().__new__(cls, *args)
119
+
120
+ @property
121
+ def shape(self):
122
+ rows, cols = self.args[0].shape
123
+ for mat in self.args[1:]:
124
+ rows *= mat.rows
125
+ cols *= mat.cols
126
+ return (rows, cols)
127
+
128
+ def _entry(self, i, j, **kwargs):
129
+ result = 1
130
+ for mat in reversed(self.args):
131
+ i, m = divmod(i, mat.rows)
132
+ j, n = divmod(j, mat.cols)
133
+ result *= mat[m, n]
134
+ return result
135
+
136
+ def _eval_adjoint(self):
137
+ return KroneckerProduct(*list(map(adjoint, self.args))).doit()
138
+
139
+ def _eval_conjugate(self):
140
+ return KroneckerProduct(*[a.conjugate() for a in self.args]).doit()
141
+
142
+ def _eval_transpose(self):
143
+ return KroneckerProduct(*list(map(transpose, self.args))).doit()
144
+
145
+ def _eval_trace(self):
146
+ from .trace import trace
147
+ return Mul(*[trace(a) for a in self.args])
148
+
149
+ def _eval_determinant(self):
150
+ from .determinant import det, Determinant
151
+ if not all(a.is_square for a in self.args):
152
+ return Determinant(self)
153
+
154
+ m = self.rows
155
+ return Mul(*[det(a)**(m/a.rows) for a in self.args])
156
+
157
+ def _eval_inverse(self):
158
+ try:
159
+ return KroneckerProduct(*[a.inverse() for a in self.args])
160
+ except ShapeError:
161
+ from sympy.matrices.expressions.inverse import Inverse
162
+ return Inverse(self)
163
+
164
+ def structurally_equal(self, other):
165
+ '''Determine whether two matrices have the same Kronecker product structure
166
+
167
+ Examples
168
+ ========
169
+
170
+ >>> from sympy import KroneckerProduct, MatrixSymbol, symbols
171
+ >>> m, n = symbols(r'm, n', integer=True)
172
+ >>> A = MatrixSymbol('A', m, m)
173
+ >>> B = MatrixSymbol('B', n, n)
174
+ >>> C = MatrixSymbol('C', m, m)
175
+ >>> D = MatrixSymbol('D', n, n)
176
+ >>> KroneckerProduct(A, B).structurally_equal(KroneckerProduct(C, D))
177
+ True
178
+ >>> KroneckerProduct(A, B).structurally_equal(KroneckerProduct(D, C))
179
+ False
180
+ >>> KroneckerProduct(A, B).structurally_equal(C)
181
+ False
182
+ '''
183
+ # Inspired by BlockMatrix
184
+ return (isinstance(other, KroneckerProduct)
185
+ and self.shape == other.shape
186
+ and len(self.args) == len(other.args)
187
+ and all(a.shape == b.shape for (a, b) in zip(self.args, other.args)))
188
+
189
+ def has_matching_shape(self, other):
190
+ '''Determine whether two matrices have the appropriate structure to bring matrix
191
+ multiplication inside the KroneckerProdut
192
+
193
+ Examples
194
+ ========
195
+ >>> from sympy import KroneckerProduct, MatrixSymbol, symbols
196
+ >>> m, n = symbols(r'm, n', integer=True)
197
+ >>> A = MatrixSymbol('A', m, n)
198
+ >>> B = MatrixSymbol('B', n, m)
199
+ >>> KroneckerProduct(A, B).has_matching_shape(KroneckerProduct(B, A))
200
+ True
201
+ >>> KroneckerProduct(A, B).has_matching_shape(KroneckerProduct(A, B))
202
+ False
203
+ >>> KroneckerProduct(A, B).has_matching_shape(A)
204
+ False
205
+ '''
206
+ return (isinstance(other, KroneckerProduct)
207
+ and self.cols == other.rows
208
+ and len(self.args) == len(other.args)
209
+ and all(a.cols == b.rows for (a, b) in zip(self.args, other.args)))
210
+
211
+ def _eval_expand_kroneckerproduct(self, **hints):
212
+ return flatten(canon(typed({KroneckerProduct: distribute(KroneckerProduct, MatAdd)}))(self))
213
+
214
+ def _kronecker_add(self, other):
215
+ if self.structurally_equal(other):
216
+ return self.__class__(*[a + b for (a, b) in zip(self.args, other.args)])
217
+ else:
218
+ return self + other
219
+
220
+ def _kronecker_mul(self, other):
221
+ if self.has_matching_shape(other):
222
+ return self.__class__(*[a*b for (a, b) in zip(self.args, other.args)])
223
+ else:
224
+ return self * other
225
+
226
+ def doit(self, **hints):
227
+ deep = hints.get('deep', True)
228
+ if deep:
229
+ args = [arg.doit(**hints) for arg in self.args]
230
+ else:
231
+ args = self.args
232
+ return canonicalize(KroneckerProduct(*args))
233
+
234
+
235
+ def validate(*args):
236
+ if not all(arg.is_Matrix for arg in args):
237
+ raise TypeError("Mix of Matrix and Scalar symbols")
238
+
239
+
240
+ # rules
241
+
242
+ def extract_commutative(kron):
243
+ c_part = []
244
+ nc_part = []
245
+ for arg in kron.args:
246
+ c, nc = arg.args_cnc()
247
+ c_part.extend(c)
248
+ nc_part.append(Mul._from_args(nc))
249
+
250
+ c_part = Mul(*c_part)
251
+ if c_part != 1:
252
+ return c_part*KroneckerProduct(*nc_part)
253
+ return kron
254
+
255
+
256
+ def matrix_kronecker_product(*matrices):
257
+ """Compute the Kronecker product of a sequence of SymPy Matrices.
258
+
259
+ This is the standard Kronecker product of matrices [1].
260
+
261
+ Parameters
262
+ ==========
263
+
264
+ matrices : tuple of MatrixBase instances
265
+ The matrices to take the Kronecker product of.
266
+
267
+ Returns
268
+ =======
269
+
270
+ matrix : MatrixBase
271
+ The Kronecker product matrix.
272
+
273
+ Examples
274
+ ========
275
+
276
+ >>> from sympy import Matrix
277
+ >>> from sympy.matrices.expressions.kronecker import (
278
+ ... matrix_kronecker_product)
279
+
280
+ >>> m1 = Matrix([[1,2],[3,4]])
281
+ >>> m2 = Matrix([[1,0],[0,1]])
282
+ >>> matrix_kronecker_product(m1, m2)
283
+ Matrix([
284
+ [1, 0, 2, 0],
285
+ [0, 1, 0, 2],
286
+ [3, 0, 4, 0],
287
+ [0, 3, 0, 4]])
288
+ >>> matrix_kronecker_product(m2, m1)
289
+ Matrix([
290
+ [1, 2, 0, 0],
291
+ [3, 4, 0, 0],
292
+ [0, 0, 1, 2],
293
+ [0, 0, 3, 4]])
294
+
295
+ References
296
+ ==========
297
+
298
+ .. [1] https://en.wikipedia.org/wiki/Kronecker_product
299
+ """
300
+ # Make sure we have a sequence of Matrices
301
+ if not all(isinstance(m, MatrixBase) for m in matrices):
302
+ raise TypeError(
303
+ 'Sequence of Matrices expected, got: %s' % repr(matrices)
304
+ )
305
+
306
+ # Pull out the first element in the product.
307
+ matrix_expansion = matrices[-1]
308
+ # Do the kronecker product working from right to left.
309
+ for mat in reversed(matrices[:-1]):
310
+ rows = mat.rows
311
+ cols = mat.cols
312
+ # Go through each row appending kronecker product to.
313
+ # running matrix_expansion.
314
+ for i in range(rows):
315
+ start = matrix_expansion*mat[i*cols]
316
+ # Go through each column joining each item
317
+ for j in range(cols - 1):
318
+ start = start.row_join(
319
+ matrix_expansion*mat[i*cols + j + 1]
320
+ )
321
+ # If this is the first element, make it the start of the
322
+ # new row.
323
+ if i == 0:
324
+ next = start
325
+ else:
326
+ next = next.col_join(start)
327
+ matrix_expansion = next
328
+
329
+ MatrixClass = max(matrices, key=lambda M: M._class_priority).__class__
330
+ if isinstance(matrix_expansion, MatrixClass):
331
+ return matrix_expansion
332
+ else:
333
+ return MatrixClass(matrix_expansion)
334
+
335
+
336
+ def explicit_kronecker_product(kron):
337
+ # Make sure we have a sequence of Matrices
338
+ if not all(isinstance(m, MatrixBase) for m in kron.args):
339
+ return kron
340
+
341
+ return matrix_kronecker_product(*kron.args)
342
+
343
+
344
+ rules = (unpack,
345
+ explicit_kronecker_product,
346
+ flatten,
347
+ extract_commutative)
348
+
349
+ canonicalize = exhaust(condition(lambda x: isinstance(x, KroneckerProduct),
350
+ do_one(*rules)))
351
+
352
+
353
+ def _kronecker_dims_key(expr):
354
+ if isinstance(expr, KroneckerProduct):
355
+ return tuple(a.shape for a in expr.args)
356
+ else:
357
+ return (0,)
358
+
359
+
360
+ def kronecker_mat_add(expr):
361
+ args = sift(expr.args, _kronecker_dims_key)
362
+ nonkrons = args.pop((0,), None)
363
+ if not args:
364
+ return expr
365
+
366
+ krons = [reduce(lambda x, y: x._kronecker_add(y), group)
367
+ for group in args.values()]
368
+
369
+ if not nonkrons:
370
+ return MatAdd(*krons)
371
+ else:
372
+ return MatAdd(*krons) + nonkrons
373
+
374
+
375
+ def kronecker_mat_mul(expr):
376
+ # modified from block matrix code
377
+ factor, matrices = expr.as_coeff_matrices()
378
+
379
+ i = 0
380
+ while i < len(matrices) - 1:
381
+ A, B = matrices[i:i+2]
382
+ if isinstance(A, KroneckerProduct) and isinstance(B, KroneckerProduct):
383
+ matrices[i] = A._kronecker_mul(B)
384
+ matrices.pop(i+1)
385
+ else:
386
+ i += 1
387
+
388
+ return factor*MatMul(*matrices)
389
+
390
+
391
+ def kronecker_mat_pow(expr):
392
+ if isinstance(expr.base, KroneckerProduct) and all(a.is_square for a in expr.base.args):
393
+ return KroneckerProduct(*[MatPow(a, expr.exp) for a in expr.base.args])
394
+ else:
395
+ return expr
396
+
397
+
398
+ def combine_kronecker(expr):
399
+ """Combine KronekeckerProduct with expression.
400
+
401
+ If possible write operations on KroneckerProducts of compatible shapes
402
+ as a single KroneckerProduct.
403
+
404
+ Examples
405
+ ========
406
+
407
+ >>> from sympy.matrices.expressions import combine_kronecker
408
+ >>> from sympy import MatrixSymbol, KroneckerProduct, symbols
409
+ >>> m, n = symbols(r'm, n', integer=True)
410
+ >>> A = MatrixSymbol('A', m, n)
411
+ >>> B = MatrixSymbol('B', n, m)
412
+ >>> combine_kronecker(KroneckerProduct(A, B)*KroneckerProduct(B, A))
413
+ KroneckerProduct(A*B, B*A)
414
+ >>> combine_kronecker(KroneckerProduct(A, B)+KroneckerProduct(B.T, A.T))
415
+ KroneckerProduct(A + B.T, B + A.T)
416
+ >>> C = MatrixSymbol('C', n, n)
417
+ >>> D = MatrixSymbol('D', m, m)
418
+ >>> combine_kronecker(KroneckerProduct(C, D)**m)
419
+ KroneckerProduct(C**m, D**m)
420
+ """
421
+ def haskron(expr):
422
+ return isinstance(expr, MatrixExpr) and expr.has(KroneckerProduct)
423
+
424
+ rule = exhaust(
425
+ bottom_up(exhaust(condition(haskron, typed(
426
+ {MatAdd: kronecker_mat_add,
427
+ MatMul: kronecker_mat_mul,
428
+ MatPow: kronecker_mat_pow})))))
429
+ result = rule(expr)
430
+ doit = getattr(result, 'doit', None)
431
+ if doit is not None:
432
+ return doit()
433
+ else:
434
+ return result
miniconda3/envs/ladir/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.matrixbase 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)))
miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/matrices/expressions/matexpr.py ADDED
@@ -0,0 +1,888 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.exceptions import NonSquareMatrixError
15
+ from sympy.matrices.kind import MatrixKind
16
+ from sympy.matrices.matrixbase import MatrixBase
17
+ from sympy.multipledispatch import dispatch
18
+ from sympy.utilities.misc import filldedent
19
+
20
+
21
+ def _sympifyit(arg, retval=None):
22
+ # This version of _sympifyit sympifies MutableMatrix objects
23
+ def deco(func):
24
+ @wraps(func)
25
+ def __sympifyit_wrapper(a, b):
26
+ try:
27
+ b = _sympify(b)
28
+ return func(a, b)
29
+ except SympifyError:
30
+ return retval
31
+
32
+ return __sympifyit_wrapper
33
+
34
+ return deco
35
+
36
+
37
+ class MatrixExpr(Expr):
38
+ """Superclass for Matrix Expressions
39
+
40
+ MatrixExprs represent abstract matrices, linear transformations represented
41
+ within a particular basis.
42
+
43
+ Examples
44
+ ========
45
+
46
+ >>> from sympy import MatrixSymbol
47
+ >>> A = MatrixSymbol('A', 3, 3)
48
+ >>> y = MatrixSymbol('y', 3, 1)
49
+ >>> x = (A.T*A).I * A * y
50
+
51
+ See Also
52
+ ========
53
+
54
+ MatrixSymbol, MatAdd, MatMul, Transpose, Inverse
55
+ """
56
+ __slots__: tuple[str, ...] = ()
57
+
58
+ # Should not be considered iterable by the
59
+ # sympy.utilities.iterables.iterable function. Subclass that actually are
60
+ # iterable (i.e., explicit matrices) should set this to True.
61
+ _iterable = False
62
+
63
+ _op_priority = 11.0
64
+
65
+ is_Matrix: bool = True
66
+ is_MatrixExpr: bool = True
67
+ is_Identity: FuzzyBool = None
68
+ is_Inverse = False
69
+ is_Transpose = False
70
+ is_ZeroMatrix = False
71
+ is_MatAdd = False
72
+ is_MatMul = False
73
+
74
+ is_commutative = False
75
+ is_number = False
76
+ is_symbol = False
77
+ is_scalar = False
78
+
79
+ kind: MatrixKind = MatrixKind()
80
+
81
+ def __new__(cls, *args, **kwargs):
82
+ args = map(_sympify, args)
83
+ return Basic.__new__(cls, *args, **kwargs)
84
+
85
+ # The following is adapted from the core Expr object
86
+
87
+ @property
88
+ def shape(self) -> tuple[Expr, Expr]:
89
+ raise NotImplementedError
90
+
91
+ @property
92
+ def _add_handler(self):
93
+ return MatAdd
94
+
95
+ @property
96
+ def _mul_handler(self):
97
+ return MatMul
98
+
99
+ def __neg__(self):
100
+ return MatMul(S.NegativeOne, self).doit()
101
+
102
+ def __abs__(self):
103
+ raise NotImplementedError
104
+
105
+ @_sympifyit('other', NotImplemented)
106
+ @call_highest_priority('__radd__')
107
+ def __add__(self, other):
108
+ return MatAdd(self, other).doit()
109
+
110
+ @_sympifyit('other', NotImplemented)
111
+ @call_highest_priority('__add__')
112
+ def __radd__(self, other):
113
+ return MatAdd(other, self).doit()
114
+
115
+ @_sympifyit('other', NotImplemented)
116
+ @call_highest_priority('__rsub__')
117
+ def __sub__(self, other):
118
+ return MatAdd(self, -other).doit()
119
+
120
+ @_sympifyit('other', NotImplemented)
121
+ @call_highest_priority('__sub__')
122
+ def __rsub__(self, other):
123
+ return MatAdd(other, -self).doit()
124
+
125
+ @_sympifyit('other', NotImplemented)
126
+ @call_highest_priority('__rmul__')
127
+ def __mul__(self, other):
128
+ return MatMul(self, other).doit()
129
+
130
+ @_sympifyit('other', NotImplemented)
131
+ @call_highest_priority('__rmul__')
132
+ def __matmul__(self, other):
133
+ return MatMul(self, other).doit()
134
+
135
+ @_sympifyit('other', NotImplemented)
136
+ @call_highest_priority('__mul__')
137
+ def __rmul__(self, other):
138
+ return MatMul(other, self).doit()
139
+
140
+ @_sympifyit('other', NotImplemented)
141
+ @call_highest_priority('__mul__')
142
+ def __rmatmul__(self, other):
143
+ return MatMul(other, self).doit()
144
+
145
+ @_sympifyit('other', NotImplemented)
146
+ @call_highest_priority('__rpow__')
147
+ def __pow__(self, other):
148
+ return MatPow(self, other).doit()
149
+
150
+ @_sympifyit('other', NotImplemented)
151
+ @call_highest_priority('__pow__')
152
+ def __rpow__(self, other):
153
+ raise NotImplementedError("Matrix Power not defined")
154
+
155
+ @_sympifyit('other', NotImplemented)
156
+ @call_highest_priority('__rtruediv__')
157
+ def __truediv__(self, other):
158
+ return self * other**S.NegativeOne
159
+
160
+ @_sympifyit('other', NotImplemented)
161
+ @call_highest_priority('__truediv__')
162
+ def __rtruediv__(self, other):
163
+ raise NotImplementedError()
164
+ #return MatMul(other, Pow(self, S.NegativeOne))
165
+
166
+ @property
167
+ def rows(self):
168
+ return self.shape[0]
169
+
170
+ @property
171
+ def cols(self):
172
+ return self.shape[1]
173
+
174
+ @property
175
+ def is_square(self) -> bool | None:
176
+ rows, cols = self.shape
177
+ if isinstance(rows, Integer) and isinstance(cols, Integer):
178
+ return rows == cols
179
+ if rows == cols:
180
+ return True
181
+ return None
182
+
183
+ def _eval_conjugate(self):
184
+ from sympy.matrices.expressions.adjoint import Adjoint
185
+ return Adjoint(Transpose(self))
186
+
187
+ def as_real_imag(self, deep=True, **hints):
188
+ return self._eval_as_real_imag()
189
+
190
+ def _eval_as_real_imag(self):
191
+ real = S.Half * (self + self._eval_conjugate())
192
+ im = (self - self._eval_conjugate())/(2*S.ImaginaryUnit)
193
+ return (real, im)
194
+
195
+ def _eval_inverse(self):
196
+ return Inverse(self)
197
+
198
+ def _eval_determinant(self):
199
+ return Determinant(self)
200
+
201
+ def _eval_transpose(self):
202
+ return Transpose(self)
203
+
204
+ def _eval_trace(self):
205
+ return None
206
+
207
+ def _eval_power(self, exp):
208
+ """
209
+ Override this in sub-classes to implement simplification of powers. The cases where the exponent
210
+ is -1, 0, 1 are already covered in MatPow.doit(), so implementations can exclude these cases.
211
+ """
212
+ return MatPow(self, exp)
213
+
214
+ def _eval_simplify(self, **kwargs):
215
+ if self.is_Atom:
216
+ return self
217
+ else:
218
+ from sympy.simplify import simplify
219
+ return self.func(*[simplify(x, **kwargs) for x in self.args])
220
+
221
+ def _eval_adjoint(self):
222
+ from sympy.matrices.expressions.adjoint import Adjoint
223
+ return Adjoint(self)
224
+
225
+ def _eval_derivative_n_times(self, x, n):
226
+ return Basic._eval_derivative_n_times(self, x, n)
227
+
228
+ def _eval_derivative(self, x):
229
+ # `x` is a scalar:
230
+ if self.has(x):
231
+ # See if there are other methods using it:
232
+ return super()._eval_derivative(x)
233
+ else:
234
+ return ZeroMatrix(*self.shape)
235
+
236
+ @classmethod
237
+ def _check_dim(cls, dim):
238
+ """Helper function to check invalid matrix dimensions"""
239
+ ok = not dim.is_Float and check_assumptions(
240
+ dim, integer=True, nonnegative=True)
241
+ if ok is False:
242
+ raise ValueError(
243
+ "The dimension specification {} should be "
244
+ "a nonnegative integer.".format(dim))
245
+
246
+
247
+ def _entry(self, i, j, **kwargs):
248
+ raise NotImplementedError(
249
+ "Indexing not implemented for %s" % self.__class__.__name__)
250
+
251
+ def adjoint(self):
252
+ return adjoint(self)
253
+
254
+ def as_coeff_Mul(self, rational=False):
255
+ """Efficiently extract the coefficient of a product."""
256
+ return S.One, self
257
+
258
+ def conjugate(self):
259
+ return conjugate(self)
260
+
261
+ def transpose(self):
262
+ from sympy.matrices.expressions.transpose import transpose
263
+ return transpose(self)
264
+
265
+ @property
266
+ def T(self):
267
+ '''Matrix transposition'''
268
+ return self.transpose()
269
+
270
+ def inverse(self):
271
+ if self.is_square is False:
272
+ raise NonSquareMatrixError('Inverse of non-square matrix')
273
+ return self._eval_inverse()
274
+
275
+ def inv(self):
276
+ return self.inverse()
277
+
278
+ def det(self):
279
+ from sympy.matrices.expressions.determinant import det
280
+ return det(self)
281
+
282
+ @property
283
+ def I(self):
284
+ return self.inverse()
285
+
286
+ def valid_index(self, i, j):
287
+ def is_valid(idx):
288
+ return isinstance(idx, (int, Integer, Symbol, Expr))
289
+ return (is_valid(i) and is_valid(j) and
290
+ (self.rows is None or
291
+ (i >= -self.rows) != False and (i < self.rows) != False) and
292
+ (j >= -self.cols) != False and (j < self.cols) != False)
293
+
294
+ def __getitem__(self, key):
295
+ if not isinstance(key, tuple) and isinstance(key, slice):
296
+ from sympy.matrices.expressions.slice import MatrixSlice
297
+ return MatrixSlice(self, key, (0, None, 1))
298
+ if isinstance(key, tuple) and len(key) == 2:
299
+ i, j = key
300
+ if isinstance(i, slice) or isinstance(j, slice):
301
+ from sympy.matrices.expressions.slice import MatrixSlice
302
+ return MatrixSlice(self, i, j)
303
+ i, j = _sympify(i), _sympify(j)
304
+ if self.valid_index(i, j) != False:
305
+ return self._entry(i, j)
306
+ else:
307
+ raise IndexError("Invalid indices (%s, %s)" % (i, j))
308
+ elif isinstance(key, (SYMPY_INTS, Integer)):
309
+ # row-wise decomposition of matrix
310
+ rows, cols = self.shape
311
+ # allow single indexing if number of columns is known
312
+ if not isinstance(cols, Integer):
313
+ raise IndexError(filldedent('''
314
+ Single indexing is only supported when the number
315
+ of columns is known.'''))
316
+ key = _sympify(key)
317
+ i = key // cols
318
+ j = key % cols
319
+ if self.valid_index(i, j) != False:
320
+ return self._entry(i, j)
321
+ else:
322
+ raise IndexError("Invalid index %s" % key)
323
+ elif isinstance(key, (Symbol, Expr)):
324
+ raise IndexError(filldedent('''
325
+ Only integers may be used when addressing the matrix
326
+ with a single index.'''))
327
+ raise IndexError("Invalid index, wanted %s[i,j]" % self)
328
+
329
+ def _is_shape_symbolic(self) -> bool:
330
+ return (not isinstance(self.rows, (SYMPY_INTS, Integer))
331
+ or not isinstance(self.cols, (SYMPY_INTS, Integer)))
332
+
333
+ def as_explicit(self):
334
+ """
335
+ Returns a dense Matrix with elements represented explicitly
336
+
337
+ Returns an object of type ImmutableDenseMatrix.
338
+
339
+ Examples
340
+ ========
341
+
342
+ >>> from sympy import Identity
343
+ >>> I = Identity(3)
344
+ >>> I
345
+ I
346
+ >>> I.as_explicit()
347
+ Matrix([
348
+ [1, 0, 0],
349
+ [0, 1, 0],
350
+ [0, 0, 1]])
351
+
352
+ See Also
353
+ ========
354
+ as_mutable: returns mutable Matrix type
355
+
356
+ """
357
+ if self._is_shape_symbolic():
358
+ raise ValueError(
359
+ 'Matrix with symbolic shape '
360
+ 'cannot be represented explicitly.')
361
+ from sympy.matrices.immutable import ImmutableDenseMatrix
362
+ return ImmutableDenseMatrix([[self[i, j]
363
+ for j in range(self.cols)]
364
+ for i in range(self.rows)])
365
+
366
+ def as_mutable(self):
367
+ """
368
+ Returns a dense, mutable matrix with elements represented explicitly
369
+
370
+ Examples
371
+ ========
372
+
373
+ >>> from sympy import Identity
374
+ >>> I = Identity(3)
375
+ >>> I
376
+ I
377
+ >>> I.shape
378
+ (3, 3)
379
+ >>> I.as_mutable()
380
+ Matrix([
381
+ [1, 0, 0],
382
+ [0, 1, 0],
383
+ [0, 0, 1]])
384
+
385
+ See Also
386
+ ========
387
+ as_explicit: returns ImmutableDenseMatrix
388
+ """
389
+ return self.as_explicit().as_mutable()
390
+
391
+ def __array__(self, dtype=object, copy=None):
392
+ if copy is not None and not copy:
393
+ raise TypeError("Cannot implement copy=False when converting Matrix to ndarray")
394
+ from numpy import empty
395
+ a = empty(self.shape, dtype=object)
396
+ for i in range(self.rows):
397
+ for j in range(self.cols):
398
+ a[i, j] = self[i, j]
399
+ return a
400
+
401
+ def equals(self, other):
402
+ """
403
+ Test elementwise equality between matrices, potentially of different
404
+ types
405
+
406
+ >>> from sympy import Identity, eye
407
+ >>> Identity(3).equals(eye(3))
408
+ True
409
+ """
410
+ return self.as_explicit().equals(other)
411
+
412
+ def canonicalize(self):
413
+ return self
414
+
415
+ def as_coeff_mmul(self):
416
+ return S.One, MatMul(self)
417
+
418
+ @staticmethod
419
+ def from_index_summation(expr, first_index=None, last_index=None, dimensions=None):
420
+ r"""
421
+ Parse expression of matrices with explicitly summed indices into a
422
+ matrix expression without indices, if possible.
423
+
424
+ This transformation expressed in mathematical notation:
425
+
426
+ `\sum_{j=0}^{N-1} A_{i,j} B_{j,k} \Longrightarrow \mathbf{A}\cdot \mathbf{B}`
427
+
428
+ Optional parameter ``first_index``: specify which free index to use as
429
+ the index starting the expression.
430
+
431
+ Examples
432
+ ========
433
+
434
+ >>> from sympy import MatrixSymbol, MatrixExpr, Sum
435
+ >>> from sympy.abc import i, j, k, l, N
436
+ >>> A = MatrixSymbol("A", N, N)
437
+ >>> B = MatrixSymbol("B", N, N)
438
+ >>> expr = Sum(A[i, j]*B[j, k], (j, 0, N-1))
439
+ >>> MatrixExpr.from_index_summation(expr)
440
+ A*B
441
+
442
+ Transposition is detected:
443
+
444
+ >>> expr = Sum(A[j, i]*B[j, k], (j, 0, N-1))
445
+ >>> MatrixExpr.from_index_summation(expr)
446
+ A.T*B
447
+
448
+ Detect the trace:
449
+
450
+ >>> expr = Sum(A[i, i], (i, 0, N-1))
451
+ >>> MatrixExpr.from_index_summation(expr)
452
+ Trace(A)
453
+
454
+ More complicated expressions:
455
+
456
+ >>> expr = Sum(A[i, j]*B[k, j]*A[l, k], (j, 0, N-1), (k, 0, N-1))
457
+ >>> MatrixExpr.from_index_summation(expr)
458
+ A*B.T*A.T
459
+ """
460
+ from sympy.tensor.array.expressions.from_indexed_to_array import convert_indexed_to_array
461
+ from sympy.tensor.array.expressions.from_array_to_matrix import convert_array_to_matrix
462
+ first_indices = []
463
+ if first_index is not None:
464
+ first_indices.append(first_index)
465
+ if last_index is not None:
466
+ first_indices.append(last_index)
467
+ arr = convert_indexed_to_array(expr, first_indices=first_indices)
468
+ return convert_array_to_matrix(arr)
469
+
470
+ def applyfunc(self, func):
471
+ from .applyfunc import ElementwiseApplyFunction
472
+ return ElementwiseApplyFunction(func, self)
473
+
474
+
475
+ @dispatch(MatrixExpr, Expr)
476
+ def _eval_is_eq(lhs, rhs): # noqa:F811
477
+ return False
478
+
479
+ @dispatch(MatrixExpr, MatrixExpr) # type: ignore
480
+ def _eval_is_eq(lhs, rhs): # noqa:F811
481
+ if lhs.shape != rhs.shape:
482
+ return False
483
+ if (lhs - rhs).is_ZeroMatrix:
484
+ return True
485
+
486
+ def get_postprocessor(cls):
487
+ def _postprocessor(expr):
488
+ # To avoid circular imports, we can't have MatMul/MatAdd on the top level
489
+ mat_class = {Mul: MatMul, Add: MatAdd}[cls]
490
+ nonmatrices = []
491
+ matrices = []
492
+ for term in expr.args:
493
+ if isinstance(term, MatrixExpr):
494
+ matrices.append(term)
495
+ else:
496
+ nonmatrices.append(term)
497
+
498
+ if not matrices:
499
+ return cls._from_args(nonmatrices)
500
+
501
+ if nonmatrices:
502
+ if cls == Mul:
503
+ for i in range(len(matrices)):
504
+ if not matrices[i].is_MatrixExpr:
505
+ # If one of the matrices explicit, absorb the scalar into it
506
+ # (doit will combine all explicit matrices into one, so it
507
+ # doesn't matter which)
508
+ matrices[i] = matrices[i].__mul__(cls._from_args(nonmatrices))
509
+ nonmatrices = []
510
+ break
511
+
512
+ else:
513
+ # Maintain the ability to create Add(scalar, matrix) without
514
+ # raising an exception. That way different algorithms can
515
+ # replace matrix expressions with non-commutative symbols to
516
+ # manipulate them like non-commutative scalars.
517
+ return cls._from_args(nonmatrices + [mat_class(*matrices).doit(deep=False)])
518
+
519
+ if mat_class == MatAdd:
520
+ return mat_class(*matrices).doit(deep=False)
521
+ return mat_class(cls._from_args(nonmatrices), *matrices).doit(deep=False)
522
+ return _postprocessor
523
+
524
+
525
+ Basic._constructor_postprocessor_mapping[MatrixExpr] = {
526
+ "Mul": [get_postprocessor(Mul)],
527
+ "Add": [get_postprocessor(Add)],
528
+ }
529
+
530
+
531
+ def _matrix_derivative(expr, x, old_algorithm=False):
532
+
533
+ if isinstance(expr, MatrixBase) or isinstance(x, MatrixBase):
534
+ # Do not use array expressions for explicit matrices:
535
+ old_algorithm = True
536
+
537
+ if old_algorithm:
538
+ return _matrix_derivative_old_algorithm(expr, x)
539
+
540
+ from sympy.tensor.array.expressions.from_matrix_to_array import convert_matrix_to_array
541
+ from sympy.tensor.array.expressions.arrayexpr_derivatives import array_derive
542
+ from sympy.tensor.array.expressions.from_array_to_matrix import convert_array_to_matrix
543
+
544
+ array_expr = convert_matrix_to_array(expr)
545
+ diff_array_expr = array_derive(array_expr, x)
546
+ diff_matrix_expr = convert_array_to_matrix(diff_array_expr)
547
+ return diff_matrix_expr
548
+
549
+
550
+ def _matrix_derivative_old_algorithm(expr, x):
551
+ from sympy.tensor.array.array_derivatives import ArrayDerivative
552
+ lines = expr._eval_derivative_matrix_lines(x)
553
+
554
+ parts = [i.build() for i in lines]
555
+
556
+ from sympy.tensor.array.expressions.from_array_to_matrix import convert_array_to_matrix
557
+
558
+ parts = [[convert_array_to_matrix(j) for j in i] for i in parts]
559
+
560
+ def _get_shape(elem):
561
+ if isinstance(elem, MatrixExpr):
562
+ return elem.shape
563
+ return 1, 1
564
+
565
+ def get_rank(parts):
566
+ return sum(j not in (1, None) for i in parts for j in _get_shape(i))
567
+
568
+ ranks = [get_rank(i) for i in parts]
569
+ rank = ranks[0]
570
+
571
+ def contract_one_dims(parts):
572
+ if len(parts) == 1:
573
+ return parts[0]
574
+ else:
575
+ p1, p2 = parts[:2]
576
+ if p2.is_Matrix:
577
+ p2 = p2.T
578
+ if p1 == Identity(1):
579
+ pbase = p2
580
+ elif p2 == Identity(1):
581
+ pbase = p1
582
+ else:
583
+ pbase = p1*p2
584
+ if len(parts) == 2:
585
+ return pbase
586
+ else: # len(parts) > 2
587
+ if pbase.is_Matrix:
588
+ raise ValueError("")
589
+ return pbase*Mul.fromiter(parts[2:])
590
+
591
+ if rank <= 2:
592
+ return Add.fromiter([contract_one_dims(i) for i in parts])
593
+
594
+ return ArrayDerivative(expr, x)
595
+
596
+
597
+ class MatrixElement(Expr):
598
+ parent = property(lambda self: self.args[0])
599
+ i = property(lambda self: self.args[1])
600
+ j = property(lambda self: self.args[2])
601
+ _diff_wrt = True
602
+ is_symbol = True
603
+ is_commutative = True
604
+
605
+ def __new__(cls, name, n, m):
606
+ n, m = map(_sympify, (n, m))
607
+ if isinstance(name, str):
608
+ name = Symbol(name)
609
+ else:
610
+ if isinstance(name, MatrixBase):
611
+ if n.is_Integer and m.is_Integer:
612
+ return name[n, m]
613
+ name = _sympify(name) # change mutable into immutable
614
+ else:
615
+ name = _sympify(name)
616
+ if not isinstance(name.kind, MatrixKind):
617
+ raise TypeError("First argument of MatrixElement should be a matrix")
618
+ if not getattr(name, 'valid_index', lambda n, m: True)(n, m):
619
+ raise IndexError('indices out of range')
620
+ obj = Expr.__new__(cls, name, n, m)
621
+ return obj
622
+
623
+ @property
624
+ def symbol(self):
625
+ return self.args[0]
626
+
627
+ def doit(self, **hints):
628
+ deep = hints.get('deep', True)
629
+ if deep:
630
+ args = [arg.doit(**hints) for arg in self.args]
631
+ else:
632
+ args = self.args
633
+ return args[0][args[1], args[2]]
634
+
635
+ @property
636
+ def indices(self):
637
+ return self.args[1:]
638
+
639
+ def _eval_derivative(self, v):
640
+
641
+ if not isinstance(v, MatrixElement):
642
+ return self.parent.diff(v)[self.i, self.j]
643
+
644
+ M = self.args[0]
645
+
646
+ m, n = self.parent.shape
647
+
648
+ if M == v.args[0]:
649
+ return KroneckerDelta(self.args[1], v.args[1], (0, m-1)) * \
650
+ KroneckerDelta(self.args[2], v.args[2], (0, n-1))
651
+
652
+ if isinstance(M, Inverse):
653
+ from sympy.concrete.summations import Sum
654
+ i, j = self.args[1:]
655
+ i1, i2 = symbols("z1, z2", cls=Dummy)
656
+ Y = M.args[0]
657
+ r1, r2 = Y.shape
658
+ return -Sum(M[i, i1]*Y[i1, i2].diff(v)*M[i2, j], (i1, 0, r1-1), (i2, 0, r2-1))
659
+
660
+ if self.has(v.args[0]):
661
+ return None
662
+
663
+ return S.Zero
664
+
665
+
666
+ class MatrixSymbol(MatrixExpr):
667
+ """Symbolic representation of a Matrix object
668
+
669
+ Creates a SymPy Symbol to represent a Matrix. This matrix has a shape and
670
+ can be included in Matrix Expressions
671
+
672
+ Examples
673
+ ========
674
+
675
+ >>> from sympy import MatrixSymbol, Identity
676
+ >>> A = MatrixSymbol('A', 3, 4) # A 3 by 4 Matrix
677
+ >>> B = MatrixSymbol('B', 4, 3) # A 4 by 3 Matrix
678
+ >>> A.shape
679
+ (3, 4)
680
+ >>> 2*A*B + Identity(3)
681
+ I + 2*A*B
682
+ """
683
+ is_commutative = False
684
+ is_symbol = True
685
+ _diff_wrt = True
686
+
687
+ def __new__(cls, name, n, m):
688
+ n, m = _sympify(n), _sympify(m)
689
+
690
+ cls._check_dim(m)
691
+ cls._check_dim(n)
692
+
693
+ if isinstance(name, str):
694
+ name = Str(name)
695
+ obj = Basic.__new__(cls, name, n, m)
696
+ return obj
697
+
698
+ @property
699
+ def shape(self):
700
+ return self.args[1], self.args[2]
701
+
702
+ @property
703
+ def name(self):
704
+ return self.args[0].name
705
+
706
+ def _entry(self, i, j, **kwargs):
707
+ return MatrixElement(self, i, j)
708
+
709
+ @property
710
+ def free_symbols(self):
711
+ return {self}
712
+
713
+ def _eval_simplify(self, **kwargs):
714
+ return self
715
+
716
+ def _eval_derivative(self, x):
717
+ # x is a scalar:
718
+ return ZeroMatrix(self.shape[0], self.shape[1])
719
+
720
+ def _eval_derivative_matrix_lines(self, x):
721
+ if self != x:
722
+ first = ZeroMatrix(x.shape[0], self.shape[0]) if self.shape[0] != 1 else S.Zero
723
+ second = ZeroMatrix(x.shape[1], self.shape[1]) if self.shape[1] != 1 else S.Zero
724
+ return [_LeftRightArgs(
725
+ [first, second],
726
+ )]
727
+ else:
728
+ first = Identity(self.shape[0]) if self.shape[0] != 1 else S.One
729
+ second = Identity(self.shape[1]) if self.shape[1] != 1 else S.One
730
+ return [_LeftRightArgs(
731
+ [first, second],
732
+ )]
733
+
734
+
735
+ def matrix_symbols(expr):
736
+ return [sym for sym in expr.free_symbols if sym.is_Matrix]
737
+
738
+
739
+ class _LeftRightArgs:
740
+ r"""
741
+ Helper class to compute matrix derivatives.
742
+
743
+ The logic: when an expression is derived by a matrix `X_{mn}`, two lines of
744
+ matrix multiplications are created: the one contracted to `m` (first line),
745
+ and the one contracted to `n` (second line).
746
+
747
+ Transposition flips the side by which new matrices are connected to the
748
+ lines.
749
+
750
+ The trace connects the end of the two lines.
751
+ """
752
+
753
+ def __init__(self, lines, higher=S.One):
754
+ self._lines = list(lines)
755
+ self._first_pointer_parent = self._lines
756
+ self._first_pointer_index = 0
757
+ self._first_line_index = 0
758
+ self._second_pointer_parent = self._lines
759
+ self._second_pointer_index = 1
760
+ self._second_line_index = 1
761
+ self.higher = higher
762
+
763
+ @property
764
+ def first_pointer(self):
765
+ return self._first_pointer_parent[self._first_pointer_index]
766
+
767
+ @first_pointer.setter
768
+ def first_pointer(self, value):
769
+ self._first_pointer_parent[self._first_pointer_index] = value
770
+
771
+ @property
772
+ def second_pointer(self):
773
+ return self._second_pointer_parent[self._second_pointer_index]
774
+
775
+ @second_pointer.setter
776
+ def second_pointer(self, value):
777
+ self._second_pointer_parent[self._second_pointer_index] = value
778
+
779
+ def __repr__(self):
780
+ built = [self._build(i) for i in self._lines]
781
+ return "_LeftRightArgs(lines=%s, higher=%s)" % (
782
+ built,
783
+ self.higher,
784
+ )
785
+
786
+ def transpose(self):
787
+ self._first_pointer_parent, self._second_pointer_parent = self._second_pointer_parent, self._first_pointer_parent
788
+ self._first_pointer_index, self._second_pointer_index = self._second_pointer_index, self._first_pointer_index
789
+ self._first_line_index, self._second_line_index = self._second_line_index, self._first_line_index
790
+ return self
791
+
792
+ @staticmethod
793
+ def _build(expr):
794
+ if isinstance(expr, ExprBuilder):
795
+ return expr.build()
796
+ if isinstance(expr, list):
797
+ if len(expr) == 1:
798
+ return expr[0]
799
+ else:
800
+ return expr[0](*[_LeftRightArgs._build(i) for i in expr[1]])
801
+ else:
802
+ return expr
803
+
804
+ def build(self):
805
+ data = [self._build(i) for i in self._lines]
806
+ if self.higher != 1:
807
+ data += [self._build(self.higher)]
808
+ data = list(data)
809
+ return data
810
+
811
+ def matrix_form(self):
812
+ if self.first != 1 and self.higher != 1:
813
+ raise ValueError("higher dimensional array cannot be represented")
814
+
815
+ def _get_shape(elem):
816
+ if isinstance(elem, MatrixExpr):
817
+ return elem.shape
818
+ return (None, None)
819
+
820
+ if _get_shape(self.first)[1] != _get_shape(self.second)[1]:
821
+ # Remove one-dimensional identity matrices:
822
+ # (this is needed by `a.diff(a)` where `a` is a vector)
823
+ if _get_shape(self.second) == (1, 1):
824
+ return self.first*self.second[0, 0]
825
+ if _get_shape(self.first) == (1, 1):
826
+ return self.first[1, 1]*self.second.T
827
+ raise ValueError("incompatible shapes")
828
+ if self.first != 1:
829
+ return self.first*self.second.T
830
+ else:
831
+ return self.higher
832
+
833
+ def rank(self):
834
+ """
835
+ Number of dimensions different from trivial (warning: not related to
836
+ matrix rank).
837
+ """
838
+ rank = 0
839
+ if self.first != 1:
840
+ rank += sum(i != 1 for i in self.first.shape)
841
+ if self.second != 1:
842
+ rank += sum(i != 1 for i in self.second.shape)
843
+ if self.higher != 1:
844
+ rank += 2
845
+ return rank
846
+
847
+ def _multiply_pointer(self, pointer, other):
848
+ from ...tensor.array.expressions.array_expressions import ArrayTensorProduct
849
+ from ...tensor.array.expressions.array_expressions import ArrayContraction
850
+
851
+ subexpr = ExprBuilder(
852
+ ArrayContraction,
853
+ [
854
+ ExprBuilder(
855
+ ArrayTensorProduct,
856
+ [
857
+ pointer,
858
+ other
859
+ ]
860
+ ),
861
+ (1, 2)
862
+ ],
863
+ validator=ArrayContraction._validate
864
+ )
865
+
866
+ return subexpr
867
+
868
+ def append_first(self, other):
869
+ self.first_pointer *= other
870
+
871
+ def append_second(self, other):
872
+ self.second_pointer *= other
873
+
874
+
875
+ def _make_matrix(x):
876
+ from sympy.matrices.immutable import ImmutableDenseMatrix
877
+ if isinstance(x, MatrixExpr):
878
+ return x
879
+ return ImmutableDenseMatrix([[x]])
880
+
881
+
882
+ from .matmul import MatMul
883
+ from .matadd import MatAdd
884
+ from .matpow import MatPow
885
+ from .transpose import Transpose
886
+ from .inverse import Inverse
887
+ from .special import ZeroMatrix, Identity
888
+ from .determinant import Determinant
miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/matrices/expressions/matmul.py ADDED
@@ -0,0 +1,496 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.exceptions import NonInvertibleMatrixError
11
+ from sympy.matrices.matrixbase 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
+
174
+ def _eval_determinant(self):
175
+ from sympy.matrices.expressions.determinant import Determinant
176
+ factor, matrices = self.as_coeff_matrices()
177
+ square_matrices = only_squares(*matrices)
178
+ return factor**self.rows * Mul(*list(map(Determinant, square_matrices)))
179
+
180
+ def _eval_inverse(self):
181
+ if all(arg.is_square for arg in self.args if isinstance(arg, MatrixExpr)):
182
+ return MatMul(*(
183
+ arg.inverse() if isinstance(arg, MatrixExpr) else arg**-1
184
+ for arg in self.args[::-1]
185
+ )
186
+ ).doit()
187
+ return Inverse(self)
188
+
189
+ def doit(self, **hints):
190
+ deep = hints.get('deep', True)
191
+ if deep:
192
+ args = tuple(arg.doit(**hints) for arg in self.args)
193
+ else:
194
+ args = self.args
195
+
196
+ # treat scalar*MatrixSymbol or scalar*MatPow separately
197
+ expr = canonicalize(MatMul(*args))
198
+ return expr
199
+
200
+ # Needed for partial compatibility with Mul
201
+ def args_cnc(self, cset=False, warn=True, **kwargs):
202
+ coeff_c = [x for x in self.args if x.is_commutative]
203
+ coeff_nc = [x for x in self.args if not x.is_commutative]
204
+ if cset:
205
+ clen = len(coeff_c)
206
+ coeff_c = set(coeff_c)
207
+ if clen and warn and len(coeff_c) != clen:
208
+ raise ValueError('repeated commutative arguments: %s' %
209
+ [ci for ci in coeff_c if list(self.args).count(ci) > 1])
210
+ return [coeff_c, coeff_nc]
211
+
212
+ def _eval_derivative_matrix_lines(self, x):
213
+ from .transpose import Transpose
214
+ with_x_ind = [i for i, arg in enumerate(self.args) if arg.has(x)]
215
+ lines = []
216
+ for ind in with_x_ind:
217
+ left_args = self.args[:ind]
218
+ right_args = self.args[ind+1:]
219
+
220
+ if right_args:
221
+ right_mat = MatMul.fromiter(right_args)
222
+ else:
223
+ right_mat = Identity(self.shape[1])
224
+ if left_args:
225
+ left_rev = MatMul.fromiter([Transpose(i).doit() if i.is_Matrix else i for i in reversed(left_args)])
226
+ else:
227
+ left_rev = Identity(self.shape[0])
228
+
229
+ d = self.args[ind]._eval_derivative_matrix_lines(x)
230
+ for i in d:
231
+ i.append_first(left_rev)
232
+ i.append_second(right_mat)
233
+ lines.append(i)
234
+
235
+ return lines
236
+
237
+ mul.register_handlerclass((Mul, MatMul), MatMul)
238
+
239
+
240
+ # Rules
241
+ def newmul(*args):
242
+ if args[0] == 1:
243
+ args = args[1:]
244
+ return new(MatMul, *args)
245
+
246
+ def any_zeros(mul):
247
+ if any(arg.is_zero or (arg.is_Matrix and arg.is_ZeroMatrix)
248
+ for arg in mul.args):
249
+ matrices = [arg for arg in mul.args if arg.is_Matrix]
250
+ return ZeroMatrix(matrices[0].rows, matrices[-1].cols)
251
+ return mul
252
+
253
+ def merge_explicit(matmul):
254
+ """ Merge explicit MatrixBase arguments
255
+
256
+ >>> from sympy import MatrixSymbol, Matrix, MatMul, pprint
257
+ >>> from sympy.matrices.expressions.matmul import merge_explicit
258
+ >>> A = MatrixSymbol('A', 2, 2)
259
+ >>> B = Matrix([[1, 1], [1, 1]])
260
+ >>> C = Matrix([[1, 2], [3, 4]])
261
+ >>> X = MatMul(A, B, C)
262
+ >>> pprint(X)
263
+ [1 1] [1 2]
264
+ A*[ ]*[ ]
265
+ [1 1] [3 4]
266
+ >>> pprint(merge_explicit(X))
267
+ [4 6]
268
+ A*[ ]
269
+ [4 6]
270
+
271
+ >>> X = MatMul(B, A, C)
272
+ >>> pprint(X)
273
+ [1 1] [1 2]
274
+ [ ]*A*[ ]
275
+ [1 1] [3 4]
276
+ >>> pprint(merge_explicit(X))
277
+ [1 1] [1 2]
278
+ [ ]*A*[ ]
279
+ [1 1] [3 4]
280
+ """
281
+ if not any(isinstance(arg, MatrixBase) for arg in matmul.args):
282
+ return matmul
283
+ newargs = []
284
+ last = matmul.args[0]
285
+ for arg in matmul.args[1:]:
286
+ if isinstance(arg, (MatrixBase, Number)) and isinstance(last, (MatrixBase, Number)):
287
+ last = last * arg
288
+ else:
289
+ newargs.append(last)
290
+ last = arg
291
+ newargs.append(last)
292
+
293
+ return MatMul(*newargs)
294
+
295
+ def remove_ids(mul):
296
+ """ Remove Identities from a MatMul
297
+
298
+ This is a modified version of sympy.strategies.rm_id.
299
+ This is necessary because MatMul may contain both MatrixExprs and Exprs
300
+ as args.
301
+
302
+ See Also
303
+ ========
304
+
305
+ sympy.strategies.rm_id
306
+ """
307
+ # Separate Exprs from MatrixExprs in args
308
+ factor, mmul = mul.as_coeff_mmul()
309
+ # Apply standard rm_id for MatMuls
310
+ result = rm_id(lambda x: x.is_Identity is True)(mmul)
311
+ if result != mmul:
312
+ return newmul(factor, *result.args) # Recombine and return
313
+ else:
314
+ return mul
315
+
316
+ def factor_in_front(mul):
317
+ factor, matrices = mul.as_coeff_matrices()
318
+ if factor != 1:
319
+ return newmul(factor, *matrices)
320
+ return mul
321
+
322
+ def combine_powers(mul):
323
+ r"""Combine consecutive powers with the same base into one, e.g.
324
+ $$A \times A^2 \Rightarrow A^3$$
325
+
326
+ This also cancels out the possible matrix inverses using the
327
+ knowledgebase of :class:`~.Inverse`, e.g.,
328
+ $$ Y \times X \times X^{-1} \Rightarrow Y $$
329
+ """
330
+ factor, args = mul.as_coeff_matrices()
331
+ new_args = [args[0]]
332
+
333
+ for i in range(1, len(args)):
334
+ A = new_args[-1]
335
+ B = args[i]
336
+
337
+ if isinstance(B, Inverse) and isinstance(B.arg, MatMul):
338
+ Bargs = B.arg.args
339
+ l = len(Bargs)
340
+ if list(Bargs) == new_args[-l:]:
341
+ new_args = new_args[:-l] + [Identity(B.shape[0])]
342
+ continue
343
+
344
+ if isinstance(A, Inverse) and isinstance(A.arg, MatMul):
345
+ Aargs = A.arg.args
346
+ l = len(Aargs)
347
+ if list(Aargs) == args[i:i+l]:
348
+ identity = Identity(A.shape[0])
349
+ new_args[-1] = identity
350
+ for j in range(i, i+l):
351
+ args[j] = identity
352
+ continue
353
+
354
+ if A.is_square == False or B.is_square == False:
355
+ new_args.append(B)
356
+ continue
357
+
358
+ if isinstance(A, MatPow):
359
+ A_base, A_exp = A.args
360
+ else:
361
+ A_base, A_exp = A, S.One
362
+
363
+ if isinstance(B, MatPow):
364
+ B_base, B_exp = B.args
365
+ else:
366
+ B_base, B_exp = B, S.One
367
+
368
+ if A_base == B_base:
369
+ new_exp = A_exp + B_exp
370
+ new_args[-1] = MatPow(A_base, new_exp).doit(deep=False)
371
+ continue
372
+ elif not isinstance(B_base, MatrixBase):
373
+ try:
374
+ B_base_inv = B_base.inverse()
375
+ except NonInvertibleMatrixError:
376
+ B_base_inv = None
377
+ if B_base_inv is not None and A_base == B_base_inv:
378
+ new_exp = A_exp - B_exp
379
+ new_args[-1] = MatPow(A_base, new_exp).doit(deep=False)
380
+ continue
381
+ new_args.append(B)
382
+
383
+ return newmul(factor, *new_args)
384
+
385
+ def combine_permutations(mul):
386
+ """Refine products of permutation matrices as the products of cycles.
387
+ """
388
+ args = mul.args
389
+ l = len(args)
390
+ if l < 2:
391
+ return mul
392
+
393
+ result = [args[0]]
394
+ for i in range(1, l):
395
+ A = result[-1]
396
+ B = args[i]
397
+ if isinstance(A, PermutationMatrix) and \
398
+ isinstance(B, PermutationMatrix):
399
+ cycle_1 = A.args[0]
400
+ cycle_2 = B.args[0]
401
+ result[-1] = PermutationMatrix(cycle_1 * cycle_2)
402
+ else:
403
+ result.append(B)
404
+
405
+ return MatMul(*result)
406
+
407
+ def combine_one_matrices(mul):
408
+ """
409
+ Combine products of OneMatrix
410
+
411
+ e.g. OneMatrix(2, 3) * OneMatrix(3, 4) -> 3 * OneMatrix(2, 4)
412
+ """
413
+ factor, args = mul.as_coeff_matrices()
414
+ new_args = [args[0]]
415
+
416
+ for B in args[1:]:
417
+ A = new_args[-1]
418
+ if not isinstance(A, OneMatrix) or not isinstance(B, OneMatrix):
419
+ new_args.append(B)
420
+ continue
421
+ new_args.pop()
422
+ new_args.append(OneMatrix(A.shape[0], B.shape[1]))
423
+ factor *= A.shape[1]
424
+
425
+ return newmul(factor, *new_args)
426
+
427
+ def distribute_monom(mul):
428
+ """
429
+ Simplify MatMul expressions but distributing
430
+ rational term to MatMul.
431
+
432
+ e.g. 2*(A+B) -> 2*A + 2*B
433
+ """
434
+ args = mul.args
435
+ if len(args) == 2:
436
+ from .matadd import MatAdd
437
+ if args[0].is_MatAdd and args[1].is_Rational:
438
+ return MatAdd(*[MatMul(mat, args[1]).doit() for mat in args[0].args])
439
+ if args[1].is_MatAdd and args[0].is_Rational:
440
+ return MatAdd(*[MatMul(args[0], mat).doit() for mat in args[1].args])
441
+ return mul
442
+
443
+ rules = (
444
+ distribute_monom, any_zeros, remove_ids, combine_one_matrices, combine_powers, unpack, rm_id(lambda x: x == 1),
445
+ merge_explicit, factor_in_front, flatten, combine_permutations)
446
+
447
+ canonicalize = exhaust(typed({MatMul: do_one(*rules)}))
448
+
449
+ def only_squares(*matrices):
450
+ """factor matrices only if they are square"""
451
+ if matrices[0].rows != matrices[-1].cols:
452
+ raise RuntimeError("Invalid matrices being multiplied")
453
+ out = []
454
+ start = 0
455
+ for i, M in enumerate(matrices):
456
+ if M.cols == matrices[start].rows:
457
+ out.append(MatMul(*matrices[start:i+1]).doit())
458
+ start = i+1
459
+ return out
460
+
461
+
462
+ def refine_MatMul(expr, assumptions):
463
+ """
464
+ >>> from sympy import MatrixSymbol, Q, assuming, refine
465
+ >>> X = MatrixSymbol('X', 2, 2)
466
+ >>> expr = X * X.T
467
+ >>> print(expr)
468
+ X*X.T
469
+ >>> with assuming(Q.orthogonal(X)):
470
+ ... print(refine(expr))
471
+ I
472
+ """
473
+ newargs = []
474
+ exprargs = []
475
+
476
+ for args in expr.args:
477
+ if args.is_Matrix:
478
+ exprargs.append(args)
479
+ else:
480
+ newargs.append(args)
481
+
482
+ last = exprargs[0]
483
+ for arg in exprargs[1:]:
484
+ if arg == last.T and ask(Q.orthogonal(arg), assumptions):
485
+ last = Identity(arg.shape[0])
486
+ elif arg == last.conjugate() and ask(Q.unitary(arg), assumptions):
487
+ last = Identity(arg.shape[0])
488
+ else:
489
+ newargs.append(last)
490
+ last = arg
491
+ newargs.append(last)
492
+
493
+ return MatMul(*newargs)
494
+
495
+
496
+ handlers_dict['MatMul'] = refine_MatMul
miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/matrices/expressions/matpow.py ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.exceptions 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.transpose(), exp)
93
+
94
+ def _eval_adjoint(self):
95
+ base, exp = self.args
96
+ return MatPow(base.adjoint(), exp)
97
+
98
+ def _eval_conjugate(self):
99
+ base, exp = self.args
100
+ return MatPow(base.conjugate(), exp)
101
+
102
+ def _eval_derivative(self, x):
103
+ return Pow._eval_derivative(self, x)
104
+
105
+ def _eval_derivative_matrix_lines(self, x):
106
+ from sympy.tensor.array.expressions.array_expressions import ArrayContraction
107
+ from ...tensor.array.expressions.array_expressions import ArrayTensorProduct
108
+ from .matmul import MatMul
109
+ from .inverse import Inverse
110
+ exp = self.exp
111
+ if self.base.shape == (1, 1) and not exp.has(x):
112
+ lr = self.base._eval_derivative_matrix_lines(x)
113
+ for i in lr:
114
+ subexpr = ExprBuilder(
115
+ ArrayContraction,
116
+ [
117
+ ExprBuilder(
118
+ ArrayTensorProduct,
119
+ [
120
+ Identity(1),
121
+ i._lines[0],
122
+ exp*self.base**(exp-1),
123
+ i._lines[1],
124
+ Identity(1),
125
+ ]
126
+ ),
127
+ (0, 3, 4), (5, 7, 8)
128
+ ],
129
+ validator=ArrayContraction._validate
130
+ )
131
+ i._first_pointer_parent = subexpr.args[0].args
132
+ i._first_pointer_index = 0
133
+ i._second_pointer_parent = subexpr.args[0].args
134
+ i._second_pointer_index = 4
135
+ i._lines = [subexpr]
136
+ return lr
137
+ if (exp > 0) == True:
138
+ newexpr = MatMul.fromiter([self.base for i in range(exp)])
139
+ elif (exp == -1) == True:
140
+ return Inverse(self.base)._eval_derivative_matrix_lines(x)
141
+ elif (exp < 0) == True:
142
+ newexpr = MatMul.fromiter([Inverse(self.base) for i in range(-exp)])
143
+ elif (exp == 0) == True:
144
+ return self.doit()._eval_derivative_matrix_lines(x)
145
+ else:
146
+ raise NotImplementedError("cannot evaluate %s derived by %s" % (self, x))
147
+ return newexpr._eval_derivative_matrix_lines(x)
148
+
149
+ def _eval_inverse(self):
150
+ return MatPow(self.base, -self.exp)
miniconda3/envs/ladir/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.matrixbase.MatrixBase.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.matrixbase.MatrixBase.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))
miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/matrices/expressions/sets.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.kind 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 = not dim.is_Float and check_assumptions(
61
+ dim, integer=True, nonnegative=True)
62
+ if ok is False:
63
+ raise ValueError(
64
+ "The dimension specification {} should be "
65
+ "a nonnegative integer.".format(dim))
66
+
67
+ def _kind(self):
68
+ return SetKind(MatrixKind(NumberKind))
miniconda3/envs/ladir/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)
miniconda3/envs/ladir/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.exceptions 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
miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/matrices/expressions/tests/__init__.py ADDED
File without changes
miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/matrices/expressions/tests/test_adjoint.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core import symbols, S
2
+ from sympy.functions import adjoint, conjugate, transpose
3
+ from sympy.matrices.expressions import MatrixSymbol, Adjoint, trace, Transpose
4
+ from sympy.matrices import eye, Matrix
5
+
6
+ n, m, l, k, p = symbols('n m l k p', integer=True)
7
+ A = MatrixSymbol('A', n, m)
8
+ B = MatrixSymbol('B', m, l)
9
+ C = MatrixSymbol('C', n, n)
10
+
11
+
12
+ def test_adjoint():
13
+ Sq = MatrixSymbol('Sq', n, n)
14
+
15
+ assert Adjoint(A).shape == (m, n)
16
+ assert Adjoint(A*B).shape == (l, n)
17
+ assert adjoint(Adjoint(A)) == A
18
+ assert isinstance(Adjoint(Adjoint(A)), Adjoint)
19
+
20
+ assert conjugate(Adjoint(A)) == Transpose(A)
21
+ assert transpose(Adjoint(A)) == Adjoint(Transpose(A))
22
+
23
+ assert Adjoint(eye(3)).doit() == eye(3)
24
+
25
+ assert Adjoint(S(5)).doit() == S(5)
26
+
27
+ assert Adjoint(Matrix([[1, 2], [3, 4]])).doit() == Matrix([[1, 3], [2, 4]])
28
+
29
+ assert adjoint(trace(Sq)) == conjugate(trace(Sq))
30
+ assert trace(adjoint(Sq)) == conjugate(trace(Sq))
31
+
32
+ assert Adjoint(Sq)[0, 1] == conjugate(Sq[1, 0])
33
+
34
+ assert Adjoint(A*B).doit() == Adjoint(B) * Adjoint(A)
miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/matrices/expressions/tests/test_applyfunc.py ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.symbol import symbols, Dummy
2
+ from sympy.matrices.expressions.applyfunc import ElementwiseApplyFunction
3
+ from sympy.core.function import Lambda
4
+ from sympy.functions.elementary.exponential import exp
5
+ from sympy.functions.elementary.trigonometric import sin
6
+ from sympy.matrices.dense import Matrix
7
+ from sympy.matrices.expressions.matexpr import MatrixSymbol
8
+ from sympy.matrices.expressions.matmul import MatMul
9
+ from sympy.simplify.simplify import simplify
10
+
11
+
12
+ X = MatrixSymbol("X", 3, 3)
13
+ Y = MatrixSymbol("Y", 3, 3)
14
+
15
+ k = symbols("k")
16
+ Xk = MatrixSymbol("X", k, k)
17
+
18
+ Xd = X.as_explicit()
19
+
20
+ x, y, z, t = symbols("x y z t")
21
+
22
+
23
+ def test_applyfunc_matrix():
24
+ x = Dummy('x')
25
+ double = Lambda(x, x**2)
26
+
27
+ expr = ElementwiseApplyFunction(double, Xd)
28
+ assert isinstance(expr, ElementwiseApplyFunction)
29
+ assert expr.doit() == Xd.applyfunc(lambda x: x**2)
30
+ assert expr.shape == (3, 3)
31
+ assert expr.func(*expr.args) == expr
32
+ assert simplify(expr) == expr
33
+ assert expr[0, 0] == double(Xd[0, 0])
34
+
35
+ expr = ElementwiseApplyFunction(double, X)
36
+ assert isinstance(expr, ElementwiseApplyFunction)
37
+ assert isinstance(expr.doit(), ElementwiseApplyFunction)
38
+ assert expr == X.applyfunc(double)
39
+ assert expr.func(*expr.args) == expr
40
+
41
+ expr = ElementwiseApplyFunction(exp, X*Y)
42
+ assert expr.expr == X*Y
43
+ assert expr.function.dummy_eq(Lambda(x, exp(x)))
44
+ assert expr.dummy_eq((X*Y).applyfunc(exp))
45
+ assert expr.func(*expr.args) == expr
46
+
47
+ assert isinstance(X*expr, MatMul)
48
+ assert (X*expr).shape == (3, 3)
49
+ Z = MatrixSymbol("Z", 2, 3)
50
+ assert (Z*expr).shape == (2, 3)
51
+
52
+ expr = ElementwiseApplyFunction(exp, Z.T)*ElementwiseApplyFunction(exp, Z)
53
+ assert expr.shape == (3, 3)
54
+ expr = ElementwiseApplyFunction(exp, Z)*ElementwiseApplyFunction(exp, Z.T)
55
+ assert expr.shape == (2, 2)
56
+
57
+ M = Matrix([[x, y], [z, t]])
58
+ expr = ElementwiseApplyFunction(sin, M)
59
+ assert isinstance(expr, ElementwiseApplyFunction)
60
+ assert expr.function.dummy_eq(Lambda(x, sin(x)))
61
+ assert expr.expr == M
62
+ assert expr.doit() == M.applyfunc(sin)
63
+ assert expr.doit() == Matrix([[sin(x), sin(y)], [sin(z), sin(t)]])
64
+ assert expr.func(*expr.args) == expr
65
+
66
+ expr = ElementwiseApplyFunction(double, Xk)
67
+ assert expr.doit() == expr
68
+ assert expr.subs(k, 2).shape == (2, 2)
69
+ assert (expr*expr).shape == (k, k)
70
+ M = MatrixSymbol("M", k, t)
71
+ expr2 = M.T*expr*M
72
+ assert isinstance(expr2, MatMul)
73
+ assert expr2.args[1] == expr
74
+ assert expr2.shape == (t, t)
75
+ expr3 = expr*M
76
+ assert expr3.shape == (k, t)
77
+
78
+ expr1 = ElementwiseApplyFunction(lambda x: x+1, Xk)
79
+ expr2 = ElementwiseApplyFunction(lambda x: x, Xk)
80
+ assert expr1 != expr2
81
+
82
+
83
+ def test_applyfunc_entry():
84
+
85
+ af = X.applyfunc(sin)
86
+ assert af[0, 0] == sin(X[0, 0])
87
+
88
+ af = Xd.applyfunc(sin)
89
+ assert af[0, 0] == sin(X[0, 0])
90
+
91
+
92
+ def test_applyfunc_as_explicit():
93
+
94
+ af = X.applyfunc(sin)
95
+ assert af.as_explicit() == Matrix([
96
+ [sin(X[0, 0]), sin(X[0, 1]), sin(X[0, 2])],
97
+ [sin(X[1, 0]), sin(X[1, 1]), sin(X[1, 2])],
98
+ [sin(X[2, 0]), sin(X[2, 1]), sin(X[2, 2])],
99
+ ])
100
+
101
+
102
+ def test_applyfunc_transpose():
103
+
104
+ af = Xk.applyfunc(sin)
105
+ assert af.T.dummy_eq(Xk.T.applyfunc(sin))
106
+
107
+
108
+ def test_applyfunc_shape_11_matrices():
109
+ M = MatrixSymbol("M", 1, 1)
110
+
111
+ double = Lambda(x, x*2)
112
+
113
+ expr = M.applyfunc(sin)
114
+ assert isinstance(expr, ElementwiseApplyFunction)
115
+
116
+ expr = M.applyfunc(double)
117
+ assert isinstance(expr, MatMul)
118
+ assert expr == 2*M
miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/matrices/expressions/tests/test_blockmatrix.py ADDED
@@ -0,0 +1,469 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.matrices.expressions.trace import Trace
2
+ from sympy.testing.pytest import raises, slow
3
+ from sympy.matrices.expressions.blockmatrix import (
4
+ block_collapse, bc_matmul, bc_block_plus_ident, BlockDiagMatrix,
5
+ BlockMatrix, bc_dist, bc_matadd, bc_transpose, bc_inverse,
6
+ blockcut, reblock_2x2, deblock)
7
+ from sympy.matrices.expressions import (
8
+ MatrixSymbol, Identity, trace, det, ZeroMatrix, OneMatrix)
9
+ from sympy.matrices.expressions.inverse import Inverse
10
+ from sympy.matrices.expressions.matpow import MatPow
11
+ from sympy.matrices.expressions.transpose import Transpose
12
+ from sympy.matrices.exceptions import NonInvertibleMatrixError
13
+ from sympy.matrices import (
14
+ Matrix, ImmutableMatrix, ImmutableSparseMatrix, zeros)
15
+ from sympy.core import Tuple, Expr, S, Function
16
+ from sympy.core.symbol import Symbol, symbols
17
+ from sympy.functions import transpose, im, re
18
+
19
+ i, j, k, l, m, n, p = symbols('i:n, p', integer=True)
20
+ A = MatrixSymbol('A', n, n)
21
+ B = MatrixSymbol('B', n, n)
22
+ C = MatrixSymbol('C', n, n)
23
+ D = MatrixSymbol('D', n, n)
24
+ G = MatrixSymbol('G', n, n)
25
+ H = MatrixSymbol('H', n, n)
26
+ b1 = BlockMatrix([[G, H]])
27
+ b2 = BlockMatrix([[G], [H]])
28
+
29
+ def test_bc_matmul():
30
+ assert bc_matmul(H*b1*b2*G) == BlockMatrix([[(H*G*G + H*H*H)*G]])
31
+
32
+ def test_bc_matadd():
33
+ assert bc_matadd(BlockMatrix([[G, H]]) + BlockMatrix([[H, H]])) == \
34
+ BlockMatrix([[G+H, H+H]])
35
+
36
+ def test_bc_transpose():
37
+ assert bc_transpose(Transpose(BlockMatrix([[A, B], [C, D]]))) == \
38
+ BlockMatrix([[A.T, C.T], [B.T, D.T]])
39
+
40
+ def test_bc_dist_diag():
41
+ A = MatrixSymbol('A', n, n)
42
+ B = MatrixSymbol('B', m, m)
43
+ C = MatrixSymbol('C', l, l)
44
+ X = BlockDiagMatrix(A, B, C)
45
+
46
+ assert bc_dist(X+X).equals(BlockDiagMatrix(2*A, 2*B, 2*C))
47
+
48
+ def test_block_plus_ident():
49
+ A = MatrixSymbol('A', n, n)
50
+ B = MatrixSymbol('B', n, m)
51
+ C = MatrixSymbol('C', m, n)
52
+ D = MatrixSymbol('D', m, m)
53
+ X = BlockMatrix([[A, B], [C, D]])
54
+ Z = MatrixSymbol('Z', n + m, n + m)
55
+ assert bc_block_plus_ident(X + Identity(m + n) + Z) == \
56
+ BlockDiagMatrix(Identity(n), Identity(m)) + X + Z
57
+
58
+ def test_BlockMatrix():
59
+ A = MatrixSymbol('A', n, m)
60
+ B = MatrixSymbol('B', n, k)
61
+ C = MatrixSymbol('C', l, m)
62
+ D = MatrixSymbol('D', l, k)
63
+ M = MatrixSymbol('M', m + k, p)
64
+ N = MatrixSymbol('N', l + n, k + m)
65
+ X = BlockMatrix(Matrix([[A, B], [C, D]]))
66
+
67
+ assert X.__class__(*X.args) == X
68
+
69
+ # block_collapse does nothing on normal inputs
70
+ E = MatrixSymbol('E', n, m)
71
+ assert block_collapse(A + 2*E) == A + 2*E
72
+ F = MatrixSymbol('F', m, m)
73
+ assert block_collapse(E.T*A*F) == E.T*A*F
74
+
75
+ assert X.shape == (l + n, k + m)
76
+ assert X.blockshape == (2, 2)
77
+ assert transpose(X) == BlockMatrix(Matrix([[A.T, C.T], [B.T, D.T]]))
78
+ assert transpose(X).shape == X.shape[::-1]
79
+
80
+ # Test that BlockMatrices and MatrixSymbols can still mix
81
+ assert (X*M).is_MatMul
82
+ assert X._blockmul(M).is_MatMul
83
+ assert (X*M).shape == (n + l, p)
84
+ assert (X + N).is_MatAdd
85
+ assert X._blockadd(N).is_MatAdd
86
+ assert (X + N).shape == X.shape
87
+
88
+ E = MatrixSymbol('E', m, 1)
89
+ F = MatrixSymbol('F', k, 1)
90
+
91
+ Y = BlockMatrix(Matrix([[E], [F]]))
92
+
93
+ assert (X*Y).shape == (l + n, 1)
94
+ assert block_collapse(X*Y).blocks[0, 0] == A*E + B*F
95
+ assert block_collapse(X*Y).blocks[1, 0] == C*E + D*F
96
+
97
+ # block_collapse passes down into container objects, transposes, and inverse
98
+ assert block_collapse(transpose(X*Y)) == transpose(block_collapse(X*Y))
99
+ assert block_collapse(Tuple(X*Y, 2*X)) == (
100
+ block_collapse(X*Y), block_collapse(2*X))
101
+
102
+ # Make sure that MatrixSymbols will enter 1x1 BlockMatrix if it simplifies
103
+ Ab = BlockMatrix([[A]])
104
+ Z = MatrixSymbol('Z', *A.shape)
105
+ assert block_collapse(Ab + Z) == A + Z
106
+
107
+ def test_block_collapse_explicit_matrices():
108
+ A = Matrix([[1, 2], [3, 4]])
109
+ assert block_collapse(BlockMatrix([[A]])) == A
110
+
111
+ A = ImmutableSparseMatrix([[1, 2], [3, 4]])
112
+ assert block_collapse(BlockMatrix([[A]])) == A
113
+
114
+ def test_issue_17624():
115
+ a = MatrixSymbol("a", 2, 2)
116
+ z = ZeroMatrix(2, 2)
117
+ b = BlockMatrix([[a, z], [z, z]])
118
+ assert block_collapse(b * b) == BlockMatrix([[a**2, z], [z, z]])
119
+ assert block_collapse(b * b * b) == BlockMatrix([[a**3, z], [z, z]])
120
+
121
+ def test_issue_18618():
122
+ A = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
123
+ assert A == Matrix(BlockDiagMatrix(A))
124
+
125
+ def test_BlockMatrix_trace():
126
+ A, B, C, D = [MatrixSymbol(s, 3, 3) for s in 'ABCD']
127
+ X = BlockMatrix([[A, B], [C, D]])
128
+ assert trace(X) == trace(A) + trace(D)
129
+ assert trace(BlockMatrix([ZeroMatrix(n, n)])) == 0
130
+
131
+ def test_BlockMatrix_Determinant():
132
+ A, B, C, D = [MatrixSymbol(s, 3, 3) for s in 'ABCD']
133
+ X = BlockMatrix([[A, B], [C, D]])
134
+ from sympy.assumptions.ask import Q
135
+ from sympy.assumptions.assume import assuming
136
+ with assuming(Q.invertible(A)):
137
+ assert det(X) == det(A) * det(X.schur('A'))
138
+
139
+ assert isinstance(det(X), Expr)
140
+ assert det(BlockMatrix([A])) == det(A)
141
+ assert det(BlockMatrix([ZeroMatrix(n, n)])) == 0
142
+
143
+ def test_squareBlockMatrix():
144
+ A = MatrixSymbol('A', n, n)
145
+ B = MatrixSymbol('B', n, m)
146
+ C = MatrixSymbol('C', m, n)
147
+ D = MatrixSymbol('D', m, m)
148
+ X = BlockMatrix([[A, B], [C, D]])
149
+ Y = BlockMatrix([[A]])
150
+
151
+ assert X.is_square
152
+
153
+ Q = X + Identity(m + n)
154
+ assert (block_collapse(Q) ==
155
+ BlockMatrix([[A + Identity(n), B], [C, D + Identity(m)]]))
156
+
157
+ assert (X + MatrixSymbol('Q', n + m, n + m)).is_MatAdd
158
+ assert (X * MatrixSymbol('Q', n + m, n + m)).is_MatMul
159
+
160
+ assert block_collapse(Y.I) == A.I
161
+
162
+ assert isinstance(X.inverse(), Inverse)
163
+
164
+ assert not X.is_Identity
165
+
166
+ Z = BlockMatrix([[Identity(n), B], [C, D]])
167
+ assert not Z.is_Identity
168
+
169
+
170
+ def test_BlockMatrix_2x2_inverse_symbolic():
171
+ A = MatrixSymbol('A', n, m)
172
+ B = MatrixSymbol('B', n, k - m)
173
+ C = MatrixSymbol('C', k - n, m)
174
+ D = MatrixSymbol('D', k - n, k - m)
175
+ X = BlockMatrix([[A, B], [C, D]])
176
+ assert X.is_square and X.shape == (k, k)
177
+ assert isinstance(block_collapse(X.I), Inverse) # Can't invert when none of the blocks is square
178
+
179
+ # test code path where only A is invertible
180
+ A = MatrixSymbol('A', n, n)
181
+ B = MatrixSymbol('B', n, m)
182
+ C = MatrixSymbol('C', m, n)
183
+ D = ZeroMatrix(m, m)
184
+ X = BlockMatrix([[A, B], [C, D]])
185
+ assert block_collapse(X.inverse()) == BlockMatrix([
186
+ [A.I + A.I * B * X.schur('A').I * C * A.I, -A.I * B * X.schur('A').I],
187
+ [-X.schur('A').I * C * A.I, X.schur('A').I],
188
+ ])
189
+
190
+ # test code path where only B is invertible
191
+ A = MatrixSymbol('A', n, m)
192
+ B = MatrixSymbol('B', n, n)
193
+ C = ZeroMatrix(m, m)
194
+ D = MatrixSymbol('D', m, n)
195
+ X = BlockMatrix([[A, B], [C, D]])
196
+ assert block_collapse(X.inverse()) == BlockMatrix([
197
+ [-X.schur('B').I * D * B.I, X.schur('B').I],
198
+ [B.I + B.I * A * X.schur('B').I * D * B.I, -B.I * A * X.schur('B').I],
199
+ ])
200
+
201
+ # test code path where only C is invertible
202
+ A = MatrixSymbol('A', n, m)
203
+ B = ZeroMatrix(n, n)
204
+ C = MatrixSymbol('C', m, m)
205
+ D = MatrixSymbol('D', m, n)
206
+ X = BlockMatrix([[A, B], [C, D]])
207
+ assert block_collapse(X.inverse()) == BlockMatrix([
208
+ [-C.I * D * X.schur('C').I, C.I + C.I * D * X.schur('C').I * A * C.I],
209
+ [X.schur('C').I, -X.schur('C').I * A * C.I],
210
+ ])
211
+
212
+ # test code path where only D is invertible
213
+ A = ZeroMatrix(n, n)
214
+ B = MatrixSymbol('B', n, m)
215
+ C = MatrixSymbol('C', m, n)
216
+ D = MatrixSymbol('D', m, m)
217
+ X = BlockMatrix([[A, B], [C, D]])
218
+ assert block_collapse(X.inverse()) == BlockMatrix([
219
+ [X.schur('D').I, -X.schur('D').I * B * D.I],
220
+ [-D.I * C * X.schur('D').I, D.I + D.I * C * X.schur('D').I * B * D.I],
221
+ ])
222
+
223
+
224
+ def test_BlockMatrix_2x2_inverse_numeric():
225
+ """Test 2x2 block matrix inversion numerically for all 4 formulas"""
226
+ M = Matrix([[1, 2], [3, 4]])
227
+ # rank deficient matrices that have full rank when two of them combined
228
+ D1 = Matrix([[1, 2], [2, 4]])
229
+ D2 = Matrix([[1, 3], [3, 9]])
230
+ D3 = Matrix([[1, 4], [4, 16]])
231
+ assert D1.rank() == D2.rank() == D3.rank() == 1
232
+ assert (D1 + D2).rank() == (D2 + D3).rank() == (D3 + D1).rank() == 2
233
+
234
+ # Only A is invertible
235
+ K = BlockMatrix([[M, D1], [D2, D3]])
236
+ assert block_collapse(K.inv()).as_explicit() == K.as_explicit().inv()
237
+ # Only B is invertible
238
+ K = BlockMatrix([[D1, M], [D2, D3]])
239
+ assert block_collapse(K.inv()).as_explicit() == K.as_explicit().inv()
240
+ # Only C is invertible
241
+ K = BlockMatrix([[D1, D2], [M, D3]])
242
+ assert block_collapse(K.inv()).as_explicit() == K.as_explicit().inv()
243
+ # Only D is invertible
244
+ K = BlockMatrix([[D1, D2], [D3, M]])
245
+ assert block_collapse(K.inv()).as_explicit() == K.as_explicit().inv()
246
+
247
+
248
+ @slow
249
+ def test_BlockMatrix_3x3_symbolic():
250
+ # Only test one of these, instead of all permutations, because it's slow
251
+ rowblocksizes = (n, m, k)
252
+ colblocksizes = (m, k, n)
253
+ K = BlockMatrix([
254
+ [MatrixSymbol('M%s%s' % (rows, cols), rows, cols) for cols in colblocksizes]
255
+ for rows in rowblocksizes
256
+ ])
257
+ collapse = block_collapse(K.I)
258
+ assert isinstance(collapse, BlockMatrix)
259
+
260
+
261
+ def test_BlockDiagMatrix():
262
+ A = MatrixSymbol('A', n, n)
263
+ B = MatrixSymbol('B', m, m)
264
+ C = MatrixSymbol('C', l, l)
265
+ M = MatrixSymbol('M', n + m + l, n + m + l)
266
+
267
+ X = BlockDiagMatrix(A, B, C)
268
+ Y = BlockDiagMatrix(A, 2*B, 3*C)
269
+
270
+ assert X.blocks[1, 1] == B
271
+ assert X.shape == (n + m + l, n + m + l)
272
+ assert all(X.blocks[i, j].is_ZeroMatrix if i != j else X.blocks[i, j] in [A, B, C]
273
+ for i in range(3) for j in range(3))
274
+ assert X.__class__(*X.args) == X
275
+ assert X.get_diag_blocks() == (A, B, C)
276
+
277
+ assert isinstance(block_collapse(X.I * X), Identity)
278
+
279
+ assert bc_matmul(X*X) == BlockDiagMatrix(A*A, B*B, C*C)
280
+ assert block_collapse(X*X) == BlockDiagMatrix(A*A, B*B, C*C)
281
+ #XXX: should be == ??
282
+ assert block_collapse(X + X).equals(BlockDiagMatrix(2*A, 2*B, 2*C))
283
+ assert block_collapse(X*Y) == BlockDiagMatrix(A*A, 2*B*B, 3*C*C)
284
+ assert block_collapse(X + Y) == BlockDiagMatrix(2*A, 3*B, 4*C)
285
+
286
+ # Ensure that BlockDiagMatrices can still interact with normal MatrixExprs
287
+ assert (X*(2*M)).is_MatMul
288
+ assert (X + (2*M)).is_MatAdd
289
+
290
+ assert (X._blockmul(M)).is_MatMul
291
+ assert (X._blockadd(M)).is_MatAdd
292
+
293
+ def test_BlockDiagMatrix_nonsquare():
294
+ A = MatrixSymbol('A', n, m)
295
+ B = MatrixSymbol('B', k, l)
296
+ X = BlockDiagMatrix(A, B)
297
+ assert X.shape == (n + k, m + l)
298
+ assert X.shape == (n + k, m + l)
299
+ assert X.rowblocksizes == [n, k]
300
+ assert X.colblocksizes == [m, l]
301
+ C = MatrixSymbol('C', n, m)
302
+ D = MatrixSymbol('D', k, l)
303
+ Y = BlockDiagMatrix(C, D)
304
+ assert block_collapse(X + Y) == BlockDiagMatrix(A + C, B + D)
305
+ assert block_collapse(X * Y.T) == BlockDiagMatrix(A * C.T, B * D.T)
306
+ raises(NonInvertibleMatrixError, lambda: BlockDiagMatrix(A, C.T).inverse())
307
+
308
+ def test_BlockDiagMatrix_determinant():
309
+ A = MatrixSymbol('A', n, n)
310
+ B = MatrixSymbol('B', m, m)
311
+ assert det(BlockDiagMatrix()) == 1
312
+ assert det(BlockDiagMatrix(A)) == det(A)
313
+ assert det(BlockDiagMatrix(A, B)) == det(A) * det(B)
314
+
315
+ # non-square blocks
316
+ C = MatrixSymbol('C', m, n)
317
+ D = MatrixSymbol('D', n, m)
318
+ assert det(BlockDiagMatrix(C, D)) == 0
319
+
320
+ def test_BlockDiagMatrix_trace():
321
+ assert trace(BlockDiagMatrix()) == 0
322
+ assert trace(BlockDiagMatrix(ZeroMatrix(n, n))) == 0
323
+ A = MatrixSymbol('A', n, n)
324
+ assert trace(BlockDiagMatrix(A)) == trace(A)
325
+ B = MatrixSymbol('B', m, m)
326
+ assert trace(BlockDiagMatrix(A, B)) == trace(A) + trace(B)
327
+
328
+ # non-square blocks
329
+ C = MatrixSymbol('C', m, n)
330
+ D = MatrixSymbol('D', n, m)
331
+ assert isinstance(trace(BlockDiagMatrix(C, D)), Trace)
332
+
333
+ def test_BlockDiagMatrix_transpose():
334
+ A = MatrixSymbol('A', n, m)
335
+ B = MatrixSymbol('B', k, l)
336
+ assert transpose(BlockDiagMatrix()) == BlockDiagMatrix()
337
+ assert transpose(BlockDiagMatrix(A)) == BlockDiagMatrix(A.T)
338
+ assert transpose(BlockDiagMatrix(A, B)) == BlockDiagMatrix(A.T, B.T)
339
+
340
+ def test_issue_2460():
341
+ bdm1 = BlockDiagMatrix(Matrix([i]), Matrix([j]))
342
+ bdm2 = BlockDiagMatrix(Matrix([k]), Matrix([l]))
343
+ assert block_collapse(bdm1 + bdm2) == BlockDiagMatrix(Matrix([i + k]), Matrix([j + l]))
344
+
345
+ def test_blockcut():
346
+ A = MatrixSymbol('A', n, m)
347
+ B = blockcut(A, (n/2, n/2), (m/2, m/2))
348
+ assert B == BlockMatrix([[A[:n/2, :m/2], A[:n/2, m/2:]],
349
+ [A[n/2:, :m/2], A[n/2:, m/2:]]])
350
+
351
+ M = ImmutableMatrix(4, 4, range(16))
352
+ B = blockcut(M, (2, 2), (2, 2))
353
+ assert M == ImmutableMatrix(B)
354
+
355
+ B = blockcut(M, (1, 3), (2, 2))
356
+ assert ImmutableMatrix(B.blocks[0, 1]) == ImmutableMatrix([[2, 3]])
357
+
358
+ def test_reblock_2x2():
359
+ B = BlockMatrix([[MatrixSymbol('A_%d%d'%(i,j), 2, 2)
360
+ for j in range(3)]
361
+ for i in range(3)])
362
+ assert B.blocks.shape == (3, 3)
363
+
364
+ BB = reblock_2x2(B)
365
+ assert BB.blocks.shape == (2, 2)
366
+
367
+ assert B.shape == BB.shape
368
+ assert B.as_explicit() == BB.as_explicit()
369
+
370
+ def test_deblock():
371
+ B = BlockMatrix([[MatrixSymbol('A_%d%d'%(i,j), n, n)
372
+ for j in range(4)]
373
+ for i in range(4)])
374
+
375
+ assert deblock(reblock_2x2(B)) == B
376
+
377
+ def test_block_collapse_type():
378
+ bm1 = BlockDiagMatrix(ImmutableMatrix([1]), ImmutableMatrix([2]))
379
+ bm2 = BlockDiagMatrix(ImmutableMatrix([3]), ImmutableMatrix([4]))
380
+
381
+ assert bm1.T.__class__ == BlockDiagMatrix
382
+ assert block_collapse(bm1 - bm2).__class__ == BlockDiagMatrix
383
+ assert block_collapse(Inverse(bm1)).__class__ == BlockDiagMatrix
384
+ assert block_collapse(Transpose(bm1)).__class__ == BlockDiagMatrix
385
+ assert bc_transpose(Transpose(bm1)).__class__ == BlockDiagMatrix
386
+ assert bc_inverse(Inverse(bm1)).__class__ == BlockDiagMatrix
387
+
388
+ def test_invalid_block_matrix():
389
+ raises(ValueError, lambda: BlockMatrix([
390
+ [Identity(2), Identity(5)],
391
+ ]))
392
+ raises(ValueError, lambda: BlockMatrix([
393
+ [Identity(n), Identity(m)],
394
+ ]))
395
+ raises(ValueError, lambda: BlockMatrix([
396
+ [ZeroMatrix(n, n), ZeroMatrix(n, n)],
397
+ [ZeroMatrix(n, n - 1), ZeroMatrix(n, n + 1)],
398
+ ]))
399
+ raises(ValueError, lambda: BlockMatrix([
400
+ [ZeroMatrix(n - 1, n), ZeroMatrix(n, n)],
401
+ [ZeroMatrix(n + 1, n), ZeroMatrix(n, n)],
402
+ ]))
403
+
404
+ def test_block_lu_decomposition():
405
+ A = MatrixSymbol('A', n, n)
406
+ B = MatrixSymbol('B', n, m)
407
+ C = MatrixSymbol('C', m, n)
408
+ D = MatrixSymbol('D', m, m)
409
+ X = BlockMatrix([[A, B], [C, D]])
410
+
411
+ #LDU decomposition
412
+ L, D, U = X.LDUdecomposition()
413
+ assert block_collapse(L*D*U) == X
414
+
415
+ #UDL decomposition
416
+ U, D, L = X.UDLdecomposition()
417
+ assert block_collapse(U*D*L) == X
418
+
419
+ #LU decomposition
420
+ L, U = X.LUdecomposition()
421
+ assert block_collapse(L*U) == X
422
+
423
+ def test_issue_21866():
424
+ n = 10
425
+ I = Identity(n)
426
+ O = ZeroMatrix(n, n)
427
+ A = BlockMatrix([[ I, O, O, O ],
428
+ [ O, I, O, O ],
429
+ [ O, O, I, O ],
430
+ [ I, O, O, I ]])
431
+ Ainv = block_collapse(A.inv())
432
+ AinvT = BlockMatrix([[ I, O, O, O ],
433
+ [ O, I, O, O ],
434
+ [ O, O, I, O ],
435
+ [ -I, O, O, I ]])
436
+ assert Ainv == AinvT
437
+
438
+
439
+ def test_adjoint_and_special_matrices():
440
+ A = Identity(3)
441
+ B = OneMatrix(3, 2)
442
+ C = ZeroMatrix(2, 3)
443
+ D = Identity(2)
444
+ X = BlockMatrix([[A, B], [C, D]])
445
+ X2 = BlockMatrix([[A, S.ImaginaryUnit*B], [C, D]])
446
+ assert X.adjoint() == BlockMatrix([[A, ZeroMatrix(3, 2)], [OneMatrix(2, 3), D]])
447
+ assert re(X) == X
448
+ assert X2.adjoint() == BlockMatrix([[A, ZeroMatrix(3, 2)], [-S.ImaginaryUnit*OneMatrix(2, 3), D]])
449
+ assert im(X2) == BlockMatrix([[ZeroMatrix(3, 3), OneMatrix(3, 2)], [ZeroMatrix(2, 3), ZeroMatrix(2, 2)]])
450
+
451
+
452
+ def test_block_matrix_derivative():
453
+ x = symbols('x')
454
+ A = Matrix(3, 3, [Function(f'a{i}')(x) for i in range(9)])
455
+ bc = BlockMatrix([[A[:2, :2], A[:2, 2]], [A[2, :2], A[2:, 2]]])
456
+ assert Matrix(bc.diff(x)) - A.diff(x) == zeros(3, 3)
457
+
458
+
459
+ def test_transpose_inverse_commute():
460
+ n = Symbol('n')
461
+ I = Identity(n)
462
+ Z = ZeroMatrix(n, n)
463
+ A = BlockMatrix([[I, Z], [Z, I]])
464
+
465
+ assert block_collapse(A.transpose().inverse()) == A
466
+ assert block_collapse(A.inverse().transpose()) == A
467
+
468
+ assert block_collapse(MatPow(A.transpose(), -2)) == MatPow(A, -2)
469
+ assert block_collapse(MatPow(A, -2).transpose()) == MatPow(A, -2)
miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/matrices/expressions/tests/test_companion.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.expr import unchanged
2
+ from sympy.core.symbol import Symbol, symbols
3
+ from sympy.matrices.immutable import ImmutableDenseMatrix
4
+ from sympy.matrices.expressions.companion import CompanionMatrix
5
+ from sympy.polys.polytools import Poly
6
+ from sympy.testing.pytest import raises
7
+
8
+
9
+ def test_creation():
10
+ x = Symbol('x')
11
+ y = Symbol('y')
12
+ raises(ValueError, lambda: CompanionMatrix(1))
13
+ raises(ValueError, lambda: CompanionMatrix(Poly([1], x)))
14
+ raises(ValueError, lambda: CompanionMatrix(Poly([2, 1], x)))
15
+ raises(ValueError, lambda: CompanionMatrix(Poly(x*y, [x, y])))
16
+ assert unchanged(CompanionMatrix, Poly([1, 2, 3], x))
17
+
18
+
19
+ def test_shape():
20
+ c0, c1, c2 = symbols('c0:3')
21
+ x = Symbol('x')
22
+ assert CompanionMatrix(Poly([1, c0], x)).shape == (1, 1)
23
+ assert CompanionMatrix(Poly([1, c1, c0], x)).shape == (2, 2)
24
+ assert CompanionMatrix(Poly([1, c2, c1, c0], x)).shape == (3, 3)
25
+
26
+
27
+ def test_entry():
28
+ c0, c1, c2 = symbols('c0:3')
29
+ x = Symbol('x')
30
+ A = CompanionMatrix(Poly([1, c2, c1, c0], x))
31
+ assert A[0, 0] == 0
32
+ assert A[1, 0] == 1
33
+ assert A[1, 1] == 0
34
+ assert A[2, 1] == 1
35
+ assert A[0, 2] == -c0
36
+ assert A[1, 2] == -c1
37
+ assert A[2, 2] == -c2
38
+
39
+
40
+ def test_as_explicit():
41
+ c0, c1, c2 = symbols('c0:3')
42
+ x = Symbol('x')
43
+ assert CompanionMatrix(Poly([1, c0], x)).as_explicit() == \
44
+ ImmutableDenseMatrix([-c0])
45
+ assert CompanionMatrix(Poly([1, c1, c0], x)).as_explicit() == \
46
+ ImmutableDenseMatrix([[0, -c0], [1, -c1]])
47
+ assert CompanionMatrix(Poly([1, c2, c1, c0], x)).as_explicit() == \
48
+ ImmutableDenseMatrix([[0, 0, -c0], [1, 0, -c1], [0, 1, -c2]])
miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/matrices/expressions/tests/test_derivatives.py ADDED
@@ -0,0 +1,477 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Some examples have been taken from:
3
+
4
+ http://www.math.uwaterloo.ca/~hwolkowi//matrixcookbook.pdf
5
+ """
6
+ from sympy import KroneckerProduct
7
+ from sympy.combinatorics import Permutation
8
+ from sympy.concrete.summations import Sum
9
+ from sympy.core.numbers import Rational
10
+ from sympy.core.singleton import S
11
+ from sympy.core.symbol import symbols
12
+ from sympy.functions.elementary.exponential import (exp, log)
13
+ from sympy.functions.elementary.miscellaneous import sqrt
14
+ from sympy.functions.elementary.trigonometric import (cos, sin, tan)
15
+ from sympy.functions.special.tensor_functions import KroneckerDelta
16
+ from sympy.matrices.expressions.determinant import Determinant
17
+ from sympy.matrices.expressions.diagonal import DiagMatrix
18
+ from sympy.matrices.expressions.hadamard import (HadamardPower, HadamardProduct, hadamard_product)
19
+ from sympy.matrices.expressions.inverse import Inverse
20
+ from sympy.matrices.expressions.matexpr import MatrixSymbol
21
+ from sympy.matrices.expressions.special import OneMatrix
22
+ from sympy.matrices.expressions.trace import Trace
23
+ from sympy.matrices.expressions.matadd import MatAdd
24
+ from sympy.matrices.expressions.matmul import MatMul
25
+ from sympy.matrices.expressions.special import (Identity, ZeroMatrix)
26
+ from sympy.tensor.array.array_derivatives import ArrayDerivative
27
+ from sympy.matrices.expressions import hadamard_power
28
+ from sympy.tensor.array.expressions.array_expressions import ArrayAdd, ArrayTensorProduct, PermuteDims
29
+
30
+ i, j, k = symbols("i j k")
31
+ m, n = symbols("m n")
32
+
33
+ X = MatrixSymbol("X", k, k)
34
+ x = MatrixSymbol("x", k, 1)
35
+ y = MatrixSymbol("y", k, 1)
36
+
37
+ A = MatrixSymbol("A", k, k)
38
+ B = MatrixSymbol("B", k, k)
39
+ C = MatrixSymbol("C", k, k)
40
+ D = MatrixSymbol("D", k, k)
41
+
42
+ a = MatrixSymbol("a", k, 1)
43
+ b = MatrixSymbol("b", k, 1)
44
+ c = MatrixSymbol("c", k, 1)
45
+ d = MatrixSymbol("d", k, 1)
46
+
47
+
48
+ KDelta = lambda i, j: KroneckerDelta(i, j, (0, k-1))
49
+
50
+
51
+ def _check_derivative_with_explicit_matrix(expr, x, diffexpr, dim=2):
52
+ # TODO: this is commented because it slows down the tests.
53
+ return
54
+
55
+ expr = expr.xreplace({k: dim})
56
+ x = x.xreplace({k: dim})
57
+ diffexpr = diffexpr.xreplace({k: dim})
58
+
59
+ expr = expr.as_explicit()
60
+ x = x.as_explicit()
61
+ diffexpr = diffexpr.as_explicit()
62
+
63
+ assert expr.diff(x).reshape(*diffexpr.shape).tomatrix() == diffexpr
64
+
65
+
66
+ def test_matrix_derivative_by_scalar():
67
+ assert A.diff(i) == ZeroMatrix(k, k)
68
+ assert (A*(X + B)*c).diff(i) == ZeroMatrix(k, 1)
69
+ assert x.diff(i) == ZeroMatrix(k, 1)
70
+ assert (x.T*y).diff(i) == ZeroMatrix(1, 1)
71
+ assert (x*x.T).diff(i) == ZeroMatrix(k, k)
72
+ assert (x + y).diff(i) == ZeroMatrix(k, 1)
73
+ assert hadamard_power(x, 2).diff(i) == ZeroMatrix(k, 1)
74
+ assert hadamard_power(x, i).diff(i).dummy_eq(
75
+ HadamardProduct(x.applyfunc(log), HadamardPower(x, i)))
76
+ assert hadamard_product(x, y).diff(i) == ZeroMatrix(k, 1)
77
+ assert hadamard_product(i*OneMatrix(k, 1), x, y).diff(i) == hadamard_product(x, y)
78
+ assert (i*x).diff(i) == x
79
+ assert (sin(i)*A*B*x).diff(i) == cos(i)*A*B*x
80
+ assert x.applyfunc(sin).diff(i) == ZeroMatrix(k, 1)
81
+ assert Trace(i**2*X).diff(i) == 2*i*Trace(X)
82
+
83
+ mu = symbols("mu")
84
+ expr = (2*mu*x)
85
+ assert expr.diff(x) == 2*mu*Identity(k)
86
+
87
+
88
+ def test_one_matrix():
89
+ assert MatMul(x.T, OneMatrix(k, 1)).diff(x) == OneMatrix(k, 1)
90
+
91
+
92
+ def test_matrix_derivative_non_matrix_result():
93
+ # This is a 4-dimensional array:
94
+ I = Identity(k)
95
+ AdA = PermuteDims(ArrayTensorProduct(I, I), Permutation(3)(1, 2))
96
+ assert A.diff(A) == AdA
97
+ assert A.T.diff(A) == PermuteDims(ArrayTensorProduct(I, I), Permutation(3)(1, 2, 3))
98
+ assert (2*A).diff(A) == PermuteDims(ArrayTensorProduct(2*I, I), Permutation(3)(1, 2))
99
+ assert MatAdd(A, A).diff(A) == ArrayAdd(AdA, AdA)
100
+ assert (A + B).diff(A) == AdA
101
+
102
+
103
+ def test_matrix_derivative_trivial_cases():
104
+ # Cookbook example 33:
105
+ # TODO: find a way to represent a four-dimensional zero-array:
106
+ assert X.diff(A) == ArrayDerivative(X, A)
107
+
108
+
109
+ def test_matrix_derivative_with_inverse():
110
+
111
+ # Cookbook example 61:
112
+ expr = a.T*Inverse(X)*b
113
+ assert expr.diff(X) == -Inverse(X).T*a*b.T*Inverse(X).T
114
+
115
+ # Cookbook example 62:
116
+ expr = Determinant(Inverse(X))
117
+ # Not implemented yet:
118
+ # assert expr.diff(X) == -Determinant(X.inv())*(X.inv()).T
119
+
120
+ # Cookbook example 63:
121
+ expr = Trace(A*Inverse(X)*B)
122
+ assert expr.diff(X) == -(X**(-1)*B*A*X**(-1)).T
123
+
124
+ # Cookbook example 64:
125
+ expr = Trace(Inverse(X + A))
126
+ assert expr.diff(X) == -(Inverse(X + A)).T**2
127
+
128
+
129
+ def test_matrix_derivative_vectors_and_scalars():
130
+
131
+ assert x.diff(x) == Identity(k)
132
+ assert x[i, 0].diff(x[m, 0]).doit() == KDelta(m, i)
133
+
134
+ assert x.T.diff(x) == Identity(k)
135
+
136
+ # Cookbook example 69:
137
+ expr = x.T*a
138
+ assert expr.diff(x) == a
139
+ assert expr[0, 0].diff(x[m, 0]).doit() == a[m, 0]
140
+ expr = a.T*x
141
+ assert expr.diff(x) == a
142
+
143
+ # Cookbook example 70:
144
+ expr = a.T*X*b
145
+ assert expr.diff(X) == a*b.T
146
+
147
+ # Cookbook example 71:
148
+ expr = a.T*X.T*b
149
+ assert expr.diff(X) == b*a.T
150
+
151
+ # Cookbook example 72:
152
+ expr = a.T*X*a
153
+ assert expr.diff(X) == a*a.T
154
+ expr = a.T*X.T*a
155
+ assert expr.diff(X) == a*a.T
156
+
157
+ # Cookbook example 77:
158
+ expr = b.T*X.T*X*c
159
+ assert expr.diff(X) == X*b*c.T + X*c*b.T
160
+
161
+ # Cookbook example 78:
162
+ expr = (B*x + b).T*C*(D*x + d)
163
+ assert expr.diff(x) == B.T*C*(D*x + d) + D.T*C.T*(B*x + b)
164
+
165
+ # Cookbook example 81:
166
+ expr = x.T*B*x
167
+ assert expr.diff(x) == B*x + B.T*x
168
+
169
+ # Cookbook example 82:
170
+ expr = b.T*X.T*D*X*c
171
+ assert expr.diff(X) == D.T*X*b*c.T + D*X*c*b.T
172
+
173
+ # Cookbook example 83:
174
+ expr = (X*b + c).T*D*(X*b + c)
175
+ assert expr.diff(X) == D*(X*b + c)*b.T + D.T*(X*b + c)*b.T
176
+ assert str(expr[0, 0].diff(X[m, n]).doit()) == \
177
+ 'b[n, 0]*Sum((c[_i_1, 0] + Sum(X[_i_1, _i_3]*b[_i_3, 0], (_i_3, 0, k - 1)))*D[_i_1, m], (_i_1, 0, k - 1)) + Sum((c[_i_2, 0] + Sum(X[_i_2, _i_4]*b[_i_4, 0], (_i_4, 0, k - 1)))*D[m, _i_2]*b[n, 0], (_i_2, 0, k - 1))'
178
+
179
+ # See https://github.com/sympy/sympy/issues/16504#issuecomment-1018339957
180
+ expr = x*x.T*x
181
+ I = Identity(k)
182
+ assert expr.diff(x) == KroneckerProduct(I, x.T*x) + 2*x*x.T
183
+
184
+
185
+ def test_matrix_derivatives_of_traces():
186
+
187
+ expr = Trace(A)*A
188
+ I = Identity(k)
189
+ assert expr.diff(A) == ArrayAdd(ArrayTensorProduct(I, A), PermuteDims(ArrayTensorProduct(Trace(A)*I, I), Permutation(3)(1, 2)))
190
+ assert expr[i, j].diff(A[m, n]).doit() == (
191
+ KDelta(i, m)*KDelta(j, n)*Trace(A) +
192
+ KDelta(m, n)*A[i, j]
193
+ )
194
+
195
+ ## First order:
196
+
197
+ # Cookbook example 99:
198
+ expr = Trace(X)
199
+ assert expr.diff(X) == Identity(k)
200
+ assert expr.rewrite(Sum).diff(X[m, n]).doit() == KDelta(m, n)
201
+
202
+ # Cookbook example 100:
203
+ expr = Trace(X*A)
204
+ assert expr.diff(X) == A.T
205
+ assert expr.rewrite(Sum).diff(X[m, n]).doit() == A[n, m]
206
+
207
+ # Cookbook example 101:
208
+ expr = Trace(A*X*B)
209
+ assert expr.diff(X) == A.T*B.T
210
+ assert expr.rewrite(Sum).diff(X[m, n]).doit().dummy_eq((A.T*B.T)[m, n])
211
+
212
+ # Cookbook example 102:
213
+ expr = Trace(A*X.T*B)
214
+ assert expr.diff(X) == B*A
215
+
216
+ # Cookbook example 103:
217
+ expr = Trace(X.T*A)
218
+ assert expr.diff(X) == A
219
+
220
+ # Cookbook example 104:
221
+ expr = Trace(A*X.T)
222
+ assert expr.diff(X) == A
223
+
224
+ # Cookbook example 105:
225
+ # TODO: TensorProduct is not supported
226
+ #expr = Trace(TensorProduct(A, X))
227
+ #assert expr.diff(X) == Trace(A)*Identity(k)
228
+
229
+ ## Second order:
230
+
231
+ # Cookbook example 106:
232
+ expr = Trace(X**2)
233
+ assert expr.diff(X) == 2*X.T
234
+
235
+ # Cookbook example 107:
236
+ expr = Trace(X**2*B)
237
+ assert expr.diff(X) == (X*B + B*X).T
238
+ expr = Trace(MatMul(X, X, B))
239
+ assert expr.diff(X) == (X*B + B*X).T
240
+
241
+ # Cookbook example 108:
242
+ expr = Trace(X.T*B*X)
243
+ assert expr.diff(X) == B*X + B.T*X
244
+
245
+ # Cookbook example 109:
246
+ expr = Trace(B*X*X.T)
247
+ assert expr.diff(X) == B*X + B.T*X
248
+
249
+ # Cookbook example 110:
250
+ expr = Trace(X*X.T*B)
251
+ assert expr.diff(X) == B*X + B.T*X
252
+
253
+ # Cookbook example 111:
254
+ expr = Trace(X*B*X.T)
255
+ assert expr.diff(X) == X*B.T + X*B
256
+
257
+ # Cookbook example 112:
258
+ expr = Trace(B*X.T*X)
259
+ assert expr.diff(X) == X*B.T + X*B
260
+
261
+ # Cookbook example 113:
262
+ expr = Trace(X.T*X*B)
263
+ assert expr.diff(X) == X*B.T + X*B
264
+
265
+ # Cookbook example 114:
266
+ expr = Trace(A*X*B*X)
267
+ assert expr.diff(X) == A.T*X.T*B.T + B.T*X.T*A.T
268
+
269
+ # Cookbook example 115:
270
+ expr = Trace(X.T*X)
271
+ assert expr.diff(X) == 2*X
272
+ expr = Trace(X*X.T)
273
+ assert expr.diff(X) == 2*X
274
+
275
+ # Cookbook example 116:
276
+ expr = Trace(B.T*X.T*C*X*B)
277
+ assert expr.diff(X) == C.T*X*B*B.T + C*X*B*B.T
278
+
279
+ # Cookbook example 117:
280
+ expr = Trace(X.T*B*X*C)
281
+ assert expr.diff(X) == B*X*C + B.T*X*C.T
282
+
283
+ # Cookbook example 118:
284
+ expr = Trace(A*X*B*X.T*C)
285
+ assert expr.diff(X) == A.T*C.T*X*B.T + C*A*X*B
286
+
287
+ # Cookbook example 119:
288
+ expr = Trace((A*X*B + C)*(A*X*B + C).T)
289
+ assert expr.diff(X) == 2*A.T*(A*X*B + C)*B.T
290
+
291
+ # Cookbook example 120:
292
+ # TODO: no support for TensorProduct.
293
+ # expr = Trace(TensorProduct(X, X))
294
+ # expr = Trace(X)*Trace(X)
295
+ # expr.diff(X) == 2*Trace(X)*Identity(k)
296
+
297
+ # Higher Order
298
+
299
+ # Cookbook example 121:
300
+ expr = Trace(X**k)
301
+ #assert expr.diff(X) == k*(X**(k-1)).T
302
+
303
+ # Cookbook example 122:
304
+ expr = Trace(A*X**k)
305
+ #assert expr.diff(X) == # Needs indices
306
+
307
+ # Cookbook example 123:
308
+ expr = Trace(B.T*X.T*C*X*X.T*C*X*B)
309
+ assert expr.diff(X) == C*X*X.T*C*X*B*B.T + C.T*X*B*B.T*X.T*C.T*X + C*X*B*B.T*X.T*C*X + C.T*X*X.T*C.T*X*B*B.T
310
+
311
+ # Other
312
+
313
+ # Cookbook example 124:
314
+ expr = Trace(A*X**(-1)*B)
315
+ assert expr.diff(X) == -Inverse(X).T*A.T*B.T*Inverse(X).T
316
+
317
+ # Cookbook example 125:
318
+ expr = Trace(Inverse(X.T*C*X)*A)
319
+ # Warning: result in the cookbook is equivalent if B and C are symmetric:
320
+ assert expr.diff(X) == - X.inv().T*A.T*X.inv()*C.inv().T*X.inv().T - X.inv().T*A*X.inv()*C.inv()*X.inv().T
321
+
322
+ # Cookbook example 126:
323
+ expr = Trace((X.T*C*X).inv()*(X.T*B*X))
324
+ assert expr.diff(X) == -2*C*X*(X.T*C*X).inv()*X.T*B*X*(X.T*C*X).inv() + 2*B*X*(X.T*C*X).inv()
325
+
326
+ # Cookbook example 127:
327
+ expr = Trace((A + X.T*C*X).inv()*(X.T*B*X))
328
+ # Warning: result in the cookbook is equivalent if B and C are symmetric:
329
+ assert expr.diff(X) == B*X*Inverse(A + X.T*C*X) - C*X*Inverse(A + X.T*C*X)*X.T*B*X*Inverse(A + X.T*C*X) - C.T*X*Inverse(A.T + (C*X).T*X)*X.T*B.T*X*Inverse(A.T + (C*X).T*X) + B.T*X*Inverse(A.T + (C*X).T*X)
330
+
331
+
332
+ def test_derivatives_of_complicated_matrix_expr():
333
+ expr = a.T*(A*X*(X.T*B + X*A) + B.T*X.T*(a*b.T*(X*D*X.T + X*(X.T*B + A*X)*D*B - X.T*C.T*A)*B + B*(X*D.T + B*A*X*A.T - 3*X*D))*B + 42*X*B*X.T*A.T*(X + X.T))*b
334
+ result = (B*(B*A*X*A.T - 3*X*D + X*D.T) + a*b.T*(X*(A*X + X.T*B)*D*B + X*D*X.T - X.T*C.T*A)*B)*B*b*a.T*B.T + B**2*b*a.T*B.T*X.T*a*b.T*X*D + 42*A*X*B.T*X.T*a*b.T + B*D*B**3*b*a.T*B.T*X.T*a*b.T*X + B*b*a.T*A*X + a*b.T*(42*X + 42*X.T)*A*X*B.T + b*a.T*X*B*a*b.T*B.T**2*X*D.T + b*a.T*X*B*a*b.T*B.T**3*D.T*(B.T*X + X.T*A.T) + 42*b*a.T*X*B*X.T*A.T + A.T*(42*X + 42*X.T)*b*a.T*X*B + A.T*B.T**2*X*B*a*b.T*B.T*A + A.T*a*b.T*(A.T*X.T + B.T*X) + A.T*X.T*b*a.T*X*B*a*b.T*B.T**3*D.T + B.T*X*B*a*b.T*B.T*D - 3*B.T*X*B*a*b.T*B.T*D.T - C.T*A*B**2*b*a.T*B.T*X.T*a*b.T + X.T*A.T*a*b.T*A.T
335
+ assert expr.diff(X) == result
336
+
337
+
338
+ def test_mixed_deriv_mixed_expressions():
339
+
340
+ expr = 3*Trace(A)
341
+ assert expr.diff(A) == 3*Identity(k)
342
+
343
+ expr = k
344
+ deriv = expr.diff(A)
345
+ assert isinstance(deriv, ZeroMatrix)
346
+ assert deriv == ZeroMatrix(k, k)
347
+
348
+ expr = Trace(A)**2
349
+ assert expr.diff(A) == (2*Trace(A))*Identity(k)
350
+
351
+ expr = Trace(A)*A
352
+ I = Identity(k)
353
+ assert expr.diff(A) == ArrayAdd(ArrayTensorProduct(I, A), PermuteDims(ArrayTensorProduct(Trace(A)*I, I), Permutation(3)(1, 2)))
354
+
355
+ expr = Trace(Trace(A)*A)
356
+ assert expr.diff(A) == (2*Trace(A))*Identity(k)
357
+
358
+ expr = Trace(Trace(Trace(A)*A)*A)
359
+ assert expr.diff(A) == (3*Trace(A)**2)*Identity(k)
360
+
361
+
362
+ def test_derivatives_matrix_norms():
363
+
364
+ expr = x.T*y
365
+ assert expr.diff(x) == y
366
+ assert expr[0, 0].diff(x[m, 0]).doit() == y[m, 0]
367
+
368
+ expr = (x.T*y)**S.Half
369
+ assert expr.diff(x) == y/(2*sqrt(x.T*y))
370
+
371
+ expr = (x.T*x)**S.Half
372
+ assert expr.diff(x) == x*(x.T*x)**Rational(-1, 2)
373
+
374
+ expr = (c.T*a*x.T*b)**S.Half
375
+ assert expr.diff(x) == b*a.T*c/sqrt(c.T*a*x.T*b)/2
376
+
377
+ expr = (c.T*a*x.T*b)**Rational(1, 3)
378
+ assert expr.diff(x) == b*a.T*c*(c.T*a*x.T*b)**Rational(-2, 3)/3
379
+
380
+ expr = (a.T*X*b)**S.Half
381
+ assert expr.diff(X) == a/(2*sqrt(a.T*X*b))*b.T
382
+
383
+ expr = d.T*x*(a.T*X*b)**S.Half*y.T*c
384
+ assert expr.diff(X) == a/(2*sqrt(a.T*X*b))*x.T*d*y.T*c*b.T
385
+
386
+
387
+ def test_derivatives_elementwise_applyfunc():
388
+
389
+ expr = x.applyfunc(tan)
390
+ assert expr.diff(x).dummy_eq(
391
+ DiagMatrix(x.applyfunc(lambda x: tan(x)**2 + 1)))
392
+ assert expr[i, 0].diff(x[m, 0]).doit() == (tan(x[i, 0])**2 + 1)*KDelta(i, m)
393
+ _check_derivative_with_explicit_matrix(expr, x, expr.diff(x))
394
+
395
+ expr = (i**2*x).applyfunc(sin)
396
+ assert expr.diff(i).dummy_eq(
397
+ HadamardProduct((2*i)*x, (i**2*x).applyfunc(cos)))
398
+ assert expr[i, 0].diff(i).doit() == 2*i*x[i, 0]*cos(i**2*x[i, 0])
399
+ _check_derivative_with_explicit_matrix(expr, i, expr.diff(i))
400
+
401
+ expr = (log(i)*A*B).applyfunc(sin)
402
+ assert expr.diff(i).dummy_eq(
403
+ HadamardProduct(A*B/i, (log(i)*A*B).applyfunc(cos)))
404
+ _check_derivative_with_explicit_matrix(expr, i, expr.diff(i))
405
+
406
+ expr = A*x.applyfunc(exp)
407
+ # TODO: restore this result (currently returning the transpose):
408
+ # assert expr.diff(x).dummy_eq(DiagMatrix(x.applyfunc(exp))*A.T)
409
+ _check_derivative_with_explicit_matrix(expr, x, expr.diff(x))
410
+
411
+ expr = x.T*A*x + k*y.applyfunc(sin).T*x
412
+ assert expr.diff(x).dummy_eq(A.T*x + A*x + k*y.applyfunc(sin))
413
+ _check_derivative_with_explicit_matrix(expr, x, expr.diff(x))
414
+
415
+ expr = x.applyfunc(sin).T*y
416
+ # TODO: restore (currently returning the transpose):
417
+ # assert expr.diff(x).dummy_eq(DiagMatrix(x.applyfunc(cos))*y)
418
+ _check_derivative_with_explicit_matrix(expr, x, expr.diff(x))
419
+
420
+ expr = (a.T * X * b).applyfunc(sin)
421
+ assert expr.diff(X).dummy_eq(a*(a.T*X*b).applyfunc(cos)*b.T)
422
+ _check_derivative_with_explicit_matrix(expr, X, expr.diff(X))
423
+
424
+ expr = a.T * X.applyfunc(sin) * b
425
+ assert expr.diff(X).dummy_eq(
426
+ DiagMatrix(a)*X.applyfunc(cos)*DiagMatrix(b))
427
+ _check_derivative_with_explicit_matrix(expr, X, expr.diff(X))
428
+
429
+ expr = a.T * (A*X*B).applyfunc(sin) * b
430
+ assert expr.diff(X).dummy_eq(
431
+ A.T*DiagMatrix(a)*(A*X*B).applyfunc(cos)*DiagMatrix(b)*B.T)
432
+ _check_derivative_with_explicit_matrix(expr, X, expr.diff(X))
433
+
434
+ expr = a.T * (A*X*b).applyfunc(sin) * b.T
435
+ # TODO: not implemented
436
+ #assert expr.diff(X) == ...
437
+ #_check_derivative_with_explicit_matrix(expr, X, expr.diff(X))
438
+
439
+ expr = a.T*A*X.applyfunc(sin)*B*b
440
+ assert expr.diff(X).dummy_eq(
441
+ HadamardProduct(A.T * a * b.T * B.T, X.applyfunc(cos)))
442
+
443
+ expr = a.T * (A*X.applyfunc(sin)*B).applyfunc(log) * b
444
+ # TODO: wrong
445
+ # assert expr.diff(X) == A.T*DiagMatrix(a)*(A*X.applyfunc(sin)*B).applyfunc(Lambda(k, 1/k))*DiagMatrix(b)*B.T
446
+
447
+ expr = a.T * (X.applyfunc(sin)).applyfunc(log) * b
448
+ # TODO: wrong
449
+ # assert expr.diff(X) == DiagMatrix(a)*X.applyfunc(sin).applyfunc(Lambda(k, 1/k))*DiagMatrix(b)
450
+
451
+
452
+ def test_derivatives_of_hadamard_expressions():
453
+
454
+ # Hadamard Product
455
+
456
+ expr = hadamard_product(a, x, b)
457
+ assert expr.diff(x) == DiagMatrix(hadamard_product(b, a))
458
+
459
+ expr = a.T*hadamard_product(A, X, B)*b
460
+ assert expr.diff(X) == HadamardProduct(a*b.T, A, B)
461
+
462
+ # Hadamard Power
463
+
464
+ expr = hadamard_power(x, 2)
465
+ assert expr.diff(x).doit() == 2*DiagMatrix(x)
466
+
467
+ expr = hadamard_power(x.T, 2)
468
+ assert expr.diff(x).doit() == 2*DiagMatrix(x)
469
+
470
+ expr = hadamard_power(x, S.Half)
471
+ assert expr.diff(x) == S.Half*DiagMatrix(hadamard_power(x, Rational(-1, 2)))
472
+
473
+ expr = hadamard_power(a.T*X*b, 2)
474
+ assert expr.diff(X) == 2*a*a.T*X*b*b.T
475
+
476
+ expr = hadamard_power(a.T*X*b, S.Half)
477
+ assert expr.diff(X) == a/(2*sqrt(a.T*X*b))*b.T
miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/matrices/expressions/tests/test_determinant.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core import S, symbols
2
+ from sympy.matrices import eye, ones, Matrix, ShapeError
3
+ from sympy.matrices.expressions import (
4
+ Identity, MatrixExpr, MatrixSymbol, Determinant,
5
+ det, per, ZeroMatrix, Transpose,
6
+ Permanent, MatMul
7
+ )
8
+ from sympy.matrices.expressions.special import OneMatrix
9
+ from sympy.testing.pytest import raises
10
+ from sympy.assumptions.ask import Q
11
+ from sympy.assumptions.refine import refine
12
+
13
+ n = symbols('n', integer=True)
14
+ A = MatrixSymbol('A', n, n)
15
+ B = MatrixSymbol('B', n, n)
16
+ C = MatrixSymbol('C', 3, 4)
17
+
18
+
19
+ def test_det():
20
+ assert isinstance(Determinant(A), Determinant)
21
+ assert not isinstance(Determinant(A), MatrixExpr)
22
+ raises(ShapeError, lambda: Determinant(C))
23
+ assert det(eye(3)) == 1
24
+ assert det(Matrix(3, 3, [1, 3, 2, 4, 1, 3, 2, 5, 2])) == 17
25
+ _ = A / det(A) # Make sure this is possible
26
+
27
+ raises(TypeError, lambda: Determinant(S.One))
28
+
29
+ assert Determinant(A).arg is A
30
+
31
+
32
+ def test_eval_determinant():
33
+ assert det(Identity(n)) == 1
34
+ assert det(ZeroMatrix(n, n)) == 0
35
+ assert det(OneMatrix(n, n)) == Determinant(OneMatrix(n, n))
36
+ assert det(OneMatrix(1, 1)) == 1
37
+ assert det(OneMatrix(2, 2)) == 0
38
+ assert det(Transpose(A)) == det(A)
39
+ assert Determinant(MatMul(eye(2), eye(2))).doit(deep=True) == 1
40
+
41
+
42
+ def test_refine():
43
+ assert refine(det(A), Q.orthogonal(A)) == 1
44
+ assert refine(det(A), Q.singular(A)) == 0
45
+ assert refine(det(A), Q.unit_triangular(A)) == 1
46
+ assert refine(det(A), Q.normal(A)) == det(A)
47
+
48
+
49
+ def test_commutative():
50
+ det_a = Determinant(A)
51
+ det_b = Determinant(B)
52
+ assert det_a.is_commutative
53
+ assert det_b.is_commutative
54
+ assert det_a * det_b == det_b * det_a
55
+
56
+
57
+ def test_permanent():
58
+ assert isinstance(Permanent(A), Permanent)
59
+ assert not isinstance(Permanent(A), MatrixExpr)
60
+ assert isinstance(Permanent(C), Permanent)
61
+ assert Permanent(ones(3, 3)).doit() == 6
62
+ _ = C / per(C)
63
+ assert per(Matrix(3, 3, [1, 3, 2, 4, 1, 3, 2, 5, 2])) == 103
64
+ raises(TypeError, lambda: Permanent(S.One))
65
+ assert Permanent(A).arg is A
miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/matrices/expressions/tests/test_diagonal.py ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.matrices.expressions import MatrixSymbol
2
+ from sympy.matrices.expressions.diagonal import DiagonalMatrix, DiagonalOf, DiagMatrix, diagonalize_vector
3
+ from sympy.assumptions.ask import (Q, ask)
4
+ from sympy.core.symbol import Symbol
5
+ from sympy.functions.special.tensor_functions import KroneckerDelta
6
+ from sympy.matrices.dense import Matrix
7
+ from sympy.matrices.expressions.matmul import MatMul
8
+ from sympy.matrices.expressions.special import Identity
9
+ from sympy.testing.pytest import raises
10
+
11
+
12
+ n = Symbol('n')
13
+ m = Symbol('m')
14
+
15
+
16
+ def test_DiagonalMatrix():
17
+ x = MatrixSymbol('x', n, m)
18
+ D = DiagonalMatrix(x)
19
+ assert D.diagonal_length is None
20
+ assert D.shape == (n, m)
21
+
22
+ x = MatrixSymbol('x', n, n)
23
+ D = DiagonalMatrix(x)
24
+ assert D.diagonal_length == n
25
+ assert D.shape == (n, n)
26
+ assert D[1, 2] == 0
27
+ assert D[1, 1] == x[1, 1]
28
+ i = Symbol('i')
29
+ j = Symbol('j')
30
+ x = MatrixSymbol('x', 3, 3)
31
+ ij = DiagonalMatrix(x)[i, j]
32
+ assert ij != 0
33
+ assert ij.subs({i:0, j:0}) == x[0, 0]
34
+ assert ij.subs({i:0, j:1}) == 0
35
+ assert ij.subs({i:1, j:1}) == x[1, 1]
36
+ assert ask(Q.diagonal(D)) # affirm that D is diagonal
37
+
38
+ x = MatrixSymbol('x', n, 3)
39
+ D = DiagonalMatrix(x)
40
+ assert D.diagonal_length == 3
41
+ assert D.shape == (n, 3)
42
+ assert D[2, m] == KroneckerDelta(2, m)*x[2, m]
43
+ assert D[3, m] == 0
44
+ raises(IndexError, lambda: D[m, 3])
45
+
46
+ x = MatrixSymbol('x', 3, n)
47
+ D = DiagonalMatrix(x)
48
+ assert D.diagonal_length == 3
49
+ assert D.shape == (3, n)
50
+ assert D[m, 2] == KroneckerDelta(m, 2)*x[m, 2]
51
+ assert D[m, 3] == 0
52
+ raises(IndexError, lambda: D[3, m])
53
+
54
+ x = MatrixSymbol('x', n, m)
55
+ D = DiagonalMatrix(x)
56
+ assert D.diagonal_length is None
57
+ assert D.shape == (n, m)
58
+ assert D[m, 4] != 0
59
+
60
+ x = MatrixSymbol('x', 3, 4)
61
+ assert [DiagonalMatrix(x)[i] for i in range(12)] == [
62
+ x[0, 0], 0, 0, 0, 0, x[1, 1], 0, 0, 0, 0, x[2, 2], 0]
63
+
64
+ # shape is retained, issue 12427
65
+ assert (
66
+ DiagonalMatrix(MatrixSymbol('x', 3, 4))*
67
+ DiagonalMatrix(MatrixSymbol('x', 4, 2))).shape == (3, 2)
68
+
69
+
70
+ def test_DiagonalOf():
71
+ x = MatrixSymbol('x', n, n)
72
+ d = DiagonalOf(x)
73
+ assert d.shape == (n, 1)
74
+ assert d.diagonal_length == n
75
+ assert d[2, 0] == d[2] == x[2, 2]
76
+
77
+ x = MatrixSymbol('x', n, m)
78
+ d = DiagonalOf(x)
79
+ assert d.shape == (None, 1)
80
+ assert d.diagonal_length is None
81
+ assert d[2, 0] == d[2] == x[2, 2]
82
+
83
+ d = DiagonalOf(MatrixSymbol('x', 4, 3))
84
+ assert d.shape == (3, 1)
85
+ d = DiagonalOf(MatrixSymbol('x', n, 3))
86
+ assert d.shape == (3, 1)
87
+ d = DiagonalOf(MatrixSymbol('x', 3, n))
88
+ assert d.shape == (3, 1)
89
+ x = MatrixSymbol('x', n, m)
90
+ assert [DiagonalOf(x)[i] for i in range(4)] ==[
91
+ x[0, 0], x[1, 1], x[2, 2], x[3, 3]]
92
+
93
+
94
+ def test_DiagMatrix():
95
+ x = MatrixSymbol('x', n, 1)
96
+ d = DiagMatrix(x)
97
+ assert d.shape == (n, n)
98
+ assert d[0, 1] == 0
99
+ assert d[0, 0] == x[0, 0]
100
+
101
+ a = MatrixSymbol('a', 1, 1)
102
+ d = diagonalize_vector(a)
103
+ assert isinstance(d, MatrixSymbol)
104
+ assert a == d
105
+ assert diagonalize_vector(Identity(3)) == Identity(3)
106
+ assert DiagMatrix(Identity(3)).doit() == Identity(3)
107
+ assert isinstance(DiagMatrix(Identity(3)), DiagMatrix)
108
+
109
+ # A diagonal matrix is equal to its transpose:
110
+ assert DiagMatrix(x).T == DiagMatrix(x)
111
+ assert diagonalize_vector(x.T) == DiagMatrix(x)
112
+
113
+ dx = DiagMatrix(x)
114
+ assert dx[0, 0] == x[0, 0]
115
+ assert dx[1, 1] == x[1, 0]
116
+ assert dx[0, 1] == 0
117
+ assert dx[0, m] == x[0, 0]*KroneckerDelta(0, m)
118
+
119
+ z = MatrixSymbol('z', 1, n)
120
+ dz = DiagMatrix(z)
121
+ assert dz[0, 0] == z[0, 0]
122
+ assert dz[1, 1] == z[0, 1]
123
+ assert dz[0, 1] == 0
124
+ assert dz[0, m] == z[0, m]*KroneckerDelta(0, m)
125
+
126
+ v = MatrixSymbol('v', 3, 1)
127
+ dv = DiagMatrix(v)
128
+ assert dv.as_explicit() == Matrix([
129
+ [v[0, 0], 0, 0],
130
+ [0, v[1, 0], 0],
131
+ [0, 0, v[2, 0]],
132
+ ])
133
+
134
+ v = MatrixSymbol('v', 1, 3)
135
+ dv = DiagMatrix(v)
136
+ assert dv.as_explicit() == Matrix([
137
+ [v[0, 0], 0, 0],
138
+ [0, v[0, 1], 0],
139
+ [0, 0, v[0, 2]],
140
+ ])
141
+
142
+ dv = DiagMatrix(3*v)
143
+ assert dv.args == (3*v,)
144
+ assert dv.doit() == 3*DiagMatrix(v)
145
+ assert isinstance(dv.doit(), MatMul)
146
+
147
+ a = MatrixSymbol("a", 3, 1).as_explicit()
148
+ expr = DiagMatrix(a)
149
+ result = Matrix([
150
+ [a[0, 0], 0, 0],
151
+ [0, a[1, 0], 0],
152
+ [0, 0, a[2, 0]],
153
+ ])
154
+ assert expr.doit() == result
155
+ expr = DiagMatrix(a.T)
156
+ assert expr.doit() == result
miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/matrices/expressions/tests/test_dotproduct.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.expr import unchanged
2
+ from sympy.core.mul import Mul
3
+ from sympy.matrices import Matrix
4
+ from sympy.matrices.expressions.matexpr import MatrixSymbol
5
+ from sympy.matrices.expressions.dotproduct import DotProduct
6
+ from sympy.testing.pytest import raises
7
+
8
+
9
+ A = Matrix(3, 1, [1, 2, 3])
10
+ B = Matrix(3, 1, [1, 3, 5])
11
+ C = Matrix(4, 1, [1, 2, 4, 5])
12
+ D = Matrix(2, 2, [1, 2, 3, 4])
13
+
14
+ def test_docproduct():
15
+ assert DotProduct(A, B).doit() == 22
16
+ assert DotProduct(A.T, B).doit() == 22
17
+ assert DotProduct(A, B.T).doit() == 22
18
+ assert DotProduct(A.T, B.T).doit() == 22
19
+
20
+ raises(TypeError, lambda: DotProduct(1, A))
21
+ raises(TypeError, lambda: DotProduct(A, 1))
22
+ raises(TypeError, lambda: DotProduct(A, D))
23
+ raises(TypeError, lambda: DotProduct(D, A))
24
+
25
+ raises(TypeError, lambda: DotProduct(B, C).doit())
26
+
27
+ def test_dotproduct_symbolic():
28
+ A = MatrixSymbol('A', 3, 1)
29
+ B = MatrixSymbol('B', 3, 1)
30
+
31
+ dot = DotProduct(A, B)
32
+ assert dot.is_scalar == True
33
+ assert unchanged(Mul, 2, dot)
34
+ # XXX Fix forced evaluation for arithmetics with matrix expressions
35
+ assert dot * A == (A[0, 0]*B[0, 0] + A[1, 0]*B[1, 0] + A[2, 0]*B[2, 0])*A
miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/matrices/expressions/tests/test_factorizations.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.matrices.expressions.factorizations import lu, LofCholesky, qr, svd
2
+ from sympy.assumptions.ask import (Q, ask)
3
+ from sympy.core.symbol import Symbol
4
+ from sympy.matrices.expressions.matexpr import MatrixSymbol
5
+
6
+ n = Symbol('n')
7
+ X = MatrixSymbol('X', n, n)
8
+
9
+ def test_LU():
10
+ L, U = lu(X)
11
+ assert L.shape == U.shape == X.shape
12
+ assert ask(Q.lower_triangular(L))
13
+ assert ask(Q.upper_triangular(U))
14
+
15
+ def test_Cholesky():
16
+ LofCholesky(X)
17
+
18
+ def test_QR():
19
+ Q_, R = qr(X)
20
+ assert Q_.shape == R.shape == X.shape
21
+ assert ask(Q.orthogonal(Q_))
22
+ assert ask(Q.upper_triangular(R))
23
+
24
+ def test_svd():
25
+ U, S, V = svd(X)
26
+ assert U.shape == S.shape == V.shape == X.shape
27
+ assert ask(Q.orthogonal(U))
28
+ assert ask(Q.orthogonal(V))
29
+ assert ask(Q.diagonal(S))
miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/matrices/expressions/tests/test_fourier.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.assumptions.ask import (Q, ask)
2
+ from sympy.core.numbers import (I, Rational)
3
+ from sympy.core.singleton import S
4
+ from sympy.functions.elementary.complexes import Abs
5
+ from sympy.functions.elementary.exponential import exp
6
+ from sympy.functions.elementary.miscellaneous import sqrt
7
+ from sympy.simplify.simplify import simplify
8
+ from sympy.core.symbol import symbols
9
+ from sympy.matrices.expressions.fourier import DFT, IDFT
10
+ from sympy.matrices import det, Matrix, Identity
11
+ from sympy.testing.pytest import raises
12
+
13
+
14
+ def test_dft_creation():
15
+ assert DFT(2)
16
+ assert DFT(0)
17
+ raises(ValueError, lambda: DFT(-1))
18
+ raises(ValueError, lambda: DFT(2.0))
19
+ raises(ValueError, lambda: DFT(2 + 1j))
20
+
21
+ n = symbols('n')
22
+ assert DFT(n)
23
+ n = symbols('n', integer=False)
24
+ raises(ValueError, lambda: DFT(n))
25
+ n = symbols('n', negative=True)
26
+ raises(ValueError, lambda: DFT(n))
27
+
28
+
29
+ def test_dft():
30
+ n, i, j = symbols('n i j')
31
+ assert DFT(4).shape == (4, 4)
32
+ assert ask(Q.unitary(DFT(4)))
33
+ assert Abs(simplify(det(Matrix(DFT(4))))) == 1
34
+ assert DFT(n)*IDFT(n) == Identity(n)
35
+ assert DFT(n)[i, j] == exp(-2*S.Pi*I/n)**(i*j) / sqrt(n)
36
+
37
+
38
+ def test_dft2():
39
+ assert DFT(1).as_explicit() == Matrix([[1]])
40
+ assert DFT(2).as_explicit() == 1/sqrt(2)*Matrix([[1,1],[1,-1]])
41
+ assert DFT(4).as_explicit() == Matrix([[S.Half, S.Half, S.Half, S.Half],
42
+ [S.Half, -I/2, Rational(-1,2), I/2],
43
+ [S.Half, Rational(-1,2), S.Half, Rational(-1,2)],
44
+ [S.Half, I/2, Rational(-1,2), -I/2]])
miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/matrices/expressions/tests/test_funcmatrix.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core import symbols, Lambda
2
+ from sympy.core.sympify import SympifyError
3
+ from sympy.functions import KroneckerDelta
4
+ from sympy.matrices import Matrix
5
+ from sympy.matrices.expressions import FunctionMatrix, MatrixExpr, Identity
6
+ from sympy.testing.pytest import raises
7
+
8
+
9
+ def test_funcmatrix_creation():
10
+ i, j, k = symbols('i j k')
11
+ assert FunctionMatrix(2, 2, Lambda((i, j), 0))
12
+ assert FunctionMatrix(0, 0, Lambda((i, j), 0))
13
+
14
+ raises(ValueError, lambda: FunctionMatrix(-1, 0, Lambda((i, j), 0)))
15
+ raises(ValueError, lambda: FunctionMatrix(2.0, 0, Lambda((i, j), 0)))
16
+ raises(ValueError, lambda: FunctionMatrix(2j, 0, Lambda((i, j), 0)))
17
+ raises(ValueError, lambda: FunctionMatrix(0, -1, Lambda((i, j), 0)))
18
+ raises(ValueError, lambda: FunctionMatrix(0, 2.0, Lambda((i, j), 0)))
19
+ raises(ValueError, lambda: FunctionMatrix(0, 2j, Lambda((i, j), 0)))
20
+
21
+ raises(ValueError, lambda: FunctionMatrix(2, 2, Lambda(i, 0)))
22
+ raises(SympifyError, lambda: FunctionMatrix(2, 2, lambda i, j: 0))
23
+ raises(ValueError, lambda: FunctionMatrix(2, 2, Lambda((i,), 0)))
24
+ raises(ValueError, lambda: FunctionMatrix(2, 2, Lambda((i, j, k), 0)))
25
+ raises(ValueError, lambda: FunctionMatrix(2, 2, i+j))
26
+ assert FunctionMatrix(2, 2, "lambda i, j: 0") == \
27
+ FunctionMatrix(2, 2, Lambda((i, j), 0))
28
+
29
+ m = FunctionMatrix(2, 2, KroneckerDelta)
30
+ assert m.as_explicit() == Identity(2).as_explicit()
31
+ assert m.args[2].dummy_eq(Lambda((i, j), KroneckerDelta(i, j)))
32
+
33
+ n = symbols('n')
34
+ assert FunctionMatrix(n, n, Lambda((i, j), 0))
35
+ n = symbols('n', integer=False)
36
+ raises(ValueError, lambda: FunctionMatrix(n, n, Lambda((i, j), 0)))
37
+ n = symbols('n', negative=True)
38
+ raises(ValueError, lambda: FunctionMatrix(n, n, Lambda((i, j), 0)))
39
+
40
+
41
+ def test_funcmatrix():
42
+ i, j = symbols('i,j')
43
+ X = FunctionMatrix(3, 3, Lambda((i, j), i - j))
44
+ assert X[1, 1] == 0
45
+ assert X[1, 2] == -1
46
+ assert X.shape == (3, 3)
47
+ assert X.rows == X.cols == 3
48
+ assert Matrix(X) == Matrix(3, 3, lambda i, j: i - j)
49
+ assert isinstance(X*X + X, MatrixExpr)
50
+
51
+
52
+ def test_replace_issue():
53
+ X = FunctionMatrix(3, 3, KroneckerDelta)
54
+ assert X.replace(lambda x: True, lambda x: x) == X
miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/matrices/expressions/tests/test_hadamard.py ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.matrices.dense import Matrix, eye
2
+ from sympy.matrices.exceptions import ShapeError
3
+ from sympy.matrices.expressions.matadd import MatAdd
4
+ from sympy.matrices.expressions.special import Identity, OneMatrix, ZeroMatrix
5
+ from sympy.core import symbols
6
+ from sympy.testing.pytest import raises, warns_deprecated_sympy
7
+
8
+ from sympy.matrices import MatrixSymbol
9
+ from sympy.matrices.expressions import (HadamardProduct, hadamard_product, HadamardPower, hadamard_power)
10
+
11
+ n, m, k = symbols('n,m,k')
12
+ Z = MatrixSymbol('Z', n, n)
13
+ A = MatrixSymbol('A', n, m)
14
+ B = MatrixSymbol('B', n, m)
15
+ C = MatrixSymbol('C', m, k)
16
+
17
+
18
+ def test_HadamardProduct():
19
+ assert HadamardProduct(A, B, A).shape == A.shape
20
+
21
+ raises(TypeError, lambda: HadamardProduct(A, n))
22
+ raises(TypeError, lambda: HadamardProduct(A, 1))
23
+
24
+ assert HadamardProduct(A, 2*B, -A)[1, 1] == \
25
+ -2 * A[1, 1] * B[1, 1] * A[1, 1]
26
+
27
+ mix = HadamardProduct(Z*A, B)*C
28
+ assert mix.shape == (n, k)
29
+
30
+ assert set(HadamardProduct(A, B, A).T.args) == {A.T, A.T, B.T}
31
+
32
+
33
+ def test_HadamardProduct_isnt_commutative():
34
+ assert HadamardProduct(A, B) != HadamardProduct(B, A)
35
+
36
+
37
+ def test_mixed_indexing():
38
+ X = MatrixSymbol('X', 2, 2)
39
+ Y = MatrixSymbol('Y', 2, 2)
40
+ Z = MatrixSymbol('Z', 2, 2)
41
+
42
+ assert (X*HadamardProduct(Y, Z))[0, 0] == \
43
+ X[0, 0]*Y[0, 0]*Z[0, 0] + X[0, 1]*Y[1, 0]*Z[1, 0]
44
+
45
+
46
+ def test_canonicalize():
47
+ X = MatrixSymbol('X', 2, 2)
48
+ Y = MatrixSymbol('Y', 2, 2)
49
+ with warns_deprecated_sympy():
50
+ expr = HadamardProduct(X, check=False)
51
+ assert isinstance(expr, HadamardProduct)
52
+ expr2 = expr.doit() # unpack is called
53
+ assert isinstance(expr2, MatrixSymbol)
54
+ Z = ZeroMatrix(2, 2)
55
+ U = OneMatrix(2, 2)
56
+ assert HadamardProduct(Z, X).doit() == Z
57
+ assert HadamardProduct(U, X, X, U).doit() == HadamardPower(X, 2)
58
+ assert HadamardProduct(X, U, Y).doit() == HadamardProduct(X, Y)
59
+ assert HadamardProduct(X, Z, U, Y).doit() == Z
60
+
61
+
62
+ def test_hadamard():
63
+ m, n, p = symbols('m, n, p', integer=True)
64
+ A = MatrixSymbol('A', m, n)
65
+ B = MatrixSymbol('B', m, n)
66
+ X = MatrixSymbol('X', m, m)
67
+ I = Identity(m)
68
+
69
+ raises(TypeError, lambda: hadamard_product())
70
+ assert hadamard_product(A) == A
71
+ assert isinstance(hadamard_product(A, B), HadamardProduct)
72
+ assert hadamard_product(A, B).doit() == hadamard_product(A, B)
73
+ assert hadamard_product(X, I) == HadamardProduct(I, X)
74
+ assert isinstance(hadamard_product(X, I), HadamardProduct)
75
+
76
+ a = MatrixSymbol("a", k, 1)
77
+ expr = MatAdd(ZeroMatrix(k, 1), OneMatrix(k, 1))
78
+ expr = HadamardProduct(expr, a)
79
+ assert expr.doit() == a
80
+
81
+ raises(ValueError, lambda: HadamardProduct())
82
+
83
+
84
+ def test_hadamard_product_with_explicit_mat():
85
+ A = MatrixSymbol("A", 3, 3).as_explicit()
86
+ B = MatrixSymbol("B", 3, 3).as_explicit()
87
+ X = MatrixSymbol("X", 3, 3)
88
+ expr = hadamard_product(A, B)
89
+ ret = Matrix([i*j for i, j in zip(A, B)]).reshape(3, 3)
90
+ assert expr == ret
91
+ expr = hadamard_product(A, X, B)
92
+ assert expr == HadamardProduct(ret, X)
93
+ expr = hadamard_product(eye(3), A)
94
+ assert expr == Matrix([[A[0, 0], 0, 0], [0, A[1, 1], 0], [0, 0, A[2, 2]]])
95
+ expr = hadamard_product(eye(3), eye(3))
96
+ assert expr == eye(3)
97
+
98
+
99
+ def test_hadamard_power():
100
+ m, n, p = symbols('m, n, p', integer=True)
101
+ A = MatrixSymbol('A', m, n)
102
+
103
+ assert hadamard_power(A, 1) == A
104
+ assert isinstance(hadamard_power(A, 2), HadamardPower)
105
+ assert hadamard_power(A, n).T == hadamard_power(A.T, n)
106
+ assert hadamard_power(A, n)[0, 0] == A[0, 0]**n
107
+ assert hadamard_power(m, n) == m**n
108
+ raises(ValueError, lambda: hadamard_power(A, A))
109
+
110
+
111
+ def test_hadamard_power_explicit():
112
+ A = MatrixSymbol('A', 2, 2)
113
+ B = MatrixSymbol('B', 2, 2)
114
+ a, b = symbols('a b')
115
+
116
+ assert HadamardPower(a, b) == a**b
117
+
118
+ assert HadamardPower(a, B).as_explicit() == \
119
+ Matrix([
120
+ [a**B[0, 0], a**B[0, 1]],
121
+ [a**B[1, 0], a**B[1, 1]]])
122
+
123
+ assert HadamardPower(A, b).as_explicit() == \
124
+ Matrix([
125
+ [A[0, 0]**b, A[0, 1]**b],
126
+ [A[1, 0]**b, A[1, 1]**b]])
127
+
128
+ assert HadamardPower(A, B).as_explicit() == \
129
+ Matrix([
130
+ [A[0, 0]**B[0, 0], A[0, 1]**B[0, 1]],
131
+ [A[1, 0]**B[1, 0], A[1, 1]**B[1, 1]]])
132
+
133
+
134
+ def test_shape_error():
135
+ A = MatrixSymbol('A', 2, 3)
136
+ B = MatrixSymbol('B', 3, 3)
137
+ raises(ShapeError, lambda: HadamardProduct(A, B))
138
+ raises(ShapeError, lambda: HadamardPower(A, B))
139
+ A = MatrixSymbol('A', 3, 2)
140
+ raises(ShapeError, lambda: HadamardProduct(A, B))
141
+ raises(ShapeError, lambda: HadamardPower(A, B))
miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/matrices/expressions/tests/test_indexing.py ADDED
@@ -0,0 +1,299 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.concrete.summations import Sum
2
+ from sympy.core.symbol import symbols, Symbol, Dummy
3
+ from sympy.functions.elementary.miscellaneous import sqrt
4
+ from sympy.functions.special.tensor_functions import KroneckerDelta
5
+ from sympy.matrices.dense import eye
6
+ from sympy.matrices.expressions.blockmatrix import BlockMatrix
7
+ from sympy.matrices.expressions.hadamard import HadamardPower
8
+ from sympy.matrices.expressions.matexpr import (MatrixSymbol,
9
+ MatrixExpr, MatrixElement)
10
+ from sympy.matrices.expressions.matpow import MatPow
11
+ from sympy.matrices.expressions.special import (ZeroMatrix, Identity,
12
+ OneMatrix)
13
+ from sympy.matrices.expressions.trace import Trace, trace
14
+ from sympy.matrices.immutable import ImmutableMatrix
15
+ from sympy.tensor.array.expressions.array_expressions import ArrayTensorProduct
16
+ from sympy.testing.pytest import XFAIL, raises
17
+
18
+ k, l, m, n = symbols('k l m n', integer=True)
19
+ i, j = symbols('i j', integer=True)
20
+
21
+ W = MatrixSymbol('W', k, l)
22
+ X = MatrixSymbol('X', l, m)
23
+ Y = MatrixSymbol('Y', l, m)
24
+ Z = MatrixSymbol('Z', m, n)
25
+
26
+ X1 = MatrixSymbol('X1', m, m)
27
+ X2 = MatrixSymbol('X2', m, m)
28
+ X3 = MatrixSymbol('X3', m, m)
29
+ X4 = MatrixSymbol('X4', m, m)
30
+
31
+ A = MatrixSymbol('A', 2, 2)
32
+ B = MatrixSymbol('B', 2, 2)
33
+ x = MatrixSymbol('x', 1, 2)
34
+ y = MatrixSymbol('x', 2, 1)
35
+
36
+
37
+ def test_symbolic_indexing():
38
+ x12 = X[1, 2]
39
+ assert all(s in str(x12) for s in ['1', '2', X.name])
40
+ # We don't care about the exact form of this. We do want to make sure
41
+ # that all of these features are present
42
+
43
+
44
+ def test_add_index():
45
+ assert (X + Y)[i, j] == X[i, j] + Y[i, j]
46
+
47
+
48
+ def test_mul_index():
49
+ assert (A*y)[0, 0] == A[0, 0]*y[0, 0] + A[0, 1]*y[1, 0]
50
+ assert (A*B).as_mutable() == (A.as_mutable() * B.as_mutable())
51
+ X = MatrixSymbol('X', n, m)
52
+ Y = MatrixSymbol('Y', m, k)
53
+
54
+ result = (X*Y)[4,2]
55
+ expected = Sum(X[4, i]*Y[i, 2], (i, 0, m - 1))
56
+ assert result.args[0].dummy_eq(expected.args[0], i)
57
+ assert result.args[1][1:] == expected.args[1][1:]
58
+
59
+
60
+ def test_pow_index():
61
+ Q = MatPow(A, 2)
62
+ assert Q[0, 0] == A[0, 0]**2 + A[0, 1]*A[1, 0]
63
+ n = symbols("n")
64
+ Q2 = A**n
65
+ assert Q2[0, 0] == 2*(
66
+ -sqrt((A[0, 0] + A[1, 1])**2 - 4*A[0, 0]*A[1, 1] +
67
+ 4*A[0, 1]*A[1, 0])/2 + A[0, 0]/2 + A[1, 1]/2
68
+ )**n * \
69
+ A[0, 1]*A[1, 0]/(
70
+ (sqrt(A[0, 0]**2 - 2*A[0, 0]*A[1, 1] + 4*A[0, 1]*A[1, 0] +
71
+ A[1, 1]**2) + A[0, 0] - A[1, 1])*
72
+ sqrt(A[0, 0]**2 - 2*A[0, 0]*A[1, 1] + 4*A[0, 1]*A[1, 0] + A[1, 1]**2)
73
+ ) - 2*(
74
+ sqrt((A[0, 0] + A[1, 1])**2 - 4*A[0, 0]*A[1, 1] +
75
+ 4*A[0, 1]*A[1, 0])/2 + A[0, 0]/2 + A[1, 1]/2
76
+ )**n * A[0, 1]*A[1, 0]/(
77
+ (-sqrt(A[0, 0]**2 - 2*A[0, 0]*A[1, 1] + 4*A[0, 1]*A[1, 0] +
78
+ A[1, 1]**2) + A[0, 0] - A[1, 1])*
79
+ sqrt(A[0, 0]**2 - 2*A[0, 0]*A[1, 1] + 4*A[0, 1]*A[1, 0] + A[1, 1]**2)
80
+ )
81
+
82
+
83
+ def test_transpose_index():
84
+ assert X.T[i, j] == X[j, i]
85
+
86
+
87
+ def test_Identity_index():
88
+ I = Identity(3)
89
+ assert I[0, 0] == I[1, 1] == I[2, 2] == 1
90
+ assert I[1, 0] == I[0, 1] == I[2, 1] == 0
91
+ assert I[i, 0].delta_range == (0, 2)
92
+ raises(IndexError, lambda: I[3, 3])
93
+
94
+
95
+ def test_block_index():
96
+ I = Identity(3)
97
+ Z = ZeroMatrix(3, 3)
98
+ B = BlockMatrix([[I, I], [I, I]])
99
+ e3 = ImmutableMatrix(eye(3))
100
+ BB = BlockMatrix([[e3, e3], [e3, e3]])
101
+ assert B[0, 0] == B[3, 0] == B[0, 3] == B[3, 3] == 1
102
+ assert B[4, 3] == B[5, 1] == 0
103
+
104
+ BB = BlockMatrix([[e3, e3], [e3, e3]])
105
+ assert B.as_explicit() == BB.as_explicit()
106
+
107
+ BI = BlockMatrix([[I, Z], [Z, I]])
108
+
109
+ assert BI.as_explicit().equals(eye(6))
110
+
111
+
112
+ def test_block_index_symbolic():
113
+ # Note that these matrices may be zero-sized and indices may be negative, which causes
114
+ # all naive simplifications given in the comments to be invalid
115
+ A1 = MatrixSymbol('A1', n, k)
116
+ A2 = MatrixSymbol('A2', n, l)
117
+ A3 = MatrixSymbol('A3', m, k)
118
+ A4 = MatrixSymbol('A4', m, l)
119
+ A = BlockMatrix([[A1, A2], [A3, A4]])
120
+ assert A[0, 0] == MatrixElement(A, 0, 0) # Cannot be A1[0, 0]
121
+ assert A[n - 1, k - 1] == A1[n - 1, k - 1]
122
+ assert A[n, k] == A4[0, 0]
123
+ assert A[n + m - 1, 0] == MatrixElement(A, n + m - 1, 0) # Cannot be A3[m - 1, 0]
124
+ assert A[0, k + l - 1] == MatrixElement(A, 0, k + l - 1) # Cannot be A2[0, l - 1]
125
+ assert A[n + m - 1, k + l - 1] == MatrixElement(A, n + m - 1, k + l - 1) # Cannot be A4[m - 1, l - 1]
126
+ assert A[i, j] == MatrixElement(A, i, j)
127
+ assert A[n + i, k + j] == MatrixElement(A, n + i, k + j) # Cannot be A4[i, j]
128
+ assert A[n - i - 1, k - j - 1] == MatrixElement(A, n - i - 1, k - j - 1) # Cannot be A1[n - i - 1, k - j - 1]
129
+
130
+
131
+ def test_block_index_symbolic_nonzero():
132
+ # All invalid simplifications from test_block_index_symbolic() that become valid if all
133
+ # matrices have nonzero size and all indices are nonnegative
134
+ k, l, m, n = symbols('k l m n', integer=True, positive=True)
135
+ i, j = symbols('i j', integer=True, nonnegative=True)
136
+ A1 = MatrixSymbol('A1', n, k)
137
+ A2 = MatrixSymbol('A2', n, l)
138
+ A3 = MatrixSymbol('A3', m, k)
139
+ A4 = MatrixSymbol('A4', m, l)
140
+ A = BlockMatrix([[A1, A2], [A3, A4]])
141
+ assert A[0, 0] == A1[0, 0]
142
+ assert A[n + m - 1, 0] == A3[m - 1, 0]
143
+ assert A[0, k + l - 1] == A2[0, l - 1]
144
+ assert A[n + m - 1, k + l - 1] == A4[m - 1, l - 1]
145
+ assert A[i, j] == MatrixElement(A, i, j)
146
+ assert A[n + i, k + j] == A4[i, j]
147
+ assert A[n - i - 1, k - j - 1] == A1[n - i - 1, k - j - 1]
148
+ assert A[2 * n, 2 * k] == A4[n, k]
149
+
150
+
151
+ def test_block_index_large():
152
+ n, m, k = symbols('n m k', integer=True, positive=True)
153
+ i = symbols('i', integer=True, nonnegative=True)
154
+ A1 = MatrixSymbol('A1', n, n)
155
+ A2 = MatrixSymbol('A2', n, m)
156
+ A3 = MatrixSymbol('A3', n, k)
157
+ A4 = MatrixSymbol('A4', m, n)
158
+ A5 = MatrixSymbol('A5', m, m)
159
+ A6 = MatrixSymbol('A6', m, k)
160
+ A7 = MatrixSymbol('A7', k, n)
161
+ A8 = MatrixSymbol('A8', k, m)
162
+ A9 = MatrixSymbol('A9', k, k)
163
+ A = BlockMatrix([[A1, A2, A3], [A4, A5, A6], [A7, A8, A9]])
164
+ assert A[n + i, n + i] == MatrixElement(A, n + i, n + i)
165
+
166
+
167
+ @XFAIL
168
+ def test_block_index_symbolic_fail():
169
+ # To make this work, symbolic matrix dimensions would need to be somehow assumed nonnegative
170
+ # even if the symbols aren't specified as such. Then 2 * n < n would correctly evaluate to
171
+ # False in BlockMatrix._entry()
172
+ A1 = MatrixSymbol('A1', n, 1)
173
+ A2 = MatrixSymbol('A2', m, 1)
174
+ A = BlockMatrix([[A1], [A2]])
175
+ assert A[2 * n, 0] == A2[n, 0]
176
+
177
+
178
+ def test_slicing():
179
+ A.as_explicit()[0, :] # does not raise an error
180
+
181
+
182
+ def test_errors():
183
+ raises(IndexError, lambda: Identity(2)[1, 2, 3, 4, 5])
184
+ raises(IndexError, lambda: Identity(2)[[1, 2, 3, 4, 5]])
185
+
186
+
187
+ def test_matrix_expression_to_indices():
188
+ i, j = symbols("i, j")
189
+ i1, i2, i3 = symbols("i_1:4")
190
+
191
+ def replace_dummies(expr):
192
+ repl = {i: Symbol(i.name) for i in expr.atoms(Dummy)}
193
+ return expr.xreplace(repl)
194
+
195
+ expr = W*X*Z
196
+ assert replace_dummies(expr._entry(i, j)) == \
197
+ Sum(W[i, i1]*X[i1, i2]*Z[i2, j], (i1, 0, l-1), (i2, 0, m-1))
198
+ assert MatrixExpr.from_index_summation(expr._entry(i, j)) == expr
199
+
200
+ expr = Z.T*X.T*W.T
201
+ assert replace_dummies(expr._entry(i, j)) == \
202
+ Sum(W[j, i2]*X[i2, i1]*Z[i1, i], (i1, 0, m-1), (i2, 0, l-1))
203
+ assert MatrixExpr.from_index_summation(expr._entry(i, j), i) == expr
204
+
205
+ expr = W*X*Z + W*Y*Z
206
+ assert replace_dummies(expr._entry(i, j)) == \
207
+ Sum(W[i, i1]*X[i1, i2]*Z[i2, j], (i1, 0, l-1), (i2, 0, m-1)) +\
208
+ Sum(W[i, i1]*Y[i1, i2]*Z[i2, j], (i1, 0, l-1), (i2, 0, m-1))
209
+ assert MatrixExpr.from_index_summation(expr._entry(i, j)) == expr
210
+
211
+ expr = 2*W*X*Z + 3*W*Y*Z
212
+ assert replace_dummies(expr._entry(i, j)) == \
213
+ 2*Sum(W[i, i1]*X[i1, i2]*Z[i2, j], (i1, 0, l-1), (i2, 0, m-1)) +\
214
+ 3*Sum(W[i, i1]*Y[i1, i2]*Z[i2, j], (i1, 0, l-1), (i2, 0, m-1))
215
+ assert MatrixExpr.from_index_summation(expr._entry(i, j)) == expr
216
+
217
+ expr = W*(X + Y)*Z
218
+ assert replace_dummies(expr._entry(i, j)) == \
219
+ Sum(W[i, i1]*(X[i1, i2] + Y[i1, i2])*Z[i2, j], (i1, 0, l-1), (i2, 0, m-1))
220
+ assert MatrixExpr.from_index_summation(expr._entry(i, j)) == expr
221
+
222
+ expr = A*B**2*A
223
+ #assert replace_dummies(expr._entry(i, j)) == \
224
+ # Sum(A[i, i1]*B[i1, i2]*B[i2, i3]*A[i3, j], (i1, 0, 1), (i2, 0, 1), (i3, 0, 1))
225
+
226
+ # Check that different dummies are used in sub-multiplications:
227
+ expr = (X1*X2 + X2*X1)*X3
228
+ assert replace_dummies(expr._entry(i, j)) == \
229
+ Sum((Sum(X1[i, i2] * X2[i2, i1], (i2, 0, m - 1)) + Sum(X1[i3, i1] * X2[i, i3], (i3, 0, m - 1))) * X3[
230
+ i1, j], (i1, 0, m - 1))
231
+
232
+
233
+ def test_matrix_expression_from_index_summation():
234
+ from sympy.abc import a,b,c,d
235
+ A = MatrixSymbol("A", k, k)
236
+ B = MatrixSymbol("B", k, k)
237
+ C = MatrixSymbol("C", k, k)
238
+ w1 = MatrixSymbol("w1", k, 1)
239
+
240
+ i0, i1, i2, i3, i4 = symbols("i0:5", cls=Dummy)
241
+
242
+ expr = Sum(W[a,b]*X[b,c]*Z[c,d], (b, 0, l-1), (c, 0, m-1))
243
+ assert MatrixExpr.from_index_summation(expr, a) == W*X*Z
244
+ expr = Sum(W.T[b,a]*X[b,c]*Z[c,d], (b, 0, l-1), (c, 0, m-1))
245
+ assert MatrixExpr.from_index_summation(expr, a) == W*X*Z
246
+ expr = Sum(A[b, a]*B[b, c]*C[c, d], (b, 0, k-1), (c, 0, k-1))
247
+ assert MatrixSymbol.from_index_summation(expr, a) == A.T*B*C
248
+ expr = Sum(A[b, a]*B[c, b]*C[c, d], (b, 0, k-1), (c, 0, k-1))
249
+ assert MatrixSymbol.from_index_summation(expr, a) == A.T*B.T*C
250
+ expr = Sum(C[c, d]*A[b, a]*B[c, b], (b, 0, k-1), (c, 0, k-1))
251
+ assert MatrixSymbol.from_index_summation(expr, a) == A.T*B.T*C
252
+ expr = Sum(A[a, b] + B[a, b], (a, 0, k-1), (b, 0, k-1))
253
+ assert MatrixExpr.from_index_summation(expr, a) == OneMatrix(1, k)*A*OneMatrix(k, 1) + OneMatrix(1, k)*B*OneMatrix(k, 1)
254
+ expr = Sum(A[a, b]**2, (a, 0, k - 1), (b, 0, k - 1))
255
+ assert MatrixExpr.from_index_summation(expr, a) == Trace(A * A.T)
256
+ expr = Sum(A[a, b]**3, (a, 0, k - 1), (b, 0, k - 1))
257
+ assert MatrixExpr.from_index_summation(expr, a) == Trace(HadamardPower(A.T, 2) * A)
258
+ expr = Sum((A[a, b] + B[a, b])*C[b, c], (b, 0, k-1))
259
+ assert MatrixExpr.from_index_summation(expr, a) == (A+B)*C
260
+ expr = Sum((A[a, b] + B[b, a])*C[b, c], (b, 0, k-1))
261
+ assert MatrixExpr.from_index_summation(expr, a) == (A+B.T)*C
262
+ expr = Sum(A[a, b]*A[b, c]*A[c, d], (b, 0, k-1), (c, 0, k-1))
263
+ assert MatrixExpr.from_index_summation(expr, a) == A**3
264
+ expr = Sum(A[a, b]*A[b, c]*B[c, d], (b, 0, k-1), (c, 0, k-1))
265
+ assert MatrixExpr.from_index_summation(expr, a) == A**2*B
266
+
267
+ # Parse the trace of a matrix:
268
+
269
+ expr = Sum(A[a, a], (a, 0, k-1))
270
+ assert MatrixExpr.from_index_summation(expr, None) == trace(A)
271
+ expr = Sum(A[a, a]*B[b, c]*C[c, d], (a, 0, k-1), (c, 0, k-1))
272
+ assert MatrixExpr.from_index_summation(expr, b) == trace(A)*B*C
273
+
274
+ # Check wrong sum ranges (should raise an exception):
275
+
276
+ ## Case 1: 0 to m instead of 0 to m-1
277
+ expr = Sum(W[a,b]*X[b,c]*Z[c,d], (b, 0, l-1), (c, 0, m))
278
+ raises(ValueError, lambda: MatrixExpr.from_index_summation(expr, a))
279
+ ## Case 2: 1 to m-1 instead of 0 to m-1
280
+ expr = Sum(W[a,b]*X[b,c]*Z[c,d], (b, 0, l-1), (c, 1, m-1))
281
+ raises(ValueError, lambda: MatrixExpr.from_index_summation(expr, a))
282
+
283
+ # Parse nested sums:
284
+ expr = Sum(A[a, b]*Sum(B[b, c]*C[c, d], (c, 0, k-1)), (b, 0, k-1))
285
+ assert MatrixExpr.from_index_summation(expr, a) == A*B*C
286
+
287
+ # Test Kronecker delta:
288
+ expr = Sum(A[a, b]*KroneckerDelta(b, c)*B[c, d], (b, 0, k-1), (c, 0, k-1))
289
+ assert MatrixExpr.from_index_summation(expr, a) == A*B
290
+
291
+ expr = Sum(KroneckerDelta(i1, m)*KroneckerDelta(i2, n)*A[i, i1]*A[j, i2], (i1, 0, k-1), (i2, 0, k-1))
292
+ assert MatrixExpr.from_index_summation(expr, m) == ArrayTensorProduct(A.T, A)
293
+
294
+ # Test numbered indices:
295
+ expr = Sum(A[i1, i2]*w1[i2, 0], (i2, 0, k-1))
296
+ assert MatrixExpr.from_index_summation(expr, i1) == MatrixElement(A*w1, i1, 0)
297
+
298
+ expr = Sum(A[i1, i2]*B[i2, 0], (i2, 0, k-1))
299
+ assert MatrixExpr.from_index_summation(expr, i1) == MatrixElement(A*B, i1, 0)
miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/matrices/expressions/tests/test_inverse.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core import symbols, S
2
+ from sympy.matrices.expressions import MatrixSymbol, Inverse, MatPow, ZeroMatrix, OneMatrix
3
+ from sympy.matrices.exceptions import NonInvertibleMatrixError, NonSquareMatrixError
4
+ from sympy.matrices import eye, Identity
5
+ from sympy.testing.pytest import raises
6
+ from sympy.assumptions.ask import Q
7
+ from sympy.assumptions.refine import refine
8
+
9
+ n, m, l = symbols('n m l', integer=True)
10
+ A = MatrixSymbol('A', n, m)
11
+ B = MatrixSymbol('B', m, l)
12
+ C = MatrixSymbol('C', n, n)
13
+ D = MatrixSymbol('D', n, n)
14
+ E = MatrixSymbol('E', m, n)
15
+
16
+
17
+ def test_inverse():
18
+ assert Inverse(C).args == (C, S.NegativeOne)
19
+ assert Inverse(C).shape == (n, n)
20
+ assert Inverse(A*E).shape == (n, n)
21
+ assert Inverse(E*A).shape == (m, m)
22
+ assert Inverse(C).inverse() == C
23
+ assert Inverse(Inverse(C)).doit() == C
24
+ assert isinstance(Inverse(Inverse(C)), Inverse)
25
+
26
+ assert Inverse(*Inverse(E*A).args) == Inverse(E*A)
27
+
28
+ assert C.inverse().inverse() == C
29
+
30
+ assert C.inverse()*C == Identity(C.rows)
31
+
32
+ assert Identity(n).inverse() == Identity(n)
33
+ assert (3*Identity(n)).inverse() == Identity(n)/3
34
+
35
+ # Simplifies Muls if possible (i.e. submatrices are square)
36
+ assert (C*D).inverse() == D.I*C.I
37
+ # But still works when not possible
38
+ assert isinstance((A*E).inverse(), Inverse)
39
+ assert Inverse(C*D).doit(inv_expand=False) == Inverse(C*D)
40
+
41
+ assert Inverse(eye(3)).doit() == eye(3)
42
+ assert Inverse(eye(3)).doit(deep=False) == eye(3)
43
+
44
+ assert OneMatrix(1, 1).I == Identity(1)
45
+ assert isinstance(OneMatrix(n, n).I, Inverse)
46
+
47
+ def test_inverse_non_invertible():
48
+ raises(NonInvertibleMatrixError, lambda: ZeroMatrix(n, n).I)
49
+ raises(NonInvertibleMatrixError, lambda: OneMatrix(2, 2).I)
50
+
51
+ def test_refine():
52
+ assert refine(C.I, Q.orthogonal(C)) == C.T
53
+
54
+
55
+ def test_inverse_matpow_canonicalization():
56
+ A = MatrixSymbol('A', 3, 3)
57
+ assert Inverse(MatPow(A, 3)).doit() == MatPow(Inverse(A), 3).doit()
58
+
59
+
60
+ def test_nonsquare_error():
61
+ A = MatrixSymbol('A', 3, 4)
62
+ raises(NonSquareMatrixError, lambda: Inverse(A))
63
+
64
+
65
+ def test_adjoint_trnaspose_conjugate():
66
+ A = MatrixSymbol('A', n, n)
67
+ assert A.transpose().inverse() == A.inverse().transpose()
68
+ assert A.conjugate().inverse() == A.inverse().conjugate()
69
+ assert A.adjoint().inverse() == A.inverse().adjoint()
miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/matrices/expressions/tests/test_kronecker.py ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.mod import Mod
2
+ from sympy.core.numbers import I
3
+ from sympy.core.symbol import symbols
4
+ from sympy.functions.elementary.integers import floor
5
+ from sympy.matrices.dense import (Matrix, eye)
6
+ from sympy.matrices import MatrixSymbol, Identity
7
+ from sympy.matrices.expressions import det, trace
8
+
9
+ from sympy.matrices.expressions.kronecker import (KroneckerProduct,
10
+ kronecker_product,
11
+ combine_kronecker)
12
+
13
+
14
+ mat1 = Matrix([[1, 2 * I], [1 + I, 3]])
15
+ mat2 = Matrix([[2 * I, 3], [4 * I, 2]])
16
+
17
+ i, j, k, n, m, o, p, x = symbols('i,j,k,n,m,o,p,x')
18
+ Z = MatrixSymbol('Z', n, n)
19
+ W = MatrixSymbol('W', m, m)
20
+ A = MatrixSymbol('A', n, m)
21
+ B = MatrixSymbol('B', n, m)
22
+ C = MatrixSymbol('C', m, k)
23
+
24
+
25
+ def test_KroneckerProduct():
26
+ assert isinstance(KroneckerProduct(A, B), KroneckerProduct)
27
+ assert KroneckerProduct(A, B).subs(A, C) == KroneckerProduct(C, B)
28
+ assert KroneckerProduct(A, C).shape == (n*m, m*k)
29
+ assert (KroneckerProduct(A, C) + KroneckerProduct(-A, C)).is_ZeroMatrix
30
+ assert (KroneckerProduct(W, Z) * KroneckerProduct(W.I, Z.I)).is_Identity
31
+
32
+
33
+ def test_KroneckerProduct_identity():
34
+ assert KroneckerProduct(Identity(m), Identity(n)) == Identity(m*n)
35
+ assert KroneckerProduct(eye(2), eye(3)) == eye(6)
36
+
37
+
38
+ def test_KroneckerProduct_explicit():
39
+ X = MatrixSymbol('X', 2, 2)
40
+ Y = MatrixSymbol('Y', 2, 2)
41
+ kp = KroneckerProduct(X, Y)
42
+ assert kp.shape == (4, 4)
43
+ assert kp.as_explicit() == Matrix(
44
+ [
45
+ [X[0, 0]*Y[0, 0], X[0, 0]*Y[0, 1], X[0, 1]*Y[0, 0], X[0, 1]*Y[0, 1]],
46
+ [X[0, 0]*Y[1, 0], X[0, 0]*Y[1, 1], X[0, 1]*Y[1, 0], X[0, 1]*Y[1, 1]],
47
+ [X[1, 0]*Y[0, 0], X[1, 0]*Y[0, 1], X[1, 1]*Y[0, 0], X[1, 1]*Y[0, 1]],
48
+ [X[1, 0]*Y[1, 0], X[1, 0]*Y[1, 1], X[1, 1]*Y[1, 0], X[1, 1]*Y[1, 1]]
49
+ ]
50
+ )
51
+
52
+
53
+ def test_tensor_product_adjoint():
54
+ assert KroneckerProduct(I*A, B).adjoint() == \
55
+ -I*KroneckerProduct(A.adjoint(), B.adjoint())
56
+ assert KroneckerProduct(mat1, mat2).adjoint() == \
57
+ kronecker_product(mat1.adjoint(), mat2.adjoint())
58
+
59
+
60
+ def test_tensor_product_conjugate():
61
+ assert KroneckerProduct(I*A, B).conjugate() == \
62
+ -I*KroneckerProduct(A.conjugate(), B.conjugate())
63
+ assert KroneckerProduct(mat1, mat2).conjugate() == \
64
+ kronecker_product(mat1.conjugate(), mat2.conjugate())
65
+
66
+
67
+ def test_tensor_product_transpose():
68
+ assert KroneckerProduct(I*A, B).transpose() == \
69
+ I*KroneckerProduct(A.transpose(), B.transpose())
70
+ assert KroneckerProduct(mat1, mat2).transpose() == \
71
+ kronecker_product(mat1.transpose(), mat2.transpose())
72
+
73
+
74
+ def test_KroneckerProduct_is_associative():
75
+ assert kronecker_product(A, kronecker_product(
76
+ B, C)) == kronecker_product(kronecker_product(A, B), C)
77
+ assert kronecker_product(A, kronecker_product(
78
+ B, C)) == KroneckerProduct(A, B, C)
79
+
80
+
81
+ def test_KroneckerProduct_is_bilinear():
82
+ assert kronecker_product(x*A, B) == x*kronecker_product(A, B)
83
+ assert kronecker_product(A, x*B) == x*kronecker_product(A, B)
84
+
85
+
86
+ def test_KroneckerProduct_determinant():
87
+ kp = kronecker_product(W, Z)
88
+ assert det(kp) == det(W)**n * det(Z)**m
89
+
90
+
91
+ def test_KroneckerProduct_trace():
92
+ kp = kronecker_product(W, Z)
93
+ assert trace(kp) == trace(W)*trace(Z)
94
+
95
+
96
+ def test_KroneckerProduct_isnt_commutative():
97
+ assert KroneckerProduct(A, B) != KroneckerProduct(B, A)
98
+ assert KroneckerProduct(A, B).is_commutative is False
99
+
100
+
101
+ def test_KroneckerProduct_extracts_commutative_part():
102
+ assert kronecker_product(x * A, 2 * B) == x * \
103
+ 2 * KroneckerProduct(A, B)
104
+
105
+
106
+ def test_KroneckerProduct_inverse():
107
+ kp = kronecker_product(W, Z)
108
+ assert kp.inverse() == kronecker_product(W.inverse(), Z.inverse())
109
+
110
+
111
+ def test_KroneckerProduct_combine_add():
112
+ kp1 = kronecker_product(A, B)
113
+ kp2 = kronecker_product(C, W)
114
+ assert combine_kronecker(kp1*kp2) == kronecker_product(A*C, B*W)
115
+
116
+
117
+ def test_KroneckerProduct_combine_mul():
118
+ X = MatrixSymbol('X', m, n)
119
+ Y = MatrixSymbol('Y', m, n)
120
+ kp1 = kronecker_product(A, X)
121
+ kp2 = kronecker_product(B, Y)
122
+ assert combine_kronecker(kp1+kp2) == kronecker_product(A+B, X+Y)
123
+
124
+
125
+ def test_KroneckerProduct_combine_pow():
126
+ X = MatrixSymbol('X', n, n)
127
+ Y = MatrixSymbol('Y', n, n)
128
+ assert combine_kronecker(KroneckerProduct(
129
+ X, Y)**x) == KroneckerProduct(X**x, Y**x)
130
+ assert combine_kronecker(x * KroneckerProduct(X, Y)
131
+ ** 2) == x * KroneckerProduct(X**2, Y**2)
132
+ assert combine_kronecker(
133
+ x * (KroneckerProduct(X, Y)**2) * KroneckerProduct(A, B)) == x * KroneckerProduct(X**2 * A, Y**2 * B)
134
+ # cannot simplify because of non-square arguments to kronecker product:
135
+ assert combine_kronecker(KroneckerProduct(A, B.T) ** m) == KroneckerProduct(A, B.T) ** m
136
+
137
+
138
+ def test_KroneckerProduct_expand():
139
+ X = MatrixSymbol('X', n, n)
140
+ Y = MatrixSymbol('Y', n, n)
141
+
142
+ assert KroneckerProduct(X + Y, Y + Z).expand(kroneckerproduct=True) == \
143
+ KroneckerProduct(X, Y) + KroneckerProduct(X, Z) + \
144
+ KroneckerProduct(Y, Y) + KroneckerProduct(Y, Z)
145
+
146
+ def test_KroneckerProduct_entry():
147
+ A = MatrixSymbol('A', n, m)
148
+ B = MatrixSymbol('B', o, p)
149
+
150
+ assert KroneckerProduct(A, B)._entry(i, j) == A[Mod(floor(i/o), n), Mod(floor(j/p), m)]*B[Mod(i, o), Mod(j, p)]
miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/matrices/expressions/tests/test_matadd.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.matrices.expressions import MatrixSymbol, MatAdd, MatPow, MatMul
2
+ from sympy.matrices.expressions.special import GenericZeroMatrix, ZeroMatrix
3
+ from sympy.matrices.exceptions import ShapeError
4
+ from sympy.matrices import eye, ImmutableMatrix
5
+ from sympy.core import Add, Basic, S
6
+ from sympy.core.add import add
7
+ from sympy.testing.pytest import XFAIL, raises
8
+
9
+ X = MatrixSymbol('X', 2, 2)
10
+ Y = MatrixSymbol('Y', 2, 2)
11
+
12
+ def test_evaluate():
13
+ assert MatAdd(X, X, evaluate=True) == add(X, X, evaluate=True) == MatAdd(X, X).doit()
14
+
15
+ def test_sort_key():
16
+ assert MatAdd(Y, X).doit().args == add(Y, X).doit().args == (X, Y)
17
+
18
+
19
+ def test_matadd_sympify():
20
+ assert isinstance(MatAdd(eye(1), eye(1)).args[0], Basic)
21
+ assert isinstance(add(eye(1), eye(1)).args[0], Basic)
22
+
23
+
24
+ def test_matadd_of_matrices():
25
+ assert MatAdd(eye(2), 4*eye(2), eye(2)).doit() == ImmutableMatrix(6*eye(2))
26
+ assert add(eye(2), 4*eye(2), eye(2)).doit() == ImmutableMatrix(6*eye(2))
27
+
28
+
29
+ def test_doit_args():
30
+ A = ImmutableMatrix([[1, 2], [3, 4]])
31
+ B = ImmutableMatrix([[2, 3], [4, 5]])
32
+ assert MatAdd(A, MatPow(B, 2)).doit() == A + B**2
33
+ assert MatAdd(A, MatMul(A, B)).doit() == A + A*B
34
+ assert (MatAdd(A, X, MatMul(A, B), Y, MatAdd(2*A, B)).doit() ==
35
+ add(A, X, MatMul(A, B), Y, add(2*A, B)).doit() ==
36
+ MatAdd(3*A + A*B + B, X, Y))
37
+
38
+
39
+ def test_generic_identity():
40
+ assert MatAdd.identity == GenericZeroMatrix()
41
+ assert MatAdd.identity != S.Zero
42
+
43
+
44
+ def test_zero_matrix_add():
45
+ assert Add(ZeroMatrix(2, 2), ZeroMatrix(2, 2)) == ZeroMatrix(2, 2)
46
+
47
+ @XFAIL
48
+ def test_matrix_Add_with_scalar():
49
+ raises(TypeError, lambda: Add(0, ZeroMatrix(2, 2)))
50
+
51
+
52
+ def test_shape_error():
53
+ A = MatrixSymbol('A', 2, 3)
54
+ B = MatrixSymbol('B', 3, 3)
55
+ raises(ShapeError, lambda: MatAdd(A, B))
56
+
57
+ A = MatrixSymbol('A', 3, 2)
58
+ raises(ShapeError, lambda: MatAdd(A, B))
miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/matrices/expressions/tests/test_matexpr.py ADDED
@@ -0,0 +1,592 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.concrete.summations import Sum
2
+ from sympy.core.exprtools import gcd_terms
3
+ from sympy.core.function import (diff, expand)
4
+ from sympy.core.relational import Eq
5
+ from sympy.core.symbol import (Dummy, Symbol, Str)
6
+ from sympy.functions.special.tensor_functions import KroneckerDelta
7
+ from sympy.matrices.dense import zeros
8
+ from sympy.polys.polytools import factor
9
+
10
+ from sympy.core import (S, symbols, Add, Mul, SympifyError, Rational,
11
+ Function)
12
+ from sympy.functions import sin, cos, tan, sqrt, cbrt, exp
13
+ from sympy.simplify import simplify
14
+ from sympy.matrices import (ImmutableMatrix, Inverse, MatAdd, MatMul,
15
+ MatPow, Matrix, MatrixExpr, MatrixSymbol,
16
+ SparseMatrix, Transpose, Adjoint, MatrixSet)
17
+ from sympy.matrices.exceptions import NonSquareMatrixError
18
+ from sympy.matrices.expressions.determinant import Determinant, det
19
+ from sympy.matrices.expressions.matexpr import MatrixElement
20
+ from sympy.matrices.expressions.special import ZeroMatrix, Identity
21
+ from sympy.testing.pytest import raises, XFAIL, skip
22
+ from importlib.metadata import version
23
+
24
+ n, m, l, k, p = symbols('n m l k p', integer=True)
25
+ x = symbols('x')
26
+ A = MatrixSymbol('A', n, m)
27
+ B = MatrixSymbol('B', m, l)
28
+ C = MatrixSymbol('C', n, n)
29
+ D = MatrixSymbol('D', n, n)
30
+ E = MatrixSymbol('E', m, n)
31
+ w = MatrixSymbol('w', n, 1)
32
+
33
+
34
+ def test_matrix_symbol_creation():
35
+ assert MatrixSymbol('A', 2, 2)
36
+ assert MatrixSymbol('A', 0, 0)
37
+ raises(ValueError, lambda: MatrixSymbol('A', -1, 2))
38
+ raises(ValueError, lambda: MatrixSymbol('A', 2.0, 2))
39
+ raises(ValueError, lambda: MatrixSymbol('A', 2j, 2))
40
+ raises(ValueError, lambda: MatrixSymbol('A', 2, -1))
41
+ raises(ValueError, lambda: MatrixSymbol('A', 2, 2.0))
42
+ raises(ValueError, lambda: MatrixSymbol('A', 2, 2j))
43
+
44
+ n = symbols('n')
45
+ assert MatrixSymbol('A', n, n)
46
+ n = symbols('n', integer=False)
47
+ raises(ValueError, lambda: MatrixSymbol('A', n, n))
48
+ n = symbols('n', negative=True)
49
+ raises(ValueError, lambda: MatrixSymbol('A', n, n))
50
+
51
+
52
+ def test_matexpr_properties():
53
+ assert A.shape == (n, m)
54
+ assert (A * B).shape == (n, l)
55
+ assert A[0, 1].indices == (0, 1)
56
+ assert A[0, 0].symbol == A
57
+ assert A[0, 0].symbol.name == 'A'
58
+
59
+
60
+ def test_matexpr():
61
+ assert (x*A).shape == A.shape
62
+ assert (x*A).__class__ == MatMul
63
+ assert 2*A - A - A == ZeroMatrix(*A.shape)
64
+ assert (A*B).shape == (n, l)
65
+
66
+
67
+ def test_matexpr_subs():
68
+ A = MatrixSymbol('A', n, m)
69
+ B = MatrixSymbol('B', m, l)
70
+ C = MatrixSymbol('C', m, l)
71
+
72
+ assert A.subs(n, m).shape == (m, m)
73
+ assert (A*B).subs(B, C) == A*C
74
+ assert (A*B).subs(l, n).is_square
75
+
76
+ W = MatrixSymbol("W", 3, 3)
77
+ X = MatrixSymbol("X", 2, 2)
78
+ Y = MatrixSymbol("Y", 1, 2)
79
+ Z = MatrixSymbol("Z", n, 2)
80
+ # no restrictions on Symbol replacement
81
+ assert X.subs(X, Y) == Y
82
+ # it might be better to just change the name
83
+ y = Str('y')
84
+ assert X.subs(Str("X"), y).args == (y, 2, 2)
85
+ # it's ok to introduce a wider matrix
86
+ assert X[1, 1].subs(X, W) == W[1, 1]
87
+ # but for a given MatrixExpression, only change
88
+ # name if indexing on the new shape is valid.
89
+ # Here, X is 2,2; Y is 1,2 and Y[1, 1] is out
90
+ # of range so an error is raised
91
+ raises(IndexError, lambda: X[1, 1].subs(X, Y))
92
+ # here, [0, 1] is in range so the subs succeeds
93
+ assert X[0, 1].subs(X, Y) == Y[0, 1]
94
+ # and here the size of n will accept any index
95
+ # in the first position
96
+ assert W[2, 1].subs(W, Z) == Z[2, 1]
97
+ # but not in the second position
98
+ raises(IndexError, lambda: W[2, 2].subs(W, Z))
99
+ # any matrix should raise if invalid
100
+ raises(IndexError, lambda: W[2, 2].subs(W, zeros(2)))
101
+
102
+ A = SparseMatrix([[1, 2], [3, 4]])
103
+ B = Matrix([[1, 2], [3, 4]])
104
+ C, D = MatrixSymbol('C', 2, 2), MatrixSymbol('D', 2, 2)
105
+
106
+ assert (C*D).subs({C: A, D: B}) == MatMul(A, B)
107
+
108
+
109
+ def test_addition():
110
+ A = MatrixSymbol('A', n, m)
111
+ B = MatrixSymbol('B', n, m)
112
+
113
+ assert isinstance(A + B, MatAdd)
114
+ assert (A + B).shape == A.shape
115
+ assert isinstance(A - A + 2*B, MatMul)
116
+
117
+ raises(TypeError, lambda: A + 1)
118
+ raises(TypeError, lambda: 5 + A)
119
+ raises(TypeError, lambda: 5 - A)
120
+
121
+ assert A + ZeroMatrix(n, m) - A == ZeroMatrix(n, m)
122
+ raises(TypeError, lambda: ZeroMatrix(n, m) + S.Zero)
123
+
124
+
125
+ def test_multiplication():
126
+ A = MatrixSymbol('A', n, m)
127
+ B = MatrixSymbol('B', m, l)
128
+ C = MatrixSymbol('C', n, n)
129
+
130
+ assert (2*A*B).shape == (n, l)
131
+ assert (A*0*B) == ZeroMatrix(n, l)
132
+ assert (2*A).shape == A.shape
133
+
134
+ assert A * ZeroMatrix(m, m) * B == ZeroMatrix(n, l)
135
+
136
+ assert C * Identity(n) * C.I == Identity(n)
137
+
138
+ assert B/2 == S.Half*B
139
+ raises(NotImplementedError, lambda: 2/B)
140
+
141
+ A = MatrixSymbol('A', n, n)
142
+ B = MatrixSymbol('B', n, n)
143
+ assert Identity(n) * (A + B) == A + B
144
+
145
+ assert A**2*A == A**3
146
+ assert A**2*(A.I)**3 == A.I
147
+ assert A**3*(A.I)**2 == A
148
+
149
+
150
+ def test_MatPow():
151
+ A = MatrixSymbol('A', n, n)
152
+
153
+ AA = MatPow(A, 2)
154
+ assert AA.exp == 2
155
+ assert AA.base == A
156
+ assert (A**n).exp == n
157
+
158
+ assert A**0 == Identity(n)
159
+ assert A**1 == A
160
+ assert A**2 == AA
161
+ assert A**-1 == Inverse(A)
162
+ assert (A**-1)**-1 == A
163
+ assert (A**2)**3 == A**6
164
+ assert A**S.Half == sqrt(A)
165
+ assert A**Rational(1, 3) == cbrt(A)
166
+ raises(NonSquareMatrixError, lambda: MatrixSymbol('B', 3, 2)**2)
167
+
168
+
169
+ def test_MatrixSymbol():
170
+ n, m, t = symbols('n,m,t')
171
+ X = MatrixSymbol('X', n, m)
172
+ assert X.shape == (n, m)
173
+ raises(TypeError, lambda: MatrixSymbol('X', n, m)(t)) # issue 5855
174
+ assert X.doit() == X
175
+
176
+
177
+ def test_dense_conversion():
178
+ X = MatrixSymbol('X', 2, 2)
179
+ assert ImmutableMatrix(X) == ImmutableMatrix(2, 2, lambda i, j: X[i, j])
180
+ assert Matrix(X) == Matrix(2, 2, lambda i, j: X[i, j])
181
+
182
+
183
+ def test_free_symbols():
184
+ assert (C*D).free_symbols == {C, D}
185
+
186
+
187
+ def test_zero_matmul():
188
+ assert isinstance(S.Zero * MatrixSymbol('X', 2, 2), MatrixExpr)
189
+
190
+
191
+ def test_matadd_simplify():
192
+ A = MatrixSymbol('A', 1, 1)
193
+ assert simplify(MatAdd(A, ImmutableMatrix([[sin(x)**2 + cos(x)**2]]))) == \
194
+ MatAdd(A, Matrix([[1]]))
195
+
196
+
197
+ def test_matmul_simplify():
198
+ A = MatrixSymbol('A', 1, 1)
199
+ assert simplify(MatMul(A, ImmutableMatrix([[sin(x)**2 + cos(x)**2]]))) == \
200
+ MatMul(A, Matrix([[1]]))
201
+
202
+
203
+ def test_invariants():
204
+ A = MatrixSymbol('A', n, m)
205
+ B = MatrixSymbol('B', m, l)
206
+ X = MatrixSymbol('X', n, n)
207
+ objs = [Identity(n), ZeroMatrix(m, n), A, MatMul(A, B), MatAdd(A, A),
208
+ Transpose(A), Adjoint(A), Inverse(X), MatPow(X, 2), MatPow(X, -1),
209
+ MatPow(X, 0)]
210
+ for obj in objs:
211
+ assert obj == obj.__class__(*obj.args)
212
+
213
+
214
+ def test_matexpr_indexing():
215
+ A = MatrixSymbol('A', n, m)
216
+ A[1, 2]
217
+ A[l, k]
218
+ A[l + 1, k + 1]
219
+ A = MatrixSymbol('A', 2, 1)
220
+ for i in range(-2, 2):
221
+ for j in range(-1, 1):
222
+ A[i, j]
223
+
224
+
225
+ def test_single_indexing():
226
+ A = MatrixSymbol('A', 2, 3)
227
+ assert A[1] == A[0, 1]
228
+ assert A[int(1)] == A[0, 1]
229
+ assert A[3] == A[1, 0]
230
+ assert list(A[:2, :2]) == [A[0, 0], A[0, 1], A[1, 0], A[1, 1]]
231
+ raises(IndexError, lambda: A[6])
232
+ raises(IndexError, lambda: A[n])
233
+ B = MatrixSymbol('B', n, m)
234
+ raises(IndexError, lambda: B[1])
235
+ B = MatrixSymbol('B', n, 3)
236
+ assert B[3] == B[1, 0]
237
+
238
+
239
+ def test_MatrixElement_commutative():
240
+ assert A[0, 1]*A[1, 0] == A[1, 0]*A[0, 1]
241
+
242
+
243
+ def test_MatrixSymbol_determinant():
244
+ A = MatrixSymbol('A', 4, 4)
245
+ assert A.as_explicit().det() == A[0, 0]*A[1, 1]*A[2, 2]*A[3, 3] - \
246
+ A[0, 0]*A[1, 1]*A[2, 3]*A[3, 2] - A[0, 0]*A[1, 2]*A[2, 1]*A[3, 3] + \
247
+ A[0, 0]*A[1, 2]*A[2, 3]*A[3, 1] + A[0, 0]*A[1, 3]*A[2, 1]*A[3, 2] - \
248
+ A[0, 0]*A[1, 3]*A[2, 2]*A[3, 1] - A[0, 1]*A[1, 0]*A[2, 2]*A[3, 3] + \
249
+ A[0, 1]*A[1, 0]*A[2, 3]*A[3, 2] + A[0, 1]*A[1, 2]*A[2, 0]*A[3, 3] - \
250
+ A[0, 1]*A[1, 2]*A[2, 3]*A[3, 0] - A[0, 1]*A[1, 3]*A[2, 0]*A[3, 2] + \
251
+ A[0, 1]*A[1, 3]*A[2, 2]*A[3, 0] + A[0, 2]*A[1, 0]*A[2, 1]*A[3, 3] - \
252
+ A[0, 2]*A[1, 0]*A[2, 3]*A[3, 1] - A[0, 2]*A[1, 1]*A[2, 0]*A[3, 3] + \
253
+ A[0, 2]*A[1, 1]*A[2, 3]*A[3, 0] + A[0, 2]*A[1, 3]*A[2, 0]*A[3, 1] - \
254
+ A[0, 2]*A[1, 3]*A[2, 1]*A[3, 0] - A[0, 3]*A[1, 0]*A[2, 1]*A[3, 2] + \
255
+ A[0, 3]*A[1, 0]*A[2, 2]*A[3, 1] + A[0, 3]*A[1, 1]*A[2, 0]*A[3, 2] - \
256
+ A[0, 3]*A[1, 1]*A[2, 2]*A[3, 0] - A[0, 3]*A[1, 2]*A[2, 0]*A[3, 1] + \
257
+ A[0, 3]*A[1, 2]*A[2, 1]*A[3, 0]
258
+
259
+ B = MatrixSymbol('B', 4, 4)
260
+ assert Determinant(A + B).doit() == det(A + B) == (A + B).det()
261
+
262
+
263
+ def test_MatrixElement_diff():
264
+ assert (A[3, 0]*A[0, 0]).diff(A[0, 0]) == A[3, 0]
265
+
266
+
267
+ def test_MatrixElement_doit():
268
+ u = MatrixSymbol('u', 2, 1)
269
+ v = ImmutableMatrix([3, 5])
270
+ assert u[0, 0].subs(u, v).doit() == v[0, 0]
271
+
272
+
273
+ def test_identity_powers():
274
+ M = Identity(n)
275
+ assert MatPow(M, 3).doit() == M**3
276
+ assert M**n == M
277
+ assert MatPow(M, 0).doit() == M**2
278
+ assert M**-2 == M
279
+ assert MatPow(M, -2).doit() == M**0
280
+ N = Identity(3)
281
+ assert MatPow(N, 2).doit() == N**n
282
+ assert MatPow(N, 3).doit() == N
283
+ assert MatPow(N, -2).doit() == N**4
284
+ assert MatPow(N, 2).doit() == N**0
285
+
286
+
287
+ def test_Zero_power():
288
+ z1 = ZeroMatrix(n, n)
289
+ assert z1**4 == z1
290
+ raises(ValueError, lambda:z1**-2)
291
+ assert z1**0 == Identity(n)
292
+ assert MatPow(z1, 2).doit() == z1**2
293
+ raises(ValueError, lambda:MatPow(z1, -2).doit())
294
+ z2 = ZeroMatrix(3, 3)
295
+ assert MatPow(z2, 4).doit() == z2**4
296
+ raises(ValueError, lambda:z2**-3)
297
+ assert z2**3 == MatPow(z2, 3).doit()
298
+ assert z2**0 == Identity(3)
299
+ raises(ValueError, lambda:MatPow(z2, -1).doit())
300
+
301
+
302
+ def test_matrixelement_diff():
303
+ dexpr = diff((D*w)[k,0], w[p,0])
304
+
305
+ assert w[k, p].diff(w[k, p]) == 1
306
+ assert w[k, p].diff(w[0, 0]) == KroneckerDelta(0, k, (0, n-1))*KroneckerDelta(0, p, (0, 0))
307
+ _i_1 = Dummy("_i_1")
308
+ assert dexpr.dummy_eq(Sum(KroneckerDelta(_i_1, p, (0, n-1))*D[k, _i_1], (_i_1, 0, n - 1)))
309
+ assert dexpr.doit() == D[k, p]
310
+
311
+
312
+ def test_MatrixElement_with_values():
313
+ x, y, z, w = symbols("x y z w")
314
+ M = Matrix([[x, y], [z, w]])
315
+ i, j = symbols("i, j")
316
+ Mij = M[i, j]
317
+ assert isinstance(Mij, MatrixElement)
318
+ Ms = SparseMatrix([[2, 3], [4, 5]])
319
+ msij = Ms[i, j]
320
+ assert isinstance(msij, MatrixElement)
321
+ for oi, oj in [(0, 0), (0, 1), (1, 0), (1, 1)]:
322
+ assert Mij.subs({i: oi, j: oj}) == M[oi, oj]
323
+ assert msij.subs({i: oi, j: oj}) == Ms[oi, oj]
324
+ A = MatrixSymbol("A", 2, 2)
325
+ assert A[0, 0].subs(A, M) == x
326
+ assert A[i, j].subs(A, M) == M[i, j]
327
+ assert M[i, j].subs(M, A) == A[i, j]
328
+
329
+ assert isinstance(M[3*i - 2, j], MatrixElement)
330
+ assert M[3*i - 2, j].subs({i: 1, j: 0}) == M[1, 0]
331
+ assert isinstance(M[i, 0], MatrixElement)
332
+ assert M[i, 0].subs(i, 0) == M[0, 0]
333
+ assert M[0, i].subs(i, 1) == M[0, 1]
334
+
335
+ assert M[i, j].diff(x) == Matrix([[1, 0], [0, 0]])[i, j]
336
+
337
+ raises(ValueError, lambda: M[i, 2])
338
+ raises(ValueError, lambda: M[i, -1])
339
+ raises(ValueError, lambda: M[2, i])
340
+ raises(ValueError, lambda: M[-1, i])
341
+
342
+
343
+ def test_inv():
344
+ B = MatrixSymbol('B', 3, 3)
345
+ assert B.inv() == B**-1
346
+
347
+ # https://github.com/sympy/sympy/issues/19162
348
+ X = MatrixSymbol('X', 1, 1).as_explicit()
349
+ assert X.inv() == Matrix([[1/X[0, 0]]])
350
+
351
+ X = MatrixSymbol('X', 2, 2).as_explicit()
352
+ detX = X[0, 0]*X[1, 1] - X[0, 1]*X[1, 0]
353
+ invX = Matrix([[ X[1, 1], -X[0, 1]],
354
+ [-X[1, 0], X[0, 0]]]) / detX
355
+ assert X.inv() == invX
356
+
357
+
358
+ @XFAIL
359
+ def test_factor_expand():
360
+ A = MatrixSymbol("A", n, n)
361
+ B = MatrixSymbol("B", n, n)
362
+ expr1 = (A + B)*(C + D)
363
+ expr2 = A*C + B*C + A*D + B*D
364
+ assert expr1 != expr2
365
+ assert expand(expr1) == expr2
366
+ assert factor(expr2) == expr1
367
+
368
+ expr = B**(-1)*(A**(-1)*B**(-1) - A**(-1)*C*B**(-1))**(-1)*A**(-1)
369
+ I = Identity(n)
370
+ # Ideally we get the first, but we at least don't want a wrong answer
371
+ assert factor(expr) in [I - C, B**-1*(A**-1*(I - C)*B**-1)**-1*A**-1]
372
+
373
+ def test_numpy_conversion():
374
+ try:
375
+ from numpy import array, array_equal
376
+ except ImportError:
377
+ skip('NumPy must be available to test creating matrices from ndarrays')
378
+ A = MatrixSymbol('A', 2, 2)
379
+ np_array = array([[MatrixElement(A, 0, 0), MatrixElement(A, 0, 1)],
380
+ [MatrixElement(A, 1, 0), MatrixElement(A, 1, 1)]])
381
+ assert array_equal(array(A), np_array)
382
+ assert array_equal(array(A, copy=True), np_array)
383
+ if(int(version('numpy').split('.')[0]) >= 2): #run this test only if numpy is new enough that copy variable is passed properly.
384
+ raises(TypeError, lambda: array(A, copy=False))
385
+
386
+ def test_issue_2749():
387
+ A = MatrixSymbol("A", 5, 2)
388
+ assert (A.T * A).I.as_explicit() == Matrix([[(A.T * A).I[0, 0], (A.T * A).I[0, 1]], \
389
+ [(A.T * A).I[1, 0], (A.T * A).I[1, 1]]])
390
+
391
+
392
+ def test_issue_2750():
393
+ x = MatrixSymbol('x', 1, 1)
394
+ assert (x.T*x).as_explicit()**-1 == Matrix([[x[0, 0]**(-2)]])
395
+
396
+
397
+ def test_issue_7842():
398
+ A = MatrixSymbol('A', 3, 1)
399
+ B = MatrixSymbol('B', 2, 1)
400
+ assert Eq(A, B) == False
401
+ assert Eq(A[1,0], B[1, 0]).func is Eq
402
+ A = ZeroMatrix(2, 3)
403
+ B = ZeroMatrix(2, 3)
404
+ assert Eq(A, B) == True
405
+
406
+
407
+ def test_issue_21195():
408
+ t = symbols('t')
409
+ x = Function('x')(t)
410
+ dx = x.diff(t)
411
+ exp1 = cos(x) + cos(x)*dx
412
+ exp2 = sin(x) + tan(x)*(dx.diff(t))
413
+ exp3 = sin(x)*sin(t)*(dx.diff(t)).diff(t)
414
+ A = Matrix([[exp1], [exp2], [exp3]])
415
+ B = Matrix([[exp1.diff(x)], [exp2.diff(x)], [exp3.diff(x)]])
416
+ assert A.diff(x) == B
417
+
418
+
419
+ def test_issue_24859():
420
+ A = MatrixSymbol('A', 2, 3)
421
+ B = MatrixSymbol('B', 3, 2)
422
+ J = A*B
423
+ Jinv = Matrix(J).adjugate()
424
+ u = MatrixSymbol('u', 2, 3)
425
+ Jk = Jinv.subs(A, A + x*u)
426
+
427
+ expected = B[0, 1]*u[1, 0] + B[1, 1]*u[1, 1] + B[2, 1]*u[1, 2]
428
+ assert Jk[0, 0].diff(x) == expected
429
+ assert diff(Jk[0, 0], x).doit() == expected
430
+
431
+
432
+ def test_MatMul_postprocessor():
433
+ z = zeros(2)
434
+ z1 = ZeroMatrix(2, 2)
435
+ assert Mul(0, z) == Mul(z, 0) in [z, z1]
436
+
437
+ M = Matrix([[1, 2], [3, 4]])
438
+ Mx = Matrix([[x, 2*x], [3*x, 4*x]])
439
+ assert Mul(x, M) == Mul(M, x) == Mx
440
+
441
+ A = MatrixSymbol("A", 2, 2)
442
+ assert Mul(A, M) == MatMul(A, M)
443
+ assert Mul(M, A) == MatMul(M, A)
444
+ # Scalars should be absorbed into constant matrices
445
+ a = Mul(x, M, A)
446
+ b = Mul(M, x, A)
447
+ c = Mul(M, A, x)
448
+ assert a == b == c == MatMul(Mx, A)
449
+ a = Mul(x, A, M)
450
+ b = Mul(A, x, M)
451
+ c = Mul(A, M, x)
452
+ assert a == b == c == MatMul(A, Mx)
453
+ assert Mul(M, M) == M**2
454
+ assert Mul(A, M, M) == MatMul(A, M**2)
455
+ assert Mul(M, M, A) == MatMul(M**2, A)
456
+ assert Mul(M, A, M) == MatMul(M, A, M)
457
+
458
+ assert Mul(A, x, M, M, x) == MatMul(A, Mx**2)
459
+
460
+
461
+ @XFAIL
462
+ def test_MatAdd_postprocessor_xfail():
463
+ # This is difficult to get working because of the way that Add processes
464
+ # its args.
465
+ z = zeros(2)
466
+ assert Add(z, S.NaN) == Add(S.NaN, z)
467
+
468
+
469
+ def test_MatAdd_postprocessor():
470
+ # Some of these are nonsensical, but we do not raise errors for Add
471
+ # because that breaks algorithms that want to replace matrices with dummy
472
+ # symbols.
473
+
474
+ z = zeros(2)
475
+
476
+ assert Add(0, z) == Add(z, 0) == z
477
+
478
+ a = Add(S.Infinity, z)
479
+ assert a == Add(z, S.Infinity)
480
+ assert isinstance(a, Add)
481
+ assert a.args == (S.Infinity, z)
482
+
483
+ a = Add(S.ComplexInfinity, z)
484
+ assert a == Add(z, S.ComplexInfinity)
485
+ assert isinstance(a, Add)
486
+ assert a.args == (S.ComplexInfinity, z)
487
+
488
+ a = Add(z, S.NaN)
489
+ # assert a == Add(S.NaN, z) # See the XFAIL above
490
+ assert isinstance(a, Add)
491
+ assert a.args == (S.NaN, z)
492
+
493
+ M = Matrix([[1, 2], [3, 4]])
494
+ a = Add(x, M)
495
+ assert a == Add(M, x)
496
+ assert isinstance(a, Add)
497
+ assert a.args == (x, M)
498
+
499
+ A = MatrixSymbol("A", 2, 2)
500
+ assert Add(A, M) == Add(M, A) == A + M
501
+
502
+ # Scalars should be absorbed into constant matrices (producing an error)
503
+ a = Add(x, M, A)
504
+ assert a == Add(M, x, A) == Add(M, A, x) == Add(x, A, M) == Add(A, x, M) == Add(A, M, x)
505
+ assert isinstance(a, Add)
506
+ assert a.args == (x, A + M)
507
+
508
+ assert Add(M, M) == 2*M
509
+ assert Add(M, A, M) == Add(M, M, A) == Add(A, M, M) == A + 2*M
510
+
511
+ a = Add(A, x, M, M, x)
512
+ assert isinstance(a, Add)
513
+ assert a.args == (2*x, A + 2*M)
514
+
515
+
516
+ def test_simplify_matrix_expressions():
517
+ # Various simplification functions
518
+ assert type(gcd_terms(C*D + D*C)) == MatAdd
519
+ a = gcd_terms(2*C*D + 4*D*C)
520
+ assert type(a) == MatAdd
521
+ assert a.args == (2*C*D, 4*D*C)
522
+
523
+
524
+ def test_exp():
525
+ A = MatrixSymbol('A', 2, 2)
526
+ B = MatrixSymbol('B', 2, 2)
527
+ expr1 = exp(A)*exp(B)
528
+ expr2 = exp(B)*exp(A)
529
+ assert expr1 != expr2
530
+ assert expr1 - expr2 != 0
531
+ assert not isinstance(expr1, exp)
532
+ assert not isinstance(expr2, exp)
533
+
534
+
535
+ def test_invalid_args():
536
+ raises(SympifyError, lambda: MatrixSymbol(1, 2, 'A'))
537
+
538
+
539
+ def test_matrixsymbol_from_symbol():
540
+ # The label should be preserved during doit and subs
541
+ A_label = Symbol('A', complex=True)
542
+ A = MatrixSymbol(A_label, 2, 2)
543
+
544
+ A_1 = A.doit()
545
+ A_2 = A.subs(2, 3)
546
+ assert A_1.args == A.args
547
+ assert A_2.args[0] == A.args[0]
548
+
549
+
550
+ def test_as_explicit():
551
+ Z = MatrixSymbol('Z', 2, 3)
552
+ assert Z.as_explicit() == ImmutableMatrix([
553
+ [Z[0, 0], Z[0, 1], Z[0, 2]],
554
+ [Z[1, 0], Z[1, 1], Z[1, 2]],
555
+ ])
556
+ raises(ValueError, lambda: A.as_explicit())
557
+
558
+
559
+ def test_MatrixSet():
560
+ M = MatrixSet(2, 2, set=S.Reals)
561
+ assert M.shape == (2, 2)
562
+ assert M.set == S.Reals
563
+ X = Matrix([[1, 2], [3, 4]])
564
+ assert X in M
565
+ X = ZeroMatrix(2, 2)
566
+ assert X in M
567
+ raises(TypeError, lambda: A in M)
568
+ raises(TypeError, lambda: 1 in M)
569
+ M = MatrixSet(n, m, set=S.Reals)
570
+ assert A in M
571
+ raises(TypeError, lambda: C in M)
572
+ raises(TypeError, lambda: X in M)
573
+ M = MatrixSet(2, 2, set={1, 2, 3})
574
+ X = Matrix([[1, 2], [3, 4]])
575
+ Y = Matrix([[1, 2]])
576
+ assert (X in M) == S.false
577
+ assert (Y in M) == S.false
578
+ raises(ValueError, lambda: MatrixSet(2, -2, S.Reals))
579
+ raises(ValueError, lambda: MatrixSet(2.4, -1, S.Reals))
580
+ raises(TypeError, lambda: MatrixSet(2, 2, (1, 2, 3)))
581
+
582
+
583
+ def test_matrixsymbol_solving():
584
+ A = MatrixSymbol('A', 2, 2)
585
+ B = MatrixSymbol('B', 2, 2)
586
+ Z = ZeroMatrix(2, 2)
587
+ assert -(-A + B) - A + B == Z
588
+ assert (-(-A + B) - A + B).simplify() == Z
589
+ assert (-(-A + B) - A + B).expand() == Z
590
+ assert (-(-A + B) - A + B - Z).simplify() == Z
591
+ assert (-(-A + B) - A + B - Z).expand() == Z
592
+ assert (A*(A + B) + B*(A.T + B.T)).expand() == A**2 + A*B + B*A.T + B*B.T
miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/matrices/expressions/tests/test_matmul.py ADDED
@@ -0,0 +1,193 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core import I, symbols, Basic, Mul, S
2
+ from sympy.core.mul import mul
3
+ from sympy.functions import adjoint, transpose
4
+ from sympy.matrices.exceptions import ShapeError
5
+ from sympy.matrices import (Identity, Inverse, Matrix, MatrixSymbol, ZeroMatrix,
6
+ eye, ImmutableMatrix)
7
+ from sympy.matrices.expressions import Adjoint, Transpose, det, MatPow
8
+ from sympy.matrices.expressions.special import GenericIdentity
9
+ from sympy.matrices.expressions.matmul import (factor_in_front, remove_ids,
10
+ MatMul, combine_powers, any_zeros, unpack, only_squares)
11
+ from sympy.strategies import null_safe
12
+ from sympy.assumptions.ask import Q
13
+ from sympy.assumptions.refine import refine
14
+ from sympy.core.symbol import Symbol
15
+
16
+ from sympy.testing.pytest import XFAIL, raises
17
+
18
+ n, m, l, k = symbols('n m l k', integer=True)
19
+ x = symbols('x')
20
+ A = MatrixSymbol('A', n, m)
21
+ B = MatrixSymbol('B', m, l)
22
+ C = MatrixSymbol('C', n, n)
23
+ D = MatrixSymbol('D', n, n)
24
+ E = MatrixSymbol('E', m, n)
25
+
26
+ def test_evaluate():
27
+ assert MatMul(C, C, evaluate=True) == MatMul(C, C).doit()
28
+
29
+ def test_adjoint():
30
+ assert adjoint(A*B) == Adjoint(B)*Adjoint(A)
31
+ assert adjoint(2*A*B) == 2*Adjoint(B)*Adjoint(A)
32
+ assert adjoint(2*I*C) == -2*I*Adjoint(C)
33
+
34
+ M = Matrix(2, 2, [1, 2 + I, 3, 4])
35
+ MA = Matrix(2, 2, [1, 3, 2 - I, 4])
36
+ assert adjoint(M) == MA
37
+ assert adjoint(2*M) == 2*MA
38
+ assert adjoint(MatMul(2, M)) == MatMul(2, MA).doit()
39
+
40
+
41
+ def test_transpose():
42
+ assert transpose(A*B) == Transpose(B)*Transpose(A)
43
+ assert transpose(2*A*B) == 2*Transpose(B)*Transpose(A)
44
+ assert transpose(2*I*C) == 2*I*Transpose(C)
45
+
46
+ M = Matrix(2, 2, [1, 2 + I, 3, 4])
47
+ MT = Matrix(2, 2, [1, 3, 2 + I, 4])
48
+ assert transpose(M) == MT
49
+ assert transpose(2*M) == 2*MT
50
+ assert transpose(x*M) == x*MT
51
+ assert transpose(MatMul(2, M)) == MatMul(2, MT).doit()
52
+
53
+
54
+ def test_factor_in_front():
55
+ assert factor_in_front(MatMul(A, 2, B, evaluate=False)) ==\
56
+ MatMul(2, A, B, evaluate=False)
57
+
58
+
59
+ def test_remove_ids():
60
+ assert remove_ids(MatMul(A, Identity(m), B, evaluate=False)) == \
61
+ MatMul(A, B, evaluate=False)
62
+ assert null_safe(remove_ids)(MatMul(Identity(n), evaluate=False)) == \
63
+ MatMul(Identity(n), evaluate=False)
64
+
65
+
66
+ def test_combine_powers():
67
+ assert combine_powers(MatMul(D, Inverse(D), D, evaluate=False)) == \
68
+ MatMul(Identity(n), D, evaluate=False)
69
+ assert combine_powers(MatMul(B.T, Inverse(E*A), E, A, B, evaluate=False)) == \
70
+ MatMul(B.T, Identity(m), B, evaluate=False)
71
+ assert combine_powers(MatMul(A, E, Inverse(A*E), D, evaluate=False)) == \
72
+ MatMul(Identity(n), D, evaluate=False)
73
+
74
+
75
+ def test_any_zeros():
76
+ assert any_zeros(MatMul(A, ZeroMatrix(m, k), evaluate=False)) == \
77
+ ZeroMatrix(n, k)
78
+
79
+
80
+ def test_unpack():
81
+ assert unpack(MatMul(A, evaluate=False)) == A
82
+ x = MatMul(A, B)
83
+ assert unpack(x) == x
84
+
85
+
86
+ def test_only_squares():
87
+ assert only_squares(C) == [C]
88
+ assert only_squares(C, D) == [C, D]
89
+ assert only_squares(C, A, A.T, D) == [C, A*A.T, D]
90
+
91
+
92
+ def test_determinant():
93
+ assert det(2*C) == 2**n*det(C)
94
+ assert det(2*C*D) == 2**n*det(C)*det(D)
95
+ assert det(3*C*A*A.T*D) == 3**n*det(C)*det(A*A.T)*det(D)
96
+
97
+
98
+ def test_doit():
99
+ assert MatMul(C, 2, D).args == (C, 2, D)
100
+ assert MatMul(C, 2, D).doit().args == (2, C, D)
101
+ assert MatMul(C, Transpose(D*C)).args == (C, Transpose(D*C))
102
+ assert MatMul(C, Transpose(D*C)).doit(deep=True).args == (C, C.T, D.T)
103
+
104
+
105
+ def test_doit_drills_down():
106
+ X = ImmutableMatrix([[1, 2], [3, 4]])
107
+ Y = ImmutableMatrix([[2, 3], [4, 5]])
108
+ assert MatMul(X, MatPow(Y, 2)).doit() == X*Y**2
109
+ assert MatMul(C, Transpose(D*C)).doit().args == (C, C.T, D.T)
110
+
111
+
112
+ def test_doit_deep_false_still_canonical():
113
+ assert (MatMul(C, Transpose(D*C), 2).doit(deep=False).args ==
114
+ (2, C, Transpose(D*C)))
115
+
116
+
117
+ def test_matmul_scalar_Matrix_doit():
118
+ # Issue 9053
119
+ X = Matrix([[1, 2], [3, 4]])
120
+ assert MatMul(2, X).doit() == 2*X
121
+
122
+
123
+ def test_matmul_sympify():
124
+ assert isinstance(MatMul(eye(1), eye(1)).args[0], Basic)
125
+
126
+
127
+ def test_collapse_MatrixBase():
128
+ A = Matrix([[1, 1], [1, 1]])
129
+ B = Matrix([[1, 2], [3, 4]])
130
+ assert MatMul(A, B).doit() == ImmutableMatrix([[4, 6], [4, 6]])
131
+
132
+
133
+ def test_refine():
134
+ assert refine(C*C.T*D, Q.orthogonal(C)).doit() == D
135
+
136
+ kC = k*C
137
+ assert refine(kC*C.T, Q.orthogonal(C)).doit() == k*Identity(n)
138
+ assert refine(kC* kC.T, Q.orthogonal(C)).doit() == (k**2)*Identity(n)
139
+
140
+ def test_matmul_no_matrices():
141
+ assert MatMul(1) == 1
142
+ assert MatMul(n, m) == n*m
143
+ assert not isinstance(MatMul(n, m), MatMul)
144
+
145
+ def test_matmul_args_cnc():
146
+ assert MatMul(n, A, A.T).args_cnc() == [[n], [A, A.T]]
147
+ assert MatMul(A, A.T).args_cnc() == [[], [A, A.T]]
148
+
149
+ @XFAIL
150
+ def test_matmul_args_cnc_symbols():
151
+ # Not currently supported
152
+ a, b = symbols('a b', commutative=False)
153
+ assert MatMul(n, a, b, A, A.T).args_cnc() == [[n], [a, b, A, A.T]]
154
+ assert MatMul(n, a, A, b, A.T).args_cnc() == [[n], [a, A, b, A.T]]
155
+
156
+ def test_issue_12950():
157
+ M = Matrix([[Symbol("x")]]) * MatrixSymbol("A", 1, 1)
158
+ assert MatrixSymbol("A", 1, 1).as_explicit()[0]*Symbol('x') == M.as_explicit()[0]
159
+
160
+ def test_construction_with_Mul():
161
+ assert Mul(C, D) == MatMul(C, D)
162
+ assert Mul(D, C) == MatMul(D, C)
163
+
164
+ def test_construction_with_mul():
165
+ assert mul(C, D) == MatMul(C, D)
166
+ assert mul(D, C) == MatMul(D, C)
167
+ assert mul(C, D) != MatMul(D, C)
168
+
169
+ def test_generic_identity():
170
+ assert MatMul.identity == GenericIdentity()
171
+ assert MatMul.identity != S.One
172
+
173
+
174
+ def test_issue_23519():
175
+ N = Symbol("N", integer=True)
176
+ M1 = MatrixSymbol("M1", N, N)
177
+ M2 = MatrixSymbol("M2", N, N)
178
+ I = Identity(N)
179
+ z = (M2 + 2 * (M2 + I) * M1 + I)
180
+ assert z.coeff(M1) == 2*I + 2*M2
181
+
182
+
183
+ def test_shape_error():
184
+ A = MatrixSymbol('A', 2, 2)
185
+ B = MatrixSymbol('B', 3, 3)
186
+ raises(ShapeError, lambda: MatMul(A, B))
187
+
188
+
189
+ def test_matmul_transpose():
190
+ # https://github.com/sympy/sympy/issues/9503
191
+ M = Matrix(2, 2, [1, 2 + I, 3, 4])
192
+ a = Symbol('a')
193
+ assert (MatMul(a, M).T).expand() == (a*Matrix([[1, 3],[2 + I, 4]])).expand()
miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/matrices/expressions/tests/test_matpow.py ADDED
@@ -0,0 +1,217 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.functions.elementary.miscellaneous import sqrt
2
+ from sympy.simplify.powsimp import powsimp
3
+ from sympy.testing.pytest import raises
4
+ from sympy.core.expr import unchanged
5
+ from sympy.core import symbols, S
6
+ from sympy.matrices import Identity, MatrixSymbol, ImmutableMatrix, ZeroMatrix, OneMatrix, Matrix
7
+ from sympy.matrices.exceptions import NonSquareMatrixError
8
+ from sympy.matrices.expressions import MatPow, MatAdd, MatMul
9
+ from sympy.matrices.expressions.inverse import Inverse
10
+ from sympy.matrices.expressions.matexpr import MatrixElement
11
+
12
+ n, m, l, k = symbols('n m l k', integer=True)
13
+ A = MatrixSymbol('A', n, m)
14
+ B = MatrixSymbol('B', m, l)
15
+ C = MatrixSymbol('C', n, n)
16
+ D = MatrixSymbol('D', n, n)
17
+ E = MatrixSymbol('E', m, n)
18
+
19
+
20
+ def test_entry_matrix():
21
+ X = ImmutableMatrix([[1, 2], [3, 4]])
22
+ assert MatPow(X, 0)[0, 0] == 1
23
+ assert MatPow(X, 0)[0, 1] == 0
24
+ assert MatPow(X, 1)[0, 0] == 1
25
+ assert MatPow(X, 1)[0, 1] == 2
26
+ assert MatPow(X, 2)[0, 0] == 7
27
+
28
+
29
+ def test_entry_symbol():
30
+ from sympy.concrete import Sum
31
+ assert MatPow(C, 0)[0, 0] == 1
32
+ assert MatPow(C, 0)[0, 1] == 0
33
+ assert MatPow(C, 1)[0, 0] == C[0, 0]
34
+ assert isinstance(MatPow(C, 2)[0, 0], Sum)
35
+ assert isinstance(MatPow(C, n)[0, 0], MatrixElement)
36
+
37
+
38
+ def test_as_explicit_symbol():
39
+ X = MatrixSymbol('X', 2, 2)
40
+ assert MatPow(X, 0).as_explicit() == ImmutableMatrix(Identity(2))
41
+ assert MatPow(X, 1).as_explicit() == X.as_explicit()
42
+ assert MatPow(X, 2).as_explicit() == (X.as_explicit())**2
43
+ assert MatPow(X, n).as_explicit() == ImmutableMatrix([
44
+ [(X ** n)[0, 0], (X ** n)[0, 1]],
45
+ [(X ** n)[1, 0], (X ** n)[1, 1]],
46
+ ])
47
+
48
+ a = MatrixSymbol("a", 3, 1)
49
+ b = MatrixSymbol("b", 3, 1)
50
+ c = MatrixSymbol("c", 3, 1)
51
+
52
+ expr = (a.T*b)**S.Half
53
+ assert expr.as_explicit() == Matrix([[sqrt(a[0, 0]*b[0, 0] + a[1, 0]*b[1, 0] + a[2, 0]*b[2, 0])]])
54
+
55
+ expr = c*(a.T*b)**S.Half
56
+ m = sqrt(a[0, 0]*b[0, 0] + a[1, 0]*b[1, 0] + a[2, 0]*b[2, 0])
57
+ assert expr.as_explicit() == Matrix([[c[0, 0]*m], [c[1, 0]*m], [c[2, 0]*m]])
58
+
59
+ expr = (a*b.T)**S.Half
60
+ denom = sqrt(a[0, 0]*b[0, 0] + a[1, 0]*b[1, 0] + a[2, 0]*b[2, 0])
61
+ expected = (a*b.T).as_explicit()/denom
62
+ assert expr.as_explicit() == expected
63
+
64
+ expr = X**-1
65
+ det = X[0, 0]*X[1, 1] - X[1, 0]*X[0, 1]
66
+ expected = Matrix([[X[1, 1], -X[0, 1]], [-X[1, 0], X[0, 0]]])/det
67
+ assert expr.as_explicit() == expected
68
+
69
+ expr = X**m
70
+ assert expr.as_explicit() == X.as_explicit()**m
71
+
72
+
73
+ def test_as_explicit_matrix():
74
+ A = ImmutableMatrix([[1, 2], [3, 4]])
75
+ assert MatPow(A, 0).as_explicit() == ImmutableMatrix(Identity(2))
76
+ assert MatPow(A, 1).as_explicit() == A
77
+ assert MatPow(A, 2).as_explicit() == A**2
78
+ assert MatPow(A, -1).as_explicit() == A.inv()
79
+ assert MatPow(A, -2).as_explicit() == (A.inv())**2
80
+ # less expensive than testing on a 2x2
81
+ A = ImmutableMatrix([4])
82
+ assert MatPow(A, S.Half).as_explicit() == A**S.Half
83
+
84
+
85
+ def test_doit_symbol():
86
+ assert MatPow(C, 0).doit() == Identity(n)
87
+ assert MatPow(C, 1).doit() == C
88
+ assert MatPow(C, -1).doit() == C.I
89
+ for r in [2, S.Half, S.Pi, n]:
90
+ assert MatPow(C, r).doit() == MatPow(C, r)
91
+
92
+
93
+ def test_doit_matrix():
94
+ X = ImmutableMatrix([[1, 2], [3, 4]])
95
+ assert MatPow(X, 0).doit() == ImmutableMatrix(Identity(2))
96
+ assert MatPow(X, 1).doit() == X
97
+ assert MatPow(X, 2).doit() == X**2
98
+ assert MatPow(X, -1).doit() == X.inv()
99
+ assert MatPow(X, -2).doit() == (X.inv())**2
100
+ # less expensive than testing on a 2x2
101
+ assert MatPow(ImmutableMatrix([4]), S.Half).doit() == ImmutableMatrix([2])
102
+ X = ImmutableMatrix([[0, 2], [0, 4]]) # det() == 0
103
+ raises(ValueError, lambda: MatPow(X,-1).doit())
104
+ raises(ValueError, lambda: MatPow(X,-2).doit())
105
+
106
+
107
+ def test_nonsquare():
108
+ A = MatrixSymbol('A', 2, 3)
109
+ B = ImmutableMatrix([[1, 2, 3], [4, 5, 6]])
110
+ for r in [-1, 0, 1, 2, S.Half, S.Pi, n]:
111
+ raises(NonSquareMatrixError, lambda: MatPow(A, r))
112
+ raises(NonSquareMatrixError, lambda: MatPow(B, r))
113
+
114
+
115
+ def test_doit_equals_pow(): #17179
116
+ X = ImmutableMatrix ([[1,0],[0,1]])
117
+ assert MatPow(X, n).doit() == X**n == X
118
+
119
+
120
+ def test_doit_nested_MatrixExpr():
121
+ X = ImmutableMatrix([[1, 2], [3, 4]])
122
+ Y = ImmutableMatrix([[2, 3], [4, 5]])
123
+ assert MatPow(MatMul(X, Y), 2).doit() == (X*Y)**2
124
+ assert MatPow(MatAdd(X, Y), 2).doit() == (X + Y)**2
125
+
126
+
127
+ def test_identity_power():
128
+ k = Identity(n)
129
+ assert MatPow(k, 4).doit() == k
130
+ assert MatPow(k, n).doit() == k
131
+ assert MatPow(k, -3).doit() == k
132
+ assert MatPow(k, 0).doit() == k
133
+ l = Identity(3)
134
+ assert MatPow(l, n).doit() == l
135
+ assert MatPow(l, -1).doit() == l
136
+ assert MatPow(l, 0).doit() == l
137
+
138
+
139
+ def test_zero_power():
140
+ z1 = ZeroMatrix(n, n)
141
+ assert MatPow(z1, 3).doit() == z1
142
+ raises(ValueError, lambda:MatPow(z1, -1).doit())
143
+ assert MatPow(z1, 0).doit() == Identity(n)
144
+ assert MatPow(z1, n).doit() == z1
145
+ raises(ValueError, lambda:MatPow(z1, -2).doit())
146
+ z2 = ZeroMatrix(4, 4)
147
+ assert MatPow(z2, n).doit() == z2
148
+ raises(ValueError, lambda:MatPow(z2, -3).doit())
149
+ assert MatPow(z2, 2).doit() == z2
150
+ assert MatPow(z2, 0).doit() == Identity(4)
151
+ raises(ValueError, lambda:MatPow(z2, -1).doit())
152
+
153
+
154
+ def test_OneMatrix_power():
155
+ o = OneMatrix(3, 3)
156
+ assert o ** 0 == Identity(3)
157
+ assert o ** 1 == o
158
+ assert o * o == o ** 2 == 3 * o
159
+ assert o * o * o == o ** 3 == 9 * o
160
+
161
+ o = OneMatrix(n, n)
162
+ assert o * o == o ** 2 == n * o
163
+ # powsimp necessary as n ** (n - 2) * n does not produce n ** (n - 1)
164
+ assert powsimp(o ** (n - 1) * o) == o ** n == n ** (n - 1) * o
165
+
166
+
167
+ def test_transpose_power():
168
+ from sympy.matrices.expressions.transpose import Transpose as TP
169
+
170
+ assert (C*D).T**5 == ((C*D)**5).T == (D.T * C.T)**5
171
+ assert ((C*D).T**5).T == (C*D)**5
172
+
173
+ assert (C.T.I.T)**7 == C**-7
174
+ assert (C.T**l).T**k == C**(l*k)
175
+
176
+ assert ((E.T * A.T)**5).T == (A*E)**5
177
+ assert ((A*E).T**5).T**7 == (A*E)**35
178
+ assert TP(TP(C**2 * D**3)**5).doit() == (C**2 * D**3)**5
179
+
180
+ assert ((D*C)**-5).T**-5 == ((D*C)**25).T
181
+ assert (((D*C)**l).T**k).T == (D*C)**(l*k)
182
+
183
+
184
+ def test_Inverse():
185
+ assert Inverse(MatPow(C, 0)).doit() == Identity(n)
186
+ assert Inverse(MatPow(C, 1)).doit() == Inverse(C)
187
+ assert Inverse(MatPow(C, 2)).doit() == MatPow(C, -2)
188
+ assert Inverse(MatPow(C, -1)).doit() == C
189
+
190
+ assert MatPow(Inverse(C), 0).doit() == Identity(n)
191
+ assert MatPow(Inverse(C), 1).doit() == Inverse(C)
192
+ assert MatPow(Inverse(C), 2).doit() == MatPow(C, -2)
193
+ assert MatPow(Inverse(C), -1).doit() == C
194
+
195
+
196
+ def test_combine_powers():
197
+ assert (C ** 1) ** 1 == C
198
+ assert (C ** 2) ** 3 == MatPow(C, 6)
199
+ assert (C ** -2) ** -3 == MatPow(C, 6)
200
+ assert (C ** -1) ** -1 == C
201
+ assert (((C ** 2) ** 3) ** 4) ** 5 == MatPow(C, 120)
202
+ assert (C ** n) ** n == C ** (n ** 2)
203
+
204
+
205
+ def test_unchanged():
206
+ assert unchanged(MatPow, C, 0)
207
+ assert unchanged(MatPow, C, 1)
208
+ assert unchanged(MatPow, Inverse(C), -1)
209
+ assert unchanged(Inverse, MatPow(C, -1), -1)
210
+ assert unchanged(MatPow, MatPow(C, -1), -1)
211
+ assert unchanged(MatPow, MatPow(C, 1), 1)
212
+
213
+
214
+ def test_no_exponentiation():
215
+ # if this passes, Pow.as_numer_denom should recognize
216
+ # MatAdd as exponent
217
+ raises(NotImplementedError, lambda: 3**(-2*C))
miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/matrices/expressions/tests/test_permutation.py ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.combinatorics import Permutation
2
+ from sympy.core.expr import unchanged
3
+ from sympy.matrices import Matrix
4
+ from sympy.matrices.expressions import \
5
+ MatMul, BlockDiagMatrix, Determinant, Inverse
6
+ from sympy.matrices.expressions.matexpr import MatrixSymbol
7
+ from sympy.matrices.expressions.special import ZeroMatrix, OneMatrix, Identity
8
+ from sympy.matrices.expressions.permutation import \
9
+ MatrixPermute, PermutationMatrix
10
+ from sympy.testing.pytest import raises
11
+ from sympy.core.symbol import Symbol
12
+
13
+
14
+ def test_PermutationMatrix_basic():
15
+ p = Permutation([1, 0])
16
+ assert unchanged(PermutationMatrix, p)
17
+ raises(ValueError, lambda: PermutationMatrix((0, 1, 2)))
18
+ assert PermutationMatrix(p).as_explicit() == Matrix([[0, 1], [1, 0]])
19
+ assert isinstance(PermutationMatrix(p)*MatrixSymbol('A', 2, 2), MatMul)
20
+
21
+
22
+ def test_PermutationMatrix_matmul():
23
+ p = Permutation([1, 2, 0])
24
+ P = PermutationMatrix(p)
25
+ M = Matrix([[0, 1, 2], [3, 4, 5], [6, 7, 8]])
26
+ assert (P*M).as_explicit() == P.as_explicit()*M
27
+ assert (M*P).as_explicit() == M*P.as_explicit()
28
+
29
+ P1 = PermutationMatrix(Permutation([1, 2, 0]))
30
+ P2 = PermutationMatrix(Permutation([2, 1, 0]))
31
+ P3 = PermutationMatrix(Permutation([1, 0, 2]))
32
+ assert P1*P2 == P3
33
+
34
+
35
+ def test_PermutationMatrix_matpow():
36
+ p1 = Permutation([1, 2, 0])
37
+ P1 = PermutationMatrix(p1)
38
+ p2 = Permutation([2, 0, 1])
39
+ P2 = PermutationMatrix(p2)
40
+ assert P1**2 == P2
41
+ assert P1**3 == Identity(3)
42
+
43
+
44
+ def test_PermutationMatrix_identity():
45
+ p = Permutation([0, 1])
46
+ assert PermutationMatrix(p).is_Identity
47
+
48
+ p = Permutation([1, 0])
49
+ assert not PermutationMatrix(p).is_Identity
50
+
51
+
52
+ def test_PermutationMatrix_determinant():
53
+ P = PermutationMatrix(Permutation([0, 1, 2]))
54
+ assert Determinant(P).doit() == 1
55
+ P = PermutationMatrix(Permutation([0, 2, 1]))
56
+ assert Determinant(P).doit() == -1
57
+ P = PermutationMatrix(Permutation([2, 0, 1]))
58
+ assert Determinant(P).doit() == 1
59
+
60
+
61
+ def test_PermutationMatrix_inverse():
62
+ P = PermutationMatrix(Permutation(0, 1, 2))
63
+ assert Inverse(P).doit() == PermutationMatrix(Permutation(0, 2, 1))
64
+
65
+
66
+ def test_PermutationMatrix_rewrite_BlockDiagMatrix():
67
+ P = PermutationMatrix(Permutation([0, 1, 2, 3, 4, 5]))
68
+ P0 = PermutationMatrix(Permutation([0]))
69
+ assert P.rewrite(BlockDiagMatrix) == \
70
+ BlockDiagMatrix(P0, P0, P0, P0, P0, P0)
71
+
72
+ P = PermutationMatrix(Permutation([0, 1, 3, 2, 4, 5]))
73
+ P10 = PermutationMatrix(Permutation(0, 1))
74
+ assert P.rewrite(BlockDiagMatrix) == \
75
+ BlockDiagMatrix(P0, P0, P10, P0, P0)
76
+
77
+ P = PermutationMatrix(Permutation([1, 0, 3, 2, 5, 4]))
78
+ assert P.rewrite(BlockDiagMatrix) == \
79
+ BlockDiagMatrix(P10, P10, P10)
80
+
81
+ P = PermutationMatrix(Permutation([0, 4, 3, 2, 1, 5]))
82
+ P3210 = PermutationMatrix(Permutation([3, 2, 1, 0]))
83
+ assert P.rewrite(BlockDiagMatrix) == \
84
+ BlockDiagMatrix(P0, P3210, P0)
85
+
86
+ P = PermutationMatrix(Permutation([0, 4, 2, 3, 1, 5]))
87
+ P3120 = PermutationMatrix(Permutation([3, 1, 2, 0]))
88
+ assert P.rewrite(BlockDiagMatrix) == \
89
+ BlockDiagMatrix(P0, P3120, P0)
90
+
91
+ P = PermutationMatrix(Permutation(0, 3)(1, 4)(2, 5))
92
+ assert P.rewrite(BlockDiagMatrix) == BlockDiagMatrix(P)
93
+
94
+
95
+ def test_MartrixPermute_basic():
96
+ p = Permutation(0, 1)
97
+ P = PermutationMatrix(p)
98
+ A = MatrixSymbol('A', 2, 2)
99
+
100
+ raises(ValueError, lambda: MatrixPermute(Symbol('x'), p))
101
+ raises(ValueError, lambda: MatrixPermute(A, Symbol('x')))
102
+
103
+ assert MatrixPermute(A, P) == MatrixPermute(A, p)
104
+ raises(ValueError, lambda: MatrixPermute(A, p, 2))
105
+
106
+ pp = Permutation(0, 1, size=3)
107
+ assert MatrixPermute(A, pp) == MatrixPermute(A, p)
108
+ pp = Permutation(0, 1, 2)
109
+ raises(ValueError, lambda: MatrixPermute(A, pp))
110
+
111
+
112
+ def test_MatrixPermute_shape():
113
+ p = Permutation(0, 1)
114
+ A = MatrixSymbol('A', 2, 3)
115
+ assert MatrixPermute(A, p).shape == (2, 3)
116
+
117
+
118
+ def test_MatrixPermute_explicit():
119
+ p = Permutation(0, 1, 2)
120
+ A = MatrixSymbol('A', 3, 3)
121
+ AA = A.as_explicit()
122
+ assert MatrixPermute(A, p, 0).as_explicit() == \
123
+ AA.permute(p, orientation='rows')
124
+ assert MatrixPermute(A, p, 1).as_explicit() == \
125
+ AA.permute(p, orientation='cols')
126
+
127
+
128
+ def test_MatrixPermute_rewrite_MatMul():
129
+ p = Permutation(0, 1, 2)
130
+ A = MatrixSymbol('A', 3, 3)
131
+
132
+ assert MatrixPermute(A, p, 0).rewrite(MatMul).as_explicit() == \
133
+ MatrixPermute(A, p, 0).as_explicit()
134
+ assert MatrixPermute(A, p, 1).rewrite(MatMul).as_explicit() == \
135
+ MatrixPermute(A, p, 1).as_explicit()
136
+
137
+
138
+ def test_MatrixPermute_doit():
139
+ p = Permutation(0, 1, 2)
140
+ A = MatrixSymbol('A', 3, 3)
141
+ assert MatrixPermute(A, p).doit() == MatrixPermute(A, p)
142
+
143
+ p = Permutation(0, size=3)
144
+ A = MatrixSymbol('A', 3, 3)
145
+ assert MatrixPermute(A, p).doit().as_explicit() == \
146
+ MatrixPermute(A, p).as_explicit()
147
+
148
+ p = Permutation(0, 1, 2)
149
+ A = Identity(3)
150
+ assert MatrixPermute(A, p, 0).doit().as_explicit() == \
151
+ MatrixPermute(A, p, 0).as_explicit()
152
+ assert MatrixPermute(A, p, 1).doit().as_explicit() == \
153
+ MatrixPermute(A, p, 1).as_explicit()
154
+
155
+ A = ZeroMatrix(3, 3)
156
+ assert MatrixPermute(A, p).doit() == A
157
+ A = OneMatrix(3, 3)
158
+ assert MatrixPermute(A, p).doit() == A
159
+
160
+ A = MatrixSymbol('A', 4, 4)
161
+ p1 = Permutation(0, 1, 2, 3)
162
+ p2 = Permutation(0, 2, 3, 1)
163
+ expr = MatrixPermute(MatrixPermute(A, p1, 0), p2, 0)
164
+ assert expr.as_explicit() == expr.doit().as_explicit()
165
+ expr = MatrixPermute(MatrixPermute(A, p1, 1), p2, 1)
166
+ assert expr.as_explicit() == expr.doit().as_explicit()
miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/matrices/expressions/tests/test_sets.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.singleton import S
2
+ from sympy.core.symbol import symbols
3
+ from sympy.matrices import Matrix
4
+ from sympy.matrices.expressions.matexpr import MatrixSymbol
5
+ from sympy.matrices.expressions.sets import MatrixSet
6
+ from sympy.matrices.expressions.special import ZeroMatrix
7
+ from sympy.testing.pytest import raises
8
+ from sympy.sets.sets import SetKind
9
+ from sympy.matrices.kind import MatrixKind
10
+ from sympy.core.kind import NumberKind
11
+
12
+
13
+ def test_MatrixSet():
14
+ n, m = symbols('n m', integer=True)
15
+ A = MatrixSymbol('A', n, m)
16
+ C = MatrixSymbol('C', n, n)
17
+
18
+ M = MatrixSet(2, 2, set=S.Reals)
19
+ assert M.shape == (2, 2)
20
+ assert M.set == S.Reals
21
+ X = Matrix([[1, 2], [3, 4]])
22
+ assert X in M
23
+ X = ZeroMatrix(2, 2)
24
+ assert X in M
25
+ raises(TypeError, lambda: A in M)
26
+ raises(TypeError, lambda: 1 in M)
27
+ M = MatrixSet(n, m, set=S.Reals)
28
+ assert A in M
29
+ raises(TypeError, lambda: C in M)
30
+ raises(TypeError, lambda: X in M)
31
+ M = MatrixSet(2, 2, set={1, 2, 3})
32
+ X = Matrix([[1, 2], [3, 4]])
33
+ Y = Matrix([[1, 2]])
34
+ assert (X in M) == S.false
35
+ assert (Y in M) == S.false
36
+ raises(ValueError, lambda: MatrixSet(2, -2, S.Reals))
37
+ raises(ValueError, lambda: MatrixSet(2.4, -1, S.Reals))
38
+ raises(TypeError, lambda: MatrixSet(2, 2, (1, 2, 3)))
39
+
40
+
41
+ def test_SetKind_MatrixSet():
42
+ assert MatrixSet(2, 2, set=S.Reals).kind is SetKind(MatrixKind(NumberKind))
miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/matrices/expressions/tests/test_slice.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.matrices.expressions.slice import MatrixSlice
2
+ from sympy.matrices.expressions import MatrixSymbol
3
+ from sympy.abc import a, b, c, d, k, l, m, n
4
+ from sympy.testing.pytest import raises, XFAIL
5
+ from sympy.functions.elementary.integers import floor
6
+ from sympy.assumptions import assuming, Q
7
+
8
+
9
+ X = MatrixSymbol('X', n, m)
10
+ Y = MatrixSymbol('Y', m, k)
11
+
12
+ def test_shape():
13
+ B = MatrixSlice(X, (a, b), (c, d))
14
+ assert B.shape == (b - a, d - c)
15
+
16
+ def test_entry():
17
+ B = MatrixSlice(X, (a, b), (c, d))
18
+ assert B[0,0] == X[a, c]
19
+ assert B[k,l] == X[a+k, c+l]
20
+ raises(IndexError, lambda : MatrixSlice(X, 1, (2, 5))[1, 0])
21
+
22
+ assert X[1::2, :][1, 3] == X[1+2, 3]
23
+ assert X[:, 1::2][3, 1] == X[3, 1+2]
24
+
25
+ def test_on_diag():
26
+ assert not MatrixSlice(X, (a, b), (c, d)).on_diag
27
+ assert MatrixSlice(X, (a, b), (a, b)).on_diag
28
+
29
+ def test_inputs():
30
+ assert MatrixSlice(X, 1, (2, 5)) == MatrixSlice(X, (1, 2), (2, 5))
31
+ assert MatrixSlice(X, 1, (2, 5)).shape == (1, 3)
32
+
33
+ def test_slicing():
34
+ assert X[1:5, 2:4] == MatrixSlice(X, (1, 5), (2, 4))
35
+ assert X[1, 2:4] == MatrixSlice(X, 1, (2, 4))
36
+ assert X[1:5, :].shape == (4, X.shape[1])
37
+ assert X[:, 1:5].shape == (X.shape[0], 4)
38
+
39
+ assert X[::2, ::2].shape == (floor(n/2), floor(m/2))
40
+ assert X[2, :] == MatrixSlice(X, 2, (0, m))
41
+ assert X[k, :] == MatrixSlice(X, k, (0, m))
42
+
43
+ def test_exceptions():
44
+ X = MatrixSymbol('x', 10, 20)
45
+ raises(IndexError, lambda: X[0:12, 2])
46
+ raises(IndexError, lambda: X[0:9, 22])
47
+ raises(IndexError, lambda: X[-1:5, 2])
48
+
49
+ @XFAIL
50
+ def test_symmetry():
51
+ X = MatrixSymbol('x', 10, 10)
52
+ Y = X[:5, 5:]
53
+ with assuming(Q.symmetric(X)):
54
+ assert Y.T == X[5:, :5]
55
+
56
+ def test_slice_of_slice():
57
+ X = MatrixSymbol('x', 10, 10)
58
+ assert X[2, :][:, 3][0, 0] == X[2, 3]
59
+ assert X[:5, :5][:4, :4] == X[:4, :4]
60
+ assert X[1:5, 2:6][1:3, 2] == X[2:4, 4]
61
+ assert X[1:9:2, 2:6][1:3, 2] == X[3:7:2, 4]
62
+
63
+ def test_negative_index():
64
+ X = MatrixSymbol('x', 10, 10)
65
+ assert X[-1, :] == X[9, :]
miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/matrices/expressions/tests/test_special.py ADDED
@@ -0,0 +1,228 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.add import Add
2
+ from sympy.core.expr import unchanged
3
+ from sympy.core.mul import Mul
4
+ from sympy.core.symbol import symbols
5
+ from sympy.core.relational import Eq
6
+ from sympy.concrete.summations import Sum
7
+ from sympy.functions.elementary.complexes import im, re
8
+ from sympy.functions.elementary.piecewise import Piecewise
9
+ from sympy.matrices.immutable import ImmutableDenseMatrix
10
+ from sympy.matrices.expressions.matexpr import MatrixSymbol
11
+ from sympy.matrices.expressions.matadd import MatAdd
12
+ from sympy.matrices.expressions.special import (
13
+ ZeroMatrix, GenericZeroMatrix, Identity, GenericIdentity, OneMatrix)
14
+ from sympy.matrices.expressions.matmul import MatMul
15
+ from sympy.testing.pytest import raises
16
+
17
+
18
+ def test_zero_matrix_creation():
19
+ assert unchanged(ZeroMatrix, 2, 2)
20
+ assert unchanged(ZeroMatrix, 0, 0)
21
+ raises(ValueError, lambda: ZeroMatrix(-1, 2))
22
+ raises(ValueError, lambda: ZeroMatrix(2.0, 2))
23
+ raises(ValueError, lambda: ZeroMatrix(2j, 2))
24
+ raises(ValueError, lambda: ZeroMatrix(2, -1))
25
+ raises(ValueError, lambda: ZeroMatrix(2, 2.0))
26
+ raises(ValueError, lambda: ZeroMatrix(2, 2j))
27
+
28
+ n = symbols('n')
29
+ assert unchanged(ZeroMatrix, n, n)
30
+ n = symbols('n', integer=False)
31
+ raises(ValueError, lambda: ZeroMatrix(n, n))
32
+ n = symbols('n', negative=True)
33
+ raises(ValueError, lambda: ZeroMatrix(n, n))
34
+
35
+
36
+ def test_generic_zero_matrix():
37
+ z = GenericZeroMatrix()
38
+ n = symbols('n', integer=True)
39
+ A = MatrixSymbol("A", n, n)
40
+
41
+ assert z == z
42
+ assert z != A
43
+ assert A != z
44
+
45
+ assert z.is_ZeroMatrix
46
+
47
+ raises(TypeError, lambda: z.shape)
48
+ raises(TypeError, lambda: z.rows)
49
+ raises(TypeError, lambda: z.cols)
50
+
51
+ assert MatAdd() == z
52
+ assert MatAdd(z, A) == MatAdd(A)
53
+ # Make sure it is hashable
54
+ hash(z)
55
+
56
+
57
+ def test_identity_matrix_creation():
58
+ assert Identity(2)
59
+ assert Identity(0)
60
+ raises(ValueError, lambda: Identity(-1))
61
+ raises(ValueError, lambda: Identity(2.0))
62
+ raises(ValueError, lambda: Identity(2j))
63
+
64
+ n = symbols('n')
65
+ assert Identity(n)
66
+ n = symbols('n', integer=False)
67
+ raises(ValueError, lambda: Identity(n))
68
+ n = symbols('n', negative=True)
69
+ raises(ValueError, lambda: Identity(n))
70
+
71
+
72
+ def test_generic_identity():
73
+ I = GenericIdentity()
74
+ n = symbols('n', integer=True)
75
+ A = MatrixSymbol("A", n, n)
76
+
77
+ assert I == I
78
+ assert I != A
79
+ assert A != I
80
+
81
+ assert I.is_Identity
82
+ assert I**-1 == I
83
+
84
+ raises(TypeError, lambda: I.shape)
85
+ raises(TypeError, lambda: I.rows)
86
+ raises(TypeError, lambda: I.cols)
87
+
88
+ assert MatMul() == I
89
+ assert MatMul(I, A) == MatMul(A)
90
+ # Make sure it is hashable
91
+ hash(I)
92
+
93
+
94
+ def test_one_matrix_creation():
95
+ assert OneMatrix(2, 2)
96
+ assert OneMatrix(0, 0)
97
+ assert Eq(OneMatrix(1, 1), Identity(1))
98
+ raises(ValueError, lambda: OneMatrix(-1, 2))
99
+ raises(ValueError, lambda: OneMatrix(2.0, 2))
100
+ raises(ValueError, lambda: OneMatrix(2j, 2))
101
+ raises(ValueError, lambda: OneMatrix(2, -1))
102
+ raises(ValueError, lambda: OneMatrix(2, 2.0))
103
+ raises(ValueError, lambda: OneMatrix(2, 2j))
104
+
105
+ n = symbols('n')
106
+ assert OneMatrix(n, n)
107
+ n = symbols('n', integer=False)
108
+ raises(ValueError, lambda: OneMatrix(n, n))
109
+ n = symbols('n', negative=True)
110
+ raises(ValueError, lambda: OneMatrix(n, n))
111
+
112
+
113
+ def test_ZeroMatrix():
114
+ n, m = symbols('n m', integer=True)
115
+ A = MatrixSymbol('A', n, m)
116
+ Z = ZeroMatrix(n, m)
117
+
118
+ assert A + Z == A
119
+ assert A*Z.T == ZeroMatrix(n, n)
120
+ assert Z*A.T == ZeroMatrix(n, n)
121
+ assert A - A == ZeroMatrix(*A.shape)
122
+
123
+ assert Z
124
+
125
+ assert Z.transpose() == ZeroMatrix(m, n)
126
+ assert Z.conjugate() == Z
127
+ assert Z.adjoint() == ZeroMatrix(m, n)
128
+ assert re(Z) == Z
129
+ assert im(Z) == Z
130
+
131
+ assert ZeroMatrix(n, n)**0 == Identity(n)
132
+ assert ZeroMatrix(3, 3).as_explicit() == ImmutableDenseMatrix.zeros(3, 3)
133
+
134
+
135
+ def test_ZeroMatrix_doit():
136
+ n = symbols('n', integer=True)
137
+ Znn = ZeroMatrix(Add(n, n, evaluate=False), n)
138
+ assert isinstance(Znn.rows, Add)
139
+ assert Znn.doit() == ZeroMatrix(2*n, n)
140
+ assert isinstance(Znn.doit().rows, Mul)
141
+
142
+
143
+ def test_OneMatrix():
144
+ n, m = symbols('n m', integer=True)
145
+ A = MatrixSymbol('A', n, m)
146
+ U = OneMatrix(n, m)
147
+
148
+ assert U.shape == (n, m)
149
+ assert isinstance(A + U, Add)
150
+ assert U.transpose() == OneMatrix(m, n)
151
+ assert U.conjugate() == U
152
+ assert U.adjoint() == OneMatrix(m, n)
153
+ assert re(U) == U
154
+ assert im(U) == ZeroMatrix(n, m)
155
+
156
+ assert OneMatrix(n, n) ** 0 == Identity(n)
157
+
158
+ U = OneMatrix(n, n)
159
+ assert U[1, 2] == 1
160
+
161
+ U = OneMatrix(2, 3)
162
+ assert U.as_explicit() == ImmutableDenseMatrix.ones(2, 3)
163
+
164
+
165
+ def test_OneMatrix_doit():
166
+ n = symbols('n', integer=True)
167
+ Unn = OneMatrix(Add(n, n, evaluate=False), n)
168
+ assert isinstance(Unn.rows, Add)
169
+ assert Unn.doit() == OneMatrix(2 * n, n)
170
+ assert isinstance(Unn.doit().rows, Mul)
171
+
172
+
173
+ def test_OneMatrix_mul():
174
+ n, m, k = symbols('n m k', integer=True)
175
+ w = MatrixSymbol('w', n, 1)
176
+ assert OneMatrix(n, m) * OneMatrix(m, k) == OneMatrix(n, k) * m
177
+ assert w * OneMatrix(1, 1) == w
178
+ assert OneMatrix(1, 1) * w.T == w.T
179
+
180
+
181
+ def test_Identity():
182
+ n, m = symbols('n m', integer=True)
183
+ A = MatrixSymbol('A', n, m)
184
+ i, j = symbols('i j')
185
+
186
+ In = Identity(n)
187
+ Im = Identity(m)
188
+
189
+ assert A*Im == A
190
+ assert In*A == A
191
+
192
+ assert In.transpose() == In
193
+ assert In.inverse() == In
194
+ assert In.conjugate() == In
195
+ assert In.adjoint() == In
196
+ assert re(In) == In
197
+ assert im(In) == ZeroMatrix(n, n)
198
+
199
+ assert In[i, j] != 0
200
+ assert Sum(In[i, j], (i, 0, n-1), (j, 0, n-1)).subs(n,3).doit() == 3
201
+ assert Sum(Sum(In[i, j], (i, 0, n-1)), (j, 0, n-1)).subs(n,3).doit() == 3
202
+
203
+ # If range exceeds the limit `(0, n-1)`, do not remove `Piecewise`:
204
+ expr = Sum(In[i, j], (i, 0, n-1))
205
+ assert expr.doit() == 1
206
+ expr = Sum(In[i, j], (i, 0, n-2))
207
+ assert expr.doit().dummy_eq(
208
+ Piecewise(
209
+ (1, (j >= 0) & (j <= n-2)),
210
+ (0, True)
211
+ )
212
+ )
213
+ expr = Sum(In[i, j], (i, 1, n-1))
214
+ assert expr.doit().dummy_eq(
215
+ Piecewise(
216
+ (1, (j >= 1) & (j <= n-1)),
217
+ (0, True)
218
+ )
219
+ )
220
+ assert Identity(3).as_explicit() == ImmutableDenseMatrix.eye(3)
221
+
222
+
223
+ def test_Identity_doit():
224
+ n = symbols('n', integer=True)
225
+ Inn = Identity(Add(n, n, evaluate=False))
226
+ assert isinstance(Inn.rows, Add)
227
+ assert Inn.doit() == Identity(2*n)
228
+ assert isinstance(Inn.doit().rows, Mul)
miniconda3/envs/ladir/lib/python3.10/site-packages/sympy/matrices/expressions/tests/test_trace.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core import Lambda, S, symbols
2
+ from sympy.concrete import Sum
3
+ from sympy.functions import adjoint, conjugate, transpose
4
+ from sympy.matrices import eye, Matrix, ShapeError, ImmutableMatrix
5
+ from sympy.matrices.expressions import (
6
+ Adjoint, Identity, FunctionMatrix, MatrixExpr, MatrixSymbol, Trace,
7
+ ZeroMatrix, trace, MatPow, MatAdd, MatMul
8
+ )
9
+ from sympy.matrices.expressions.special import OneMatrix
10
+ from sympy.testing.pytest import raises
11
+ from sympy.abc import i
12
+
13
+
14
+ n = symbols('n', integer=True)
15
+ A = MatrixSymbol('A', n, n)
16
+ B = MatrixSymbol('B', n, n)
17
+ C = MatrixSymbol('C', 3, 4)
18
+
19
+
20
+ def test_Trace():
21
+ assert isinstance(Trace(A), Trace)
22
+ assert not isinstance(Trace(A), MatrixExpr)
23
+ raises(ShapeError, lambda: Trace(C))
24
+ assert trace(eye(3)) == 3
25
+ assert trace(Matrix(3, 3, [1, 2, 3, 4, 5, 6, 7, 8, 9])) == 15
26
+
27
+ assert adjoint(Trace(A)) == trace(Adjoint(A))
28
+ assert conjugate(Trace(A)) == trace(Adjoint(A))
29
+ assert transpose(Trace(A)) == Trace(A)
30
+
31
+ _ = A / Trace(A) # Make sure this is possible
32
+
33
+ # Some easy simplifications
34
+ assert trace(Identity(5)) == 5
35
+ assert trace(ZeroMatrix(5, 5)) == 0
36
+ assert trace(OneMatrix(1, 1)) == 1
37
+ assert trace(OneMatrix(2, 2)) == 2
38
+ assert trace(OneMatrix(n, n)) == n
39
+ assert trace(2*A*B) == 2*Trace(A*B)
40
+ assert trace(A.T) == trace(A)
41
+
42
+ i, j = symbols('i j')
43
+ F = FunctionMatrix(3, 3, Lambda((i, j), i + j))
44
+ assert trace(F) == (0 + 0) + (1 + 1) + (2 + 2)
45
+
46
+ raises(TypeError, lambda: Trace(S.One))
47
+
48
+ assert Trace(A).arg is A
49
+
50
+ assert str(trace(A)) == str(Trace(A).doit())
51
+
52
+ assert Trace(A).is_commutative is True
53
+
54
+ def test_Trace_A_plus_B():
55
+ assert trace(A + B) == Trace(A) + Trace(B)
56
+ assert Trace(A + B).arg == MatAdd(A, B)
57
+ assert Trace(A + B).doit() == Trace(A) + Trace(B)
58
+
59
+
60
+ def test_Trace_MatAdd_doit():
61
+ # See issue #9028
62
+ X = ImmutableMatrix([[1, 2, 3]]*3)
63
+ Y = MatrixSymbol('Y', 3, 3)
64
+ q = MatAdd(X, 2*X, Y, -3*Y)
65
+ assert Trace(q).arg == q
66
+ assert Trace(q).doit() == 18 - 2*Trace(Y)
67
+
68
+
69
+ def test_Trace_MatPow_doit():
70
+ X = Matrix([[1, 2], [3, 4]])
71
+ assert Trace(X).doit() == 5
72
+ q = MatPow(X, 2)
73
+ assert Trace(q).arg == q
74
+ assert Trace(q).doit() == 29
75
+
76
+
77
+ def test_Trace_MutableMatrix_plus():
78
+ # See issue #9043
79
+ X = Matrix([[1, 2], [3, 4]])
80
+ assert Trace(X) + Trace(X) == 2*Trace(X)
81
+
82
+
83
+ def test_Trace_doit_deep_False():
84
+ X = Matrix([[1, 2], [3, 4]])
85
+ q = MatPow(X, 2)
86
+ assert Trace(q).doit(deep=False).arg == q
87
+ q = MatAdd(X, 2*X)
88
+ assert Trace(q).doit(deep=False).arg == q
89
+ q = MatMul(X, 2*X)
90
+ assert Trace(q).doit(deep=False).arg == q
91
+
92
+
93
+ def test_trace_constant_factor():
94
+ # Issue 9052: gave 2*Trace(MatMul(A)) instead of 2*Trace(A)
95
+ assert trace(2*A) == 2*Trace(A)
96
+ X = ImmutableMatrix([[1, 2], [3, 4]])
97
+ assert trace(MatMul(2, X)) == 10
98
+
99
+
100
+ def test_trace_rewrite():
101
+ assert trace(A).rewrite(Sum) == Sum(A[i, i], (i, 0, n - 1))
102
+ assert trace(eye(3)).rewrite(Sum) == 3
103
+
104
+
105
+ def test_trace_normalize():
106
+ assert Trace(B*A) != Trace(A*B)
107
+ assert Trace(B*A)._normalize() == Trace(A*B)
108
+ assert Trace(B*A.T)._normalize() == Trace(A*B.T)
109
+
110
+
111
+ def test_trace_as_explicit():
112
+ raises(ValueError, lambda: Trace(A).as_explicit())
113
+
114
+ X = MatrixSymbol("X", 3, 3)
115
+ assert Trace(X).as_explicit() == X[0, 0] + X[1, 1] + X[2, 2]
116
+ assert Trace(eye(3)).as_explicit() == 3