ZTWHHH commited on
Commit
be53f98
·
verified ·
1 Parent(s): b153b95

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. .gitattributes +1 -0
  2. openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/_transformer_encoder_layer_fwd_cuda_dispatch.h +23 -0
  3. openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/avg_pool3d_backward_meta.h +27 -0
  4. openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/geqrf_ops.h +39 -0
  5. openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/is_distributed_native.h +21 -0
  6. openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/polygamma_native.h +24 -0
  7. openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/replication_pad2d_ops.h +39 -0
  8. openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/rnn_relu_ops.h +39 -0
  9. openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/special_i1_cuda_dispatch.h +25 -0
  10. openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/triu_compositeexplicitautogradnonfunctional_dispatch.h +24 -0
  11. phi4/lib/python3.10/site-packages/sympy/matrices/__init__.py +72 -0
  12. phi4/lib/python3.10/site-packages/sympy/matrices/__pycache__/common.cpython-310.pyc +0 -0
  13. phi4/lib/python3.10/site-packages/sympy/matrices/__pycache__/decompositions.cpython-310.pyc +0 -0
  14. phi4/lib/python3.10/site-packages/sympy/matrices/__pycache__/dense.cpython-310.pyc +0 -0
  15. phi4/lib/python3.10/site-packages/sympy/matrices/__pycache__/determinant.cpython-310.pyc +0 -0
  16. phi4/lib/python3.10/site-packages/sympy/matrices/__pycache__/eigen.cpython-310.pyc +0 -0
  17. phi4/lib/python3.10/site-packages/sympy/matrices/__pycache__/exceptions.cpython-310.pyc +0 -0
  18. phi4/lib/python3.10/site-packages/sympy/matrices/__pycache__/graph.cpython-310.pyc +0 -0
  19. phi4/lib/python3.10/site-packages/sympy/matrices/__pycache__/immutable.cpython-310.pyc +0 -0
  20. phi4/lib/python3.10/site-packages/sympy/matrices/__pycache__/inverse.cpython-310.pyc +0 -0
  21. phi4/lib/python3.10/site-packages/sympy/matrices/__pycache__/kind.cpython-310.pyc +0 -0
  22. phi4/lib/python3.10/site-packages/sympy/matrices/__pycache__/normalforms.cpython-310.pyc +0 -0
  23. phi4/lib/python3.10/site-packages/sympy/matrices/__pycache__/reductions.cpython-310.pyc +0 -0
  24. phi4/lib/python3.10/site-packages/sympy/matrices/__pycache__/repmatrix.cpython-310.pyc +0 -0
  25. phi4/lib/python3.10/site-packages/sympy/matrices/__pycache__/solvers.cpython-310.pyc +0 -0
  26. phi4/lib/python3.10/site-packages/sympy/matrices/__pycache__/sparse.cpython-310.pyc +0 -0
  27. phi4/lib/python3.10/site-packages/sympy/matrices/__pycache__/sparsetools.cpython-310.pyc +0 -0
  28. phi4/lib/python3.10/site-packages/sympy/matrices/__pycache__/subspaces.cpython-310.pyc +0 -0
  29. phi4/lib/python3.10/site-packages/sympy/matrices/__pycache__/utilities.cpython-310.pyc +0 -0
  30. phi4/lib/python3.10/site-packages/sympy/matrices/common.py +3263 -0
  31. phi4/lib/python3.10/site-packages/sympy/matrices/dense.py +1093 -0
  32. phi4/lib/python3.10/site-packages/sympy/matrices/determinant.py +1021 -0
  33. phi4/lib/python3.10/site-packages/sympy/matrices/exceptions.py +26 -0
  34. phi4/lib/python3.10/site-packages/sympy/matrices/expressions/transpose.py +103 -0
  35. phi4/lib/python3.10/site-packages/sympy/matrices/graph.py +279 -0
  36. phi4/lib/python3.10/site-packages/sympy/matrices/immutable.py +196 -0
  37. phi4/lib/python3.10/site-packages/sympy/matrices/inverse.py +524 -0
  38. phi4/lib/python3.10/site-packages/sympy/matrices/kind.py +97 -0
  39. phi4/lib/python3.10/site-packages/sympy/matrices/matrices.py +687 -0
  40. phi4/lib/python3.10/site-packages/sympy/matrices/matrixbase.py +0 -0
  41. phi4/lib/python3.10/site-packages/sympy/matrices/normalforms.py +127 -0
  42. phi4/lib/python3.10/site-packages/sympy/matrices/reductions.py +387 -0
  43. phi4/lib/python3.10/site-packages/sympy/matrices/repmatrix.py +1025 -0
  44. phi4/lib/python3.10/site-packages/sympy/matrices/solvers.py +942 -0
  45. phi4/lib/python3.10/site-packages/sympy/matrices/sparse.py +473 -0
  46. phi4/lib/python3.10/site-packages/sympy/matrices/subspaces.py +174 -0
  47. phi4/lib/python3.10/site-packages/sympy/matrices/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  48. phi4/lib/python3.10/site-packages/sympy/matrices/tests/__pycache__/test_commonmatrix.cpython-310.pyc +0 -0
  49. phi4/lib/python3.10/site-packages/sympy/matrices/tests/__pycache__/test_decompositions.cpython-310.pyc +0 -0
  50. phi4/lib/python3.10/site-packages/sympy/matrices/tests/__pycache__/test_determinant.cpython-310.pyc +0 -0
.gitattributes CHANGED
@@ -745,3 +745,4 @@ phi4/lib/libtinfow.so.6.4 filter=lfs diff=lfs merge=lfs -text
745
  openflamingo/lib/python3.10/site-packages/pycocoevalcap/spice/lib/guava-19.0.jar filter=lfs diff=lfs merge=lfs -text
746
  openflamingo/lib/python3.10/site-packages/torch/__pycache__/overrides.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
747
  phi4/lib/python3.10/site-packages/transformers/models/seamless_m4t_v2/__pycache__/modeling_seamless_m4t_v2.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
 
 
745
  openflamingo/lib/python3.10/site-packages/pycocoevalcap/spice/lib/guava-19.0.jar filter=lfs diff=lfs merge=lfs -text
746
  openflamingo/lib/python3.10/site-packages/torch/__pycache__/overrides.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
747
  phi4/lib/python3.10/site-packages/transformers/models/seamless_m4t_v2/__pycache__/modeling_seamless_m4t_v2.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
748
+ phi4/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_spin.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/_transformer_encoder_layer_fwd_cuda_dispatch.h ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace cuda {
19
+
20
+ TORCH_API at::Tensor _transformer_encoder_layer_fwd(const at::Tensor & src, int64_t embed_dim, int64_t num_heads, const at::Tensor & qkv_weight, const at::Tensor & qkv_bias, const at::Tensor & proj_weight, const at::Tensor & proj_bias, bool use_gelu, bool norm_first, double eps, const at::Tensor & norm_weight_1, const at::Tensor & norm_bias_1, const at::Tensor & norm_weight_2, const at::Tensor & norm_bias_2, const at::Tensor & ffn_weight_1, const at::Tensor & ffn_bias_1, const at::Tensor & ffn_weight_2, const at::Tensor & ffn_bias_2, const c10::optional<at::Tensor> & mask={}, c10::optional<int64_t> mask_type=c10::nullopt);
21
+
22
+ } // namespace cuda
23
+ } // namespace at
openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/avg_pool3d_backward_meta.h ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from NativeMetaFunction.h
4
+
5
+ #include <c10/core/Scalar.h>
6
+ #include <c10/core/Storage.h>
7
+ #include <c10/core/TensorOptions.h>
8
+ #include <c10/util/Deprecated.h>
9
+ #include <c10/util/Optional.h>
10
+ #include <c10/core/QScheme.h>
11
+ #include <ATen/core/Reduction.h>
12
+ #include <ATen/TensorIterator.h>
13
+ #include <ATen/TensorMeta.h>
14
+ #include <tuple>
15
+ #include <vector>
16
+
17
+ namespace at {
18
+ namespace meta {
19
+
20
+ struct TORCH_API structured_avg_pool3d_backward : public at::impl::MetaBase {
21
+
22
+
23
+ void meta(const at::Tensor & grad_output, const at::Tensor & self, at::IntArrayRef kernel_size, at::IntArrayRef stride, at::IntArrayRef padding, bool ceil_mode, bool count_include_pad, c10::optional<int64_t> divisor_override);
24
+ };
25
+
26
+ } // namespace native
27
+ } // namespace at
openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/geqrf_ops.h ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Operator.h
4
+
5
+ #include <tuple>
6
+ #include <vector>
7
+
8
+ // Forward declarations of any types needed in the operator signatures.
9
+ // We can't directly include these classes because it will cause circular include dependencies.
10
+ // This file is included by TensorBody.h, which defines the Tensor class.
11
+ #include <ATen/core/ATen_fwd.h>
12
+
13
+ namespace at {
14
+ namespace _ops {
15
+
16
+
17
+ struct TORCH_API geqrf_a {
18
+ using schema = ::std::tuple<at::Tensor &,at::Tensor &> (const at::Tensor &, at::Tensor &, at::Tensor &);
19
+ using ptr_schema = schema*;
20
+ // See Note [static constexpr char* members for windows NVCC]
21
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::geqrf")
22
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "a")
23
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "geqrf.a(Tensor self, *, Tensor(a!) a, Tensor(b!) tau) -> (Tensor(a!) a, Tensor(b!) tau)")
24
+ static ::std::tuple<at::Tensor &,at::Tensor &> call(const at::Tensor & self, at::Tensor & a, at::Tensor & tau);
25
+ static ::std::tuple<at::Tensor &,at::Tensor &> redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::Tensor & a, at::Tensor & tau);
26
+ };
27
+
28
+ struct TORCH_API geqrf {
29
+ using schema = ::std::tuple<at::Tensor,at::Tensor> (const at::Tensor &);
30
+ using ptr_schema = schema*;
31
+ // See Note [static constexpr char* members for windows NVCC]
32
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::geqrf")
33
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
34
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "geqrf(Tensor self) -> (Tensor a, Tensor tau)")
35
+ static ::std::tuple<at::Tensor,at::Tensor> call(const at::Tensor & self);
36
+ static ::std::tuple<at::Tensor,at::Tensor> redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self);
37
+ };
38
+
39
+ }} // namespace at::_ops
openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/is_distributed_native.h ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from NativeFunction.h
4
+
5
+ #include <c10/core/Scalar.h>
6
+ #include <c10/core/Storage.h>
7
+ #include <c10/core/TensorOptions.h>
8
+ #include <c10/util/Deprecated.h>
9
+ #include <c10/util/Optional.h>
10
+ #include <c10/core/QScheme.h>
11
+ #include <ATen/core/Reduction.h>
12
+ #include <ATen/core/Tensor.h>
13
+ #include <tuple>
14
+ #include <vector>
15
+
16
+
17
+ namespace at {
18
+ namespace native {
19
+ TORCH_API bool is_distributed(const at::Tensor & self);
20
+ } // namespace native
21
+ } // namespace at
openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/polygamma_native.h ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from NativeFunction.h
4
+
5
+ #include <c10/core/Scalar.h>
6
+ #include <c10/core/Storage.h>
7
+ #include <c10/core/TensorOptions.h>
8
+ #include <c10/util/Deprecated.h>
9
+ #include <c10/util/Optional.h>
10
+ #include <c10/core/QScheme.h>
11
+ #include <ATen/core/Reduction.h>
12
+ #include <ATen/core/Tensor.h>
13
+ #include <tuple>
14
+ #include <vector>
15
+ #include <ATen/ops/polygamma_meta.h>
16
+
17
+ namespace at {
18
+ namespace native {
19
+ struct TORCH_API structured_polygamma_out : public at::meta::structured_polygamma {
20
+ void impl(int64_t n, const at::Tensor & self, const at::Tensor & out);
21
+ };
22
+ TORCH_API at::Tensor & polygamma_(at::Tensor & self, int64_t n);
23
+ } // namespace native
24
+ } // namespace at
openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/replication_pad2d_ops.h ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Operator.h
4
+
5
+ #include <tuple>
6
+ #include <vector>
7
+
8
+ // Forward declarations of any types needed in the operator signatures.
9
+ // We can't directly include these classes because it will cause circular include dependencies.
10
+ // This file is included by TensorBody.h, which defines the Tensor class.
11
+ #include <ATen/core/ATen_fwd.h>
12
+
13
+ namespace at {
14
+ namespace _ops {
15
+
16
+
17
+ struct TORCH_API replication_pad2d_out {
18
+ using schema = at::Tensor & (const at::Tensor &, c10::SymIntArrayRef, at::Tensor &);
19
+ using ptr_schema = schema*;
20
+ // See Note [static constexpr char* members for windows NVCC]
21
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::replication_pad2d")
22
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out")
23
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "replication_pad2d.out(Tensor self, SymInt[4] padding, *, Tensor(a!) out) -> Tensor(a!)")
24
+ static at::Tensor & call(const at::Tensor & self, c10::SymIntArrayRef padding, at::Tensor & out);
25
+ static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, c10::SymIntArrayRef padding, at::Tensor & out);
26
+ };
27
+
28
+ struct TORCH_API replication_pad2d {
29
+ using schema = at::Tensor (const at::Tensor &, c10::SymIntArrayRef);
30
+ using ptr_schema = schema*;
31
+ // See Note [static constexpr char* members for windows NVCC]
32
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::replication_pad2d")
33
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
34
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "replication_pad2d(Tensor self, SymInt[4] padding) -> Tensor")
35
+ static at::Tensor call(const at::Tensor & self, c10::SymIntArrayRef padding);
36
+ static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, c10::SymIntArrayRef padding);
37
+ };
38
+
39
+ }} // namespace at::_ops
openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/rnn_relu_ops.h ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Operator.h
4
+
5
+ #include <tuple>
6
+ #include <vector>
7
+
8
+ // Forward declarations of any types needed in the operator signatures.
9
+ // We can't directly include these classes because it will cause circular include dependencies.
10
+ // This file is included by TensorBody.h, which defines the Tensor class.
11
+ #include <ATen/core/ATen_fwd.h>
12
+
13
+ namespace at {
14
+ namespace _ops {
15
+
16
+
17
+ struct TORCH_API rnn_relu_input {
18
+ using schema = ::std::tuple<at::Tensor,at::Tensor> (const at::Tensor &, const at::Tensor &, at::TensorList, bool, int64_t, double, bool, bool, bool);
19
+ using ptr_schema = schema*;
20
+ // See Note [static constexpr char* members for windows NVCC]
21
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::rnn_relu")
22
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "input")
23
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "rnn_relu.input(Tensor input, Tensor hx, Tensor[] params, bool has_biases, int num_layers, float dropout, bool train, bool bidirectional, bool batch_first) -> (Tensor, Tensor)")
24
+ static ::std::tuple<at::Tensor,at::Tensor> call(const at::Tensor & input, const at::Tensor & hx, at::TensorList params, bool has_biases, int64_t num_layers, double dropout, bool train, bool bidirectional, bool batch_first);
25
+ static ::std::tuple<at::Tensor,at::Tensor> redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & input, const at::Tensor & hx, at::TensorList params, bool has_biases, int64_t num_layers, double dropout, bool train, bool bidirectional, bool batch_first);
26
+ };
27
+
28
+ struct TORCH_API rnn_relu_data {
29
+ using schema = ::std::tuple<at::Tensor,at::Tensor> (const at::Tensor &, const at::Tensor &, const at::Tensor &, at::TensorList, bool, int64_t, double, bool, bool);
30
+ using ptr_schema = schema*;
31
+ // See Note [static constexpr char* members for windows NVCC]
32
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::rnn_relu")
33
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "data")
34
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "rnn_relu.data(Tensor data, Tensor batch_sizes, Tensor hx, Tensor[] params, bool has_biases, int num_layers, float dropout, bool train, bool bidirectional) -> (Tensor, Tensor)")
35
+ static ::std::tuple<at::Tensor,at::Tensor> call(const at::Tensor & data, const at::Tensor & batch_sizes, const at::Tensor & hx, at::TensorList params, bool has_biases, int64_t num_layers, double dropout, bool train, bool bidirectional);
36
+ static ::std::tuple<at::Tensor,at::Tensor> redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & data, const at::Tensor & batch_sizes, const at::Tensor & hx, at::TensorList params, bool has_biases, int64_t num_layers, double dropout, bool train, bool bidirectional);
37
+ };
38
+
39
+ }} // namespace at::_ops
openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/special_i1_cuda_dispatch.h ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace cuda {
19
+
20
+ TORCH_API at::Tensor special_i1(const at::Tensor & self);
21
+ TORCH_API at::Tensor & special_i1_out(at::Tensor & out, const at::Tensor & self);
22
+ TORCH_API at::Tensor & special_i1_outf(const at::Tensor & self, at::Tensor & out);
23
+
24
+ } // namespace cuda
25
+ } // namespace at
openflamingo/lib/python3.10/site-packages/torch/include/ATen/ops/triu_compositeexplicitautogradnonfunctional_dispatch.h ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace compositeexplicitautogradnonfunctional {
19
+
20
+ TORCH_API at::Tensor triu(const at::Tensor & self, int64_t diagonal=0);
21
+ TORCH_API at::Tensor & triu_(at::Tensor & self, int64_t diagonal=0);
22
+
23
+ } // namespace compositeexplicitautogradnonfunctional
24
+ } // namespace at
phi4/lib/python3.10/site-packages/sympy/matrices/__init__.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """A module that handles matrices.
2
+
3
+ Includes functions for fast creating matrices like zero, one/eye, random
4
+ matrix, etc.
5
+ """
6
+ from .exceptions import ShapeError, NonSquareMatrixError
7
+ from .kind import MatrixKind
8
+ from .dense import (
9
+ GramSchmidt, casoratian, diag, eye, hessian, jordan_cell,
10
+ list2numpy, matrix2numpy, matrix_multiply_elementwise, ones,
11
+ randMatrix, rot_axis1, rot_axis2, rot_axis3, rot_ccw_axis1,
12
+ rot_ccw_axis2, rot_ccw_axis3, rot_givens,
13
+ symarray, wronskian, zeros)
14
+ from .dense import MutableDenseMatrix
15
+ from .matrixbase import DeferredVector, MatrixBase
16
+
17
+ MutableMatrix = MutableDenseMatrix
18
+ Matrix = MutableMatrix
19
+
20
+ from .sparse import MutableSparseMatrix
21
+ from .sparsetools import banded
22
+ from .immutable import ImmutableDenseMatrix, ImmutableSparseMatrix
23
+
24
+ ImmutableMatrix = ImmutableDenseMatrix
25
+ SparseMatrix = MutableSparseMatrix
26
+
27
+ from .expressions import (
28
+ MatrixSlice, BlockDiagMatrix, BlockMatrix, FunctionMatrix, Identity,
29
+ Inverse, MatAdd, MatMul, MatPow, MatrixExpr, MatrixSymbol, Trace,
30
+ Transpose, ZeroMatrix, OneMatrix, blockcut, block_collapse, matrix_symbols, Adjoint,
31
+ hadamard_product, HadamardProduct, HadamardPower, Determinant, det,
32
+ diagonalize_vector, DiagMatrix, DiagonalMatrix, DiagonalOf, trace,
33
+ DotProduct, kronecker_product, KroneckerProduct,
34
+ PermutationMatrix, MatrixPermute, MatrixSet, Permanent, per)
35
+
36
+ from .utilities import dotprodsimp
37
+
38
+ __all__ = [
39
+ 'ShapeError', 'NonSquareMatrixError', 'MatrixKind',
40
+
41
+ 'GramSchmidt', 'casoratian', 'diag', 'eye', 'hessian', 'jordan_cell',
42
+ 'list2numpy', 'matrix2numpy', 'matrix_multiply_elementwise', 'ones',
43
+ 'randMatrix', 'rot_axis1', 'rot_axis2', 'rot_axis3', 'symarray',
44
+ 'wronskian', 'zeros', 'rot_ccw_axis1', 'rot_ccw_axis2', 'rot_ccw_axis3',
45
+ 'rot_givens',
46
+
47
+ 'MutableDenseMatrix',
48
+
49
+ 'DeferredVector', 'MatrixBase',
50
+
51
+ 'Matrix', 'MutableMatrix',
52
+
53
+ 'MutableSparseMatrix',
54
+
55
+ 'banded',
56
+
57
+ 'ImmutableDenseMatrix', 'ImmutableSparseMatrix',
58
+
59
+ 'ImmutableMatrix', 'SparseMatrix',
60
+
61
+ 'MatrixSlice', 'BlockDiagMatrix', 'BlockMatrix', 'FunctionMatrix',
62
+ 'Identity', 'Inverse', 'MatAdd', 'MatMul', 'MatPow', 'MatrixExpr',
63
+ 'MatrixSymbol', 'Trace', 'Transpose', 'ZeroMatrix', 'OneMatrix',
64
+ 'blockcut', 'block_collapse', 'matrix_symbols', 'Adjoint',
65
+ 'hadamard_product', 'HadamardProduct', 'HadamardPower', 'Determinant',
66
+ 'det', 'diagonalize_vector', 'DiagMatrix', 'DiagonalMatrix',
67
+ 'DiagonalOf', 'trace', 'DotProduct', 'kronecker_product',
68
+ 'KroneckerProduct', 'PermutationMatrix', 'MatrixPermute', 'MatrixSet',
69
+ 'Permanent', 'per',
70
+
71
+ 'dotprodsimp',
72
+ ]
phi4/lib/python3.10/site-packages/sympy/matrices/__pycache__/common.cpython-310.pyc ADDED
Binary file (99.3 kB). View file
 
phi4/lib/python3.10/site-packages/sympy/matrices/__pycache__/decompositions.cpython-310.pyc ADDED
Binary file (41.3 kB). View file
 
phi4/lib/python3.10/site-packages/sympy/matrices/__pycache__/dense.cpython-310.pyc ADDED
Binary file (31.2 kB). View file
 
phi4/lib/python3.10/site-packages/sympy/matrices/__pycache__/determinant.cpython-310.pyc ADDED
Binary file (27.4 kB). View file
 
phi4/lib/python3.10/site-packages/sympy/matrices/__pycache__/eigen.cpython-310.pyc ADDED
Binary file (36.8 kB). View file
 
phi4/lib/python3.10/site-packages/sympy/matrices/__pycache__/exceptions.cpython-310.pyc ADDED
Binary file (1.08 kB). View file
 
phi4/lib/python3.10/site-packages/sympy/matrices/__pycache__/graph.cpython-310.pyc ADDED
Binary file (9.1 kB). View file
 
phi4/lib/python3.10/site-packages/sympy/matrices/__pycache__/immutable.cpython-310.pyc ADDED
Binary file (6.41 kB). View file
 
phi4/lib/python3.10/site-packages/sympy/matrices/__pycache__/inverse.cpython-310.pyc ADDED
Binary file (11.9 kB). View file
 
phi4/lib/python3.10/site-packages/sympy/matrices/__pycache__/kind.cpython-310.pyc ADDED
Binary file (2.96 kB). View file
 
phi4/lib/python3.10/site-packages/sympy/matrices/__pycache__/normalforms.cpython-310.pyc ADDED
Binary file (4.37 kB). View file
 
phi4/lib/python3.10/site-packages/sympy/matrices/__pycache__/reductions.cpython-310.pyc ADDED
Binary file (10.9 kB). View file
 
phi4/lib/python3.10/site-packages/sympy/matrices/__pycache__/repmatrix.cpython-310.pyc ADDED
Binary file (28.8 kB). View file
 
phi4/lib/python3.10/site-packages/sympy/matrices/__pycache__/solvers.cpython-310.pyc ADDED
Binary file (24 kB). View file
 
phi4/lib/python3.10/site-packages/sympy/matrices/__pycache__/sparse.cpython-310.pyc ADDED
Binary file (13.8 kB). View file
 
phi4/lib/python3.10/site-packages/sympy/matrices/__pycache__/sparsetools.cpython-310.pyc ADDED
Binary file (8.5 kB). View file
 
phi4/lib/python3.10/site-packages/sympy/matrices/__pycache__/subspaces.cpython-310.pyc ADDED
Binary file (4.34 kB). View file
 
phi4/lib/python3.10/site-packages/sympy/matrices/__pycache__/utilities.cpython-310.pyc ADDED
Binary file (2.7 kB). View file
 
phi4/lib/python3.10/site-packages/sympy/matrices/common.py ADDED
@@ -0,0 +1,3263 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ A module contining deprecated matrix mixin classes.
3
+
4
+ The classes in this module are deprecated and will be removed in a future
5
+ release. They are kept here for backwards compatibility in case downstream
6
+ code was subclassing them.
7
+
8
+ Importing anything else from this module is deprecated so anything here
9
+ should either not be used or should be imported from somewhere else.
10
+ """
11
+
12
+ from collections import defaultdict
13
+ from collections.abc import Iterable
14
+ from inspect import isfunction
15
+ from functools import reduce
16
+
17
+ from sympy.assumptions.refine import refine
18
+ from sympy.core import SympifyError, Add
19
+ from sympy.core.basic import Atom
20
+ from sympy.core.decorators import call_highest_priority
21
+ from sympy.core.logic import fuzzy_and, FuzzyBool
22
+ from sympy.core.numbers import Integer
23
+ from sympy.core.mod import Mod
24
+ from sympy.core.singleton import S
25
+ from sympy.core.symbol import Symbol
26
+ from sympy.core.sympify import sympify
27
+ from sympy.functions.elementary.complexes import Abs, re, im
28
+ from sympy.utilities.exceptions import sympy_deprecation_warning
29
+ from .utilities import _dotprodsimp, _simplify
30
+ from sympy.polys.polytools import Poly
31
+ from sympy.utilities.iterables import flatten, is_sequence
32
+ from sympy.utilities.misc import as_int, filldedent
33
+ from sympy.tensor.array import NDimArray
34
+
35
+ from .utilities import _get_intermediate_simp_bool
36
+
37
+
38
+ # These exception types were previously defined in this module but were moved
39
+ # to exceptions.py. We reimport them here for backwards compatibility in case
40
+ # downstream code was importing them from here.
41
+ from .exceptions import ( # noqa: F401
42
+ MatrixError, ShapeError, NonSquareMatrixError, NonInvertibleMatrixError,
43
+ NonPositiveDefiniteMatrixError
44
+ )
45
+
46
+
47
+ _DEPRECATED_MIXINS = (
48
+ 'MatrixShaping',
49
+ 'MatrixSpecial',
50
+ 'MatrixProperties',
51
+ 'MatrixOperations',
52
+ 'MatrixArithmetic',
53
+ 'MatrixCommon',
54
+ 'MatrixDeterminant',
55
+ 'MatrixReductions',
56
+ 'MatrixSubspaces',
57
+ 'MatrixEigen',
58
+ 'MatrixCalculus',
59
+ 'MatrixDeprecated',
60
+ )
61
+
62
+
63
+ class _MatrixDeprecatedMeta(type):
64
+
65
+ #
66
+ # Override the default __instancecheck__ implementation to ensure that
67
+ # e.g. isinstance(M, MatrixCommon) still works when M is one of the
68
+ # matrix classes. Matrix no longer inherits from MatrixCommon so
69
+ # isinstance(M, MatrixCommon) would now return False by default.
70
+ #
71
+ # There were lots of places in the codebase where this was being done
72
+ # so it seems likely that downstream code may be doing it too. All use
73
+ # of these mixins is deprecated though so we give a deprecation warning
74
+ # unconditionally if they are being used with isinstance.
75
+ #
76
+ # Any code seeing this deprecation warning should be changed to use
77
+ # isinstance(M, MatrixBase) instead which also works in previous versions
78
+ # of SymPy.
79
+ #
80
+
81
+ def __instancecheck__(cls, instance):
82
+
83
+ sympy_deprecation_warning(
84
+ f"""
85
+ Checking whether an object is an instance of {cls.__name__} is
86
+ deprecated.
87
+
88
+ Use `isinstance(obj, Matrix)` instead of `isinstance(obj, {cls.__name__})`.
89
+ """,
90
+ deprecated_since_version="1.13",
91
+ active_deprecations_target="deprecated-matrix-mixins",
92
+ stacklevel=3,
93
+ )
94
+
95
+ from sympy.matrices.matrixbase import MatrixBase
96
+ from sympy.matrices.matrices import (
97
+ MatrixDeterminant,
98
+ MatrixReductions,
99
+ MatrixSubspaces,
100
+ MatrixEigen,
101
+ MatrixCalculus,
102
+ MatrixDeprecated
103
+ )
104
+
105
+ all_mixins = (
106
+ MatrixRequired,
107
+ MatrixShaping,
108
+ MatrixSpecial,
109
+ MatrixProperties,
110
+ MatrixOperations,
111
+ MatrixArithmetic,
112
+ MatrixCommon,
113
+ MatrixDeterminant,
114
+ MatrixReductions,
115
+ MatrixSubspaces,
116
+ MatrixEigen,
117
+ MatrixCalculus,
118
+ MatrixDeprecated
119
+ )
120
+
121
+ if cls in all_mixins and isinstance(instance, MatrixBase):
122
+ return True
123
+ else:
124
+ return super().__instancecheck__(instance)
125
+
126
+
127
+ class MatrixRequired(metaclass=_MatrixDeprecatedMeta):
128
+ """Deprecated mixin class for making matrix classes."""
129
+
130
+ rows = None # type: int
131
+ cols = None # type: int
132
+ _simplify = None
133
+
134
+ def __init_subclass__(cls, **kwargs):
135
+
136
+ # Warn if any downstream code is subclassing this class or any of the
137
+ # deprecated mixin classes that are all ultimately subclasses of this
138
+ # class.
139
+ #
140
+ # We don't want to warn about the deprecated mixins themselves being
141
+ # created, but only about them being used as mixins by downstream code.
142
+ # Otherwise just importing this module would trigger a warning.
143
+ # Ultimately the whole module should be deprecated and removed but for
144
+ # SymPy 1.13 it is premature to do that given that this module was the
145
+ # main way to import matrix exception types in all previous versions.
146
+
147
+ if cls.__name__ not in _DEPRECATED_MIXINS:
148
+ sympy_deprecation_warning(
149
+ f"""
150
+ Inheriting from the Matrix mixin classes is deprecated.
151
+
152
+ The class {cls.__name__} is subclassing a deprecated mixin.
153
+ """,
154
+ deprecated_since_version="1.13",
155
+ active_deprecations_target="deprecated-matrix-mixins",
156
+ stacklevel=3,
157
+ )
158
+
159
+ super().__init_subclass__(**kwargs)
160
+
161
+ @classmethod
162
+ def _new(cls, *args, **kwargs):
163
+ """`_new` must, at minimum, be callable as
164
+ `_new(rows, cols, mat) where mat is a flat list of the
165
+ elements of the matrix."""
166
+ raise NotImplementedError("Subclasses must implement this.")
167
+
168
+ def __eq__(self, other):
169
+ raise NotImplementedError("Subclasses must implement this.")
170
+
171
+ def __getitem__(self, key):
172
+ """Implementations of __getitem__ should accept ints, in which
173
+ case the matrix is indexed as a flat list, tuples (i,j) in which
174
+ case the (i,j) entry is returned, slices, or mixed tuples (a,b)
175
+ where a and b are any combination of slices and integers."""
176
+ raise NotImplementedError("Subclasses must implement this.")
177
+
178
+ def __len__(self):
179
+ """The total number of entries in the matrix."""
180
+ raise NotImplementedError("Subclasses must implement this.")
181
+
182
+ @property
183
+ def shape(self):
184
+ raise NotImplementedError("Subclasses must implement this.")
185
+
186
+
187
+ class MatrixShaping(MatrixRequired):
188
+ """Provides basic matrix shaping and extracting of submatrices"""
189
+
190
+ def _eval_col_del(self, col):
191
+ def entry(i, j):
192
+ return self[i, j] if j < col else self[i, j + 1]
193
+ return self._new(self.rows, self.cols - 1, entry)
194
+
195
+ def _eval_col_insert(self, pos, other):
196
+
197
+ def entry(i, j):
198
+ if j < pos:
199
+ return self[i, j]
200
+ elif pos <= j < pos + other.cols:
201
+ return other[i, j - pos]
202
+ return self[i, j - other.cols]
203
+
204
+ return self._new(self.rows, self.cols + other.cols, entry)
205
+
206
+ def _eval_col_join(self, other):
207
+ rows = self.rows
208
+
209
+ def entry(i, j):
210
+ if i < rows:
211
+ return self[i, j]
212
+ return other[i - rows, j]
213
+
214
+ return classof(self, other)._new(self.rows + other.rows, self.cols,
215
+ entry)
216
+
217
+ def _eval_extract(self, rowsList, colsList):
218
+ mat = list(self)
219
+ cols = self.cols
220
+ indices = (i * cols + j for i in rowsList for j in colsList)
221
+ return self._new(len(rowsList), len(colsList),
222
+ [mat[i] for i in indices])
223
+
224
+ def _eval_get_diag_blocks(self):
225
+ sub_blocks = []
226
+
227
+ def recurse_sub_blocks(M):
228
+ i = 1
229
+ while i <= M.shape[0]:
230
+ if i == 1:
231
+ to_the_right = M[0, i:]
232
+ to_the_bottom = M[i:, 0]
233
+ else:
234
+ to_the_right = M[:i, i:]
235
+ to_the_bottom = M[i:, :i]
236
+ if any(to_the_right) or any(to_the_bottom):
237
+ i += 1
238
+ continue
239
+ else:
240
+ sub_blocks.append(M[:i, :i])
241
+ if M.shape == M[:i, :i].shape:
242
+ return
243
+ else:
244
+ recurse_sub_blocks(M[i:, i:])
245
+ return
246
+
247
+ recurse_sub_blocks(self)
248
+ return sub_blocks
249
+
250
+ def _eval_row_del(self, row):
251
+ def entry(i, j):
252
+ return self[i, j] if i < row else self[i + 1, j]
253
+ return self._new(self.rows - 1, self.cols, entry)
254
+
255
+ def _eval_row_insert(self, pos, other):
256
+ entries = list(self)
257
+ insert_pos = pos * self.cols
258
+ entries[insert_pos:insert_pos] = list(other)
259
+ return self._new(self.rows + other.rows, self.cols, entries)
260
+
261
+ def _eval_row_join(self, other):
262
+ cols = self.cols
263
+
264
+ def entry(i, j):
265
+ if j < cols:
266
+ return self[i, j]
267
+ return other[i, j - cols]
268
+
269
+ return classof(self, other)._new(self.rows, self.cols + other.cols,
270
+ entry)
271
+
272
+ def _eval_tolist(self):
273
+ return [list(self[i,:]) for i in range(self.rows)]
274
+
275
+ def _eval_todok(self):
276
+ dok = {}
277
+ rows, cols = self.shape
278
+ for i in range(rows):
279
+ for j in range(cols):
280
+ val = self[i, j]
281
+ if val != self.zero:
282
+ dok[i, j] = val
283
+ return dok
284
+
285
+ def _eval_vec(self):
286
+ rows = self.rows
287
+
288
+ def entry(n, _):
289
+ # we want to read off the columns first
290
+ j = n // rows
291
+ i = n - j * rows
292
+ return self[i, j]
293
+
294
+ return self._new(len(self), 1, entry)
295
+
296
+ def _eval_vech(self, diagonal):
297
+ c = self.cols
298
+ v = []
299
+ if diagonal:
300
+ for j in range(c):
301
+ for i in range(j, c):
302
+ v.append(self[i, j])
303
+ else:
304
+ for j in range(c):
305
+ for i in range(j + 1, c):
306
+ v.append(self[i, j])
307
+ return self._new(len(v), 1, v)
308
+
309
+ def col_del(self, col):
310
+ """Delete the specified column."""
311
+ if col < 0:
312
+ col += self.cols
313
+ if not 0 <= col < self.cols:
314
+ raise IndexError("Column {} is out of range.".format(col))
315
+ return self._eval_col_del(col)
316
+
317
+ def col_insert(self, pos, other):
318
+ """Insert one or more columns at the given column position.
319
+
320
+ Examples
321
+ ========
322
+
323
+ >>> from sympy import zeros, ones
324
+ >>> M = zeros(3)
325
+ >>> V = ones(3, 1)
326
+ >>> M.col_insert(1, V)
327
+ Matrix([
328
+ [0, 1, 0, 0],
329
+ [0, 1, 0, 0],
330
+ [0, 1, 0, 0]])
331
+
332
+ See Also
333
+ ========
334
+
335
+ col
336
+ row_insert
337
+ """
338
+ # Allows you to build a matrix even if it is null matrix
339
+ if not self:
340
+ return type(self)(other)
341
+
342
+ pos = as_int(pos)
343
+
344
+ if pos < 0:
345
+ pos = self.cols + pos
346
+ if pos < 0:
347
+ pos = 0
348
+ elif pos > self.cols:
349
+ pos = self.cols
350
+
351
+ if self.rows != other.rows:
352
+ raise ShapeError(
353
+ "The matrices have incompatible number of rows ({} and {})"
354
+ .format(self.rows, other.rows))
355
+
356
+ return self._eval_col_insert(pos, other)
357
+
358
+ def col_join(self, other):
359
+ """Concatenates two matrices along self's last and other's first row.
360
+
361
+ Examples
362
+ ========
363
+
364
+ >>> from sympy import zeros, ones
365
+ >>> M = zeros(3)
366
+ >>> V = ones(1, 3)
367
+ >>> M.col_join(V)
368
+ Matrix([
369
+ [0, 0, 0],
370
+ [0, 0, 0],
371
+ [0, 0, 0],
372
+ [1, 1, 1]])
373
+
374
+ See Also
375
+ ========
376
+
377
+ col
378
+ row_join
379
+ """
380
+ # A null matrix can always be stacked (see #10770)
381
+ if self.rows == 0 and self.cols != other.cols:
382
+ return self._new(0, other.cols, []).col_join(other)
383
+
384
+ if self.cols != other.cols:
385
+ raise ShapeError(
386
+ "The matrices have incompatible number of columns ({} and {})"
387
+ .format(self.cols, other.cols))
388
+ return self._eval_col_join(other)
389
+
390
+ def col(self, j):
391
+ """Elementary column selector.
392
+
393
+ Examples
394
+ ========
395
+
396
+ >>> from sympy import eye
397
+ >>> eye(2).col(0)
398
+ Matrix([
399
+ [1],
400
+ [0]])
401
+
402
+ See Also
403
+ ========
404
+
405
+ row
406
+ col_del
407
+ col_join
408
+ col_insert
409
+ """
410
+ return self[:, j]
411
+
412
+ def extract(self, rowsList, colsList):
413
+ r"""Return a submatrix by specifying a list of rows and columns.
414
+ Negative indices can be given. All indices must be in the range
415
+ $-n \le i < n$ where $n$ is the number of rows or columns.
416
+
417
+ Examples
418
+ ========
419
+
420
+ >>> from sympy import Matrix
421
+ >>> m = Matrix(4, 3, range(12))
422
+ >>> m
423
+ Matrix([
424
+ [0, 1, 2],
425
+ [3, 4, 5],
426
+ [6, 7, 8],
427
+ [9, 10, 11]])
428
+ >>> m.extract([0, 1, 3], [0, 1])
429
+ Matrix([
430
+ [0, 1],
431
+ [3, 4],
432
+ [9, 10]])
433
+
434
+ Rows or columns can be repeated:
435
+
436
+ >>> m.extract([0, 0, 1], [-1])
437
+ Matrix([
438
+ [2],
439
+ [2],
440
+ [5]])
441
+
442
+ Every other row can be taken by using range to provide the indices:
443
+
444
+ >>> m.extract(range(0, m.rows, 2), [-1])
445
+ Matrix([
446
+ [2],
447
+ [8]])
448
+
449
+ RowsList or colsList can also be a list of booleans, in which case
450
+ the rows or columns corresponding to the True values will be selected:
451
+
452
+ >>> m.extract([0, 1, 2, 3], [True, False, True])
453
+ Matrix([
454
+ [0, 2],
455
+ [3, 5],
456
+ [6, 8],
457
+ [9, 11]])
458
+ """
459
+
460
+ if not is_sequence(rowsList) or not is_sequence(colsList):
461
+ raise TypeError("rowsList and colsList must be iterable")
462
+ # ensure rowsList and colsList are lists of integers
463
+ if rowsList and all(isinstance(i, bool) for i in rowsList):
464
+ rowsList = [index for index, item in enumerate(rowsList) if item]
465
+ if colsList and all(isinstance(i, bool) for i in colsList):
466
+ colsList = [index for index, item in enumerate(colsList) if item]
467
+
468
+ # ensure everything is in range
469
+ rowsList = [a2idx(k, self.rows) for k in rowsList]
470
+ colsList = [a2idx(k, self.cols) for k in colsList]
471
+
472
+ return self._eval_extract(rowsList, colsList)
473
+
474
+ def get_diag_blocks(self):
475
+ """Obtains the square sub-matrices on the main diagonal of a square matrix.
476
+
477
+ Useful for inverting symbolic matrices or solving systems of
478
+ linear equations which may be decoupled by having a block diagonal
479
+ structure.
480
+
481
+ Examples
482
+ ========
483
+
484
+ >>> from sympy import Matrix
485
+ >>> from sympy.abc import x, y, z
486
+ >>> A = Matrix([[1, 3, 0, 0], [y, z*z, 0, 0], [0, 0, x, 0], [0, 0, 0, 0]])
487
+ >>> a1, a2, a3 = A.get_diag_blocks()
488
+ >>> a1
489
+ Matrix([
490
+ [1, 3],
491
+ [y, z**2]])
492
+ >>> a2
493
+ Matrix([[x]])
494
+ >>> a3
495
+ Matrix([[0]])
496
+
497
+ """
498
+ return self._eval_get_diag_blocks()
499
+
500
+ @classmethod
501
+ def hstack(cls, *args):
502
+ """Return a matrix formed by joining args horizontally (i.e.
503
+ by repeated application of row_join).
504
+
505
+ Examples
506
+ ========
507
+
508
+ >>> from sympy import Matrix, eye
509
+ >>> Matrix.hstack(eye(2), 2*eye(2))
510
+ Matrix([
511
+ [1, 0, 2, 0],
512
+ [0, 1, 0, 2]])
513
+ """
514
+ if len(args) == 0:
515
+ return cls._new()
516
+
517
+ kls = type(args[0])
518
+ return reduce(kls.row_join, args)
519
+
520
+ def reshape(self, rows, cols):
521
+ """Reshape the matrix. Total number of elements must remain the same.
522
+
523
+ Examples
524
+ ========
525
+
526
+ >>> from sympy import Matrix
527
+ >>> m = Matrix(2, 3, lambda i, j: 1)
528
+ >>> m
529
+ Matrix([
530
+ [1, 1, 1],
531
+ [1, 1, 1]])
532
+ >>> m.reshape(1, 6)
533
+ Matrix([[1, 1, 1, 1, 1, 1]])
534
+ >>> m.reshape(3, 2)
535
+ Matrix([
536
+ [1, 1],
537
+ [1, 1],
538
+ [1, 1]])
539
+
540
+ """
541
+ if self.rows * self.cols != rows * cols:
542
+ raise ValueError("Invalid reshape parameters %d %d" % (rows, cols))
543
+ return self._new(rows, cols, lambda i, j: self[i * cols + j])
544
+
545
+ def row_del(self, row):
546
+ """Delete the specified row."""
547
+ if row < 0:
548
+ row += self.rows
549
+ if not 0 <= row < self.rows:
550
+ raise IndexError("Row {} is out of range.".format(row))
551
+
552
+ return self._eval_row_del(row)
553
+
554
+ def row_insert(self, pos, other):
555
+ """Insert one or more rows at the given row position.
556
+
557
+ Examples
558
+ ========
559
+
560
+ >>> from sympy import zeros, ones
561
+ >>> M = zeros(3)
562
+ >>> V = ones(1, 3)
563
+ >>> M.row_insert(1, V)
564
+ Matrix([
565
+ [0, 0, 0],
566
+ [1, 1, 1],
567
+ [0, 0, 0],
568
+ [0, 0, 0]])
569
+
570
+ See Also
571
+ ========
572
+
573
+ row
574
+ col_insert
575
+ """
576
+ # Allows you to build a matrix even if it is null matrix
577
+ if not self:
578
+ return self._new(other)
579
+
580
+ pos = as_int(pos)
581
+
582
+ if pos < 0:
583
+ pos = self.rows + pos
584
+ if pos < 0:
585
+ pos = 0
586
+ elif pos > self.rows:
587
+ pos = self.rows
588
+
589
+ if self.cols != other.cols:
590
+ raise ShapeError(
591
+ "The matrices have incompatible number of columns ({} and {})"
592
+ .format(self.cols, other.cols))
593
+
594
+ return self._eval_row_insert(pos, other)
595
+
596
+ def row_join(self, other):
597
+ """Concatenates two matrices along self's last and rhs's first column
598
+
599
+ Examples
600
+ ========
601
+
602
+ >>> from sympy import zeros, ones
603
+ >>> M = zeros(3)
604
+ >>> V = ones(3, 1)
605
+ >>> M.row_join(V)
606
+ Matrix([
607
+ [0, 0, 0, 1],
608
+ [0, 0, 0, 1],
609
+ [0, 0, 0, 1]])
610
+
611
+ See Also
612
+ ========
613
+
614
+ row
615
+ col_join
616
+ """
617
+ # A null matrix can always be stacked (see #10770)
618
+ if self.cols == 0 and self.rows != other.rows:
619
+ return self._new(other.rows, 0, []).row_join(other)
620
+
621
+ if self.rows != other.rows:
622
+ raise ShapeError(
623
+ "The matrices have incompatible number of rows ({} and {})"
624
+ .format(self.rows, other.rows))
625
+ return self._eval_row_join(other)
626
+
627
+ def diagonal(self, k=0):
628
+ """Returns the kth diagonal of self. The main diagonal
629
+ corresponds to `k=0`; diagonals above and below correspond to
630
+ `k > 0` and `k < 0`, respectively. The values of `self[i, j]`
631
+ for which `j - i = k`, are returned in order of increasing
632
+ `i + j`, starting with `i + j = |k|`.
633
+
634
+ Examples
635
+ ========
636
+
637
+ >>> from sympy import Matrix
638
+ >>> m = Matrix(3, 3, lambda i, j: j - i); m
639
+ Matrix([
640
+ [ 0, 1, 2],
641
+ [-1, 0, 1],
642
+ [-2, -1, 0]])
643
+ >>> _.diagonal()
644
+ Matrix([[0, 0, 0]])
645
+ >>> m.diagonal(1)
646
+ Matrix([[1, 1]])
647
+ >>> m.diagonal(-2)
648
+ Matrix([[-2]])
649
+
650
+ Even though the diagonal is returned as a Matrix, the element
651
+ retrieval can be done with a single index:
652
+
653
+ >>> Matrix.diag(1, 2, 3).diagonal()[1] # instead of [0, 1]
654
+ 2
655
+
656
+ See Also
657
+ ========
658
+
659
+ diag
660
+ """
661
+ rv = []
662
+ k = as_int(k)
663
+ r = 0 if k > 0 else -k
664
+ c = 0 if r else k
665
+ while True:
666
+ if r == self.rows or c == self.cols:
667
+ break
668
+ rv.append(self[r, c])
669
+ r += 1
670
+ c += 1
671
+ if not rv:
672
+ raise ValueError(filldedent('''
673
+ The %s diagonal is out of range [%s, %s]''' % (
674
+ k, 1 - self.rows, self.cols - 1)))
675
+ return self._new(1, len(rv), rv)
676
+
677
+ def row(self, i):
678
+ """Elementary row selector.
679
+
680
+ Examples
681
+ ========
682
+
683
+ >>> from sympy import eye
684
+ >>> eye(2).row(0)
685
+ Matrix([[1, 0]])
686
+
687
+ See Also
688
+ ========
689
+
690
+ col
691
+ row_del
692
+ row_join
693
+ row_insert
694
+ """
695
+ return self[i, :]
696
+
697
+ @property
698
+ def shape(self):
699
+ """The shape (dimensions) of the matrix as the 2-tuple (rows, cols).
700
+
701
+ Examples
702
+ ========
703
+
704
+ >>> from sympy import zeros
705
+ >>> M = zeros(2, 3)
706
+ >>> M.shape
707
+ (2, 3)
708
+ >>> M.rows
709
+ 2
710
+ >>> M.cols
711
+ 3
712
+ """
713
+ return (self.rows, self.cols)
714
+
715
+ def todok(self):
716
+ """Return the matrix as dictionary of keys.
717
+
718
+ Examples
719
+ ========
720
+
721
+ >>> from sympy import Matrix
722
+ >>> M = Matrix.eye(3)
723
+ >>> M.todok()
724
+ {(0, 0): 1, (1, 1): 1, (2, 2): 1}
725
+ """
726
+ return self._eval_todok()
727
+
728
+ def tolist(self):
729
+ """Return the Matrix as a nested Python list.
730
+
731
+ Examples
732
+ ========
733
+
734
+ >>> from sympy import Matrix, ones
735
+ >>> m = Matrix(3, 3, range(9))
736
+ >>> m
737
+ Matrix([
738
+ [0, 1, 2],
739
+ [3, 4, 5],
740
+ [6, 7, 8]])
741
+ >>> m.tolist()
742
+ [[0, 1, 2], [3, 4, 5], [6, 7, 8]]
743
+ >>> ones(3, 0).tolist()
744
+ [[], [], []]
745
+
746
+ When there are no rows then it will not be possible to tell how
747
+ many columns were in the original matrix:
748
+
749
+ >>> ones(0, 3).tolist()
750
+ []
751
+
752
+ """
753
+ if not self.rows:
754
+ return []
755
+ if not self.cols:
756
+ return [[] for i in range(self.rows)]
757
+ return self._eval_tolist()
758
+
759
+ def todod(M):
760
+ """Returns matrix as dict of dicts containing non-zero elements of the Matrix
761
+
762
+ Examples
763
+ ========
764
+
765
+ >>> from sympy import Matrix
766
+ >>> A = Matrix([[0, 1],[0, 3]])
767
+ >>> A
768
+ Matrix([
769
+ [0, 1],
770
+ [0, 3]])
771
+ >>> A.todod()
772
+ {0: {1: 1}, 1: {1: 3}}
773
+
774
+
775
+ """
776
+ rowsdict = {}
777
+ Mlol = M.tolist()
778
+ for i, Mi in enumerate(Mlol):
779
+ row = {j: Mij for j, Mij in enumerate(Mi) if Mij}
780
+ if row:
781
+ rowsdict[i] = row
782
+ return rowsdict
783
+
784
+ def vec(self):
785
+ """Return the Matrix converted into a one column matrix by stacking columns
786
+
787
+ Examples
788
+ ========
789
+
790
+ >>> from sympy import Matrix
791
+ >>> m=Matrix([[1, 3], [2, 4]])
792
+ >>> m
793
+ Matrix([
794
+ [1, 3],
795
+ [2, 4]])
796
+ >>> m.vec()
797
+ Matrix([
798
+ [1],
799
+ [2],
800
+ [3],
801
+ [4]])
802
+
803
+ See Also
804
+ ========
805
+
806
+ vech
807
+ """
808
+ return self._eval_vec()
809
+
810
+ def vech(self, diagonal=True, check_symmetry=True):
811
+ """Reshapes the matrix into a column vector by stacking the
812
+ elements in the lower triangle.
813
+
814
+ Parameters
815
+ ==========
816
+
817
+ diagonal : bool, optional
818
+ If ``True``, it includes the diagonal elements.
819
+
820
+ check_symmetry : bool, optional
821
+ If ``True``, it checks whether the matrix is symmetric.
822
+
823
+ Examples
824
+ ========
825
+
826
+ >>> from sympy import Matrix
827
+ >>> m=Matrix([[1, 2], [2, 3]])
828
+ >>> m
829
+ Matrix([
830
+ [1, 2],
831
+ [2, 3]])
832
+ >>> m.vech()
833
+ Matrix([
834
+ [1],
835
+ [2],
836
+ [3]])
837
+ >>> m.vech(diagonal=False)
838
+ Matrix([[2]])
839
+
840
+ Notes
841
+ =====
842
+
843
+ This should work for symmetric matrices and ``vech`` can
844
+ represent symmetric matrices in vector form with less size than
845
+ ``vec``.
846
+
847
+ See Also
848
+ ========
849
+
850
+ vec
851
+ """
852
+ if not self.is_square:
853
+ raise NonSquareMatrixError
854
+
855
+ if check_symmetry and not self.is_symmetric():
856
+ raise ValueError("The matrix is not symmetric.")
857
+
858
+ return self._eval_vech(diagonal)
859
+
860
+ @classmethod
861
+ def vstack(cls, *args):
862
+ """Return a matrix formed by joining args vertically (i.e.
863
+ by repeated application of col_join).
864
+
865
+ Examples
866
+ ========
867
+
868
+ >>> from sympy import Matrix, eye
869
+ >>> Matrix.vstack(eye(2), 2*eye(2))
870
+ Matrix([
871
+ [1, 0],
872
+ [0, 1],
873
+ [2, 0],
874
+ [0, 2]])
875
+ """
876
+ if len(args) == 0:
877
+ return cls._new()
878
+
879
+ kls = type(args[0])
880
+ return reduce(kls.col_join, args)
881
+
882
+
883
+ class MatrixSpecial(MatrixRequired):
884
+ """Construction of special matrices"""
885
+
886
+ @classmethod
887
+ def _eval_diag(cls, rows, cols, diag_dict):
888
+ """diag_dict is a defaultdict containing
889
+ all the entries of the diagonal matrix."""
890
+ def entry(i, j):
891
+ return diag_dict[(i, j)]
892
+ return cls._new(rows, cols, entry)
893
+
894
+ @classmethod
895
+ def _eval_eye(cls, rows, cols):
896
+ vals = [cls.zero]*(rows*cols)
897
+ vals[::cols+1] = [cls.one]*min(rows, cols)
898
+ return cls._new(rows, cols, vals, copy=False)
899
+
900
+ @classmethod
901
+ def _eval_jordan_block(cls, size: int, eigenvalue, band='upper'):
902
+ if band == 'lower':
903
+ def entry(i, j):
904
+ if i == j:
905
+ return eigenvalue
906
+ elif j + 1 == i:
907
+ return cls.one
908
+ return cls.zero
909
+ else:
910
+ def entry(i, j):
911
+ if i == j:
912
+ return eigenvalue
913
+ elif i + 1 == j:
914
+ return cls.one
915
+ return cls.zero
916
+ return cls._new(size, size, entry)
917
+
918
+ @classmethod
919
+ def _eval_ones(cls, rows, cols):
920
+ def entry(i, j):
921
+ return cls.one
922
+ return cls._new(rows, cols, entry)
923
+
924
+ @classmethod
925
+ def _eval_zeros(cls, rows, cols):
926
+ return cls._new(rows, cols, [cls.zero]*(rows*cols), copy=False)
927
+
928
+ @classmethod
929
+ def _eval_wilkinson(cls, n):
930
+ def entry(i, j):
931
+ return cls.one if i + 1 == j else cls.zero
932
+
933
+ D = cls._new(2*n + 1, 2*n + 1, entry)
934
+
935
+ wminus = cls.diag(list(range(-n, n + 1)), unpack=True) + D + D.T
936
+ wplus = abs(cls.diag(list(range(-n, n + 1)), unpack=True)) + D + D.T
937
+
938
+ return wminus, wplus
939
+
940
+ @classmethod
941
+ def diag(kls, *args, strict=False, unpack=True, rows=None, cols=None, **kwargs):
942
+ """Returns a matrix with the specified diagonal.
943
+ If matrices are passed, a block-diagonal matrix
944
+ is created (i.e. the "direct sum" of the matrices).
945
+
946
+ kwargs
947
+ ======
948
+
949
+ rows : rows of the resulting matrix; computed if
950
+ not given.
951
+
952
+ cols : columns of the resulting matrix; computed if
953
+ not given.
954
+
955
+ cls : class for the resulting matrix
956
+
957
+ unpack : bool which, when True (default), unpacks a single
958
+ sequence rather than interpreting it as a Matrix.
959
+
960
+ strict : bool which, when False (default), allows Matrices to
961
+ have variable-length rows.
962
+
963
+ Examples
964
+ ========
965
+
966
+ >>> from sympy import Matrix
967
+ >>> Matrix.diag(1, 2, 3)
968
+ Matrix([
969
+ [1, 0, 0],
970
+ [0, 2, 0],
971
+ [0, 0, 3]])
972
+
973
+ The current default is to unpack a single sequence. If this is
974
+ not desired, set `unpack=False` and it will be interpreted as
975
+ a matrix.
976
+
977
+ >>> Matrix.diag([1, 2, 3]) == Matrix.diag(1, 2, 3)
978
+ True
979
+
980
+ When more than one element is passed, each is interpreted as
981
+ something to put on the diagonal. Lists are converted to
982
+ matrices. Filling of the diagonal always continues from
983
+ the bottom right hand corner of the previous item: this
984
+ will create a block-diagonal matrix whether the matrices
985
+ are square or not.
986
+
987
+ >>> col = [1, 2, 3]
988
+ >>> row = [[4, 5]]
989
+ >>> Matrix.diag(col, row)
990
+ Matrix([
991
+ [1, 0, 0],
992
+ [2, 0, 0],
993
+ [3, 0, 0],
994
+ [0, 4, 5]])
995
+
996
+ When `unpack` is False, elements within a list need not all be
997
+ of the same length. Setting `strict` to True would raise a
998
+ ValueError for the following:
999
+
1000
+ >>> Matrix.diag([[1, 2, 3], [4, 5], [6]], unpack=False)
1001
+ Matrix([
1002
+ [1, 2, 3],
1003
+ [4, 5, 0],
1004
+ [6, 0, 0]])
1005
+
1006
+ The type of the returned matrix can be set with the ``cls``
1007
+ keyword.
1008
+
1009
+ >>> from sympy import ImmutableMatrix
1010
+ >>> from sympy.utilities.misc import func_name
1011
+ >>> func_name(Matrix.diag(1, cls=ImmutableMatrix))
1012
+ 'ImmutableDenseMatrix'
1013
+
1014
+ A zero dimension matrix can be used to position the start of
1015
+ the filling at the start of an arbitrary row or column:
1016
+
1017
+ >>> from sympy import ones
1018
+ >>> r2 = ones(0, 2)
1019
+ >>> Matrix.diag(r2, 1, 2)
1020
+ Matrix([
1021
+ [0, 0, 1, 0],
1022
+ [0, 0, 0, 2]])
1023
+
1024
+ See Also
1025
+ ========
1026
+ eye
1027
+ diagonal
1028
+ .dense.diag
1029
+ .expressions.blockmatrix.BlockMatrix
1030
+ .sparsetools.banded
1031
+ """
1032
+ from sympy.matrices.matrixbase import MatrixBase
1033
+ from sympy.matrices.dense import Matrix
1034
+ from sympy.matrices import SparseMatrix
1035
+ klass = kwargs.get('cls', kls)
1036
+ if unpack and len(args) == 1 and is_sequence(args[0]) and \
1037
+ not isinstance(args[0], MatrixBase):
1038
+ args = args[0]
1039
+
1040
+ # fill a default dict with the diagonal entries
1041
+ diag_entries = defaultdict(int)
1042
+ rmax = cmax = 0 # keep track of the biggest index seen
1043
+ for m in args:
1044
+ if isinstance(m, list):
1045
+ if strict:
1046
+ # if malformed, Matrix will raise an error
1047
+ _ = Matrix(m)
1048
+ r, c = _.shape
1049
+ m = _.tolist()
1050
+ else:
1051
+ r, c, smat = SparseMatrix._handle_creation_inputs(m)
1052
+ for (i, j), _ in smat.items():
1053
+ diag_entries[(i + rmax, j + cmax)] = _
1054
+ m = [] # to skip process below
1055
+ elif hasattr(m, 'shape'): # a Matrix
1056
+ # convert to list of lists
1057
+ r, c = m.shape
1058
+ m = m.tolist()
1059
+ else: # in this case, we're a single value
1060
+ diag_entries[(rmax, cmax)] = m
1061
+ rmax += 1
1062
+ cmax += 1
1063
+ continue
1064
+ # process list of lists
1065
+ for i, mi in enumerate(m):
1066
+ for j, _ in enumerate(mi):
1067
+ diag_entries[(i + rmax, j + cmax)] = _
1068
+ rmax += r
1069
+ cmax += c
1070
+ if rows is None:
1071
+ rows, cols = cols, rows
1072
+ if rows is None:
1073
+ rows, cols = rmax, cmax
1074
+ else:
1075
+ cols = rows if cols is None else cols
1076
+ if rows < rmax or cols < cmax:
1077
+ raise ValueError(filldedent('''
1078
+ The constructed matrix is {} x {} but a size of {} x {}
1079
+ was specified.'''.format(rmax, cmax, rows, cols)))
1080
+ return klass._eval_diag(rows, cols, diag_entries)
1081
+
1082
+ @classmethod
1083
+ def eye(kls, rows, cols=None, **kwargs):
1084
+ """Returns an identity matrix.
1085
+
1086
+ Parameters
1087
+ ==========
1088
+
1089
+ rows : rows of the matrix
1090
+ cols : cols of the matrix (if None, cols=rows)
1091
+
1092
+ kwargs
1093
+ ======
1094
+ cls : class of the returned matrix
1095
+ """
1096
+ if cols is None:
1097
+ cols = rows
1098
+ if rows < 0 or cols < 0:
1099
+ raise ValueError("Cannot create a {} x {} matrix. "
1100
+ "Both dimensions must be positive".format(rows, cols))
1101
+ klass = kwargs.get('cls', kls)
1102
+ rows, cols = as_int(rows), as_int(cols)
1103
+
1104
+ return klass._eval_eye(rows, cols)
1105
+
1106
+ @classmethod
1107
+ def jordan_block(kls, size=None, eigenvalue=None, *, band='upper', **kwargs):
1108
+ """Returns a Jordan block
1109
+
1110
+ Parameters
1111
+ ==========
1112
+
1113
+ size : Integer, optional
1114
+ Specifies the shape of the Jordan block matrix.
1115
+
1116
+ eigenvalue : Number or Symbol
1117
+ Specifies the value for the main diagonal of the matrix.
1118
+
1119
+ .. note::
1120
+ The keyword ``eigenval`` is also specified as an alias
1121
+ of this keyword, but it is not recommended to use.
1122
+
1123
+ We may deprecate the alias in later release.
1124
+
1125
+ band : 'upper' or 'lower', optional
1126
+ Specifies the position of the off-diagonal to put `1` s on.
1127
+
1128
+ cls : Matrix, optional
1129
+ Specifies the matrix class of the output form.
1130
+
1131
+ If it is not specified, the class type where the method is
1132
+ being executed on will be returned.
1133
+
1134
+ Returns
1135
+ =======
1136
+
1137
+ Matrix
1138
+ A Jordan block matrix.
1139
+
1140
+ Raises
1141
+ ======
1142
+
1143
+ ValueError
1144
+ If insufficient arguments are given for matrix size
1145
+ specification, or no eigenvalue is given.
1146
+
1147
+ Examples
1148
+ ========
1149
+
1150
+ Creating a default Jordan block:
1151
+
1152
+ >>> from sympy import Matrix
1153
+ >>> from sympy.abc import x
1154
+ >>> Matrix.jordan_block(4, x)
1155
+ Matrix([
1156
+ [x, 1, 0, 0],
1157
+ [0, x, 1, 0],
1158
+ [0, 0, x, 1],
1159
+ [0, 0, 0, x]])
1160
+
1161
+ Creating an alternative Jordan block matrix where `1` is on
1162
+ lower off-diagonal:
1163
+
1164
+ >>> Matrix.jordan_block(4, x, band='lower')
1165
+ Matrix([
1166
+ [x, 0, 0, 0],
1167
+ [1, x, 0, 0],
1168
+ [0, 1, x, 0],
1169
+ [0, 0, 1, x]])
1170
+
1171
+ Creating a Jordan block with keyword arguments
1172
+
1173
+ >>> Matrix.jordan_block(size=4, eigenvalue=x)
1174
+ Matrix([
1175
+ [x, 1, 0, 0],
1176
+ [0, x, 1, 0],
1177
+ [0, 0, x, 1],
1178
+ [0, 0, 0, x]])
1179
+
1180
+ References
1181
+ ==========
1182
+
1183
+ .. [1] https://en.wikipedia.org/wiki/Jordan_matrix
1184
+ """
1185
+ klass = kwargs.pop('cls', kls)
1186
+
1187
+ eigenval = kwargs.get('eigenval', None)
1188
+ if eigenvalue is None and eigenval is None:
1189
+ raise ValueError("Must supply an eigenvalue")
1190
+ elif eigenvalue != eigenval and None not in (eigenval, eigenvalue):
1191
+ raise ValueError(
1192
+ "Inconsistent values are given: 'eigenval'={}, "
1193
+ "'eigenvalue'={}".format(eigenval, eigenvalue))
1194
+ else:
1195
+ if eigenval is not None:
1196
+ eigenvalue = eigenval
1197
+
1198
+ if size is None:
1199
+ raise ValueError("Must supply a matrix size")
1200
+
1201
+ size = as_int(size)
1202
+ return klass._eval_jordan_block(size, eigenvalue, band)
1203
+
1204
+ @classmethod
1205
+ def ones(kls, rows, cols=None, **kwargs):
1206
+ """Returns a matrix of ones.
1207
+
1208
+ Parameters
1209
+ ==========
1210
+
1211
+ rows : rows of the matrix
1212
+ cols : cols of the matrix (if None, cols=rows)
1213
+
1214
+ kwargs
1215
+ ======
1216
+ cls : class of the returned matrix
1217
+ """
1218
+ if cols is None:
1219
+ cols = rows
1220
+ klass = kwargs.get('cls', kls)
1221
+ rows, cols = as_int(rows), as_int(cols)
1222
+
1223
+ return klass._eval_ones(rows, cols)
1224
+
1225
+ @classmethod
1226
+ def zeros(kls, rows, cols=None, **kwargs):
1227
+ """Returns a matrix of zeros.
1228
+
1229
+ Parameters
1230
+ ==========
1231
+
1232
+ rows : rows of the matrix
1233
+ cols : cols of the matrix (if None, cols=rows)
1234
+
1235
+ kwargs
1236
+ ======
1237
+ cls : class of the returned matrix
1238
+ """
1239
+ if cols is None:
1240
+ cols = rows
1241
+ if rows < 0 or cols < 0:
1242
+ raise ValueError("Cannot create a {} x {} matrix. "
1243
+ "Both dimensions must be positive".format(rows, cols))
1244
+ klass = kwargs.get('cls', kls)
1245
+ rows, cols = as_int(rows), as_int(cols)
1246
+
1247
+ return klass._eval_zeros(rows, cols)
1248
+
1249
+ @classmethod
1250
+ def companion(kls, poly):
1251
+ """Returns a companion matrix of a polynomial.
1252
+
1253
+ Examples
1254
+ ========
1255
+
1256
+ >>> from sympy import Matrix, Poly, Symbol, symbols
1257
+ >>> x = Symbol('x')
1258
+ >>> c0, c1, c2, c3, c4 = symbols('c0:5')
1259
+ >>> p = Poly(c0 + c1*x + c2*x**2 + c3*x**3 + c4*x**4 + x**5, x)
1260
+ >>> Matrix.companion(p)
1261
+ Matrix([
1262
+ [0, 0, 0, 0, -c0],
1263
+ [1, 0, 0, 0, -c1],
1264
+ [0, 1, 0, 0, -c2],
1265
+ [0, 0, 1, 0, -c3],
1266
+ [0, 0, 0, 1, -c4]])
1267
+ """
1268
+ poly = kls._sympify(poly)
1269
+ if not isinstance(poly, Poly):
1270
+ raise ValueError("{} must be a Poly instance.".format(poly))
1271
+ if not poly.is_monic:
1272
+ raise ValueError("{} must be a monic polynomial.".format(poly))
1273
+ if not poly.is_univariate:
1274
+ raise ValueError(
1275
+ "{} must be a univariate polynomial.".format(poly))
1276
+
1277
+ size = poly.degree()
1278
+ if not size >= 1:
1279
+ raise ValueError(
1280
+ "{} must have degree not less than 1.".format(poly))
1281
+
1282
+ coeffs = poly.all_coeffs()
1283
+ def entry(i, j):
1284
+ if j == size - 1:
1285
+ return -coeffs[-1 - i]
1286
+ elif i == j + 1:
1287
+ return kls.one
1288
+ return kls.zero
1289
+ return kls._new(size, size, entry)
1290
+
1291
+
1292
+ @classmethod
1293
+ def wilkinson(kls, n, **kwargs):
1294
+ """Returns two square Wilkinson Matrix of size 2*n + 1
1295
+ $W_{2n + 1}^-, W_{2n + 1}^+ =$ Wilkinson(n)
1296
+
1297
+ Examples
1298
+ ========
1299
+
1300
+ >>> from sympy import Matrix
1301
+ >>> wminus, wplus = Matrix.wilkinson(3)
1302
+ >>> wminus
1303
+ Matrix([
1304
+ [-3, 1, 0, 0, 0, 0, 0],
1305
+ [ 1, -2, 1, 0, 0, 0, 0],
1306
+ [ 0, 1, -1, 1, 0, 0, 0],
1307
+ [ 0, 0, 1, 0, 1, 0, 0],
1308
+ [ 0, 0, 0, 1, 1, 1, 0],
1309
+ [ 0, 0, 0, 0, 1, 2, 1],
1310
+ [ 0, 0, 0, 0, 0, 1, 3]])
1311
+ >>> wplus
1312
+ Matrix([
1313
+ [3, 1, 0, 0, 0, 0, 0],
1314
+ [1, 2, 1, 0, 0, 0, 0],
1315
+ [0, 1, 1, 1, 0, 0, 0],
1316
+ [0, 0, 1, 0, 1, 0, 0],
1317
+ [0, 0, 0, 1, 1, 1, 0],
1318
+ [0, 0, 0, 0, 1, 2, 1],
1319
+ [0, 0, 0, 0, 0, 1, 3]])
1320
+
1321
+ References
1322
+ ==========
1323
+
1324
+ .. [1] https://blogs.mathworks.com/cleve/2013/04/15/wilkinsons-matrices-2/
1325
+ .. [2] J. H. Wilkinson, The Algebraic Eigenvalue Problem, Claredon Press, Oxford, 1965, 662 pp.
1326
+
1327
+ """
1328
+ klass = kwargs.get('cls', kls)
1329
+ n = as_int(n)
1330
+ return klass._eval_wilkinson(n)
1331
+
1332
+ class MatrixProperties(MatrixRequired):
1333
+ """Provides basic properties of a matrix."""
1334
+
1335
+ def _eval_atoms(self, *types):
1336
+ result = set()
1337
+ for i in self:
1338
+ result.update(i.atoms(*types))
1339
+ return result
1340
+
1341
+ def _eval_free_symbols(self):
1342
+ return set().union(*(i.free_symbols for i in self if i))
1343
+
1344
+ def _eval_has(self, *patterns):
1345
+ return any(a.has(*patterns) for a in self)
1346
+
1347
+ def _eval_is_anti_symmetric(self, simpfunc):
1348
+ if not all(simpfunc(self[i, j] + self[j, i]).is_zero for i in range(self.rows) for j in range(self.cols)):
1349
+ return False
1350
+ return True
1351
+
1352
+ def _eval_is_diagonal(self):
1353
+ for i in range(self.rows):
1354
+ for j in range(self.cols):
1355
+ if i != j and self[i, j]:
1356
+ return False
1357
+ return True
1358
+
1359
+ # _eval_is_hermitian is called by some general SymPy
1360
+ # routines and has a different *args signature. Make
1361
+ # sure the names don't clash by adding `_matrix_` in name.
1362
+ def _eval_is_matrix_hermitian(self, simpfunc):
1363
+ mat = self._new(self.rows, self.cols, lambda i, j: simpfunc(self[i, j] - self[j, i].conjugate()))
1364
+ return mat.is_zero_matrix
1365
+
1366
+ def _eval_is_Identity(self) -> FuzzyBool:
1367
+ def dirac(i, j):
1368
+ if i == j:
1369
+ return 1
1370
+ return 0
1371
+
1372
+ return all(self[i, j] == dirac(i, j)
1373
+ for i in range(self.rows)
1374
+ for j in range(self.cols))
1375
+
1376
+ def _eval_is_lower_hessenberg(self):
1377
+ return all(self[i, j].is_zero
1378
+ for i in range(self.rows)
1379
+ for j in range(i + 2, self.cols))
1380
+
1381
+ def _eval_is_lower(self):
1382
+ return all(self[i, j].is_zero
1383
+ for i in range(self.rows)
1384
+ for j in range(i + 1, self.cols))
1385
+
1386
+ def _eval_is_symbolic(self):
1387
+ return self.has(Symbol)
1388
+
1389
+ def _eval_is_symmetric(self, simpfunc):
1390
+ mat = self._new(self.rows, self.cols, lambda i, j: simpfunc(self[i, j] - self[j, i]))
1391
+ return mat.is_zero_matrix
1392
+
1393
+ def _eval_is_zero_matrix(self):
1394
+ if any(i.is_zero == False for i in self):
1395
+ return False
1396
+ if any(i.is_zero is None for i in self):
1397
+ return None
1398
+ return True
1399
+
1400
+ def _eval_is_upper_hessenberg(self):
1401
+ return all(self[i, j].is_zero
1402
+ for i in range(2, self.rows)
1403
+ for j in range(min(self.cols, (i - 1))))
1404
+
1405
+ def _eval_values(self):
1406
+ return [i for i in self if not i.is_zero]
1407
+
1408
+ def _has_positive_diagonals(self):
1409
+ diagonal_entries = (self[i, i] for i in range(self.rows))
1410
+ return fuzzy_and(x.is_positive for x in diagonal_entries)
1411
+
1412
+ def _has_nonnegative_diagonals(self):
1413
+ diagonal_entries = (self[i, i] for i in range(self.rows))
1414
+ return fuzzy_and(x.is_nonnegative for x in diagonal_entries)
1415
+
1416
+ def atoms(self, *types):
1417
+ """Returns the atoms that form the current object.
1418
+
1419
+ Examples
1420
+ ========
1421
+
1422
+ >>> from sympy.abc import x, y
1423
+ >>> from sympy import Matrix
1424
+ >>> Matrix([[x]])
1425
+ Matrix([[x]])
1426
+ >>> _.atoms()
1427
+ {x}
1428
+ >>> Matrix([[x, y], [y, x]])
1429
+ Matrix([
1430
+ [x, y],
1431
+ [y, x]])
1432
+ >>> _.atoms()
1433
+ {x, y}
1434
+ """
1435
+
1436
+ types = tuple(t if isinstance(t, type) else type(t) for t in types)
1437
+ if not types:
1438
+ types = (Atom,)
1439
+ return self._eval_atoms(*types)
1440
+
1441
+ @property
1442
+ def free_symbols(self):
1443
+ """Returns the free symbols within the matrix.
1444
+
1445
+ Examples
1446
+ ========
1447
+
1448
+ >>> from sympy.abc import x
1449
+ >>> from sympy import Matrix
1450
+ >>> Matrix([[x], [1]]).free_symbols
1451
+ {x}
1452
+ """
1453
+ return self._eval_free_symbols()
1454
+
1455
+ def has(self, *patterns):
1456
+ """Test whether any subexpression matches any of the patterns.
1457
+
1458
+ Examples
1459
+ ========
1460
+
1461
+ >>> from sympy import Matrix, SparseMatrix, Float
1462
+ >>> from sympy.abc import x, y
1463
+ >>> A = Matrix(((1, x), (0.2, 3)))
1464
+ >>> B = SparseMatrix(((1, x), (0.2, 3)))
1465
+ >>> A.has(x)
1466
+ True
1467
+ >>> A.has(y)
1468
+ False
1469
+ >>> A.has(Float)
1470
+ True
1471
+ >>> B.has(x)
1472
+ True
1473
+ >>> B.has(y)
1474
+ False
1475
+ >>> B.has(Float)
1476
+ True
1477
+ """
1478
+ return self._eval_has(*patterns)
1479
+
1480
+ def is_anti_symmetric(self, simplify=True):
1481
+ """Check if matrix M is an antisymmetric matrix,
1482
+ that is, M is a square matrix with all M[i, j] == -M[j, i].
1483
+
1484
+ When ``simplify=True`` (default), the sum M[i, j] + M[j, i] is
1485
+ simplified before testing to see if it is zero. By default,
1486
+ the SymPy simplify function is used. To use a custom function
1487
+ set simplify to a function that accepts a single argument which
1488
+ returns a simplified expression. To skip simplification, set
1489
+ simplify to False but note that although this will be faster,
1490
+ it may induce false negatives.
1491
+
1492
+ Examples
1493
+ ========
1494
+
1495
+ >>> from sympy import Matrix, symbols
1496
+ >>> m = Matrix(2, 2, [0, 1, -1, 0])
1497
+ >>> m
1498
+ Matrix([
1499
+ [ 0, 1],
1500
+ [-1, 0]])
1501
+ >>> m.is_anti_symmetric()
1502
+ True
1503
+ >>> x, y = symbols('x y')
1504
+ >>> m = Matrix(2, 3, [0, 0, x, -y, 0, 0])
1505
+ >>> m
1506
+ Matrix([
1507
+ [ 0, 0, x],
1508
+ [-y, 0, 0]])
1509
+ >>> m.is_anti_symmetric()
1510
+ False
1511
+
1512
+ >>> from sympy.abc import x, y
1513
+ >>> m = Matrix(3, 3, [0, x**2 + 2*x + 1, y,
1514
+ ... -(x + 1)**2, 0, x*y,
1515
+ ... -y, -x*y, 0])
1516
+
1517
+ Simplification of matrix elements is done by default so even
1518
+ though two elements which should be equal and opposite would not
1519
+ pass an equality test, the matrix is still reported as
1520
+ anti-symmetric:
1521
+
1522
+ >>> m[0, 1] == -m[1, 0]
1523
+ False
1524
+ >>> m.is_anti_symmetric()
1525
+ True
1526
+
1527
+ If ``simplify=False`` is used for the case when a Matrix is already
1528
+ simplified, this will speed things up. Here, we see that without
1529
+ simplification the matrix does not appear anti-symmetric:
1530
+
1531
+ >>> print(m.is_anti_symmetric(simplify=False))
1532
+ None
1533
+
1534
+ But if the matrix were already expanded, then it would appear
1535
+ anti-symmetric and simplification in the is_anti_symmetric routine
1536
+ is not needed:
1537
+
1538
+ >>> m = m.expand()
1539
+ >>> m.is_anti_symmetric(simplify=False)
1540
+ True
1541
+ """
1542
+ # accept custom simplification
1543
+ simpfunc = simplify
1544
+ if not isfunction(simplify):
1545
+ simpfunc = _simplify if simplify else lambda x: x
1546
+
1547
+ if not self.is_square:
1548
+ return False
1549
+ return self._eval_is_anti_symmetric(simpfunc)
1550
+
1551
+ def is_diagonal(self):
1552
+ """Check if matrix is diagonal,
1553
+ that is matrix in which the entries outside the main diagonal are all zero.
1554
+
1555
+ Examples
1556
+ ========
1557
+
1558
+ >>> from sympy import Matrix, diag
1559
+ >>> m = Matrix(2, 2, [1, 0, 0, 2])
1560
+ >>> m
1561
+ Matrix([
1562
+ [1, 0],
1563
+ [0, 2]])
1564
+ >>> m.is_diagonal()
1565
+ True
1566
+
1567
+ >>> m = Matrix(2, 2, [1, 1, 0, 2])
1568
+ >>> m
1569
+ Matrix([
1570
+ [1, 1],
1571
+ [0, 2]])
1572
+ >>> m.is_diagonal()
1573
+ False
1574
+
1575
+ >>> m = diag(1, 2, 3)
1576
+ >>> m
1577
+ Matrix([
1578
+ [1, 0, 0],
1579
+ [0, 2, 0],
1580
+ [0, 0, 3]])
1581
+ >>> m.is_diagonal()
1582
+ True
1583
+
1584
+ See Also
1585
+ ========
1586
+
1587
+ is_lower
1588
+ is_upper
1589
+ sympy.matrices.matrixbase.MatrixCommon.is_diagonalizable
1590
+ diagonalize
1591
+ """
1592
+ return self._eval_is_diagonal()
1593
+
1594
+ @property
1595
+ def is_weakly_diagonally_dominant(self):
1596
+ r"""Tests if the matrix is row weakly diagonally dominant.
1597
+
1598
+ Explanation
1599
+ ===========
1600
+
1601
+ A $n, n$ matrix $A$ is row weakly diagonally dominant if
1602
+
1603
+ .. math::
1604
+ \left|A_{i, i}\right| \ge \sum_{j = 0, j \neq i}^{n-1}
1605
+ \left|A_{i, j}\right| \quad {\text{for all }}
1606
+ i \in \{ 0, ..., n-1 \}
1607
+
1608
+ Examples
1609
+ ========
1610
+
1611
+ >>> from sympy import Matrix
1612
+ >>> A = Matrix([[3, -2, 1], [1, -3, 2], [-1, 2, 4]])
1613
+ >>> A.is_weakly_diagonally_dominant
1614
+ True
1615
+
1616
+ >>> A = Matrix([[-2, 2, 1], [1, 3, 2], [1, -2, 0]])
1617
+ >>> A.is_weakly_diagonally_dominant
1618
+ False
1619
+
1620
+ >>> A = Matrix([[-4, 2, 1], [1, 6, 2], [1, -2, 5]])
1621
+ >>> A.is_weakly_diagonally_dominant
1622
+ True
1623
+
1624
+ Notes
1625
+ =====
1626
+
1627
+ If you want to test whether a matrix is column diagonally
1628
+ dominant, you can apply the test after transposing the matrix.
1629
+ """
1630
+ if not self.is_square:
1631
+ return False
1632
+
1633
+ rows, cols = self.shape
1634
+
1635
+ def test_row(i):
1636
+ summation = self.zero
1637
+ for j in range(cols):
1638
+ if i != j:
1639
+ summation += Abs(self[i, j])
1640
+ return (Abs(self[i, i]) - summation).is_nonnegative
1641
+
1642
+ return fuzzy_and(test_row(i) for i in range(rows))
1643
+
1644
+ @property
1645
+ def is_strongly_diagonally_dominant(self):
1646
+ r"""Tests if the matrix is row strongly diagonally dominant.
1647
+
1648
+ Explanation
1649
+ ===========
1650
+
1651
+ A $n, n$ matrix $A$ is row strongly diagonally dominant if
1652
+
1653
+ .. math::
1654
+ \left|A_{i, i}\right| > \sum_{j = 0, j \neq i}^{n-1}
1655
+ \left|A_{i, j}\right| \quad {\text{for all }}
1656
+ i \in \{ 0, ..., n-1 \}
1657
+
1658
+ Examples
1659
+ ========
1660
+
1661
+ >>> from sympy import Matrix
1662
+ >>> A = Matrix([[3, -2, 1], [1, -3, 2], [-1, 2, 4]])
1663
+ >>> A.is_strongly_diagonally_dominant
1664
+ False
1665
+
1666
+ >>> A = Matrix([[-2, 2, 1], [1, 3, 2], [1, -2, 0]])
1667
+ >>> A.is_strongly_diagonally_dominant
1668
+ False
1669
+
1670
+ >>> A = Matrix([[-4, 2, 1], [1, 6, 2], [1, -2, 5]])
1671
+ >>> A.is_strongly_diagonally_dominant
1672
+ True
1673
+
1674
+ Notes
1675
+ =====
1676
+
1677
+ If you want to test whether a matrix is column diagonally
1678
+ dominant, you can apply the test after transposing the matrix.
1679
+ """
1680
+ if not self.is_square:
1681
+ return False
1682
+
1683
+ rows, cols = self.shape
1684
+
1685
+ def test_row(i):
1686
+ summation = self.zero
1687
+ for j in range(cols):
1688
+ if i != j:
1689
+ summation += Abs(self[i, j])
1690
+ return (Abs(self[i, i]) - summation).is_positive
1691
+
1692
+ return fuzzy_and(test_row(i) for i in range(rows))
1693
+
1694
+ @property
1695
+ def is_hermitian(self):
1696
+ """Checks if the matrix is Hermitian.
1697
+
1698
+ In a Hermitian matrix element i,j is the complex conjugate of
1699
+ element j,i.
1700
+
1701
+ Examples
1702
+ ========
1703
+
1704
+ >>> from sympy import Matrix
1705
+ >>> from sympy import I
1706
+ >>> from sympy.abc import x
1707
+ >>> a = Matrix([[1, I], [-I, 1]])
1708
+ >>> a
1709
+ Matrix([
1710
+ [ 1, I],
1711
+ [-I, 1]])
1712
+ >>> a.is_hermitian
1713
+ True
1714
+ >>> a[0, 0] = 2*I
1715
+ >>> a.is_hermitian
1716
+ False
1717
+ >>> a[0, 0] = x
1718
+ >>> a.is_hermitian
1719
+ >>> a[0, 1] = a[1, 0]*I
1720
+ >>> a.is_hermitian
1721
+ False
1722
+ """
1723
+ if not self.is_square:
1724
+ return False
1725
+
1726
+ return self._eval_is_matrix_hermitian(_simplify)
1727
+
1728
+ @property
1729
+ def is_Identity(self) -> FuzzyBool:
1730
+ if not self.is_square:
1731
+ return False
1732
+ return self._eval_is_Identity()
1733
+
1734
+ @property
1735
+ def is_lower_hessenberg(self):
1736
+ r"""Checks if the matrix is in the lower-Hessenberg form.
1737
+
1738
+ The lower hessenberg matrix has zero entries
1739
+ above the first superdiagonal.
1740
+
1741
+ Examples
1742
+ ========
1743
+
1744
+ >>> from sympy import Matrix
1745
+ >>> a = Matrix([[1, 2, 0, 0], [5, 2, 3, 0], [3, 4, 3, 7], [5, 6, 1, 1]])
1746
+ >>> a
1747
+ Matrix([
1748
+ [1, 2, 0, 0],
1749
+ [5, 2, 3, 0],
1750
+ [3, 4, 3, 7],
1751
+ [5, 6, 1, 1]])
1752
+ >>> a.is_lower_hessenberg
1753
+ True
1754
+
1755
+ See Also
1756
+ ========
1757
+
1758
+ is_upper_hessenberg
1759
+ is_lower
1760
+ """
1761
+ return self._eval_is_lower_hessenberg()
1762
+
1763
+ @property
1764
+ def is_lower(self):
1765
+ """Check if matrix is a lower triangular matrix. True can be returned
1766
+ even if the matrix is not square.
1767
+
1768
+ Examples
1769
+ ========
1770
+
1771
+ >>> from sympy import Matrix
1772
+ >>> m = Matrix(2, 2, [1, 0, 0, 1])
1773
+ >>> m
1774
+ Matrix([
1775
+ [1, 0],
1776
+ [0, 1]])
1777
+ >>> m.is_lower
1778
+ True
1779
+
1780
+ >>> m = Matrix(4, 3, [0, 0, 0, 2, 0, 0, 1, 4, 0, 6, 6, 5])
1781
+ >>> m
1782
+ Matrix([
1783
+ [0, 0, 0],
1784
+ [2, 0, 0],
1785
+ [1, 4, 0],
1786
+ [6, 6, 5]])
1787
+ >>> m.is_lower
1788
+ True
1789
+
1790
+ >>> from sympy.abc import x, y
1791
+ >>> m = Matrix(2, 2, [x**2 + y, y**2 + x, 0, x + y])
1792
+ >>> m
1793
+ Matrix([
1794
+ [x**2 + y, x + y**2],
1795
+ [ 0, x + y]])
1796
+ >>> m.is_lower
1797
+ False
1798
+
1799
+ See Also
1800
+ ========
1801
+
1802
+ is_upper
1803
+ is_diagonal
1804
+ is_lower_hessenberg
1805
+ """
1806
+ return self._eval_is_lower()
1807
+
1808
+ @property
1809
+ def is_square(self):
1810
+ """Checks if a matrix is square.
1811
+
1812
+ A matrix is square if the number of rows equals the number of columns.
1813
+ The empty matrix is square by definition, since the number of rows and
1814
+ the number of columns are both zero.
1815
+
1816
+ Examples
1817
+ ========
1818
+
1819
+ >>> from sympy import Matrix
1820
+ >>> a = Matrix([[1, 2, 3], [4, 5, 6]])
1821
+ >>> b = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
1822
+ >>> c = Matrix([])
1823
+ >>> a.is_square
1824
+ False
1825
+ >>> b.is_square
1826
+ True
1827
+ >>> c.is_square
1828
+ True
1829
+ """
1830
+ return self.rows == self.cols
1831
+
1832
+ def is_symbolic(self):
1833
+ """Checks if any elements contain Symbols.
1834
+
1835
+ Examples
1836
+ ========
1837
+
1838
+ >>> from sympy import Matrix
1839
+ >>> from sympy.abc import x, y
1840
+ >>> M = Matrix([[x, y], [1, 0]])
1841
+ >>> M.is_symbolic()
1842
+ True
1843
+
1844
+ """
1845
+ return self._eval_is_symbolic()
1846
+
1847
+ def is_symmetric(self, simplify=True):
1848
+ """Check if matrix is symmetric matrix,
1849
+ that is square matrix and is equal to its transpose.
1850
+
1851
+ By default, simplifications occur before testing symmetry.
1852
+ They can be skipped using 'simplify=False'; while speeding things a bit,
1853
+ this may however induce false negatives.
1854
+
1855
+ Examples
1856
+ ========
1857
+
1858
+ >>> from sympy import Matrix
1859
+ >>> m = Matrix(2, 2, [0, 1, 1, 2])
1860
+ >>> m
1861
+ Matrix([
1862
+ [0, 1],
1863
+ [1, 2]])
1864
+ >>> m.is_symmetric()
1865
+ True
1866
+
1867
+ >>> m = Matrix(2, 2, [0, 1, 2, 0])
1868
+ >>> m
1869
+ Matrix([
1870
+ [0, 1],
1871
+ [2, 0]])
1872
+ >>> m.is_symmetric()
1873
+ False
1874
+
1875
+ >>> m = Matrix(2, 3, [0, 0, 0, 0, 0, 0])
1876
+ >>> m
1877
+ Matrix([
1878
+ [0, 0, 0],
1879
+ [0, 0, 0]])
1880
+ >>> m.is_symmetric()
1881
+ False
1882
+
1883
+ >>> from sympy.abc import x, y
1884
+ >>> m = Matrix(3, 3, [1, x**2 + 2*x + 1, y, (x + 1)**2, 2, 0, y, 0, 3])
1885
+ >>> m
1886
+ Matrix([
1887
+ [ 1, x**2 + 2*x + 1, y],
1888
+ [(x + 1)**2, 2, 0],
1889
+ [ y, 0, 3]])
1890
+ >>> m.is_symmetric()
1891
+ True
1892
+
1893
+ If the matrix is already simplified, you may speed-up is_symmetric()
1894
+ test by using 'simplify=False'.
1895
+
1896
+ >>> bool(m.is_symmetric(simplify=False))
1897
+ False
1898
+ >>> m1 = m.expand()
1899
+ >>> m1.is_symmetric(simplify=False)
1900
+ True
1901
+ """
1902
+ simpfunc = simplify
1903
+ if not isfunction(simplify):
1904
+ simpfunc = _simplify if simplify else lambda x: x
1905
+
1906
+ if not self.is_square:
1907
+ return False
1908
+
1909
+ return self._eval_is_symmetric(simpfunc)
1910
+
1911
+ @property
1912
+ def is_upper_hessenberg(self):
1913
+ """Checks if the matrix is the upper-Hessenberg form.
1914
+
1915
+ The upper hessenberg matrix has zero entries
1916
+ below the first subdiagonal.
1917
+
1918
+ Examples
1919
+ ========
1920
+
1921
+ >>> from sympy import Matrix
1922
+ >>> a = Matrix([[1, 4, 2, 3], [3, 4, 1, 7], [0, 2, 3, 4], [0, 0, 1, 3]])
1923
+ >>> a
1924
+ Matrix([
1925
+ [1, 4, 2, 3],
1926
+ [3, 4, 1, 7],
1927
+ [0, 2, 3, 4],
1928
+ [0, 0, 1, 3]])
1929
+ >>> a.is_upper_hessenberg
1930
+ True
1931
+
1932
+ See Also
1933
+ ========
1934
+
1935
+ is_lower_hessenberg
1936
+ is_upper
1937
+ """
1938
+ return self._eval_is_upper_hessenberg()
1939
+
1940
+ @property
1941
+ def is_upper(self):
1942
+ """Check if matrix is an upper triangular matrix. True can be returned
1943
+ even if the matrix is not square.
1944
+
1945
+ Examples
1946
+ ========
1947
+
1948
+ >>> from sympy import Matrix
1949
+ >>> m = Matrix(2, 2, [1, 0, 0, 1])
1950
+ >>> m
1951
+ Matrix([
1952
+ [1, 0],
1953
+ [0, 1]])
1954
+ >>> m.is_upper
1955
+ True
1956
+
1957
+ >>> m = Matrix(4, 3, [5, 1, 9, 0, 4, 6, 0, 0, 5, 0, 0, 0])
1958
+ >>> m
1959
+ Matrix([
1960
+ [5, 1, 9],
1961
+ [0, 4, 6],
1962
+ [0, 0, 5],
1963
+ [0, 0, 0]])
1964
+ >>> m.is_upper
1965
+ True
1966
+
1967
+ >>> m = Matrix(2, 3, [4, 2, 5, 6, 1, 1])
1968
+ >>> m
1969
+ Matrix([
1970
+ [4, 2, 5],
1971
+ [6, 1, 1]])
1972
+ >>> m.is_upper
1973
+ False
1974
+
1975
+ See Also
1976
+ ========
1977
+
1978
+ is_lower
1979
+ is_diagonal
1980
+ is_upper_hessenberg
1981
+ """
1982
+ return all(self[i, j].is_zero
1983
+ for i in range(1, self.rows)
1984
+ for j in range(min(i, self.cols)))
1985
+
1986
+ @property
1987
+ def is_zero_matrix(self):
1988
+ """Checks if a matrix is a zero matrix.
1989
+
1990
+ A matrix is zero if every element is zero. A matrix need not be square
1991
+ to be considered zero. The empty matrix is zero by the principle of
1992
+ vacuous truth. For a matrix that may or may not be zero (e.g.
1993
+ contains a symbol), this will be None
1994
+
1995
+ Examples
1996
+ ========
1997
+
1998
+ >>> from sympy import Matrix, zeros
1999
+ >>> from sympy.abc import x
2000
+ >>> a = Matrix([[0, 0], [0, 0]])
2001
+ >>> b = zeros(3, 4)
2002
+ >>> c = Matrix([[0, 1], [0, 0]])
2003
+ >>> d = Matrix([])
2004
+ >>> e = Matrix([[x, 0], [0, 0]])
2005
+ >>> a.is_zero_matrix
2006
+ True
2007
+ >>> b.is_zero_matrix
2008
+ True
2009
+ >>> c.is_zero_matrix
2010
+ False
2011
+ >>> d.is_zero_matrix
2012
+ True
2013
+ >>> e.is_zero_matrix
2014
+ """
2015
+ return self._eval_is_zero_matrix()
2016
+
2017
+ def values(self):
2018
+ """Return non-zero values of self."""
2019
+ return self._eval_values()
2020
+
2021
+
2022
+ class MatrixOperations(MatrixRequired):
2023
+ """Provides basic matrix shape and elementwise
2024
+ operations. Should not be instantiated directly."""
2025
+
2026
+ def _eval_adjoint(self):
2027
+ return self.transpose().conjugate()
2028
+
2029
+ def _eval_applyfunc(self, f):
2030
+ out = self._new(self.rows, self.cols, [f(x) for x in self])
2031
+ return out
2032
+
2033
+ def _eval_as_real_imag(self): # type: ignore
2034
+ return (self.applyfunc(re), self.applyfunc(im))
2035
+
2036
+ def _eval_conjugate(self):
2037
+ return self.applyfunc(lambda x: x.conjugate())
2038
+
2039
+ def _eval_permute_cols(self, perm):
2040
+ # apply the permutation to a list
2041
+ mapping = list(perm)
2042
+
2043
+ def entry(i, j):
2044
+ return self[i, mapping[j]]
2045
+
2046
+ return self._new(self.rows, self.cols, entry)
2047
+
2048
+ def _eval_permute_rows(self, perm):
2049
+ # apply the permutation to a list
2050
+ mapping = list(perm)
2051
+
2052
+ def entry(i, j):
2053
+ return self[mapping[i], j]
2054
+
2055
+ return self._new(self.rows, self.cols, entry)
2056
+
2057
+ def _eval_trace(self):
2058
+ return sum(self[i, i] for i in range(self.rows))
2059
+
2060
+ def _eval_transpose(self):
2061
+ return self._new(self.cols, self.rows, lambda i, j: self[j, i])
2062
+
2063
+ def adjoint(self):
2064
+ """Conjugate transpose or Hermitian conjugation."""
2065
+ return self._eval_adjoint()
2066
+
2067
+ def applyfunc(self, f):
2068
+ """Apply a function to each element of the matrix.
2069
+
2070
+ Examples
2071
+ ========
2072
+
2073
+ >>> from sympy import Matrix
2074
+ >>> m = Matrix(2, 2, lambda i, j: i*2+j)
2075
+ >>> m
2076
+ Matrix([
2077
+ [0, 1],
2078
+ [2, 3]])
2079
+ >>> m.applyfunc(lambda i: 2*i)
2080
+ Matrix([
2081
+ [0, 2],
2082
+ [4, 6]])
2083
+
2084
+ """
2085
+ if not callable(f):
2086
+ raise TypeError("`f` must be callable.")
2087
+
2088
+ return self._eval_applyfunc(f)
2089
+
2090
+ def as_real_imag(self, deep=True, **hints):
2091
+ """Returns a tuple containing the (real, imaginary) part of matrix."""
2092
+ # XXX: Ignoring deep and hints...
2093
+ return self._eval_as_real_imag()
2094
+
2095
+ def conjugate(self):
2096
+ """Return the by-element conjugation.
2097
+
2098
+ Examples
2099
+ ========
2100
+
2101
+ >>> from sympy import SparseMatrix, I
2102
+ >>> a = SparseMatrix(((1, 2 + I), (3, 4), (I, -I)))
2103
+ >>> a
2104
+ Matrix([
2105
+ [1, 2 + I],
2106
+ [3, 4],
2107
+ [I, -I]])
2108
+ >>> a.C
2109
+ Matrix([
2110
+ [ 1, 2 - I],
2111
+ [ 3, 4],
2112
+ [-I, I]])
2113
+
2114
+ See Also
2115
+ ========
2116
+
2117
+ transpose: Matrix transposition
2118
+ H: Hermite conjugation
2119
+ sympy.matrices.matrixbase.MatrixBase.D: Dirac conjugation
2120
+ """
2121
+ return self._eval_conjugate()
2122
+
2123
+ def doit(self, **hints):
2124
+ return self.applyfunc(lambda x: x.doit(**hints))
2125
+
2126
+ def evalf(self, n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False):
2127
+ """Apply evalf() to each element of self."""
2128
+ options = {'subs':subs, 'maxn':maxn, 'chop':chop, 'strict':strict,
2129
+ 'quad':quad, 'verbose':verbose}
2130
+ return self.applyfunc(lambda i: i.evalf(n, **options))
2131
+
2132
+ def expand(self, deep=True, modulus=None, power_base=True, power_exp=True,
2133
+ mul=True, log=True, multinomial=True, basic=True, **hints):
2134
+ """Apply core.function.expand to each entry of the matrix.
2135
+
2136
+ Examples
2137
+ ========
2138
+
2139
+ >>> from sympy.abc import x
2140
+ >>> from sympy import Matrix
2141
+ >>> Matrix(1, 1, [x*(x+1)])
2142
+ Matrix([[x*(x + 1)]])
2143
+ >>> _.expand()
2144
+ Matrix([[x**2 + x]])
2145
+
2146
+ """
2147
+ return self.applyfunc(lambda x: x.expand(
2148
+ deep, modulus, power_base, power_exp, mul, log, multinomial, basic,
2149
+ **hints))
2150
+
2151
+ @property
2152
+ def H(self):
2153
+ """Return Hermite conjugate.
2154
+
2155
+ Examples
2156
+ ========
2157
+
2158
+ >>> from sympy import Matrix, I
2159
+ >>> m = Matrix((0, 1 + I, 2, 3))
2160
+ >>> m
2161
+ Matrix([
2162
+ [ 0],
2163
+ [1 + I],
2164
+ [ 2],
2165
+ [ 3]])
2166
+ >>> m.H
2167
+ Matrix([[0, 1 - I, 2, 3]])
2168
+
2169
+ See Also
2170
+ ========
2171
+
2172
+ conjugate: By-element conjugation
2173
+ sympy.matrices.matrixbase.MatrixBase.D: Dirac conjugation
2174
+ """
2175
+ return self.T.C
2176
+
2177
+ def permute(self, perm, orientation='rows', direction='forward'):
2178
+ r"""Permute the rows or columns of a matrix by the given list of
2179
+ swaps.
2180
+
2181
+ Parameters
2182
+ ==========
2183
+
2184
+ perm : Permutation, list, or list of lists
2185
+ A representation for the permutation.
2186
+
2187
+ If it is ``Permutation``, it is used directly with some
2188
+ resizing with respect to the matrix size.
2189
+
2190
+ If it is specified as list of lists,
2191
+ (e.g., ``[[0, 1], [0, 2]]``), then the permutation is formed
2192
+ from applying the product of cycles. The direction how the
2193
+ cyclic product is applied is described in below.
2194
+
2195
+ If it is specified as a list, the list should represent
2196
+ an array form of a permutation. (e.g., ``[1, 2, 0]``) which
2197
+ would would form the swapping function
2198
+ `0 \mapsto 1, 1 \mapsto 2, 2\mapsto 0`.
2199
+
2200
+ orientation : 'rows', 'cols'
2201
+ A flag to control whether to permute the rows or the columns
2202
+
2203
+ direction : 'forward', 'backward'
2204
+ A flag to control whether to apply the permutations from
2205
+ the start of the list first, or from the back of the list
2206
+ first.
2207
+
2208
+ For example, if the permutation specification is
2209
+ ``[[0, 1], [0, 2]]``,
2210
+
2211
+ If the flag is set to ``'forward'``, the cycle would be
2212
+ formed as `0 \mapsto 2, 2 \mapsto 1, 1 \mapsto 0`.
2213
+
2214
+ If the flag is set to ``'backward'``, the cycle would be
2215
+ formed as `0 \mapsto 1, 1 \mapsto 2, 2 \mapsto 0`.
2216
+
2217
+ If the argument ``perm`` is not in a form of list of lists,
2218
+ this flag takes no effect.
2219
+
2220
+ Examples
2221
+ ========
2222
+
2223
+ >>> from sympy import eye
2224
+ >>> M = eye(3)
2225
+ >>> M.permute([[0, 1], [0, 2]], orientation='rows', direction='forward')
2226
+ Matrix([
2227
+ [0, 0, 1],
2228
+ [1, 0, 0],
2229
+ [0, 1, 0]])
2230
+
2231
+ >>> from sympy import eye
2232
+ >>> M = eye(3)
2233
+ >>> M.permute([[0, 1], [0, 2]], orientation='rows', direction='backward')
2234
+ Matrix([
2235
+ [0, 1, 0],
2236
+ [0, 0, 1],
2237
+ [1, 0, 0]])
2238
+
2239
+ Notes
2240
+ =====
2241
+
2242
+ If a bijective function
2243
+ `\sigma : \mathbb{N}_0 \rightarrow \mathbb{N}_0` denotes the
2244
+ permutation.
2245
+
2246
+ If the matrix `A` is the matrix to permute, represented as
2247
+ a horizontal or a vertical stack of vectors:
2248
+
2249
+ .. math::
2250
+ A =
2251
+ \begin{bmatrix}
2252
+ a_0 \\ a_1 \\ \vdots \\ a_{n-1}
2253
+ \end{bmatrix} =
2254
+ \begin{bmatrix}
2255
+ \alpha_0 & \alpha_1 & \cdots & \alpha_{n-1}
2256
+ \end{bmatrix}
2257
+
2258
+ If the matrix `B` is the result, the permutation of matrix rows
2259
+ is defined as:
2260
+
2261
+ .. math::
2262
+ B := \begin{bmatrix}
2263
+ a_{\sigma(0)} \\ a_{\sigma(1)} \\ \vdots \\ a_{\sigma(n-1)}
2264
+ \end{bmatrix}
2265
+
2266
+ And the permutation of matrix columns is defined as:
2267
+
2268
+ .. math::
2269
+ B := \begin{bmatrix}
2270
+ \alpha_{\sigma(0)} & \alpha_{\sigma(1)} &
2271
+ \cdots & \alpha_{\sigma(n-1)}
2272
+ \end{bmatrix}
2273
+ """
2274
+ from sympy.combinatorics import Permutation
2275
+
2276
+ # allow british variants and `columns`
2277
+ if direction == 'forwards':
2278
+ direction = 'forward'
2279
+ if direction == 'backwards':
2280
+ direction = 'backward'
2281
+ if orientation == 'columns':
2282
+ orientation = 'cols'
2283
+
2284
+ if direction not in ('forward', 'backward'):
2285
+ raise TypeError("direction='{}' is an invalid kwarg. "
2286
+ "Try 'forward' or 'backward'".format(direction))
2287
+ if orientation not in ('rows', 'cols'):
2288
+ raise TypeError("orientation='{}' is an invalid kwarg. "
2289
+ "Try 'rows' or 'cols'".format(orientation))
2290
+
2291
+ if not isinstance(perm, (Permutation, Iterable)):
2292
+ raise ValueError(
2293
+ "{} must be a list, a list of lists, "
2294
+ "or a SymPy permutation object.".format(perm))
2295
+
2296
+ # ensure all swaps are in range
2297
+ max_index = self.rows if orientation == 'rows' else self.cols
2298
+ if not all(0 <= t <= max_index for t in flatten(list(perm))):
2299
+ raise IndexError("`swap` indices out of range.")
2300
+
2301
+ if perm and not isinstance(perm, Permutation) and \
2302
+ isinstance(perm[0], Iterable):
2303
+ if direction == 'forward':
2304
+ perm = list(reversed(perm))
2305
+ perm = Permutation(perm, size=max_index+1)
2306
+ else:
2307
+ perm = Permutation(perm, size=max_index+1)
2308
+
2309
+ if orientation == 'rows':
2310
+ return self._eval_permute_rows(perm)
2311
+ if orientation == 'cols':
2312
+ return self._eval_permute_cols(perm)
2313
+
2314
+ def permute_cols(self, swaps, direction='forward'):
2315
+ """Alias for
2316
+ ``self.permute(swaps, orientation='cols', direction=direction)``
2317
+
2318
+ See Also
2319
+ ========
2320
+
2321
+ permute
2322
+ """
2323
+ return self.permute(swaps, orientation='cols', direction=direction)
2324
+
2325
+ def permute_rows(self, swaps, direction='forward'):
2326
+ """Alias for
2327
+ ``self.permute(swaps, orientation='rows', direction=direction)``
2328
+
2329
+ See Also
2330
+ ========
2331
+
2332
+ permute
2333
+ """
2334
+ return self.permute(swaps, orientation='rows', direction=direction)
2335
+
2336
+ def refine(self, assumptions=True):
2337
+ """Apply refine to each element of the matrix.
2338
+
2339
+ Examples
2340
+ ========
2341
+
2342
+ >>> from sympy import Symbol, Matrix, Abs, sqrt, Q
2343
+ >>> x = Symbol('x')
2344
+ >>> Matrix([[Abs(x)**2, sqrt(x**2)],[sqrt(x**2), Abs(x)**2]])
2345
+ Matrix([
2346
+ [ Abs(x)**2, sqrt(x**2)],
2347
+ [sqrt(x**2), Abs(x)**2]])
2348
+ >>> _.refine(Q.real(x))
2349
+ Matrix([
2350
+ [ x**2, Abs(x)],
2351
+ [Abs(x), x**2]])
2352
+
2353
+ """
2354
+ return self.applyfunc(lambda x: refine(x, assumptions))
2355
+
2356
+ def replace(self, F, G, map=False, simultaneous=True, exact=None):
2357
+ """Replaces Function F in Matrix entries with Function G.
2358
+
2359
+ Examples
2360
+ ========
2361
+
2362
+ >>> from sympy import symbols, Function, Matrix
2363
+ >>> F, G = symbols('F, G', cls=Function)
2364
+ >>> M = Matrix(2, 2, lambda i, j: F(i+j)) ; M
2365
+ Matrix([
2366
+ [F(0), F(1)],
2367
+ [F(1), F(2)]])
2368
+ >>> N = M.replace(F,G)
2369
+ >>> N
2370
+ Matrix([
2371
+ [G(0), G(1)],
2372
+ [G(1), G(2)]])
2373
+ """
2374
+ return self.applyfunc(
2375
+ lambda x: x.replace(F, G, map=map, simultaneous=simultaneous, exact=exact))
2376
+
2377
+ def rot90(self, k=1):
2378
+ """Rotates Matrix by 90 degrees
2379
+
2380
+ Parameters
2381
+ ==========
2382
+
2383
+ k : int
2384
+ Specifies how many times the matrix is rotated by 90 degrees
2385
+ (clockwise when positive, counter-clockwise when negative).
2386
+
2387
+ Examples
2388
+ ========
2389
+
2390
+ >>> from sympy import Matrix, symbols
2391
+ >>> A = Matrix(2, 2, symbols('a:d'))
2392
+ >>> A
2393
+ Matrix([
2394
+ [a, b],
2395
+ [c, d]])
2396
+
2397
+ Rotating the matrix clockwise one time:
2398
+
2399
+ >>> A.rot90(1)
2400
+ Matrix([
2401
+ [c, a],
2402
+ [d, b]])
2403
+
2404
+ Rotating the matrix anticlockwise two times:
2405
+
2406
+ >>> A.rot90(-2)
2407
+ Matrix([
2408
+ [d, c],
2409
+ [b, a]])
2410
+ """
2411
+
2412
+ mod = k%4
2413
+ if mod == 0:
2414
+ return self
2415
+ if mod == 1:
2416
+ return self[::-1, ::].T
2417
+ if mod == 2:
2418
+ return self[::-1, ::-1]
2419
+ if mod == 3:
2420
+ return self[::, ::-1].T
2421
+
2422
+ def simplify(self, **kwargs):
2423
+ """Apply simplify to each element of the matrix.
2424
+
2425
+ Examples
2426
+ ========
2427
+
2428
+ >>> from sympy.abc import x, y
2429
+ >>> from sympy import SparseMatrix, sin, cos
2430
+ >>> SparseMatrix(1, 1, [x*sin(y)**2 + x*cos(y)**2])
2431
+ Matrix([[x*sin(y)**2 + x*cos(y)**2]])
2432
+ >>> _.simplify()
2433
+ Matrix([[x]])
2434
+ """
2435
+ return self.applyfunc(lambda x: x.simplify(**kwargs))
2436
+
2437
+ def subs(self, *args, **kwargs): # should mirror core.basic.subs
2438
+ """Return a new matrix with subs applied to each entry.
2439
+
2440
+ Examples
2441
+ ========
2442
+
2443
+ >>> from sympy.abc import x, y
2444
+ >>> from sympy import SparseMatrix, Matrix
2445
+ >>> SparseMatrix(1, 1, [x])
2446
+ Matrix([[x]])
2447
+ >>> _.subs(x, y)
2448
+ Matrix([[y]])
2449
+ >>> Matrix(_).subs(y, x)
2450
+ Matrix([[x]])
2451
+ """
2452
+
2453
+ if len(args) == 1 and not isinstance(args[0], (dict, set)) and iter(args[0]) and not is_sequence(args[0]):
2454
+ args = (list(args[0]),)
2455
+
2456
+ return self.applyfunc(lambda x: x.subs(*args, **kwargs))
2457
+
2458
+ def trace(self):
2459
+ """
2460
+ Returns the trace of a square matrix i.e. the sum of the
2461
+ diagonal elements.
2462
+
2463
+ Examples
2464
+ ========
2465
+
2466
+ >>> from sympy import Matrix
2467
+ >>> A = Matrix(2, 2, [1, 2, 3, 4])
2468
+ >>> A.trace()
2469
+ 5
2470
+
2471
+ """
2472
+ if self.rows != self.cols:
2473
+ raise NonSquareMatrixError()
2474
+ return self._eval_trace()
2475
+
2476
+ def transpose(self):
2477
+ """
2478
+ Returns the transpose of the matrix.
2479
+
2480
+ Examples
2481
+ ========
2482
+
2483
+ >>> from sympy import Matrix
2484
+ >>> A = Matrix(2, 2, [1, 2, 3, 4])
2485
+ >>> A.transpose()
2486
+ Matrix([
2487
+ [1, 3],
2488
+ [2, 4]])
2489
+
2490
+ >>> from sympy import Matrix, I
2491
+ >>> m=Matrix(((1, 2+I), (3, 4)))
2492
+ >>> m
2493
+ Matrix([
2494
+ [1, 2 + I],
2495
+ [3, 4]])
2496
+ >>> m.transpose()
2497
+ Matrix([
2498
+ [ 1, 3],
2499
+ [2 + I, 4]])
2500
+ >>> m.T == m.transpose()
2501
+ True
2502
+
2503
+ See Also
2504
+ ========
2505
+
2506
+ conjugate: By-element conjugation
2507
+
2508
+ """
2509
+ return self._eval_transpose()
2510
+
2511
+ @property
2512
+ def T(self):
2513
+ '''Matrix transposition'''
2514
+ return self.transpose()
2515
+
2516
+ @property
2517
+ def C(self):
2518
+ '''By-element conjugation'''
2519
+ return self.conjugate()
2520
+
2521
+ def n(self, *args, **kwargs):
2522
+ """Apply evalf() to each element of self."""
2523
+ return self.evalf(*args, **kwargs)
2524
+
2525
+ def xreplace(self, rule): # should mirror core.basic.xreplace
2526
+ """Return a new matrix with xreplace applied to each entry.
2527
+
2528
+ Examples
2529
+ ========
2530
+
2531
+ >>> from sympy.abc import x, y
2532
+ >>> from sympy import SparseMatrix, Matrix
2533
+ >>> SparseMatrix(1, 1, [x])
2534
+ Matrix([[x]])
2535
+ >>> _.xreplace({x: y})
2536
+ Matrix([[y]])
2537
+ >>> Matrix(_).xreplace({y: x})
2538
+ Matrix([[x]])
2539
+ """
2540
+ return self.applyfunc(lambda x: x.xreplace(rule))
2541
+
2542
+ def _eval_simplify(self, **kwargs):
2543
+ # XXX: We can't use self.simplify here as mutable subclasses will
2544
+ # override simplify and have it return None
2545
+ return MatrixOperations.simplify(self, **kwargs)
2546
+
2547
+ def _eval_trigsimp(self, **opts):
2548
+ from sympy.simplify.trigsimp import trigsimp
2549
+ return self.applyfunc(lambda x: trigsimp(x, **opts))
2550
+
2551
+ def upper_triangular(self, k=0):
2552
+ """Return the elements on and above the kth diagonal of a matrix.
2553
+ If k is not specified then simply returns upper-triangular portion
2554
+ of a matrix
2555
+
2556
+ Examples
2557
+ ========
2558
+
2559
+ >>> from sympy import ones
2560
+ >>> A = ones(4)
2561
+ >>> A.upper_triangular()
2562
+ Matrix([
2563
+ [1, 1, 1, 1],
2564
+ [0, 1, 1, 1],
2565
+ [0, 0, 1, 1],
2566
+ [0, 0, 0, 1]])
2567
+
2568
+ >>> A.upper_triangular(2)
2569
+ Matrix([
2570
+ [0, 0, 1, 1],
2571
+ [0, 0, 0, 1],
2572
+ [0, 0, 0, 0],
2573
+ [0, 0, 0, 0]])
2574
+
2575
+ >>> A.upper_triangular(-1)
2576
+ Matrix([
2577
+ [1, 1, 1, 1],
2578
+ [1, 1, 1, 1],
2579
+ [0, 1, 1, 1],
2580
+ [0, 0, 1, 1]])
2581
+
2582
+ """
2583
+
2584
+ def entry(i, j):
2585
+ return self[i, j] if i + k <= j else self.zero
2586
+
2587
+ return self._new(self.rows, self.cols, entry)
2588
+
2589
+
2590
+ def lower_triangular(self, k=0):
2591
+ """Return the elements on and below the kth diagonal of a matrix.
2592
+ If k is not specified then simply returns lower-triangular portion
2593
+ of a matrix
2594
+
2595
+ Examples
2596
+ ========
2597
+
2598
+ >>> from sympy import ones
2599
+ >>> A = ones(4)
2600
+ >>> A.lower_triangular()
2601
+ Matrix([
2602
+ [1, 0, 0, 0],
2603
+ [1, 1, 0, 0],
2604
+ [1, 1, 1, 0],
2605
+ [1, 1, 1, 1]])
2606
+
2607
+ >>> A.lower_triangular(-2)
2608
+ Matrix([
2609
+ [0, 0, 0, 0],
2610
+ [0, 0, 0, 0],
2611
+ [1, 0, 0, 0],
2612
+ [1, 1, 0, 0]])
2613
+
2614
+ >>> A.lower_triangular(1)
2615
+ Matrix([
2616
+ [1, 1, 0, 0],
2617
+ [1, 1, 1, 0],
2618
+ [1, 1, 1, 1],
2619
+ [1, 1, 1, 1]])
2620
+
2621
+ """
2622
+
2623
+ def entry(i, j):
2624
+ return self[i, j] if i + k >= j else self.zero
2625
+
2626
+ return self._new(self.rows, self.cols, entry)
2627
+
2628
+
2629
+
2630
+ class MatrixArithmetic(MatrixRequired):
2631
+ """Provides basic matrix arithmetic operations.
2632
+ Should not be instantiated directly."""
2633
+
2634
+ _op_priority = 10.01
2635
+
2636
+ def _eval_Abs(self):
2637
+ return self._new(self.rows, self.cols, lambda i, j: Abs(self[i, j]))
2638
+
2639
+ def _eval_add(self, other):
2640
+ return self._new(self.rows, self.cols,
2641
+ lambda i, j: self[i, j] + other[i, j])
2642
+
2643
+ def _eval_matrix_mul(self, other):
2644
+ def entry(i, j):
2645
+ vec = [self[i,k]*other[k,j] for k in range(self.cols)]
2646
+ try:
2647
+ return Add(*vec)
2648
+ except (TypeError, SympifyError):
2649
+ # Some matrices don't work with `sum` or `Add`
2650
+ # They don't work with `sum` because `sum` tries to add `0`
2651
+ # Fall back to a safe way to multiply if the `Add` fails.
2652
+ return reduce(lambda a, b: a + b, vec)
2653
+
2654
+ return self._new(self.rows, other.cols, entry)
2655
+
2656
+ def _eval_matrix_mul_elementwise(self, other):
2657
+ return self._new(self.rows, self.cols, lambda i, j: self[i,j]*other[i,j])
2658
+
2659
+ def _eval_matrix_rmul(self, other):
2660
+ def entry(i, j):
2661
+ return sum(other[i,k]*self[k,j] for k in range(other.cols))
2662
+ return self._new(other.rows, self.cols, entry)
2663
+
2664
+ def _eval_pow_by_recursion(self, num):
2665
+ if num == 1:
2666
+ return self
2667
+
2668
+ if num % 2 == 1:
2669
+ a, b = self, self._eval_pow_by_recursion(num - 1)
2670
+ else:
2671
+ a = b = self._eval_pow_by_recursion(num // 2)
2672
+
2673
+ return a.multiply(b)
2674
+
2675
+ def _eval_pow_by_cayley(self, exp):
2676
+ from sympy.discrete.recurrences import linrec_coeffs
2677
+ row = self.shape[0]
2678
+ p = self.charpoly()
2679
+
2680
+ coeffs = (-p).all_coeffs()[1:]
2681
+ coeffs = linrec_coeffs(coeffs, exp)
2682
+ new_mat = self.eye(row)
2683
+ ans = self.zeros(row)
2684
+
2685
+ for i in range(row):
2686
+ ans += coeffs[i]*new_mat
2687
+ new_mat *= self
2688
+
2689
+ return ans
2690
+
2691
+ def _eval_pow_by_recursion_dotprodsimp(self, num, prevsimp=None):
2692
+ if prevsimp is None:
2693
+ prevsimp = [True]*len(self)
2694
+
2695
+ if num == 1:
2696
+ return self
2697
+
2698
+ if num % 2 == 1:
2699
+ a, b = self, self._eval_pow_by_recursion_dotprodsimp(num - 1,
2700
+ prevsimp=prevsimp)
2701
+ else:
2702
+ a = b = self._eval_pow_by_recursion_dotprodsimp(num // 2,
2703
+ prevsimp=prevsimp)
2704
+
2705
+ m = a.multiply(b, dotprodsimp=False)
2706
+ lenm = len(m)
2707
+ elems = [None]*lenm
2708
+
2709
+ for i in range(lenm):
2710
+ if prevsimp[i]:
2711
+ elems[i], prevsimp[i] = _dotprodsimp(m[i], withsimp=True)
2712
+ else:
2713
+ elems[i] = m[i]
2714
+
2715
+ return m._new(m.rows, m.cols, elems)
2716
+
2717
+ def _eval_scalar_mul(self, other):
2718
+ return self._new(self.rows, self.cols, lambda i, j: self[i,j]*other)
2719
+
2720
+ def _eval_scalar_rmul(self, other):
2721
+ return self._new(self.rows, self.cols, lambda i, j: other*self[i,j])
2722
+
2723
+ def _eval_Mod(self, other):
2724
+ return self._new(self.rows, self.cols, lambda i, j: Mod(self[i, j], other))
2725
+
2726
+ # Python arithmetic functions
2727
+ def __abs__(self):
2728
+ """Returns a new matrix with entry-wise absolute values."""
2729
+ return self._eval_Abs()
2730
+
2731
+ @call_highest_priority('__radd__')
2732
+ def __add__(self, other):
2733
+ """Return self + other, raising ShapeError if shapes do not match."""
2734
+ if isinstance(other, NDimArray): # Matrix and array addition is currently not implemented
2735
+ return NotImplemented
2736
+ other = _matrixify(other)
2737
+ # matrix-like objects can have shapes. This is
2738
+ # our first sanity check.
2739
+ if hasattr(other, 'shape'):
2740
+ if self.shape != other.shape:
2741
+ raise ShapeError("Matrix size mismatch: %s + %s" % (
2742
+ self.shape, other.shape))
2743
+
2744
+ # honest SymPy matrices defer to their class's routine
2745
+ if getattr(other, 'is_Matrix', False):
2746
+ # call the highest-priority class's _eval_add
2747
+ a, b = self, other
2748
+ if a.__class__ != classof(a, b):
2749
+ b, a = a, b
2750
+ return a._eval_add(b)
2751
+ # Matrix-like objects can be passed to CommonMatrix routines directly.
2752
+ if getattr(other, 'is_MatrixLike', False):
2753
+ return MatrixArithmetic._eval_add(self, other)
2754
+
2755
+ raise TypeError('cannot add %s and %s' % (type(self), type(other)))
2756
+
2757
+ @call_highest_priority('__rtruediv__')
2758
+ def __truediv__(self, other):
2759
+ return self * (self.one / other)
2760
+
2761
+ @call_highest_priority('__rmatmul__')
2762
+ def __matmul__(self, other):
2763
+ other = _matrixify(other)
2764
+ if not getattr(other, 'is_Matrix', False) and not getattr(other, 'is_MatrixLike', False):
2765
+ return NotImplemented
2766
+
2767
+ return self.__mul__(other)
2768
+
2769
+ def __mod__(self, other):
2770
+ return self.applyfunc(lambda x: x % other)
2771
+
2772
+ @call_highest_priority('__rmul__')
2773
+ def __mul__(self, other):
2774
+ """Return self*other where other is either a scalar or a matrix
2775
+ of compatible dimensions.
2776
+
2777
+ Examples
2778
+ ========
2779
+
2780
+ >>> from sympy import Matrix
2781
+ >>> A = Matrix([[1, 2, 3], [4, 5, 6]])
2782
+ >>> 2*A == A*2 == Matrix([[2, 4, 6], [8, 10, 12]])
2783
+ True
2784
+ >>> B = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
2785
+ >>> A*B
2786
+ Matrix([
2787
+ [30, 36, 42],
2788
+ [66, 81, 96]])
2789
+ >>> B*A
2790
+ Traceback (most recent call last):
2791
+ ...
2792
+ ShapeError: Matrices size mismatch.
2793
+ >>>
2794
+
2795
+ See Also
2796
+ ========
2797
+
2798
+ matrix_multiply_elementwise
2799
+ """
2800
+
2801
+ return self.multiply(other)
2802
+
2803
+ def multiply(self, other, dotprodsimp=None):
2804
+ """Same as __mul__() but with optional simplification.
2805
+
2806
+ Parameters
2807
+ ==========
2808
+
2809
+ dotprodsimp : bool, optional
2810
+ Specifies whether intermediate term algebraic simplification is used
2811
+ during matrix multiplications to control expression blowup and thus
2812
+ speed up calculation. Default is off.
2813
+ """
2814
+
2815
+ isimpbool = _get_intermediate_simp_bool(False, dotprodsimp)
2816
+ other = _matrixify(other)
2817
+ # matrix-like objects can have shapes. This is
2818
+ # our first sanity check. Double check other is not explicitly not a Matrix.
2819
+ if (hasattr(other, 'shape') and len(other.shape) == 2 and
2820
+ (getattr(other, 'is_Matrix', True) or
2821
+ getattr(other, 'is_MatrixLike', True))):
2822
+ if self.shape[1] != other.shape[0]:
2823
+ raise ShapeError("Matrix size mismatch: %s * %s." % (
2824
+ self.shape, other.shape))
2825
+
2826
+ # honest SymPy matrices defer to their class's routine
2827
+ if getattr(other, 'is_Matrix', False):
2828
+ m = self._eval_matrix_mul(other)
2829
+ if isimpbool:
2830
+ return m._new(m.rows, m.cols, [_dotprodsimp(e) for e in m])
2831
+ return m
2832
+
2833
+ # Matrix-like objects can be passed to CommonMatrix routines directly.
2834
+ if getattr(other, 'is_MatrixLike', False):
2835
+ return MatrixArithmetic._eval_matrix_mul(self, other)
2836
+
2837
+ # if 'other' is not iterable then scalar multiplication.
2838
+ if not isinstance(other, Iterable):
2839
+ try:
2840
+ return self._eval_scalar_mul(other)
2841
+ except TypeError:
2842
+ pass
2843
+
2844
+ return NotImplemented
2845
+
2846
+ def multiply_elementwise(self, other):
2847
+ """Return the Hadamard product (elementwise product) of A and B
2848
+
2849
+ Examples
2850
+ ========
2851
+
2852
+ >>> from sympy import Matrix
2853
+ >>> A = Matrix([[0, 1, 2], [3, 4, 5]])
2854
+ >>> B = Matrix([[1, 10, 100], [100, 10, 1]])
2855
+ >>> A.multiply_elementwise(B)
2856
+ Matrix([
2857
+ [ 0, 10, 200],
2858
+ [300, 40, 5]])
2859
+
2860
+ See Also
2861
+ ========
2862
+
2863
+ sympy.matrices.matrixbase.MatrixBase.cross
2864
+ sympy.matrices.matrixbase.MatrixBase.dot
2865
+ multiply
2866
+ """
2867
+ if self.shape != other.shape:
2868
+ raise ShapeError("Matrix shapes must agree {} != {}".format(self.shape, other.shape))
2869
+
2870
+ return self._eval_matrix_mul_elementwise(other)
2871
+
2872
+ def __neg__(self):
2873
+ return self._eval_scalar_mul(-1)
2874
+
2875
+ @call_highest_priority('__rpow__')
2876
+ def __pow__(self, exp):
2877
+ """Return self**exp a scalar or symbol."""
2878
+
2879
+ return self.pow(exp)
2880
+
2881
+
2882
+ def pow(self, exp, method=None):
2883
+ r"""Return self**exp a scalar or symbol.
2884
+
2885
+ Parameters
2886
+ ==========
2887
+
2888
+ method : multiply, mulsimp, jordan, cayley
2889
+ If multiply then it returns exponentiation using recursion.
2890
+ If jordan then Jordan form exponentiation will be used.
2891
+ If cayley then the exponentiation is done using Cayley-Hamilton
2892
+ theorem.
2893
+ If mulsimp then the exponentiation is done using recursion
2894
+ with dotprodsimp. This specifies whether intermediate term
2895
+ algebraic simplification is used during naive matrix power to
2896
+ control expression blowup and thus speed up calculation.
2897
+ If None, then it heuristically decides which method to use.
2898
+
2899
+ """
2900
+
2901
+ if method is not None and method not in ['multiply', 'mulsimp', 'jordan', 'cayley']:
2902
+ raise TypeError('No such method')
2903
+ if self.rows != self.cols:
2904
+ raise NonSquareMatrixError()
2905
+ a = self
2906
+ jordan_pow = getattr(a, '_matrix_pow_by_jordan_blocks', None)
2907
+ exp = sympify(exp)
2908
+
2909
+ if exp.is_zero:
2910
+ return a._new(a.rows, a.cols, lambda i, j: int(i == j))
2911
+ if exp == 1:
2912
+ return a
2913
+
2914
+ diagonal = getattr(a, 'is_diagonal', None)
2915
+ if diagonal is not None and diagonal():
2916
+ return a._new(a.rows, a.cols, lambda i, j: a[i,j]**exp if i == j else 0)
2917
+
2918
+ if exp.is_Number and exp % 1 == 0:
2919
+ if a.rows == 1:
2920
+ return a._new([[a[0]**exp]])
2921
+ if exp < 0:
2922
+ exp = -exp
2923
+ a = a.inv()
2924
+ # When certain conditions are met,
2925
+ # Jordan block algorithm is faster than
2926
+ # computation by recursion.
2927
+ if method == 'jordan':
2928
+ try:
2929
+ return jordan_pow(exp)
2930
+ except MatrixError:
2931
+ if method == 'jordan':
2932
+ raise
2933
+
2934
+ elif method == 'cayley':
2935
+ if not exp.is_Number or exp % 1 != 0:
2936
+ raise ValueError("cayley method is only valid for integer powers")
2937
+ return a._eval_pow_by_cayley(exp)
2938
+
2939
+ elif method == "mulsimp":
2940
+ if not exp.is_Number or exp % 1 != 0:
2941
+ raise ValueError("mulsimp method is only valid for integer powers")
2942
+ return a._eval_pow_by_recursion_dotprodsimp(exp)
2943
+
2944
+ elif method == "multiply":
2945
+ if not exp.is_Number or exp % 1 != 0:
2946
+ raise ValueError("multiply method is only valid for integer powers")
2947
+ return a._eval_pow_by_recursion(exp)
2948
+
2949
+ elif method is None and exp.is_Number and exp % 1 == 0:
2950
+ if exp.is_Float:
2951
+ exp = Integer(exp)
2952
+ # Decide heuristically which method to apply
2953
+ if a.rows == 2 and exp > 100000:
2954
+ return jordan_pow(exp)
2955
+ elif _get_intermediate_simp_bool(True, None):
2956
+ return a._eval_pow_by_recursion_dotprodsimp(exp)
2957
+ elif exp > 10000:
2958
+ return a._eval_pow_by_cayley(exp)
2959
+ else:
2960
+ return a._eval_pow_by_recursion(exp)
2961
+
2962
+ if jordan_pow:
2963
+ try:
2964
+ return jordan_pow(exp)
2965
+ except NonInvertibleMatrixError:
2966
+ # Raised by jordan_pow on zero determinant matrix unless exp is
2967
+ # definitely known to be a non-negative integer.
2968
+ # Here we raise if n is definitely not a non-negative integer
2969
+ # but otherwise we can leave this as an unevaluated MatPow.
2970
+ if exp.is_integer is False or exp.is_nonnegative is False:
2971
+ raise
2972
+
2973
+ from sympy.matrices.expressions import MatPow
2974
+ return MatPow(a, exp)
2975
+
2976
+ @call_highest_priority('__add__')
2977
+ def __radd__(self, other):
2978
+ return self + other
2979
+
2980
+ @call_highest_priority('__matmul__')
2981
+ def __rmatmul__(self, other):
2982
+ other = _matrixify(other)
2983
+ if not getattr(other, 'is_Matrix', False) and not getattr(other, 'is_MatrixLike', False):
2984
+ return NotImplemented
2985
+
2986
+ return self.__rmul__(other)
2987
+
2988
+ @call_highest_priority('__mul__')
2989
+ def __rmul__(self, other):
2990
+ return self.rmultiply(other)
2991
+
2992
+ def rmultiply(self, other, dotprodsimp=None):
2993
+ """Same as __rmul__() but with optional simplification.
2994
+
2995
+ Parameters
2996
+ ==========
2997
+
2998
+ dotprodsimp : bool, optional
2999
+ Specifies whether intermediate term algebraic simplification is used
3000
+ during matrix multiplications to control expression blowup and thus
3001
+ speed up calculation. Default is off.
3002
+ """
3003
+ isimpbool = _get_intermediate_simp_bool(False, dotprodsimp)
3004
+ other = _matrixify(other)
3005
+ # matrix-like objects can have shapes. This is
3006
+ # our first sanity check. Double check other is not explicitly not a Matrix.
3007
+ if (hasattr(other, 'shape') and len(other.shape) == 2 and
3008
+ (getattr(other, 'is_Matrix', True) or
3009
+ getattr(other, 'is_MatrixLike', True))):
3010
+ if self.shape[0] != other.shape[1]:
3011
+ raise ShapeError("Matrix size mismatch.")
3012
+
3013
+ # honest SymPy matrices defer to their class's routine
3014
+ if getattr(other, 'is_Matrix', False):
3015
+ m = self._eval_matrix_rmul(other)
3016
+ if isimpbool:
3017
+ return m._new(m.rows, m.cols, [_dotprodsimp(e) for e in m])
3018
+ return m
3019
+ # Matrix-like objects can be passed to CommonMatrix routines directly.
3020
+ if getattr(other, 'is_MatrixLike', False):
3021
+ return MatrixArithmetic._eval_matrix_rmul(self, other)
3022
+
3023
+ # if 'other' is not iterable then scalar multiplication.
3024
+ if not isinstance(other, Iterable):
3025
+ try:
3026
+ return self._eval_scalar_rmul(other)
3027
+ except TypeError:
3028
+ pass
3029
+
3030
+ return NotImplemented
3031
+
3032
+ @call_highest_priority('__sub__')
3033
+ def __rsub__(self, a):
3034
+ return (-self) + a
3035
+
3036
+ @call_highest_priority('__rsub__')
3037
+ def __sub__(self, a):
3038
+ return self + (-a)
3039
+
3040
+
3041
+ class MatrixCommon(MatrixArithmetic, MatrixOperations, MatrixProperties,
3042
+ MatrixSpecial, MatrixShaping):
3043
+ """All common matrix operations including basic arithmetic, shaping,
3044
+ and special matrices like `zeros`, and `eye`."""
3045
+ _diff_wrt = True # type: bool
3046
+
3047
+
3048
+ class _MinimalMatrix:
3049
+ """Class providing the minimum functionality
3050
+ for a matrix-like object and implementing every method
3051
+ required for a `MatrixRequired`. This class does not have everything
3052
+ needed to become a full-fledged SymPy object, but it will satisfy the
3053
+ requirements of anything inheriting from `MatrixRequired`. If you wish
3054
+ to make a specialized matrix type, make sure to implement these
3055
+ methods and properties with the exception of `__init__` and `__repr__`
3056
+ which are included for convenience."""
3057
+
3058
+ is_MatrixLike = True
3059
+ _sympify = staticmethod(sympify)
3060
+ _class_priority = 3
3061
+ zero = S.Zero
3062
+ one = S.One
3063
+
3064
+ is_Matrix = True
3065
+ is_MatrixExpr = False
3066
+
3067
+ @classmethod
3068
+ def _new(cls, *args, **kwargs):
3069
+ return cls(*args, **kwargs)
3070
+
3071
+ def __init__(self, rows, cols=None, mat=None, copy=False):
3072
+ if isfunction(mat):
3073
+ # if we passed in a function, use that to populate the indices
3074
+ mat = [mat(i, j) for i in range(rows) for j in range(cols)]
3075
+ if cols is None and mat is None:
3076
+ mat = rows
3077
+ rows, cols = getattr(mat, 'shape', (rows, cols))
3078
+ try:
3079
+ # if we passed in a list of lists, flatten it and set the size
3080
+ if cols is None and mat is None:
3081
+ mat = rows
3082
+ cols = len(mat[0])
3083
+ rows = len(mat)
3084
+ mat = [x for l in mat for x in l]
3085
+ except (IndexError, TypeError):
3086
+ pass
3087
+ self.mat = tuple(self._sympify(x) for x in mat)
3088
+ self.rows, self.cols = rows, cols
3089
+ if self.rows is None or self.cols is None:
3090
+ raise NotImplementedError("Cannot initialize matrix with given parameters")
3091
+
3092
+ def __getitem__(self, key):
3093
+ def _normalize_slices(row_slice, col_slice):
3094
+ """Ensure that row_slice and col_slice do not have
3095
+ `None` in their arguments. Any integers are converted
3096
+ to slices of length 1"""
3097
+ if not isinstance(row_slice, slice):
3098
+ row_slice = slice(row_slice, row_slice + 1, None)
3099
+ row_slice = slice(*row_slice.indices(self.rows))
3100
+
3101
+ if not isinstance(col_slice, slice):
3102
+ col_slice = slice(col_slice, col_slice + 1, None)
3103
+ col_slice = slice(*col_slice.indices(self.cols))
3104
+
3105
+ return (row_slice, col_slice)
3106
+
3107
+ def _coord_to_index(i, j):
3108
+ """Return the index in _mat corresponding
3109
+ to the (i,j) position in the matrix. """
3110
+ return i * self.cols + j
3111
+
3112
+ if isinstance(key, tuple):
3113
+ i, j = key
3114
+ if isinstance(i, slice) or isinstance(j, slice):
3115
+ # if the coordinates are not slices, make them so
3116
+ # and expand the slices so they don't contain `None`
3117
+ i, j = _normalize_slices(i, j)
3118
+
3119
+ rowsList, colsList = list(range(self.rows))[i], \
3120
+ list(range(self.cols))[j]
3121
+ indices = (i * self.cols + j for i in rowsList for j in
3122
+ colsList)
3123
+ return self._new(len(rowsList), len(colsList),
3124
+ [self.mat[i] for i in indices])
3125
+
3126
+ # if the key is a tuple of ints, change
3127
+ # it to an array index
3128
+ key = _coord_to_index(i, j)
3129
+ return self.mat[key]
3130
+
3131
+ def __eq__(self, other):
3132
+ try:
3133
+ classof(self, other)
3134
+ except TypeError:
3135
+ return False
3136
+ return (
3137
+ self.shape == other.shape and list(self) == list(other))
3138
+
3139
+ def __len__(self):
3140
+ return self.rows*self.cols
3141
+
3142
+ def __repr__(self):
3143
+ return "_MinimalMatrix({}, {}, {})".format(self.rows, self.cols,
3144
+ self.mat)
3145
+
3146
+ @property
3147
+ def shape(self):
3148
+ return (self.rows, self.cols)
3149
+
3150
+
3151
+ class _CastableMatrix: # this is needed here ONLY FOR TESTS.
3152
+ def as_mutable(self):
3153
+ return self
3154
+
3155
+ def as_immutable(self):
3156
+ return self
3157
+
3158
+
3159
+ class _MatrixWrapper:
3160
+ """Wrapper class providing the minimum functionality for a matrix-like
3161
+ object: .rows, .cols, .shape, indexability, and iterability. CommonMatrix
3162
+ math operations should work on matrix-like objects. This one is intended for
3163
+ matrix-like objects which use the same indexing format as SymPy with respect
3164
+ to returning matrix elements instead of rows for non-tuple indexes.
3165
+ """
3166
+
3167
+ is_Matrix = False # needs to be here because of __getattr__
3168
+ is_MatrixLike = True
3169
+
3170
+ def __init__(self, mat, shape):
3171
+ self.mat = mat
3172
+ self.shape = shape
3173
+ self.rows, self.cols = shape
3174
+
3175
+ def __getitem__(self, key):
3176
+ if isinstance(key, tuple):
3177
+ return sympify(self.mat.__getitem__(key))
3178
+
3179
+ return sympify(self.mat.__getitem__((key // self.rows, key % self.cols)))
3180
+
3181
+ def __iter__(self): # supports numpy.matrix and numpy.array
3182
+ mat = self.mat
3183
+ cols = self.cols
3184
+
3185
+ return iter(sympify(mat[r, c]) for r in range(self.rows) for c in range(cols))
3186
+
3187
+
3188
+ def _matrixify(mat):
3189
+ """If `mat` is a Matrix or is matrix-like,
3190
+ return a Matrix or MatrixWrapper object. Otherwise
3191
+ `mat` is passed through without modification."""
3192
+
3193
+ if getattr(mat, 'is_Matrix', False) or getattr(mat, 'is_MatrixLike', False):
3194
+ return mat
3195
+
3196
+ if not(getattr(mat, 'is_Matrix', True) or getattr(mat, 'is_MatrixLike', True)):
3197
+ return mat
3198
+
3199
+ shape = None
3200
+
3201
+ if hasattr(mat, 'shape'): # numpy, scipy.sparse
3202
+ if len(mat.shape) == 2:
3203
+ shape = mat.shape
3204
+ elif hasattr(mat, 'rows') and hasattr(mat, 'cols'): # mpmath
3205
+ shape = (mat.rows, mat.cols)
3206
+
3207
+ if shape:
3208
+ return _MatrixWrapper(mat, shape)
3209
+
3210
+ return mat
3211
+
3212
+
3213
+ def a2idx(j, n=None):
3214
+ """Return integer after making positive and validating against n."""
3215
+ if not isinstance(j, int):
3216
+ jindex = getattr(j, '__index__', None)
3217
+ if jindex is not None:
3218
+ j = jindex()
3219
+ else:
3220
+ raise IndexError("Invalid index a[%r]" % (j,))
3221
+ if n is not None:
3222
+ if j < 0:
3223
+ j += n
3224
+ if not (j >= 0 and j < n):
3225
+ raise IndexError("Index out of range: a[%s]" % (j,))
3226
+ return int(j)
3227
+
3228
+
3229
+ def classof(A, B):
3230
+ """
3231
+ Get the type of the result when combining matrices of different types.
3232
+
3233
+ Currently the strategy is that immutability is contagious.
3234
+
3235
+ Examples
3236
+ ========
3237
+
3238
+ >>> from sympy import Matrix, ImmutableMatrix
3239
+ >>> from sympy.matrices.matrixbase import classof
3240
+ >>> M = Matrix([[1, 2], [3, 4]]) # a Mutable Matrix
3241
+ >>> IM = ImmutableMatrix([[1, 2], [3, 4]])
3242
+ >>> classof(M, IM)
3243
+ <class 'sympy.matrices.immutable.ImmutableDenseMatrix'>
3244
+ """
3245
+ priority_A = getattr(A, '_class_priority', None)
3246
+ priority_B = getattr(B, '_class_priority', None)
3247
+ if None not in (priority_A, priority_B):
3248
+ if A._class_priority > B._class_priority:
3249
+ return A.__class__
3250
+ else:
3251
+ return B.__class__
3252
+
3253
+ try:
3254
+ import numpy
3255
+ except ImportError:
3256
+ pass
3257
+ else:
3258
+ if isinstance(A, numpy.ndarray):
3259
+ return B.__class__
3260
+ if isinstance(B, numpy.ndarray):
3261
+ return A.__class__
3262
+
3263
+ raise TypeError("Incompatible classes %s, %s" % (A.__class__, B.__class__))
phi4/lib/python3.10/site-packages/sympy/matrices/dense.py ADDED
@@ -0,0 +1,1093 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import random
2
+
3
+ from sympy.core.basic import Basic
4
+ from sympy.core.singleton import S
5
+ from sympy.core.symbol import Symbol
6
+ from sympy.core.sympify import sympify
7
+ from sympy.functions.elementary.trigonometric import cos, sin
8
+ from sympy.utilities.decorator import doctest_depends_on
9
+ from sympy.utilities.exceptions import sympy_deprecation_warning
10
+ from sympy.utilities.iterables import is_sequence
11
+
12
+ from .exceptions import ShapeError
13
+ from .decompositions import _cholesky, _LDLdecomposition
14
+ from .matrixbase import MatrixBase
15
+ from .repmatrix import MutableRepMatrix, RepMatrix
16
+ from .solvers import _lower_triangular_solve, _upper_triangular_solve
17
+
18
+
19
+ __doctest_requires__ = {('symarray',): ['numpy']}
20
+
21
+
22
+ def _iszero(x):
23
+ """Returns True if x is zero."""
24
+ return x.is_zero
25
+
26
+
27
+ class DenseMatrix(RepMatrix):
28
+ """Matrix implementation based on DomainMatrix as the internal representation"""
29
+
30
+ #
31
+ # DenseMatrix is a superclass for both MutableDenseMatrix and
32
+ # ImmutableDenseMatrix. Methods shared by both classes but not for the
33
+ # Sparse classes should be implemented here.
34
+ #
35
+
36
+ is_MatrixExpr = False # type: bool
37
+
38
+ _op_priority = 10.01
39
+ _class_priority = 4
40
+
41
+ @property
42
+ def _mat(self):
43
+ sympy_deprecation_warning(
44
+ """
45
+ The private _mat attribute of Matrix is deprecated. Use the
46
+ .flat() method instead.
47
+ """,
48
+ deprecated_since_version="1.9",
49
+ active_deprecations_target="deprecated-private-matrix-attributes"
50
+ )
51
+
52
+ return self.flat()
53
+
54
+ def _eval_inverse(self, **kwargs):
55
+ return self.inv(method=kwargs.get('method', 'GE'),
56
+ iszerofunc=kwargs.get('iszerofunc', _iszero),
57
+ try_block_diag=kwargs.get('try_block_diag', False))
58
+
59
+ def as_immutable(self):
60
+ """Returns an Immutable version of this Matrix
61
+ """
62
+ from .immutable import ImmutableDenseMatrix as cls
63
+ return cls._fromrep(self._rep.copy())
64
+
65
+ def as_mutable(self):
66
+ """Returns a mutable version of this matrix
67
+
68
+ Examples
69
+ ========
70
+
71
+ >>> from sympy import ImmutableMatrix
72
+ >>> X = ImmutableMatrix([[1, 2], [3, 4]])
73
+ >>> Y = X.as_mutable()
74
+ >>> Y[1, 1] = 5 # Can set values in Y
75
+ >>> Y
76
+ Matrix([
77
+ [1, 2],
78
+ [3, 5]])
79
+ """
80
+ return Matrix(self)
81
+
82
+ def cholesky(self, hermitian=True):
83
+ return _cholesky(self, hermitian=hermitian)
84
+
85
+ def LDLdecomposition(self, hermitian=True):
86
+ return _LDLdecomposition(self, hermitian=hermitian)
87
+
88
+ def lower_triangular_solve(self, rhs):
89
+ return _lower_triangular_solve(self, rhs)
90
+
91
+ def upper_triangular_solve(self, rhs):
92
+ return _upper_triangular_solve(self, rhs)
93
+
94
+ cholesky.__doc__ = _cholesky.__doc__
95
+ LDLdecomposition.__doc__ = _LDLdecomposition.__doc__
96
+ lower_triangular_solve.__doc__ = _lower_triangular_solve.__doc__
97
+ upper_triangular_solve.__doc__ = _upper_triangular_solve.__doc__
98
+
99
+
100
+ def _force_mutable(x):
101
+ """Return a matrix as a Matrix, otherwise return x."""
102
+ if getattr(x, 'is_Matrix', False):
103
+ return x.as_mutable()
104
+ elif isinstance(x, Basic):
105
+ return x
106
+ elif hasattr(x, '__array__'):
107
+ a = x.__array__()
108
+ if len(a.shape) == 0:
109
+ return sympify(a)
110
+ return Matrix(x)
111
+ return x
112
+
113
+
114
+ class MutableDenseMatrix(DenseMatrix, MutableRepMatrix):
115
+
116
+ def simplify(self, **kwargs):
117
+ """Applies simplify to the elements of a matrix in place.
118
+
119
+ This is a shortcut for M.applyfunc(lambda x: simplify(x, ratio, measure))
120
+
121
+ See Also
122
+ ========
123
+
124
+ sympy.simplify.simplify.simplify
125
+ """
126
+ from sympy.simplify.simplify import simplify as _simplify
127
+ for (i, j), element in self.todok().items():
128
+ self[i, j] = _simplify(element, **kwargs)
129
+
130
+
131
+ MutableMatrix = Matrix = MutableDenseMatrix
132
+
133
+ ###########
134
+ # Numpy Utility Functions:
135
+ # list2numpy, matrix2numpy, symmarray
136
+ ###########
137
+
138
+
139
+ def list2numpy(l, dtype=object): # pragma: no cover
140
+ """Converts Python list of SymPy expressions to a NumPy array.
141
+
142
+ See Also
143
+ ========
144
+
145
+ matrix2numpy
146
+ """
147
+ from numpy import empty
148
+ a = empty(len(l), dtype)
149
+ for i, s in enumerate(l):
150
+ a[i] = s
151
+ return a
152
+
153
+
154
+ def matrix2numpy(m, dtype=object): # pragma: no cover
155
+ """Converts SymPy's matrix to a NumPy array.
156
+
157
+ See Also
158
+ ========
159
+
160
+ list2numpy
161
+ """
162
+ from numpy import empty
163
+ a = empty(m.shape, dtype)
164
+ for i in range(m.rows):
165
+ for j in range(m.cols):
166
+ a[i, j] = m[i, j]
167
+ return a
168
+
169
+
170
+ ###########
171
+ # Rotation matrices:
172
+ # rot_givens, rot_axis[123], rot_ccw_axis[123]
173
+ ###########
174
+
175
+
176
+ def rot_givens(i, j, theta, dim=3):
177
+ r"""Returns a a Givens rotation matrix, a a rotation in the
178
+ plane spanned by two coordinates axes.
179
+
180
+ Explanation
181
+ ===========
182
+
183
+ The Givens rotation corresponds to a generalization of rotation
184
+ matrices to any number of dimensions, given by:
185
+
186
+ .. math::
187
+ G(i, j, \theta) =
188
+ \begin{bmatrix}
189
+ 1 & \cdots & 0 & \cdots & 0 & \cdots & 0 \\
190
+ \vdots & \ddots & \vdots & & \vdots & & \vdots \\
191
+ 0 & \cdots & c & \cdots & -s & \cdots & 0 \\
192
+ \vdots & & \vdots & \ddots & \vdots & & \vdots \\
193
+ 0 & \cdots & s & \cdots & c & \cdots & 0 \\
194
+ \vdots & & \vdots & & \vdots & \ddots & \vdots \\
195
+ 0 & \cdots & 0 & \cdots & 0 & \cdots & 1
196
+ \end{bmatrix}
197
+
198
+ Where $c = \cos(\theta)$ and $s = \sin(\theta)$ appear at the intersections
199
+ ``i``\th and ``j``\th rows and columns.
200
+
201
+ For fixed ``i > j``\, the non-zero elements of a Givens matrix are
202
+ given by:
203
+
204
+ - $g_{kk} = 1$ for $k \ne i,\,j$
205
+ - $g_{kk} = c$ for $k = i,\,j$
206
+ - $g_{ji} = -g_{ij} = -s$
207
+
208
+ Parameters
209
+ ==========
210
+
211
+ i : int between ``0`` and ``dim - 1``
212
+ Represents first axis
213
+ j : int between ``0`` and ``dim - 1``
214
+ Represents second axis
215
+ dim : int bigger than 1
216
+ Number of dimentions. Defaults to 3.
217
+
218
+ Examples
219
+ ========
220
+
221
+ >>> from sympy import pi, rot_givens
222
+
223
+ A counterclockwise rotation of pi/3 (60 degrees) around
224
+ the third axis (z-axis):
225
+
226
+ >>> rot_givens(1, 0, pi/3)
227
+ Matrix([
228
+ [ 1/2, -sqrt(3)/2, 0],
229
+ [sqrt(3)/2, 1/2, 0],
230
+ [ 0, 0, 1]])
231
+
232
+ If we rotate by pi/2 (90 degrees):
233
+
234
+ >>> rot_givens(1, 0, pi/2)
235
+ Matrix([
236
+ [0, -1, 0],
237
+ [1, 0, 0],
238
+ [0, 0, 1]])
239
+
240
+ This can be generalized to any number
241
+ of dimensions:
242
+
243
+ >>> rot_givens(1, 0, pi/2, dim=4)
244
+ Matrix([
245
+ [0, -1, 0, 0],
246
+ [1, 0, 0, 0],
247
+ [0, 0, 1, 0],
248
+ [0, 0, 0, 1]])
249
+
250
+ References
251
+ ==========
252
+
253
+ .. [1] https://en.wikipedia.org/wiki/Givens_rotation
254
+
255
+ See Also
256
+ ========
257
+
258
+ rot_axis1: Returns a rotation matrix for a rotation of theta (in radians)
259
+ about the 1-axis (clockwise around the x axis)
260
+ rot_axis2: Returns a rotation matrix for a rotation of theta (in radians)
261
+ about the 2-axis (clockwise around the y axis)
262
+ rot_axis3: Returns a rotation matrix for a rotation of theta (in radians)
263
+ about the 3-axis (clockwise around the z axis)
264
+ rot_ccw_axis1: Returns a rotation matrix for a rotation of theta (in radians)
265
+ about the 1-axis (counterclockwise around the x axis)
266
+ rot_ccw_axis2: Returns a rotation matrix for a rotation of theta (in radians)
267
+ about the 2-axis (counterclockwise around the y axis)
268
+ rot_ccw_axis3: Returns a rotation matrix for a rotation of theta (in radians)
269
+ about the 3-axis (counterclockwise around the z axis)
270
+ """
271
+ if not isinstance(dim, int) or dim < 2:
272
+ raise ValueError('dim must be an integer biggen than one, '
273
+ 'got {}.'.format(dim))
274
+
275
+ if i == j:
276
+ raise ValueError('i and j must be different, '
277
+ 'got ({}, {})'.format(i, j))
278
+
279
+ for ij in [i, j]:
280
+ if not isinstance(ij, int) or ij < 0 or ij > dim - 1:
281
+ raise ValueError('i and j must be integers between 0 and '
282
+ '{}, got i={} and j={}.'.format(dim-1, i, j))
283
+
284
+ theta = sympify(theta)
285
+ c = cos(theta)
286
+ s = sin(theta)
287
+ M = eye(dim)
288
+ M[i, i] = c
289
+ M[j, j] = c
290
+ M[i, j] = s
291
+ M[j, i] = -s
292
+ return M
293
+
294
+
295
+ def rot_axis3(theta):
296
+ r"""Returns a rotation matrix for a rotation of theta (in radians)
297
+ about the 3-axis.
298
+
299
+ Explanation
300
+ ===========
301
+
302
+ For a right-handed coordinate system, this corresponds to a
303
+ clockwise rotation around the `z`-axis, given by:
304
+
305
+ .. math::
306
+
307
+ R = \begin{bmatrix}
308
+ \cos(\theta) & \sin(\theta) & 0 \\
309
+ -\sin(\theta) & \cos(\theta) & 0 \\
310
+ 0 & 0 & 1
311
+ \end{bmatrix}
312
+
313
+ Examples
314
+ ========
315
+
316
+ >>> from sympy import pi, rot_axis3
317
+
318
+ A rotation of pi/3 (60 degrees):
319
+
320
+ >>> theta = pi/3
321
+ >>> rot_axis3(theta)
322
+ Matrix([
323
+ [ 1/2, sqrt(3)/2, 0],
324
+ [-sqrt(3)/2, 1/2, 0],
325
+ [ 0, 0, 1]])
326
+
327
+ If we rotate by pi/2 (90 degrees):
328
+
329
+ >>> rot_axis3(pi/2)
330
+ Matrix([
331
+ [ 0, 1, 0],
332
+ [-1, 0, 0],
333
+ [ 0, 0, 1]])
334
+
335
+ See Also
336
+ ========
337
+
338
+ rot_givens: Returns a Givens rotation matrix (generalized rotation for
339
+ any number of dimensions)
340
+ rot_ccw_axis3: Returns a rotation matrix for a rotation of theta (in radians)
341
+ about the 3-axis (counterclockwise around the z axis)
342
+ rot_axis1: Returns a rotation matrix for a rotation of theta (in radians)
343
+ about the 1-axis (clockwise around the x axis)
344
+ rot_axis2: Returns a rotation matrix for a rotation of theta (in radians)
345
+ about the 2-axis (clockwise around the y axis)
346
+ """
347
+ return rot_givens(0, 1, theta, dim=3)
348
+
349
+
350
+ def rot_axis2(theta):
351
+ r"""Returns a rotation matrix for a rotation of theta (in radians)
352
+ about the 2-axis.
353
+
354
+ Explanation
355
+ ===========
356
+
357
+ For a right-handed coordinate system, this corresponds to a
358
+ clockwise rotation around the `y`-axis, given by:
359
+
360
+ .. math::
361
+
362
+ R = \begin{bmatrix}
363
+ \cos(\theta) & 0 & -\sin(\theta) \\
364
+ 0 & 1 & 0 \\
365
+ \sin(\theta) & 0 & \cos(\theta)
366
+ \end{bmatrix}
367
+
368
+ Examples
369
+ ========
370
+
371
+ >>> from sympy import pi, rot_axis2
372
+
373
+ A rotation of pi/3 (60 degrees):
374
+
375
+ >>> theta = pi/3
376
+ >>> rot_axis2(theta)
377
+ Matrix([
378
+ [ 1/2, 0, -sqrt(3)/2],
379
+ [ 0, 1, 0],
380
+ [sqrt(3)/2, 0, 1/2]])
381
+
382
+ If we rotate by pi/2 (90 degrees):
383
+
384
+ >>> rot_axis2(pi/2)
385
+ Matrix([
386
+ [0, 0, -1],
387
+ [0, 1, 0],
388
+ [1, 0, 0]])
389
+
390
+ See Also
391
+ ========
392
+
393
+ rot_givens: Returns a Givens rotation matrix (generalized rotation for
394
+ any number of dimensions)
395
+ rot_ccw_axis2: Returns a rotation matrix for a rotation of theta (in radians)
396
+ about the 2-axis (clockwise around the y axis)
397
+ rot_axis1: Returns a rotation matrix for a rotation of theta (in radians)
398
+ about the 1-axis (counterclockwise around the x axis)
399
+ rot_axis3: Returns a rotation matrix for a rotation of theta (in radians)
400
+ about the 3-axis (counterclockwise around the z axis)
401
+ """
402
+ return rot_givens(2, 0, theta, dim=3)
403
+
404
+
405
+ def rot_axis1(theta):
406
+ r"""Returns a rotation matrix for a rotation of theta (in radians)
407
+ about the 1-axis.
408
+
409
+ Explanation
410
+ ===========
411
+
412
+ For a right-handed coordinate system, this corresponds to a
413
+ clockwise rotation around the `x`-axis, given by:
414
+
415
+ .. math::
416
+
417
+ R = \begin{bmatrix}
418
+ 1 & 0 & 0 \\
419
+ 0 & \cos(\theta) & \sin(\theta) \\
420
+ 0 & -\sin(\theta) & \cos(\theta)
421
+ \end{bmatrix}
422
+
423
+ Examples
424
+ ========
425
+
426
+ >>> from sympy import pi, rot_axis1
427
+
428
+ A rotation of pi/3 (60 degrees):
429
+
430
+ >>> theta = pi/3
431
+ >>> rot_axis1(theta)
432
+ Matrix([
433
+ [1, 0, 0],
434
+ [0, 1/2, sqrt(3)/2],
435
+ [0, -sqrt(3)/2, 1/2]])
436
+
437
+ If we rotate by pi/2 (90 degrees):
438
+
439
+ >>> rot_axis1(pi/2)
440
+ Matrix([
441
+ [1, 0, 0],
442
+ [0, 0, 1],
443
+ [0, -1, 0]])
444
+
445
+ See Also
446
+ ========
447
+
448
+ rot_givens: Returns a Givens rotation matrix (generalized rotation for
449
+ any number of dimensions)
450
+ rot_ccw_axis1: Returns a rotation matrix for a rotation of theta (in radians)
451
+ about the 1-axis (counterclockwise around the x axis)
452
+ rot_axis2: Returns a rotation matrix for a rotation of theta (in radians)
453
+ about the 2-axis (clockwise around the y axis)
454
+ rot_axis3: Returns a rotation matrix for a rotation of theta (in radians)
455
+ about the 3-axis (clockwise around the z axis)
456
+ """
457
+ return rot_givens(1, 2, theta, dim=3)
458
+
459
+
460
+ def rot_ccw_axis3(theta):
461
+ r"""Returns a rotation matrix for a rotation of theta (in radians)
462
+ about the 3-axis.
463
+
464
+ Explanation
465
+ ===========
466
+
467
+ For a right-handed coordinate system, this corresponds to a
468
+ counterclockwise rotation around the `z`-axis, given by:
469
+
470
+ .. math::
471
+
472
+ R = \begin{bmatrix}
473
+ \cos(\theta) & -\sin(\theta) & 0 \\
474
+ \sin(\theta) & \cos(\theta) & 0 \\
475
+ 0 & 0 & 1
476
+ \end{bmatrix}
477
+
478
+ Examples
479
+ ========
480
+
481
+ >>> from sympy import pi, rot_ccw_axis3
482
+
483
+ A rotation of pi/3 (60 degrees):
484
+
485
+ >>> theta = pi/3
486
+ >>> rot_ccw_axis3(theta)
487
+ Matrix([
488
+ [ 1/2, -sqrt(3)/2, 0],
489
+ [sqrt(3)/2, 1/2, 0],
490
+ [ 0, 0, 1]])
491
+
492
+ If we rotate by pi/2 (90 degrees):
493
+
494
+ >>> rot_ccw_axis3(pi/2)
495
+ Matrix([
496
+ [0, -1, 0],
497
+ [1, 0, 0],
498
+ [0, 0, 1]])
499
+
500
+ See Also
501
+ ========
502
+
503
+ rot_givens: Returns a Givens rotation matrix (generalized rotation for
504
+ any number of dimensions)
505
+ rot_axis3: Returns a rotation matrix for a rotation of theta (in radians)
506
+ about the 3-axis (clockwise around the z axis)
507
+ rot_ccw_axis1: Returns a rotation matrix for a rotation of theta (in radians)
508
+ about the 1-axis (counterclockwise around the x axis)
509
+ rot_ccw_axis2: Returns a rotation matrix for a rotation of theta (in radians)
510
+ about the 2-axis (counterclockwise around the y axis)
511
+ """
512
+ return rot_givens(1, 0, theta, dim=3)
513
+
514
+
515
+ def rot_ccw_axis2(theta):
516
+ r"""Returns a rotation matrix for a rotation of theta (in radians)
517
+ about the 2-axis.
518
+
519
+ Explanation
520
+ ===========
521
+
522
+ For a right-handed coordinate system, this corresponds to a
523
+ counterclockwise rotation around the `y`-axis, given by:
524
+
525
+ .. math::
526
+
527
+ R = \begin{bmatrix}
528
+ \cos(\theta) & 0 & \sin(\theta) \\
529
+ 0 & 1 & 0 \\
530
+ -\sin(\theta) & 0 & \cos(\theta)
531
+ \end{bmatrix}
532
+
533
+ Examples
534
+ ========
535
+
536
+ >>> from sympy import pi, rot_ccw_axis2
537
+
538
+ A rotation of pi/3 (60 degrees):
539
+
540
+ >>> theta = pi/3
541
+ >>> rot_ccw_axis2(theta)
542
+ Matrix([
543
+ [ 1/2, 0, sqrt(3)/2],
544
+ [ 0, 1, 0],
545
+ [-sqrt(3)/2, 0, 1/2]])
546
+
547
+ If we rotate by pi/2 (90 degrees):
548
+
549
+ >>> rot_ccw_axis2(pi/2)
550
+ Matrix([
551
+ [ 0, 0, 1],
552
+ [ 0, 1, 0],
553
+ [-1, 0, 0]])
554
+
555
+ See Also
556
+ ========
557
+
558
+ rot_givens: Returns a Givens rotation matrix (generalized rotation for
559
+ any number of dimensions)
560
+ rot_axis2: Returns a rotation matrix for a rotation of theta (in radians)
561
+ about the 2-axis (clockwise around the y axis)
562
+ rot_ccw_axis1: Returns a rotation matrix for a rotation of theta (in radians)
563
+ about the 1-axis (counterclockwise around the x axis)
564
+ rot_ccw_axis3: Returns a rotation matrix for a rotation of theta (in radians)
565
+ about the 3-axis (counterclockwise around the z axis)
566
+ """
567
+ return rot_givens(0, 2, theta, dim=3)
568
+
569
+
570
+ def rot_ccw_axis1(theta):
571
+ r"""Returns a rotation matrix for a rotation of theta (in radians)
572
+ about the 1-axis.
573
+
574
+ Explanation
575
+ ===========
576
+
577
+ For a right-handed coordinate system, this corresponds to a
578
+ counterclockwise rotation around the `x`-axis, given by:
579
+
580
+ .. math::
581
+
582
+ R = \begin{bmatrix}
583
+ 1 & 0 & 0 \\
584
+ 0 & \cos(\theta) & -\sin(\theta) \\
585
+ 0 & \sin(\theta) & \cos(\theta)
586
+ \end{bmatrix}
587
+
588
+ Examples
589
+ ========
590
+
591
+ >>> from sympy import pi, rot_ccw_axis1
592
+
593
+ A rotation of pi/3 (60 degrees):
594
+
595
+ >>> theta = pi/3
596
+ >>> rot_ccw_axis1(theta)
597
+ Matrix([
598
+ [1, 0, 0],
599
+ [0, 1/2, -sqrt(3)/2],
600
+ [0, sqrt(3)/2, 1/2]])
601
+
602
+ If we rotate by pi/2 (90 degrees):
603
+
604
+ >>> rot_ccw_axis1(pi/2)
605
+ Matrix([
606
+ [1, 0, 0],
607
+ [0, 0, -1],
608
+ [0, 1, 0]])
609
+
610
+ See Also
611
+ ========
612
+
613
+ rot_givens: Returns a Givens rotation matrix (generalized rotation for
614
+ any number of dimensions)
615
+ rot_axis1: Returns a rotation matrix for a rotation of theta (in radians)
616
+ about the 1-axis (clockwise around the x axis)
617
+ rot_ccw_axis2: Returns a rotation matrix for a rotation of theta (in radians)
618
+ about the 2-axis (counterclockwise around the y axis)
619
+ rot_ccw_axis3: Returns a rotation matrix for a rotation of theta (in radians)
620
+ about the 3-axis (counterclockwise around the z axis)
621
+ """
622
+ return rot_givens(2, 1, theta, dim=3)
623
+
624
+
625
+ @doctest_depends_on(modules=('numpy',))
626
+ def symarray(prefix, shape, **kwargs): # pragma: no cover
627
+ r"""Create a numpy ndarray of symbols (as an object array).
628
+
629
+ The created symbols are named ``prefix_i1_i2_``... You should thus provide a
630
+ non-empty prefix if you want your symbols to be unique for different output
631
+ arrays, as SymPy symbols with identical names are the same object.
632
+
633
+ Parameters
634
+ ----------
635
+
636
+ prefix : string
637
+ A prefix prepended to the name of every symbol.
638
+
639
+ shape : int or tuple
640
+ Shape of the created array. If an int, the array is one-dimensional; for
641
+ more than one dimension the shape must be a tuple.
642
+
643
+ \*\*kwargs : dict
644
+ keyword arguments passed on to Symbol
645
+
646
+ Examples
647
+ ========
648
+ These doctests require numpy.
649
+
650
+ >>> from sympy import symarray
651
+ >>> symarray('', 3)
652
+ [_0 _1 _2]
653
+
654
+ If you want multiple symarrays to contain distinct symbols, you *must*
655
+ provide unique prefixes:
656
+
657
+ >>> a = symarray('', 3)
658
+ >>> b = symarray('', 3)
659
+ >>> a[0] == b[0]
660
+ True
661
+ >>> a = symarray('a', 3)
662
+ >>> b = symarray('b', 3)
663
+ >>> a[0] == b[0]
664
+ False
665
+
666
+ Creating symarrays with a prefix:
667
+
668
+ >>> symarray('a', 3)
669
+ [a_0 a_1 a_2]
670
+
671
+ For more than one dimension, the shape must be given as a tuple:
672
+
673
+ >>> symarray('a', (2, 3))
674
+ [[a_0_0 a_0_1 a_0_2]
675
+ [a_1_0 a_1_1 a_1_2]]
676
+ >>> symarray('a', (2, 3, 2))
677
+ [[[a_0_0_0 a_0_0_1]
678
+ [a_0_1_0 a_0_1_1]
679
+ [a_0_2_0 a_0_2_1]]
680
+ <BLANKLINE>
681
+ [[a_1_0_0 a_1_0_1]
682
+ [a_1_1_0 a_1_1_1]
683
+ [a_1_2_0 a_1_2_1]]]
684
+
685
+ For setting assumptions of the underlying Symbols:
686
+
687
+ >>> [s.is_real for s in symarray('a', 2, real=True)]
688
+ [True, True]
689
+ """
690
+ from numpy import empty, ndindex
691
+ arr = empty(shape, dtype=object)
692
+ for index in ndindex(shape):
693
+ arr[index] = Symbol('%s_%s' % (prefix, '_'.join(map(str, index))),
694
+ **kwargs)
695
+ return arr
696
+
697
+
698
+ ###############
699
+ # Functions
700
+ ###############
701
+
702
+ def casoratian(seqs, n, zero=True):
703
+ """Given linear difference operator L of order 'k' and homogeneous
704
+ equation Ly = 0 we want to compute kernel of L, which is a set
705
+ of 'k' sequences: a(n), b(n), ... z(n).
706
+
707
+ Solutions of L are linearly independent iff their Casoratian,
708
+ denoted as C(a, b, ..., z), do not vanish for n = 0.
709
+
710
+ Casoratian is defined by k x k determinant::
711
+
712
+ + a(n) b(n) . . . z(n) +
713
+ | a(n+1) b(n+1) . . . z(n+1) |
714
+ | . . . . |
715
+ | . . . . |
716
+ | . . . . |
717
+ + a(n+k-1) b(n+k-1) . . . z(n+k-1) +
718
+
719
+ It proves very useful in rsolve_hyper() where it is applied
720
+ to a generating set of a recurrence to factor out linearly
721
+ dependent solutions and return a basis:
722
+
723
+ >>> from sympy import Symbol, casoratian, factorial
724
+ >>> n = Symbol('n', integer=True)
725
+
726
+ Exponential and factorial are linearly independent:
727
+
728
+ >>> casoratian([2**n, factorial(n)], n) != 0
729
+ True
730
+
731
+ """
732
+
733
+ seqs = list(map(sympify, seqs))
734
+
735
+ if not zero:
736
+ f = lambda i, j: seqs[j].subs(n, n + i)
737
+ else:
738
+ f = lambda i, j: seqs[j].subs(n, i)
739
+
740
+ k = len(seqs)
741
+
742
+ return Matrix(k, k, f).det()
743
+
744
+
745
+ def eye(*args, **kwargs):
746
+ """Create square identity matrix n x n
747
+
748
+ See Also
749
+ ========
750
+
751
+ diag
752
+ zeros
753
+ ones
754
+ """
755
+
756
+ return Matrix.eye(*args, **kwargs)
757
+
758
+
759
+ def diag(*values, strict=True, unpack=False, **kwargs):
760
+ """Returns a matrix with the provided values placed on the
761
+ diagonal. If non-square matrices are included, they will
762
+ produce a block-diagonal matrix.
763
+
764
+ Examples
765
+ ========
766
+
767
+ This version of diag is a thin wrapper to Matrix.diag that differs
768
+ in that it treats all lists like matrices -- even when a single list
769
+ is given. If this is not desired, either put a `*` before the list or
770
+ set `unpack=True`.
771
+
772
+ >>> from sympy import diag
773
+
774
+ >>> diag([1, 2, 3], unpack=True) # = diag(1,2,3) or diag(*[1,2,3])
775
+ Matrix([
776
+ [1, 0, 0],
777
+ [0, 2, 0],
778
+ [0, 0, 3]])
779
+
780
+ >>> diag([1, 2, 3]) # a column vector
781
+ Matrix([
782
+ [1],
783
+ [2],
784
+ [3]])
785
+
786
+ See Also
787
+ ========
788
+ .matrixbase.MatrixBase.eye
789
+ .matrixbase.MatrixBase.diagonal
790
+ .matrixbase.MatrixBase.diag
791
+ .expressions.blockmatrix.BlockMatrix
792
+ """
793
+ return Matrix.diag(*values, strict=strict, unpack=unpack, **kwargs)
794
+
795
+
796
+ def GramSchmidt(vlist, orthonormal=False):
797
+ """Apply the Gram-Schmidt process to a set of vectors.
798
+
799
+ Parameters
800
+ ==========
801
+
802
+ vlist : List of Matrix
803
+ Vectors to be orthogonalized for.
804
+
805
+ orthonormal : Bool, optional
806
+ If true, return an orthonormal basis.
807
+
808
+ Returns
809
+ =======
810
+
811
+ vlist : List of Matrix
812
+ Orthogonalized vectors
813
+
814
+ Notes
815
+ =====
816
+
817
+ This routine is mostly duplicate from ``Matrix.orthogonalize``,
818
+ except for some difference that this always raises error when
819
+ linearly dependent vectors are found, and the keyword ``normalize``
820
+ has been named as ``orthonormal`` in this function.
821
+
822
+ See Also
823
+ ========
824
+
825
+ .matrixbase.MatrixBase.orthogonalize
826
+
827
+ References
828
+ ==========
829
+
830
+ .. [1] https://en.wikipedia.org/wiki/Gram%E2%80%93Schmidt_process
831
+ """
832
+ return MutableDenseMatrix.orthogonalize(
833
+ *vlist, normalize=orthonormal, rankcheck=True
834
+ )
835
+
836
+
837
+ def hessian(f, varlist, constraints=()):
838
+ """Compute Hessian matrix for a function f wrt parameters in varlist
839
+ which may be given as a sequence or a row/column vector. A list of
840
+ constraints may optionally be given.
841
+
842
+ Examples
843
+ ========
844
+
845
+ >>> from sympy import Function, hessian, pprint
846
+ >>> from sympy.abc import x, y
847
+ >>> f = Function('f')(x, y)
848
+ >>> g1 = Function('g')(x, y)
849
+ >>> g2 = x**2 + 3*y
850
+ >>> pprint(hessian(f, (x, y), [g1, g2]))
851
+ [ d d ]
852
+ [ 0 0 --(g(x, y)) --(g(x, y)) ]
853
+ [ dx dy ]
854
+ [ ]
855
+ [ 0 0 2*x 3 ]
856
+ [ ]
857
+ [ 2 2 ]
858
+ [d d d ]
859
+ [--(g(x, y)) 2*x ---(f(x, y)) -----(f(x, y))]
860
+ [dx 2 dy dx ]
861
+ [ dx ]
862
+ [ ]
863
+ [ 2 2 ]
864
+ [d d d ]
865
+ [--(g(x, y)) 3 -----(f(x, y)) ---(f(x, y)) ]
866
+ [dy dy dx 2 ]
867
+ [ dy ]
868
+
869
+ References
870
+ ==========
871
+
872
+ .. [1] https://en.wikipedia.org/wiki/Hessian_matrix
873
+
874
+ See Also
875
+ ========
876
+
877
+ sympy.matrices.matrixbase.MatrixBase.jacobian
878
+ wronskian
879
+ """
880
+ # f is the expression representing a function f, return regular matrix
881
+ if isinstance(varlist, MatrixBase):
882
+ if 1 not in varlist.shape:
883
+ raise ShapeError("`varlist` must be a column or row vector.")
884
+ if varlist.cols == 1:
885
+ varlist = varlist.T
886
+ varlist = varlist.tolist()[0]
887
+ if is_sequence(varlist):
888
+ n = len(varlist)
889
+ if not n:
890
+ raise ShapeError("`len(varlist)` must not be zero.")
891
+ else:
892
+ raise ValueError("Improper variable list in hessian function")
893
+ if not getattr(f, 'diff'):
894
+ # check differentiability
895
+ raise ValueError("Function `f` (%s) is not differentiable" % f)
896
+ m = len(constraints)
897
+ N = m + n
898
+ out = zeros(N)
899
+ for k, g in enumerate(constraints):
900
+ if not getattr(g, 'diff'):
901
+ # check differentiability
902
+ raise ValueError("Function `f` (%s) is not differentiable" % f)
903
+ for i in range(n):
904
+ out[k, i + m] = g.diff(varlist[i])
905
+ for i in range(n):
906
+ for j in range(i, n):
907
+ out[i + m, j + m] = f.diff(varlist[i]).diff(varlist[j])
908
+ for i in range(N):
909
+ for j in range(i + 1, N):
910
+ out[j, i] = out[i, j]
911
+ return out
912
+
913
+
914
+ def jordan_cell(eigenval, n):
915
+ """
916
+ Create a Jordan block:
917
+
918
+ Examples
919
+ ========
920
+
921
+ >>> from sympy import jordan_cell
922
+ >>> from sympy.abc import x
923
+ >>> jordan_cell(x, 4)
924
+ Matrix([
925
+ [x, 1, 0, 0],
926
+ [0, x, 1, 0],
927
+ [0, 0, x, 1],
928
+ [0, 0, 0, x]])
929
+ """
930
+
931
+ return Matrix.jordan_block(size=n, eigenvalue=eigenval)
932
+
933
+
934
+ def matrix_multiply_elementwise(A, B):
935
+ """Return the Hadamard product (elementwise product) of A and B
936
+
937
+ >>> from sympy import Matrix, matrix_multiply_elementwise
938
+ >>> A = Matrix([[0, 1, 2], [3, 4, 5]])
939
+ >>> B = Matrix([[1, 10, 100], [100, 10, 1]])
940
+ >>> matrix_multiply_elementwise(A, B)
941
+ Matrix([
942
+ [ 0, 10, 200],
943
+ [300, 40, 5]])
944
+
945
+ See Also
946
+ ========
947
+
948
+ sympy.matrices.matrixbase.MatrixBase.__mul__
949
+ """
950
+ return A.multiply_elementwise(B)
951
+
952
+
953
+ def ones(*args, **kwargs):
954
+ """Returns a matrix of ones with ``rows`` rows and ``cols`` columns;
955
+ if ``cols`` is omitted a square matrix will be returned.
956
+
957
+ See Also
958
+ ========
959
+
960
+ zeros
961
+ eye
962
+ diag
963
+ """
964
+
965
+ if 'c' in kwargs:
966
+ kwargs['cols'] = kwargs.pop('c')
967
+
968
+ return Matrix.ones(*args, **kwargs)
969
+
970
+
971
+ def randMatrix(r, c=None, min=0, max=99, seed=None, symmetric=False,
972
+ percent=100, prng=None):
973
+ """Create random matrix with dimensions ``r`` x ``c``. If ``c`` is omitted
974
+ the matrix will be square. If ``symmetric`` is True the matrix must be
975
+ square. If ``percent`` is less than 100 then only approximately the given
976
+ percentage of elements will be non-zero.
977
+
978
+ The pseudo-random number generator used to generate matrix is chosen in the
979
+ following way.
980
+
981
+ * If ``prng`` is supplied, it will be used as random number generator.
982
+ It should be an instance of ``random.Random``, or at least have
983
+ ``randint`` and ``shuffle`` methods with same signatures.
984
+ * if ``prng`` is not supplied but ``seed`` is supplied, then new
985
+ ``random.Random`` with given ``seed`` will be created;
986
+ * otherwise, a new ``random.Random`` with default seed will be used.
987
+
988
+ Examples
989
+ ========
990
+
991
+ >>> from sympy import randMatrix
992
+ >>> randMatrix(3) # doctest:+SKIP
993
+ [25, 45, 27]
994
+ [44, 54, 9]
995
+ [23, 96, 46]
996
+ >>> randMatrix(3, 2) # doctest:+SKIP
997
+ [87, 29]
998
+ [23, 37]
999
+ [90, 26]
1000
+ >>> randMatrix(3, 3, 0, 2) # doctest:+SKIP
1001
+ [0, 2, 0]
1002
+ [2, 0, 1]
1003
+ [0, 0, 1]
1004
+ >>> randMatrix(3, symmetric=True) # doctest:+SKIP
1005
+ [85, 26, 29]
1006
+ [26, 71, 43]
1007
+ [29, 43, 57]
1008
+ >>> A = randMatrix(3, seed=1)
1009
+ >>> B = randMatrix(3, seed=2)
1010
+ >>> A == B
1011
+ False
1012
+ >>> A == randMatrix(3, seed=1)
1013
+ True
1014
+ >>> randMatrix(3, symmetric=True, percent=50) # doctest:+SKIP
1015
+ [77, 70, 0],
1016
+ [70, 0, 0],
1017
+ [ 0, 0, 88]
1018
+ """
1019
+ # Note that ``Random()`` is equivalent to ``Random(None)``
1020
+ prng = prng or random.Random(seed)
1021
+
1022
+ if c is None:
1023
+ c = r
1024
+
1025
+ if symmetric and r != c:
1026
+ raise ValueError('For symmetric matrices, r must equal c, but %i != %i' % (r, c))
1027
+
1028
+ ij = range(r * c)
1029
+ if percent != 100:
1030
+ ij = prng.sample(ij, int(len(ij)*percent // 100))
1031
+
1032
+ m = zeros(r, c)
1033
+
1034
+ if not symmetric:
1035
+ for ijk in ij:
1036
+ i, j = divmod(ijk, c)
1037
+ m[i, j] = prng.randint(min, max)
1038
+ else:
1039
+ for ijk in ij:
1040
+ i, j = divmod(ijk, c)
1041
+ if i <= j:
1042
+ m[i, j] = m[j, i] = prng.randint(min, max)
1043
+
1044
+ return m
1045
+
1046
+
1047
+ def wronskian(functions, var, method='bareiss'):
1048
+ """
1049
+ Compute Wronskian for [] of functions
1050
+
1051
+ ::
1052
+
1053
+ | f1 f2 ... fn |
1054
+ | f1' f2' ... fn' |
1055
+ | . . . . |
1056
+ W(f1, ..., fn) = | . . . . |
1057
+ | . . . . |
1058
+ | (n) (n) (n) |
1059
+ | D (f1) D (f2) ... D (fn) |
1060
+
1061
+ see: https://en.wikipedia.org/wiki/Wronskian
1062
+
1063
+ See Also
1064
+ ========
1065
+
1066
+ sympy.matrices.matrixbase.MatrixBase.jacobian
1067
+ hessian
1068
+ """
1069
+
1070
+ functions = [sympify(f) for f in functions]
1071
+ n = len(functions)
1072
+ if n == 0:
1073
+ return S.One
1074
+ W = Matrix(n, n, lambda i, j: functions[i].diff(var, j))
1075
+ return W.det(method)
1076
+
1077
+
1078
+ def zeros(*args, **kwargs):
1079
+ """Returns a matrix of zeros with ``rows`` rows and ``cols`` columns;
1080
+ if ``cols`` is omitted a square matrix will be returned.
1081
+
1082
+ See Also
1083
+ ========
1084
+
1085
+ ones
1086
+ eye
1087
+ diag
1088
+ """
1089
+
1090
+ if 'c' in kwargs:
1091
+ kwargs['cols'] = kwargs.pop('c')
1092
+
1093
+ return Matrix.zeros(*args, **kwargs)
phi4/lib/python3.10/site-packages/sympy/matrices/determinant.py ADDED
@@ -0,0 +1,1021 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from types import FunctionType
2
+
3
+ from sympy.core.cache import cacheit
4
+ from sympy.core.numbers import Float, Integer
5
+ from sympy.core.singleton import S
6
+ from sympy.core.symbol import uniquely_named_symbol
7
+ from sympy.core.mul import Mul
8
+ from sympy.polys import PurePoly, cancel
9
+ from sympy.functions.combinatorial.numbers import nC
10
+ from sympy.polys.matrices.domainmatrix import DomainMatrix
11
+ from sympy.polys.matrices.ddm import DDM
12
+
13
+ from .exceptions import NonSquareMatrixError
14
+ from .utilities import (
15
+ _get_intermediate_simp, _get_intermediate_simp_bool,
16
+ _iszero, _is_zero_after_expand_mul, _dotprodsimp, _simplify)
17
+
18
+
19
+ def _find_reasonable_pivot(col, iszerofunc=_iszero, simpfunc=_simplify):
20
+ """ Find the lowest index of an item in ``col`` that is
21
+ suitable for a pivot. If ``col`` consists only of
22
+ Floats, the pivot with the largest norm is returned.
23
+ Otherwise, the first element where ``iszerofunc`` returns
24
+ False is used. If ``iszerofunc`` does not return false,
25
+ items are simplified and retested until a suitable
26
+ pivot is found.
27
+
28
+ Returns a 4-tuple
29
+ (pivot_offset, pivot_val, assumed_nonzero, newly_determined)
30
+ where pivot_offset is the index of the pivot, pivot_val is
31
+ the (possibly simplified) value of the pivot, assumed_nonzero
32
+ is True if an assumption that the pivot was non-zero
33
+ was made without being proved, and newly_determined are
34
+ elements that were simplified during the process of pivot
35
+ finding."""
36
+
37
+ newly_determined = []
38
+ col = list(col)
39
+ # a column that contains a mix of floats and integers
40
+ # but at least one float is considered a numerical
41
+ # column, and so we do partial pivoting
42
+ if all(isinstance(x, (Float, Integer)) for x in col) and any(
43
+ isinstance(x, Float) for x in col):
44
+ col_abs = [abs(x) for x in col]
45
+ max_value = max(col_abs)
46
+ if iszerofunc(max_value):
47
+ # just because iszerofunc returned True, doesn't
48
+ # mean the value is numerically zero. Make sure
49
+ # to replace all entries with numerical zeros
50
+ if max_value != 0:
51
+ newly_determined = [(i, 0) for i, x in enumerate(col) if x != 0]
52
+ return (None, None, False, newly_determined)
53
+ index = col_abs.index(max_value)
54
+ return (index, col[index], False, newly_determined)
55
+
56
+ # PASS 1 (iszerofunc directly)
57
+ possible_zeros = []
58
+ for i, x in enumerate(col):
59
+ is_zero = iszerofunc(x)
60
+ # is someone wrote a custom iszerofunc, it may return
61
+ # BooleanFalse or BooleanTrue instead of True or False,
62
+ # so use == for comparison instead of `is`
63
+ if is_zero == False:
64
+ # we found something that is definitely not zero
65
+ return (i, x, False, newly_determined)
66
+ possible_zeros.append(is_zero)
67
+
68
+ # by this point, we've found no certain non-zeros
69
+ if all(possible_zeros):
70
+ # if everything is definitely zero, we have
71
+ # no pivot
72
+ return (None, None, False, newly_determined)
73
+
74
+ # PASS 2 (iszerofunc after simplify)
75
+ # we haven't found any for-sure non-zeros, so
76
+ # go through the elements iszerofunc couldn't
77
+ # make a determination about and opportunistically
78
+ # simplify to see if we find something
79
+ for i, x in enumerate(col):
80
+ if possible_zeros[i] is not None:
81
+ continue
82
+ simped = simpfunc(x)
83
+ is_zero = iszerofunc(simped)
84
+ if is_zero in (True, False):
85
+ newly_determined.append((i, simped))
86
+ if is_zero == False:
87
+ return (i, simped, False, newly_determined)
88
+ possible_zeros[i] = is_zero
89
+
90
+ # after simplifying, some things that were recognized
91
+ # as zeros might be zeros
92
+ if all(possible_zeros):
93
+ # if everything is definitely zero, we have
94
+ # no pivot
95
+ return (None, None, False, newly_determined)
96
+
97
+ # PASS 3 (.equals(0))
98
+ # some expressions fail to simplify to zero, but
99
+ # ``.equals(0)`` evaluates to True. As a last-ditch
100
+ # attempt, apply ``.equals`` to these expressions
101
+ for i, x in enumerate(col):
102
+ if possible_zeros[i] is not None:
103
+ continue
104
+ if x.equals(S.Zero):
105
+ # ``.iszero`` may return False with
106
+ # an implicit assumption (e.g., ``x.equals(0)``
107
+ # when ``x`` is a symbol), so only treat it
108
+ # as proved when ``.equals(0)`` returns True
109
+ possible_zeros[i] = True
110
+ newly_determined.append((i, S.Zero))
111
+
112
+ if all(possible_zeros):
113
+ return (None, None, False, newly_determined)
114
+
115
+ # at this point there is nothing that could definitely
116
+ # be a pivot. To maintain compatibility with existing
117
+ # behavior, we'll assume that an illdetermined thing is
118
+ # non-zero. We should probably raise a warning in this case
119
+ i = possible_zeros.index(None)
120
+ return (i, col[i], True, newly_determined)
121
+
122
+
123
+ def _find_reasonable_pivot_naive(col, iszerofunc=_iszero, simpfunc=None):
124
+ """
125
+ Helper that computes the pivot value and location from a
126
+ sequence of contiguous matrix column elements. As a side effect
127
+ of the pivot search, this function may simplify some of the elements
128
+ of the input column. A list of these simplified entries and their
129
+ indices are also returned.
130
+ This function mimics the behavior of _find_reasonable_pivot(),
131
+ but does less work trying to determine if an indeterminate candidate
132
+ pivot simplifies to zero. This more naive approach can be much faster,
133
+ with the trade-off that it may erroneously return a pivot that is zero.
134
+
135
+ ``col`` is a sequence of contiguous column entries to be searched for
136
+ a suitable pivot.
137
+ ``iszerofunc`` is a callable that returns a Boolean that indicates
138
+ if its input is zero, or None if no such determination can be made.
139
+ ``simpfunc`` is a callable that simplifies its input. It must return
140
+ its input if it does not simplify its input. Passing in
141
+ ``simpfunc=None`` indicates that the pivot search should not attempt
142
+ to simplify any candidate pivots.
143
+
144
+ Returns a 4-tuple:
145
+ (pivot_offset, pivot_val, assumed_nonzero, newly_determined)
146
+ ``pivot_offset`` is the sequence index of the pivot.
147
+ ``pivot_val`` is the value of the pivot.
148
+ pivot_val and col[pivot_index] are equivalent, but will be different
149
+ when col[pivot_index] was simplified during the pivot search.
150
+ ``assumed_nonzero`` is a boolean indicating if the pivot cannot be
151
+ guaranteed to be zero. If assumed_nonzero is true, then the pivot
152
+ may or may not be non-zero. If assumed_nonzero is false, then
153
+ the pivot is non-zero.
154
+ ``newly_determined`` is a list of index-value pairs of pivot candidates
155
+ that were simplified during the pivot search.
156
+ """
157
+
158
+ # indeterminates holds the index-value pairs of each pivot candidate
159
+ # that is neither zero or non-zero, as determined by iszerofunc().
160
+ # If iszerofunc() indicates that a candidate pivot is guaranteed
161
+ # non-zero, or that every candidate pivot is zero then the contents
162
+ # of indeterminates are unused.
163
+ # Otherwise, the only viable candidate pivots are symbolic.
164
+ # In this case, indeterminates will have at least one entry,
165
+ # and all but the first entry are ignored when simpfunc is None.
166
+ indeterminates = []
167
+ for i, col_val in enumerate(col):
168
+ col_val_is_zero = iszerofunc(col_val)
169
+ if col_val_is_zero == False:
170
+ # This pivot candidate is non-zero.
171
+ return i, col_val, False, []
172
+ elif col_val_is_zero is None:
173
+ # The candidate pivot's comparison with zero
174
+ # is indeterminate.
175
+ indeterminates.append((i, col_val))
176
+
177
+ if len(indeterminates) == 0:
178
+ # All candidate pivots are guaranteed to be zero, i.e. there is
179
+ # no pivot.
180
+ return None, None, False, []
181
+
182
+ if simpfunc is None:
183
+ # Caller did not pass in a simplification function that might
184
+ # determine if an indeterminate pivot candidate is guaranteed
185
+ # to be nonzero, so assume the first indeterminate candidate
186
+ # is non-zero.
187
+ return indeterminates[0][0], indeterminates[0][1], True, []
188
+
189
+ # newly_determined holds index-value pairs of candidate pivots
190
+ # that were simplified during the search for a non-zero pivot.
191
+ newly_determined = []
192
+ for i, col_val in indeterminates:
193
+ tmp_col_val = simpfunc(col_val)
194
+ if id(col_val) != id(tmp_col_val):
195
+ # simpfunc() simplified this candidate pivot.
196
+ newly_determined.append((i, tmp_col_val))
197
+ if iszerofunc(tmp_col_val) == False:
198
+ # Candidate pivot simplified to a guaranteed non-zero value.
199
+ return i, tmp_col_val, False, newly_determined
200
+
201
+ return indeterminates[0][0], indeterminates[0][1], True, newly_determined
202
+
203
+
204
+ # This functions is a candidate for caching if it gets implemented for matrices.
205
+ def _berkowitz_toeplitz_matrix(M):
206
+ """Return (A,T) where T the Toeplitz matrix used in the Berkowitz algorithm
207
+ corresponding to ``M`` and A is the first principal submatrix.
208
+ """
209
+
210
+ # the 0 x 0 case is trivial
211
+ if M.rows == 0 and M.cols == 0:
212
+ return M._new(1,1, [M.one])
213
+
214
+ #
215
+ # Partition M = [ a_11 R ]
216
+ # [ C A ]
217
+ #
218
+
219
+ a, R = M[0,0], M[0, 1:]
220
+ C, A = M[1:, 0], M[1:,1:]
221
+
222
+ #
223
+ # The Toeplitz matrix looks like
224
+ #
225
+ # [ 1 ]
226
+ # [ -a 1 ]
227
+ # [ -RC -a 1 ]
228
+ # [ -RAC -RC -a 1 ]
229
+ # [ -RA**2C -RAC -RC -a 1 ]
230
+ # etc.
231
+
232
+ # Compute the diagonal entries.
233
+ # Because multiplying matrix times vector is so much
234
+ # more efficient than matrix times matrix, recursively
235
+ # compute -R * A**n * C.
236
+ diags = [C]
237
+ for i in range(M.rows - 2):
238
+ diags.append(A.multiply(diags[i], dotprodsimp=None))
239
+ diags = [(-R).multiply(d, dotprodsimp=None)[0, 0] for d in diags]
240
+ diags = [M.one, -a] + diags
241
+
242
+ def entry(i,j):
243
+ if j > i:
244
+ return M.zero
245
+ return diags[i - j]
246
+
247
+ toeplitz = M._new(M.cols + 1, M.rows, entry)
248
+ return (A, toeplitz)
249
+
250
+
251
+ # This functions is a candidate for caching if it gets implemented for matrices.
252
+ def _berkowitz_vector(M):
253
+ """ Run the Berkowitz algorithm and return a vector whose entries
254
+ are the coefficients of the characteristic polynomial of ``M``.
255
+
256
+ Given N x N matrix, efficiently compute
257
+ coefficients of characteristic polynomials of ``M``
258
+ without division in the ground domain.
259
+
260
+ This method is particularly useful for computing determinant,
261
+ principal minors and characteristic polynomial when ``M``
262
+ has complicated coefficients e.g. polynomials. Semi-direct
263
+ usage of this algorithm is also important in computing
264
+ efficiently sub-resultant PRS.
265
+
266
+ Assuming that M is a square matrix of dimension N x N and
267
+ I is N x N identity matrix, then the Berkowitz vector is
268
+ an N x 1 vector whose entries are coefficients of the
269
+ polynomial
270
+
271
+ charpoly(M) = det(t*I - M)
272
+
273
+ As a consequence, all polynomials generated by Berkowitz
274
+ algorithm are monic.
275
+
276
+ For more information on the implemented algorithm refer to:
277
+
278
+ [1] S.J. Berkowitz, On computing the determinant in small
279
+ parallel time using a small number of processors, ACM,
280
+ Information Processing Letters 18, 1984, pp. 147-150
281
+
282
+ [2] M. Keber, Division-Free computation of sub-resultants
283
+ using Bezout matrices, Tech. Report MPI-I-2006-1-006,
284
+ Saarbrucken, 2006
285
+ """
286
+
287
+ # handle the trivial cases
288
+ if M.rows == 0 and M.cols == 0:
289
+ return M._new(1, 1, [M.one])
290
+ elif M.rows == 1 and M.cols == 1:
291
+ return M._new(2, 1, [M.one, -M[0,0]])
292
+
293
+ submat, toeplitz = _berkowitz_toeplitz_matrix(M)
294
+
295
+ return toeplitz.multiply(_berkowitz_vector(submat), dotprodsimp=None)
296
+
297
+
298
+ def _adjugate(M, method="berkowitz"):
299
+ """Returns the adjugate, or classical adjoint, of
300
+ a matrix. That is, the transpose of the matrix of cofactors.
301
+
302
+ https://en.wikipedia.org/wiki/Adjugate
303
+
304
+ Parameters
305
+ ==========
306
+
307
+ method : string, optional
308
+ Method to use to find the cofactors, can be "bareiss", "berkowitz",
309
+ "bird", "laplace" or "lu".
310
+
311
+ Examples
312
+ ========
313
+
314
+ >>> from sympy import Matrix
315
+ >>> M = Matrix([[1, 2], [3, 4]])
316
+ >>> M.adjugate()
317
+ Matrix([
318
+ [ 4, -2],
319
+ [-3, 1]])
320
+
321
+ See Also
322
+ ========
323
+
324
+ cofactor_matrix
325
+ sympy.matrices.matrixbase.MatrixBase.transpose
326
+ """
327
+
328
+ return M.cofactor_matrix(method=method).transpose()
329
+
330
+
331
+ # This functions is a candidate for caching if it gets implemented for matrices.
332
+ def _charpoly(M, x='lambda', simplify=_simplify):
333
+ """Computes characteristic polynomial det(x*I - M) where I is
334
+ the identity matrix.
335
+
336
+ A PurePoly is returned, so using different variables for ``x`` does
337
+ not affect the comparison or the polynomials:
338
+
339
+ Parameters
340
+ ==========
341
+
342
+ x : string, optional
343
+ Name for the "lambda" variable, defaults to "lambda".
344
+
345
+ simplify : function, optional
346
+ Simplification function to use on the characteristic polynomial
347
+ calculated. Defaults to ``simplify``.
348
+
349
+ Examples
350
+ ========
351
+
352
+ >>> from sympy import Matrix
353
+ >>> from sympy.abc import x, y
354
+ >>> M = Matrix([[1, 3], [2, 0]])
355
+ >>> M.charpoly()
356
+ PurePoly(lambda**2 - lambda - 6, lambda, domain='ZZ')
357
+ >>> M.charpoly(x) == M.charpoly(y)
358
+ True
359
+ >>> M.charpoly(x) == M.charpoly(y)
360
+ True
361
+
362
+ Specifying ``x`` is optional; a symbol named ``lambda`` is used by
363
+ default (which looks good when pretty-printed in unicode):
364
+
365
+ >>> M.charpoly().as_expr()
366
+ lambda**2 - lambda - 6
367
+
368
+ And if ``x`` clashes with an existing symbol, underscores will
369
+ be prepended to the name to make it unique:
370
+
371
+ >>> M = Matrix([[1, 2], [x, 0]])
372
+ >>> M.charpoly(x).as_expr()
373
+ _x**2 - _x - 2*x
374
+
375
+ Whether you pass a symbol or not, the generator can be obtained
376
+ with the gen attribute since it may not be the same as the symbol
377
+ that was passed:
378
+
379
+ >>> M.charpoly(x).gen
380
+ _x
381
+ >>> M.charpoly(x).gen == x
382
+ False
383
+
384
+ Notes
385
+ =====
386
+
387
+ The Samuelson-Berkowitz algorithm is used to compute
388
+ the characteristic polynomial efficiently and without any
389
+ division operations. Thus the characteristic polynomial over any
390
+ commutative ring without zero divisors can be computed.
391
+
392
+ If the determinant det(x*I - M) can be found out easily as
393
+ in the case of an upper or a lower triangular matrix, then
394
+ instead of Samuelson-Berkowitz algorithm, eigenvalues are computed
395
+ and the characteristic polynomial with their help.
396
+
397
+ See Also
398
+ ========
399
+
400
+ det
401
+ """
402
+
403
+ if not M.is_square:
404
+ raise NonSquareMatrixError()
405
+
406
+ # Use DomainMatrix. We are already going to convert this to a Poly so there
407
+ # is no need to worry about expanding powers etc. Also since this algorithm
408
+ # does not require division or zero detection it is fine to use EX.
409
+ #
410
+ # M.to_DM() will fall back on EXRAW rather than EX. EXRAW is a lot faster
411
+ # for elementary arithmetic because it does not call cancel for each
412
+ # operation but it generates large unsimplified results that are slow in
413
+ # the subsequent call to simplify. Using EX instead is faster overall
414
+ # but at least in some cases EXRAW+simplify gives a simpler result so we
415
+ # preserve that existing behaviour of charpoly for now...
416
+ dM = M.to_DM()
417
+
418
+ K = dM.domain
419
+
420
+ cp = dM.charpoly()
421
+
422
+ x = uniquely_named_symbol(x, [M], modify=lambda s: '_' + s)
423
+
424
+ if K.is_EXRAW or simplify is not _simplify:
425
+ # XXX: Converting back to Expr is expensive. We only do it if the
426
+ # caller supplied a custom simplify function for backwards
427
+ # compatibility or otherwise if the domain was EX. For any other domain
428
+ # there should be no benefit in simplifying at this stage because Poly
429
+ # will put everything into canonical form anyway.
430
+ berk_vector = [K.to_sympy(c) for c in cp]
431
+ berk_vector = [simplify(a) for a in berk_vector]
432
+ p = PurePoly(berk_vector, x)
433
+
434
+ else:
435
+ # Convert from the list of domain elements directly to Poly.
436
+ p = PurePoly(cp, x, domain=K)
437
+
438
+ return p
439
+
440
+
441
+ def _cofactor(M, i, j, method="berkowitz"):
442
+ """Calculate the cofactor of an element.
443
+
444
+ Parameters
445
+ ==========
446
+
447
+ method : string, optional
448
+ Method to use to find the cofactors, can be "bareiss", "berkowitz",
449
+ "bird", "laplace" or "lu".
450
+
451
+ Examples
452
+ ========
453
+
454
+ >>> from sympy import Matrix
455
+ >>> M = Matrix([[1, 2], [3, 4]])
456
+ >>> M.cofactor(0, 1)
457
+ -3
458
+
459
+ See Also
460
+ ========
461
+
462
+ cofactor_matrix
463
+ minor
464
+ minor_submatrix
465
+ """
466
+
467
+ if not M.is_square or M.rows < 1:
468
+ raise NonSquareMatrixError()
469
+
470
+ return S.NegativeOne**((i + j) % 2) * M.minor(i, j, method)
471
+
472
+
473
+ def _cofactor_matrix(M, method="berkowitz"):
474
+ """Return a matrix containing the cofactor of each element.
475
+
476
+ Parameters
477
+ ==========
478
+
479
+ method : string, optional
480
+ Method to use to find the cofactors, can be "bareiss", "berkowitz",
481
+ "bird", "laplace" or "lu".
482
+
483
+ Examples
484
+ ========
485
+
486
+ >>> from sympy import Matrix
487
+ >>> M = Matrix([[1, 2], [3, 4]])
488
+ >>> M.cofactor_matrix()
489
+ Matrix([
490
+ [ 4, -3],
491
+ [-2, 1]])
492
+
493
+ See Also
494
+ ========
495
+
496
+ cofactor
497
+ minor
498
+ minor_submatrix
499
+ """
500
+
501
+ if not M.is_square:
502
+ raise NonSquareMatrixError()
503
+
504
+ return M._new(M.rows, M.cols,
505
+ lambda i, j: M.cofactor(i, j, method))
506
+
507
+ def _per(M):
508
+ """Returns the permanent of a matrix. Unlike determinant,
509
+ permanent is defined for both square and non-square matrices.
510
+
511
+ For an m x n matrix, with m less than or equal to n,
512
+ it is given as the sum over the permutations s of size
513
+ less than or equal to m on [1, 2, . . . n] of the product
514
+ from i = 1 to m of M[i, s[i]]. Taking the transpose will
515
+ not affect the value of the permanent.
516
+
517
+ In the case of a square matrix, this is the same as the permutation
518
+ definition of the determinant, but it does not take the sign of the
519
+ permutation into account. Computing the permanent with this definition
520
+ is quite inefficient, so here the Ryser formula is used.
521
+
522
+ Examples
523
+ ========
524
+
525
+ >>> from sympy import Matrix
526
+ >>> M = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
527
+ >>> M.per()
528
+ 450
529
+ >>> M = Matrix([1, 5, 7])
530
+ >>> M.per()
531
+ 13
532
+
533
+ References
534
+ ==========
535
+
536
+ .. [1] Prof. Frank Ben's notes: https://math.berkeley.edu/~bernd/ban275.pdf
537
+ .. [2] Wikipedia article on Permanent: https://en.wikipedia.org/wiki/Permanent_%28mathematics%29
538
+ .. [3] https://reference.wolfram.com/language/ref/Permanent.html
539
+ .. [4] Permanent of a rectangular matrix : https://arxiv.org/pdf/0904.3251.pdf
540
+ """
541
+ import itertools
542
+
543
+ m, n = M.shape
544
+ if m > n:
545
+ M = M.T
546
+ m, n = n, m
547
+ s = list(range(n))
548
+
549
+ subsets = []
550
+ for i in range(1, m + 1):
551
+ subsets += list(map(list, itertools.combinations(s, i)))
552
+
553
+ perm = 0
554
+ for subset in subsets:
555
+ prod = 1
556
+ sub_len = len(subset)
557
+ for i in range(m):
558
+ prod *= sum(M[i, j] for j in subset)
559
+ perm += prod * S.NegativeOne**sub_len * nC(n - sub_len, m - sub_len)
560
+ perm *= S.NegativeOne**m
561
+ return perm.simplify()
562
+
563
+ def _det_DOM(M):
564
+ DOM = DomainMatrix.from_Matrix(M, field=True, extension=True)
565
+ K = DOM.domain
566
+ return K.to_sympy(DOM.det())
567
+
568
+ # This functions is a candidate for caching if it gets implemented for matrices.
569
+ def _det(M, method="bareiss", iszerofunc=None):
570
+ """Computes the determinant of a matrix if ``M`` is a concrete matrix object
571
+ otherwise return an expressions ``Determinant(M)`` if ``M`` is a
572
+ ``MatrixSymbol`` or other expression.
573
+
574
+ Parameters
575
+ ==========
576
+
577
+ method : string, optional
578
+ Specifies the algorithm used for computing the matrix determinant.
579
+
580
+ If the matrix is at most 3x3, a hard-coded formula is used and the
581
+ specified method is ignored. Otherwise, it defaults to
582
+ ``'bareiss'``.
583
+
584
+ Also, if the matrix is an upper or a lower triangular matrix, determinant
585
+ is computed by simple multiplication of diagonal elements, and the
586
+ specified method is ignored.
587
+
588
+ If it is set to ``'domain-ge'``, then Gaussian elimination method will
589
+ be used via using DomainMatrix.
590
+
591
+ If it is set to ``'bareiss'``, Bareiss' fraction-free algorithm will
592
+ be used.
593
+
594
+ If it is set to ``'berkowitz'``, Berkowitz' algorithm will be used.
595
+
596
+ If it is set to ``'bird'``, Bird's algorithm will be used [1]_.
597
+
598
+ If it is set to ``'laplace'``, Laplace's algorithm will be used.
599
+
600
+ Otherwise, if it is set to ``'lu'``, LU decomposition will be used.
601
+
602
+ .. note::
603
+ For backward compatibility, legacy keys like "bareis" and
604
+ "det_lu" can still be used to indicate the corresponding
605
+ methods.
606
+ And the keys are also case-insensitive for now. However, it is
607
+ suggested to use the precise keys for specifying the method.
608
+
609
+ iszerofunc : FunctionType or None, optional
610
+ If it is set to ``None``, it will be defaulted to ``_iszero`` if the
611
+ method is set to ``'bareiss'``, and ``_is_zero_after_expand_mul`` if
612
+ the method is set to ``'lu'``.
613
+
614
+ It can also accept any user-specified zero testing function, if it
615
+ is formatted as a function which accepts a single symbolic argument
616
+ and returns ``True`` if it is tested as zero and ``False`` if it
617
+ tested as non-zero, and also ``None`` if it is undecidable.
618
+
619
+ Returns
620
+ =======
621
+
622
+ det : Basic
623
+ Result of determinant.
624
+
625
+ Raises
626
+ ======
627
+
628
+ ValueError
629
+ If unrecognized keys are given for ``method`` or ``iszerofunc``.
630
+
631
+ NonSquareMatrixError
632
+ If attempted to calculate determinant from a non-square matrix.
633
+
634
+ Examples
635
+ ========
636
+
637
+ >>> from sympy import Matrix, eye, det
638
+ >>> I3 = eye(3)
639
+ >>> det(I3)
640
+ 1
641
+ >>> M = Matrix([[1, 2], [3, 4]])
642
+ >>> det(M)
643
+ -2
644
+ >>> det(M) == M.det()
645
+ True
646
+ >>> M.det(method="domain-ge")
647
+ -2
648
+
649
+ References
650
+ ==========
651
+
652
+ .. [1] Bird, R. S. (2011). A simple division-free algorithm for computing
653
+ determinants. Inf. Process. Lett., 111(21), 1072-1074. doi:
654
+ 10.1016/j.ipl.2011.08.006
655
+ """
656
+
657
+ # sanitize `method`
658
+ method = method.lower()
659
+
660
+ if method == "bareis":
661
+ method = "bareiss"
662
+ elif method == "det_lu":
663
+ method = "lu"
664
+
665
+ if method not in ("bareiss", "berkowitz", "lu", "domain-ge", "bird",
666
+ "laplace"):
667
+ raise ValueError("Determinant method '%s' unrecognized" % method)
668
+
669
+ if iszerofunc is None:
670
+ if method == "bareiss":
671
+ iszerofunc = _is_zero_after_expand_mul
672
+ elif method == "lu":
673
+ iszerofunc = _iszero
674
+
675
+ elif not isinstance(iszerofunc, FunctionType):
676
+ raise ValueError("Zero testing method '%s' unrecognized" % iszerofunc)
677
+
678
+ n = M.rows
679
+
680
+ if n == M.cols: # square check is done in individual method functions
681
+ if n == 0:
682
+ return M.one
683
+ elif n == 1:
684
+ return M[0, 0]
685
+ elif n == 2:
686
+ m = M[0, 0] * M[1, 1] - M[0, 1] * M[1, 0]
687
+ return _get_intermediate_simp(_dotprodsimp)(m)
688
+ elif n == 3:
689
+ m = (M[0, 0] * M[1, 1] * M[2, 2]
690
+ + M[0, 1] * M[1, 2] * M[2, 0]
691
+ + M[0, 2] * M[1, 0] * M[2, 1]
692
+ - M[0, 2] * M[1, 1] * M[2, 0]
693
+ - M[0, 0] * M[1, 2] * M[2, 1]
694
+ - M[0, 1] * M[1, 0] * M[2, 2])
695
+ return _get_intermediate_simp(_dotprodsimp)(m)
696
+
697
+ dets = []
698
+ for b in M.strongly_connected_components():
699
+ if method == "domain-ge": # uses DomainMatrix to evaluate determinant
700
+ det = _det_DOM(M[b, b])
701
+ elif method == "bareiss":
702
+ det = M[b, b]._eval_det_bareiss(iszerofunc=iszerofunc)
703
+ elif method == "berkowitz":
704
+ det = M[b, b]._eval_det_berkowitz()
705
+ elif method == "lu":
706
+ det = M[b, b]._eval_det_lu(iszerofunc=iszerofunc)
707
+ elif method == "bird":
708
+ det = M[b, b]._eval_det_bird()
709
+ elif method == "laplace":
710
+ det = M[b, b]._eval_det_laplace()
711
+ dets.append(det)
712
+ return Mul(*dets)
713
+
714
+
715
+ # This functions is a candidate for caching if it gets implemented for matrices.
716
+ def _det_bareiss(M, iszerofunc=_is_zero_after_expand_mul):
717
+ """Compute matrix determinant using Bareiss' fraction-free
718
+ algorithm which is an extension of the well known Gaussian
719
+ elimination method. This approach is best suited for dense
720
+ symbolic matrices and will result in a determinant with
721
+ minimal number of fractions. It means that less term
722
+ rewriting is needed on resulting formulae.
723
+
724
+ Parameters
725
+ ==========
726
+
727
+ iszerofunc : function, optional
728
+ The function to use to determine zeros when doing an LU decomposition.
729
+ Defaults to ``lambda x: x.is_zero``.
730
+
731
+ TODO: Implement algorithm for sparse matrices (SFF),
732
+ http://www.eecis.udel.edu/~saunders/papers/sffge/it5.ps.
733
+ """
734
+
735
+ # Recursively implemented Bareiss' algorithm as per Deanna Richelle Leggett's
736
+ # thesis http://www.math.usm.edu/perry/Research/Thesis_DRL.pdf
737
+ def bareiss(mat, cumm=1):
738
+ if mat.rows == 0:
739
+ return mat.one
740
+ elif mat.rows == 1:
741
+ return mat[0, 0]
742
+
743
+ # find a pivot and extract the remaining matrix
744
+ # With the default iszerofunc, _find_reasonable_pivot slows down
745
+ # the computation by the factor of 2.5 in one test.
746
+ # Relevant issues: #10279 and #13877.
747
+ pivot_pos, pivot_val, _, _ = _find_reasonable_pivot(mat[:, 0], iszerofunc=iszerofunc)
748
+ if pivot_pos is None:
749
+ return mat.zero
750
+
751
+ # if we have a valid pivot, we'll do a "row swap", so keep the
752
+ # sign of the det
753
+ sign = (-1) ** (pivot_pos % 2)
754
+
755
+ # we want every row but the pivot row and every column
756
+ rows = [i for i in range(mat.rows) if i != pivot_pos]
757
+ cols = list(range(mat.cols))
758
+ tmp_mat = mat.extract(rows, cols)
759
+
760
+ def entry(i, j):
761
+ ret = (pivot_val*tmp_mat[i, j + 1] - mat[pivot_pos, j + 1]*tmp_mat[i, 0]) / cumm
762
+ if _get_intermediate_simp_bool(True):
763
+ return _dotprodsimp(ret)
764
+ elif not ret.is_Atom:
765
+ return cancel(ret)
766
+ return ret
767
+
768
+ return sign*bareiss(M._new(mat.rows - 1, mat.cols - 1, entry), pivot_val)
769
+
770
+ if not M.is_square:
771
+ raise NonSquareMatrixError()
772
+
773
+ if M.rows == 0:
774
+ return M.one
775
+ # sympy/matrices/tests/test_matrices.py contains a test that
776
+ # suggests that the determinant of a 0 x 0 matrix is one, by
777
+ # convention.
778
+
779
+ return bareiss(M)
780
+
781
+
782
+ def _det_berkowitz(M):
783
+ """ Use the Berkowitz algorithm to compute the determinant."""
784
+
785
+ if not M.is_square:
786
+ raise NonSquareMatrixError()
787
+
788
+ if M.rows == 0:
789
+ return M.one
790
+ # sympy/matrices/tests/test_matrices.py contains a test that
791
+ # suggests that the determinant of a 0 x 0 matrix is one, by
792
+ # convention.
793
+
794
+ berk_vector = _berkowitz_vector(M)
795
+ return (-1)**(len(berk_vector) - 1) * berk_vector[-1]
796
+
797
+
798
+ # This functions is a candidate for caching if it gets implemented for matrices.
799
+ def _det_LU(M, iszerofunc=_iszero, simpfunc=None):
800
+ """ Computes the determinant of a matrix from its LU decomposition.
801
+ This function uses the LU decomposition computed by
802
+ LUDecomposition_Simple().
803
+
804
+ The keyword arguments iszerofunc and simpfunc are passed to
805
+ LUDecomposition_Simple().
806
+ iszerofunc is a callable that returns a boolean indicating if its
807
+ input is zero, or None if it cannot make the determination.
808
+ simpfunc is a callable that simplifies its input.
809
+ The default is simpfunc=None, which indicate that the pivot search
810
+ algorithm should not attempt to simplify any candidate pivots.
811
+ If simpfunc fails to simplify its input, then it must return its input
812
+ instead of a copy.
813
+
814
+ Parameters
815
+ ==========
816
+
817
+ iszerofunc : function, optional
818
+ The function to use to determine zeros when doing an LU decomposition.
819
+ Defaults to ``lambda x: x.is_zero``.
820
+
821
+ simpfunc : function, optional
822
+ The simplification function to use when looking for zeros for pivots.
823
+ """
824
+
825
+ if not M.is_square:
826
+ raise NonSquareMatrixError()
827
+
828
+ if M.rows == 0:
829
+ return M.one
830
+ # sympy/matrices/tests/test_matrices.py contains a test that
831
+ # suggests that the determinant of a 0 x 0 matrix is one, by
832
+ # convention.
833
+
834
+ lu, row_swaps = M.LUdecomposition_Simple(iszerofunc=iszerofunc,
835
+ simpfunc=simpfunc)
836
+ # P*A = L*U => det(A) = det(L)*det(U)/det(P) = det(P)*det(U).
837
+ # Lower triangular factor L encoded in lu has unit diagonal => det(L) = 1.
838
+ # P is a permutation matrix => det(P) in {-1, 1} => 1/det(P) = det(P).
839
+ # LUdecomposition_Simple() returns a list of row exchange index pairs, rather
840
+ # than a permutation matrix, but det(P) = (-1)**len(row_swaps).
841
+
842
+ # Avoid forming the potentially time consuming product of U's diagonal entries
843
+ # if the product is zero.
844
+ # Bottom right entry of U is 0 => det(A) = 0.
845
+ # It may be impossible to determine if this entry of U is zero when it is symbolic.
846
+ if iszerofunc(lu[lu.rows-1, lu.rows-1]):
847
+ return M.zero
848
+
849
+ # Compute det(P)
850
+ det = -M.one if len(row_swaps)%2 else M.one
851
+
852
+ # Compute det(U) by calculating the product of U's diagonal entries.
853
+ # The upper triangular portion of lu is the upper triangular portion of the
854
+ # U factor in the LU decomposition.
855
+ for k in range(lu.rows):
856
+ det *= lu[k, k]
857
+
858
+ # return det(P)*det(U)
859
+ return det
860
+
861
+
862
+ @cacheit
863
+ def __det_laplace(M):
864
+ """Compute the determinant of a matrix using Laplace expansion.
865
+
866
+ This is a recursive function, and it should not be called directly.
867
+ Use _det_laplace() instead. The reason for splitting this function
868
+ into two is to allow caching of determinants of submatrices. While
869
+ one could also define this function inside _det_laplace(), that
870
+ would remove the advantage of using caching in Cramer Solve.
871
+ """
872
+ n = M.shape[0]
873
+ if n == 1:
874
+ return M[0]
875
+ elif n == 2:
876
+ return M[0, 0] * M[1, 1] - M[0, 1] * M[1, 0]
877
+ else:
878
+ return sum((-1) ** i * M[0, i] *
879
+ __det_laplace(M.minor_submatrix(0, i)) for i in range(n))
880
+
881
+
882
+ def _det_laplace(M):
883
+ """Compute the determinant of a matrix using Laplace expansion.
884
+
885
+ While Laplace expansion is not the most efficient method of computing
886
+ a determinant, it is a simple one, and it has the advantage of
887
+ being division free. To improve efficiency, this function uses
888
+ caching to avoid recomputing determinants of submatrices.
889
+ """
890
+ if not M.is_square:
891
+ raise NonSquareMatrixError()
892
+ if M.shape[0] == 0:
893
+ return M.one
894
+ # sympy/matrices/tests/test_matrices.py contains a test that
895
+ # suggests that the determinant of a 0 x 0 matrix is one, by
896
+ # convention.
897
+ return __det_laplace(M.as_immutable())
898
+
899
+
900
+ def _det_bird(M):
901
+ r"""Compute the determinant of a matrix using Bird's algorithm.
902
+
903
+ Bird's algorithm is a simple division-free algorithm for computing, which
904
+ is of lower order than the Laplace's algorithm. It is described in [1]_.
905
+
906
+ References
907
+ ==========
908
+
909
+ .. [1] Bird, R. S. (2011). A simple division-free algorithm for computing
910
+ determinants. Inf. Process. Lett., 111(21), 1072-1074. doi:
911
+ 10.1016/j.ipl.2011.08.006
912
+ """
913
+ def mu(X):
914
+ n = X.shape[0]
915
+ zero = X.domain.zero
916
+
917
+ total = zero
918
+ diag_sums = [zero]
919
+ for i in reversed(range(1, n)):
920
+ total -= X[i][i]
921
+ diag_sums.append(total)
922
+ diag_sums = diag_sums[::-1]
923
+
924
+ elems = [[zero] * i + [diag_sums[i]] + X_i[i + 1:] for i, X_i in
925
+ enumerate(X)]
926
+ return DDM(elems, X.shape, X.domain)
927
+
928
+ Mddm = M._rep.to_ddm()
929
+ n = M.shape[0]
930
+ if n == 0:
931
+ return M.one
932
+ # sympy/matrices/tests/test_matrices.py contains a test that
933
+ # suggests that the determinant of a 0 x 0 matrix is one, by
934
+ # convention.
935
+ Fn1 = Mddm
936
+ for _ in range(n - 1):
937
+ Fn1 = mu(Fn1).matmul(Mddm)
938
+ detA = Fn1[0][0]
939
+ if n % 2 == 0:
940
+ detA = -detA
941
+
942
+ return Mddm.domain.to_sympy(detA)
943
+
944
+
945
+ def _minor(M, i, j, method="berkowitz"):
946
+ """Return the (i,j) minor of ``M``. That is,
947
+ return the determinant of the matrix obtained by deleting
948
+ the `i`th row and `j`th column from ``M``.
949
+
950
+ Parameters
951
+ ==========
952
+
953
+ i, j : int
954
+ The row and column to exclude to obtain the submatrix.
955
+
956
+ method : string, optional
957
+ Method to use to find the determinant of the submatrix, can be
958
+ "bareiss", "berkowitz", "bird", "laplace" or "lu".
959
+
960
+ Examples
961
+ ========
962
+
963
+ >>> from sympy import Matrix
964
+ >>> M = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
965
+ >>> M.minor(1, 1)
966
+ -12
967
+
968
+ See Also
969
+ ========
970
+
971
+ minor_submatrix
972
+ cofactor
973
+ det
974
+ """
975
+
976
+ if not M.is_square:
977
+ raise NonSquareMatrixError()
978
+
979
+ return M.minor_submatrix(i, j).det(method=method)
980
+
981
+
982
+ def _minor_submatrix(M, i, j):
983
+ """Return the submatrix obtained by removing the `i`th row
984
+ and `j`th column from ``M`` (works with Pythonic negative indices).
985
+
986
+ Parameters
987
+ ==========
988
+
989
+ i, j : int
990
+ The row and column to exclude to obtain the submatrix.
991
+
992
+ Examples
993
+ ========
994
+
995
+ >>> from sympy import Matrix
996
+ >>> M = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
997
+ >>> M.minor_submatrix(1, 1)
998
+ Matrix([
999
+ [1, 3],
1000
+ [7, 9]])
1001
+
1002
+ See Also
1003
+ ========
1004
+
1005
+ minor
1006
+ cofactor
1007
+ """
1008
+
1009
+ if i < 0:
1010
+ i += M.rows
1011
+ if j < 0:
1012
+ j += M.cols
1013
+
1014
+ if not 0 <= i < M.rows or not 0 <= j < M.cols:
1015
+ raise ValueError("`i` and `j` must satisfy 0 <= i < ``M.rows`` "
1016
+ "(%d)" % M.rows + "and 0 <= j < ``M.cols`` (%d)." % M.cols)
1017
+
1018
+ rows = [a for a in range(M.rows) if a != i]
1019
+ cols = [a for a in range(M.cols) if a != j]
1020
+
1021
+ return M.extract(rows, cols)
phi4/lib/python3.10/site-packages/sympy/matrices/exceptions.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Exceptions raised by the matrix module.
3
+ """
4
+
5
+
6
+ class MatrixError(Exception):
7
+ pass
8
+
9
+
10
+ class ShapeError(ValueError, MatrixError):
11
+ """Wrong matrix shape"""
12
+ pass
13
+
14
+
15
+ class NonSquareMatrixError(ShapeError):
16
+ pass
17
+
18
+
19
+ class NonInvertibleMatrixError(ValueError, MatrixError):
20
+ """The matrix in not invertible (division by multidimensional zero error)."""
21
+ pass
22
+
23
+
24
+ class NonPositiveDefiniteMatrixError(ValueError, MatrixError):
25
+ """The matrix is not a positive-definite matrix."""
26
+ pass
phi4/lib/python3.10/site-packages/sympy/matrices/expressions/transpose.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.basic import Basic
2
+ from sympy.matrices.expressions.matexpr import MatrixExpr
3
+
4
+
5
+ class Transpose(MatrixExpr):
6
+ """
7
+ The transpose of a matrix expression.
8
+
9
+ This is a symbolic object that simply stores its argument without
10
+ evaluating it. To actually compute the transpose, use the ``transpose()``
11
+ function, or the ``.T`` attribute of matrices.
12
+
13
+ Examples
14
+ ========
15
+
16
+ >>> from sympy import MatrixSymbol, Transpose, transpose
17
+ >>> A = MatrixSymbol('A', 3, 5)
18
+ >>> B = MatrixSymbol('B', 5, 3)
19
+ >>> Transpose(A)
20
+ A.T
21
+ >>> A.T == transpose(A) == Transpose(A)
22
+ True
23
+ >>> Transpose(A*B)
24
+ (A*B).T
25
+ >>> transpose(A*B)
26
+ B.T*A.T
27
+
28
+ """
29
+ is_Transpose = True
30
+
31
+ def doit(self, **hints):
32
+ arg = self.arg
33
+ if hints.get('deep', True) and isinstance(arg, Basic):
34
+ arg = arg.doit(**hints)
35
+ _eval_transpose = getattr(arg, '_eval_transpose', None)
36
+ if _eval_transpose is not None:
37
+ result = _eval_transpose()
38
+ return result if result is not None else Transpose(arg)
39
+ else:
40
+ return Transpose(arg)
41
+
42
+ @property
43
+ def arg(self):
44
+ return self.args[0]
45
+
46
+ @property
47
+ def shape(self):
48
+ return self.arg.shape[::-1]
49
+
50
+ def _entry(self, i, j, expand=False, **kwargs):
51
+ return self.arg._entry(j, i, expand=expand, **kwargs)
52
+
53
+ def _eval_adjoint(self):
54
+ return self.arg.conjugate()
55
+
56
+ def _eval_conjugate(self):
57
+ return self.arg.adjoint()
58
+
59
+ def _eval_transpose(self):
60
+ return self.arg
61
+
62
+ def _eval_trace(self):
63
+ from .trace import Trace
64
+ return Trace(self.arg) # Trace(X.T) => Trace(X)
65
+
66
+ def _eval_determinant(self):
67
+ from sympy.matrices.expressions.determinant import det
68
+ return det(self.arg)
69
+
70
+ def _eval_derivative(self, x):
71
+ # x is a scalar:
72
+ return self.arg._eval_derivative(x)
73
+
74
+ def _eval_derivative_matrix_lines(self, x):
75
+ lines = self.args[0]._eval_derivative_matrix_lines(x)
76
+ return [i.transpose() for i in lines]
77
+
78
+
79
+ def transpose(expr):
80
+ """Matrix transpose"""
81
+ return Transpose(expr).doit(deep=False)
82
+
83
+
84
+ from sympy.assumptions.ask import ask, Q
85
+ from sympy.assumptions.refine import handlers_dict
86
+
87
+
88
+ def refine_Transpose(expr, assumptions):
89
+ """
90
+ >>> from sympy import MatrixSymbol, Q, assuming, refine
91
+ >>> X = MatrixSymbol('X', 2, 2)
92
+ >>> X.T
93
+ X.T
94
+ >>> with assuming(Q.symmetric(X)):
95
+ ... print(refine(X.T))
96
+ X
97
+ """
98
+ if ask(Q.symmetric(expr), assumptions):
99
+ return expr.arg
100
+
101
+ return expr
102
+
103
+ handlers_dict['Transpose'] = refine_Transpose
phi4/lib/python3.10/site-packages/sympy/matrices/graph.py ADDED
@@ -0,0 +1,279 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.utilities.iterables import \
2
+ flatten, connected_components, strongly_connected_components
3
+ from .exceptions import NonSquareMatrixError
4
+
5
+
6
+ def _connected_components(M):
7
+ """Returns the list of connected vertices of the graph when
8
+ a square matrix is viewed as a weighted graph.
9
+
10
+ Examples
11
+ ========
12
+
13
+ >>> from sympy import Matrix
14
+ >>> A = Matrix([
15
+ ... [66, 0, 0, 68, 0, 0, 0, 0, 67],
16
+ ... [0, 55, 0, 0, 0, 0, 54, 53, 0],
17
+ ... [0, 0, 0, 0, 1, 2, 0, 0, 0],
18
+ ... [86, 0, 0, 88, 0, 0, 0, 0, 87],
19
+ ... [0, 0, 10, 0, 11, 12, 0, 0, 0],
20
+ ... [0, 0, 20, 0, 21, 22, 0, 0, 0],
21
+ ... [0, 45, 0, 0, 0, 0, 44, 43, 0],
22
+ ... [0, 35, 0, 0, 0, 0, 34, 33, 0],
23
+ ... [76, 0, 0, 78, 0, 0, 0, 0, 77]])
24
+ >>> A.connected_components()
25
+ [[0, 3, 8], [1, 6, 7], [2, 4, 5]]
26
+
27
+ Notes
28
+ =====
29
+
30
+ Even if any symbolic elements of the matrix can be indeterminate
31
+ to be zero mathematically, this only takes the account of the
32
+ structural aspect of the matrix, so they will considered to be
33
+ nonzero.
34
+ """
35
+ if not M.is_square:
36
+ raise NonSquareMatrixError
37
+
38
+ V = range(M.rows)
39
+ E = sorted(M.todok().keys())
40
+ return connected_components((V, E))
41
+
42
+
43
+ def _strongly_connected_components(M):
44
+ """Returns the list of strongly connected vertices of the graph when
45
+ a square matrix is viewed as a weighted graph.
46
+
47
+ Examples
48
+ ========
49
+
50
+ >>> from sympy import Matrix
51
+ >>> A = Matrix([
52
+ ... [44, 0, 0, 0, 43, 0, 45, 0, 0],
53
+ ... [0, 66, 62, 61, 0, 68, 0, 60, 67],
54
+ ... [0, 0, 22, 21, 0, 0, 0, 20, 0],
55
+ ... [0, 0, 12, 11, 0, 0, 0, 10, 0],
56
+ ... [34, 0, 0, 0, 33, 0, 35, 0, 0],
57
+ ... [0, 86, 82, 81, 0, 88, 0, 80, 87],
58
+ ... [54, 0, 0, 0, 53, 0, 55, 0, 0],
59
+ ... [0, 0, 2, 1, 0, 0, 0, 0, 0],
60
+ ... [0, 76, 72, 71, 0, 78, 0, 70, 77]])
61
+ >>> A.strongly_connected_components()
62
+ [[0, 4, 6], [2, 3, 7], [1, 5, 8]]
63
+ """
64
+ if not M.is_square:
65
+ raise NonSquareMatrixError
66
+
67
+ # RepMatrix uses the more efficient DomainMatrix.scc() method
68
+ rep = getattr(M, '_rep', None)
69
+ if rep is not None:
70
+ return rep.scc()
71
+
72
+ V = range(M.rows)
73
+ E = sorted(M.todok().keys())
74
+ return strongly_connected_components((V, E))
75
+
76
+
77
+ def _connected_components_decomposition(M):
78
+ """Decomposes a square matrix into block diagonal form only
79
+ using the permutations.
80
+
81
+ Explanation
82
+ ===========
83
+
84
+ The decomposition is in a form of $A = P^{-1} B P$ where $P$ is a
85
+ permutation matrix and $B$ is a block diagonal matrix.
86
+
87
+ Returns
88
+ =======
89
+
90
+ P, B : PermutationMatrix, BlockDiagMatrix
91
+ *P* is a permutation matrix for the similarity transform
92
+ as in the explanation. And *B* is the block diagonal matrix of
93
+ the result of the permutation.
94
+
95
+ If you would like to get the diagonal blocks from the
96
+ BlockDiagMatrix, see
97
+ :meth:`~sympy.matrices.expressions.blockmatrix.BlockDiagMatrix.get_diag_blocks`.
98
+
99
+ Examples
100
+ ========
101
+
102
+ >>> from sympy import Matrix, pprint
103
+ >>> A = Matrix([
104
+ ... [66, 0, 0, 68, 0, 0, 0, 0, 67],
105
+ ... [0, 55, 0, 0, 0, 0, 54, 53, 0],
106
+ ... [0, 0, 0, 0, 1, 2, 0, 0, 0],
107
+ ... [86, 0, 0, 88, 0, 0, 0, 0, 87],
108
+ ... [0, 0, 10, 0, 11, 12, 0, 0, 0],
109
+ ... [0, 0, 20, 0, 21, 22, 0, 0, 0],
110
+ ... [0, 45, 0, 0, 0, 0, 44, 43, 0],
111
+ ... [0, 35, 0, 0, 0, 0, 34, 33, 0],
112
+ ... [76, 0, 0, 78, 0, 0, 0, 0, 77]])
113
+
114
+ >>> P, B = A.connected_components_decomposition()
115
+ >>> pprint(P)
116
+ PermutationMatrix((1 3)(2 8 5 7 4 6))
117
+ >>> pprint(B)
118
+ [[66 68 67] ]
119
+ [[ ] ]
120
+ [[86 88 87] 0 0 ]
121
+ [[ ] ]
122
+ [[76 78 77] ]
123
+ [ ]
124
+ [ [55 54 53] ]
125
+ [ [ ] ]
126
+ [ 0 [45 44 43] 0 ]
127
+ [ [ ] ]
128
+ [ [35 34 33] ]
129
+ [ ]
130
+ [ [0 1 2 ]]
131
+ [ [ ]]
132
+ [ 0 0 [10 11 12]]
133
+ [ [ ]]
134
+ [ [20 21 22]]
135
+
136
+ >>> P = P.as_explicit()
137
+ >>> B = B.as_explicit()
138
+ >>> P.T*B*P == A
139
+ True
140
+
141
+ Notes
142
+ =====
143
+
144
+ This problem corresponds to the finding of the connected components
145
+ of a graph, when a matrix is viewed as a weighted graph.
146
+ """
147
+ from sympy.combinatorics.permutations import Permutation
148
+ from sympy.matrices.expressions.blockmatrix import BlockDiagMatrix
149
+ from sympy.matrices.expressions.permutation import PermutationMatrix
150
+
151
+ iblocks = M.connected_components()
152
+
153
+ p = Permutation(flatten(iblocks))
154
+ P = PermutationMatrix(p)
155
+
156
+ blocks = []
157
+ for b in iblocks:
158
+ blocks.append(M[b, b])
159
+ B = BlockDiagMatrix(*blocks)
160
+ return P, B
161
+
162
+
163
+ def _strongly_connected_components_decomposition(M, lower=True):
164
+ """Decomposes a square matrix into block triangular form only
165
+ using the permutations.
166
+
167
+ Explanation
168
+ ===========
169
+
170
+ The decomposition is in a form of $A = P^{-1} B P$ where $P$ is a
171
+ permutation matrix and $B$ is a block diagonal matrix.
172
+
173
+ Parameters
174
+ ==========
175
+
176
+ lower : bool
177
+ Makes $B$ lower block triangular when ``True``.
178
+ Otherwise, makes $B$ upper block triangular.
179
+
180
+ Returns
181
+ =======
182
+
183
+ P, B : PermutationMatrix, BlockMatrix
184
+ *P* is a permutation matrix for the similarity transform
185
+ as in the explanation. And *B* is the block triangular matrix of
186
+ the result of the permutation.
187
+
188
+ Examples
189
+ ========
190
+
191
+ >>> from sympy import Matrix, pprint
192
+ >>> A = Matrix([
193
+ ... [44, 0, 0, 0, 43, 0, 45, 0, 0],
194
+ ... [0, 66, 62, 61, 0, 68, 0, 60, 67],
195
+ ... [0, 0, 22, 21, 0, 0, 0, 20, 0],
196
+ ... [0, 0, 12, 11, 0, 0, 0, 10, 0],
197
+ ... [34, 0, 0, 0, 33, 0, 35, 0, 0],
198
+ ... [0, 86, 82, 81, 0, 88, 0, 80, 87],
199
+ ... [54, 0, 0, 0, 53, 0, 55, 0, 0],
200
+ ... [0, 0, 2, 1, 0, 0, 0, 0, 0],
201
+ ... [0, 76, 72, 71, 0, 78, 0, 70, 77]])
202
+
203
+ A lower block triangular decomposition:
204
+
205
+ >>> P, B = A.strongly_connected_components_decomposition()
206
+ >>> pprint(P)
207
+ PermutationMatrix((8)(1 4 3 2 6)(5 7))
208
+ >>> pprint(B)
209
+ [[44 43 45] [0 0 0] [0 0 0] ]
210
+ [[ ] [ ] [ ] ]
211
+ [[34 33 35] [0 0 0] [0 0 0] ]
212
+ [[ ] [ ] [ ] ]
213
+ [[54 53 55] [0 0 0] [0 0 0] ]
214
+ [ ]
215
+ [ [0 0 0] [22 21 20] [0 0 0] ]
216
+ [ [ ] [ ] [ ] ]
217
+ [ [0 0 0] [12 11 10] [0 0 0] ]
218
+ [ [ ] [ ] [ ] ]
219
+ [ [0 0 0] [2 1 0 ] [0 0 0] ]
220
+ [ ]
221
+ [ [0 0 0] [62 61 60] [66 68 67]]
222
+ [ [ ] [ ] [ ]]
223
+ [ [0 0 0] [82 81 80] [86 88 87]]
224
+ [ [ ] [ ] [ ]]
225
+ [ [0 0 0] [72 71 70] [76 78 77]]
226
+
227
+ >>> P = P.as_explicit()
228
+ >>> B = B.as_explicit()
229
+ >>> P.T * B * P == A
230
+ True
231
+
232
+ An upper block triangular decomposition:
233
+
234
+ >>> P, B = A.strongly_connected_components_decomposition(lower=False)
235
+ >>> pprint(P)
236
+ PermutationMatrix((0 1 5 7 4 3 2 8 6))
237
+ >>> pprint(B)
238
+ [[66 68 67] [62 61 60] [0 0 0] ]
239
+ [[ ] [ ] [ ] ]
240
+ [[86 88 87] [82 81 80] [0 0 0] ]
241
+ [[ ] [ ] [ ] ]
242
+ [[76 78 77] [72 71 70] [0 0 0] ]
243
+ [ ]
244
+ [ [0 0 0] [22 21 20] [0 0 0] ]
245
+ [ [ ] [ ] [ ] ]
246
+ [ [0 0 0] [12 11 10] [0 0 0] ]
247
+ [ [ ] [ ] [ ] ]
248
+ [ [0 0 0] [2 1 0 ] [0 0 0] ]
249
+ [ ]
250
+ [ [0 0 0] [0 0 0] [44 43 45]]
251
+ [ [ ] [ ] [ ]]
252
+ [ [0 0 0] [0 0 0] [34 33 35]]
253
+ [ [ ] [ ] [ ]]
254
+ [ [0 0 0] [0 0 0] [54 53 55]]
255
+
256
+ >>> P = P.as_explicit()
257
+ >>> B = B.as_explicit()
258
+ >>> P.T * B * P == A
259
+ True
260
+ """
261
+ from sympy.combinatorics.permutations import Permutation
262
+ from sympy.matrices.expressions.blockmatrix import BlockMatrix
263
+ from sympy.matrices.expressions.permutation import PermutationMatrix
264
+
265
+ iblocks = M.strongly_connected_components()
266
+ if not lower:
267
+ iblocks = list(reversed(iblocks))
268
+
269
+ p = Permutation(flatten(iblocks))
270
+ P = PermutationMatrix(p)
271
+
272
+ rows = []
273
+ for a in iblocks:
274
+ cols = []
275
+ for b in iblocks:
276
+ cols.append(M[a, b])
277
+ rows.append(cols)
278
+ B = BlockMatrix(rows)
279
+ return P, B
phi4/lib/python3.10/site-packages/sympy/matrices/immutable.py ADDED
@@ -0,0 +1,196 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from mpmath.matrices.matrices import _matrix
2
+
3
+ from sympy.core import Basic, Dict, Tuple
4
+ from sympy.core.numbers import Integer
5
+ from sympy.core.cache import cacheit
6
+ from sympy.core.sympify import _sympy_converter as sympify_converter, _sympify
7
+ from sympy.matrices.dense import DenseMatrix
8
+ from sympy.matrices.expressions import MatrixExpr
9
+ from sympy.matrices.matrixbase import MatrixBase
10
+ from sympy.matrices.repmatrix import RepMatrix
11
+ from sympy.matrices.sparse import SparseRepMatrix
12
+ from sympy.multipledispatch import dispatch
13
+
14
+
15
+ def sympify_matrix(arg):
16
+ return arg.as_immutable()
17
+
18
+
19
+ sympify_converter[MatrixBase] = sympify_matrix
20
+
21
+
22
+ def sympify_mpmath_matrix(arg):
23
+ mat = [_sympify(x) for x in arg]
24
+ return ImmutableDenseMatrix(arg.rows, arg.cols, mat)
25
+
26
+
27
+ sympify_converter[_matrix] = sympify_mpmath_matrix
28
+
29
+
30
+ class ImmutableRepMatrix(RepMatrix, MatrixExpr): # type: ignore
31
+ """Immutable matrix based on RepMatrix
32
+
33
+ Uses DomainMAtrix as the internal representation.
34
+ """
35
+
36
+ #
37
+ # This is a subclass of RepMatrix that adds/overrides some methods to make
38
+ # the instances Basic and immutable. ImmutableRepMatrix is a superclass for
39
+ # both ImmutableDenseMatrix and ImmutableSparseMatrix.
40
+ #
41
+
42
+ def __new__(cls, *args, **kwargs):
43
+ return cls._new(*args, **kwargs)
44
+
45
+ __hash__ = MatrixExpr.__hash__
46
+
47
+ def copy(self):
48
+ return self
49
+
50
+ @property
51
+ def cols(self):
52
+ return self._cols
53
+
54
+ @property
55
+ def rows(self):
56
+ return self._rows
57
+
58
+ @property
59
+ def shape(self):
60
+ return self._rows, self._cols
61
+
62
+ def as_immutable(self):
63
+ return self
64
+
65
+ def _entry(self, i, j, **kwargs):
66
+ return self[i, j]
67
+
68
+ def __setitem__(self, *args):
69
+ raise TypeError("Cannot set values of {}".format(self.__class__))
70
+
71
+ def is_diagonalizable(self, reals_only=False, **kwargs):
72
+ return super().is_diagonalizable(
73
+ reals_only=reals_only, **kwargs)
74
+
75
+ is_diagonalizable.__doc__ = SparseRepMatrix.is_diagonalizable.__doc__
76
+ is_diagonalizable = cacheit(is_diagonalizable)
77
+
78
+ def analytic_func(self, f, x):
79
+ return self.as_mutable().analytic_func(f, x).as_immutable()
80
+
81
+
82
+ class ImmutableDenseMatrix(DenseMatrix, ImmutableRepMatrix): # type: ignore
83
+ """Create an immutable version of a matrix.
84
+
85
+ Examples
86
+ ========
87
+
88
+ >>> from sympy import eye, ImmutableMatrix
89
+ >>> ImmutableMatrix(eye(3))
90
+ Matrix([
91
+ [1, 0, 0],
92
+ [0, 1, 0],
93
+ [0, 0, 1]])
94
+ >>> _[0, 0] = 42
95
+ Traceback (most recent call last):
96
+ ...
97
+ TypeError: Cannot set values of ImmutableDenseMatrix
98
+ """
99
+
100
+ # MatrixExpr is set as NotIterable, but we want explicit matrices to be
101
+ # iterable
102
+ _iterable = True
103
+ _class_priority = 8
104
+ _op_priority = 10.001
105
+
106
+ @classmethod
107
+ def _new(cls, *args, **kwargs):
108
+ if len(args) == 1 and isinstance(args[0], ImmutableDenseMatrix):
109
+ return args[0]
110
+ if kwargs.get('copy', True) is False:
111
+ if len(args) != 3:
112
+ raise TypeError("'copy=False' requires a matrix be initialized as rows,cols,[list]")
113
+ rows, cols, flat_list = args
114
+ else:
115
+ rows, cols, flat_list = cls._handle_creation_inputs(*args, **kwargs)
116
+ flat_list = list(flat_list) # create a shallow copy
117
+
118
+ rep = cls._flat_list_to_DomainMatrix(rows, cols, flat_list)
119
+
120
+ return cls._fromrep(rep)
121
+
122
+ @classmethod
123
+ def _fromrep(cls, rep):
124
+ rows, cols = rep.shape
125
+ flat_list = rep.to_sympy().to_list_flat()
126
+ obj = Basic.__new__(cls,
127
+ Integer(rows),
128
+ Integer(cols),
129
+ Tuple(*flat_list, sympify=False))
130
+ obj._rows = rows
131
+ obj._cols = cols
132
+ obj._rep = rep
133
+ return obj
134
+
135
+
136
+ # make sure ImmutableDenseMatrix is aliased as ImmutableMatrix
137
+ ImmutableMatrix = ImmutableDenseMatrix
138
+
139
+
140
+ class ImmutableSparseMatrix(SparseRepMatrix, ImmutableRepMatrix): # type:ignore
141
+ """Create an immutable version of a sparse matrix.
142
+
143
+ Examples
144
+ ========
145
+
146
+ >>> from sympy import eye, ImmutableSparseMatrix
147
+ >>> ImmutableSparseMatrix(1, 1, {})
148
+ Matrix([[0]])
149
+ >>> ImmutableSparseMatrix(eye(3))
150
+ Matrix([
151
+ [1, 0, 0],
152
+ [0, 1, 0],
153
+ [0, 0, 1]])
154
+ >>> _[0, 0] = 42
155
+ Traceback (most recent call last):
156
+ ...
157
+ TypeError: Cannot set values of ImmutableSparseMatrix
158
+ >>> _.shape
159
+ (3, 3)
160
+ """
161
+ is_Matrix = True
162
+ _class_priority = 9
163
+
164
+ @classmethod
165
+ def _new(cls, *args, **kwargs):
166
+ rows, cols, smat = cls._handle_creation_inputs(*args, **kwargs)
167
+
168
+ rep = cls._smat_to_DomainMatrix(rows, cols, smat)
169
+
170
+ return cls._fromrep(rep)
171
+
172
+ @classmethod
173
+ def _fromrep(cls, rep):
174
+ rows, cols = rep.shape
175
+ smat = rep.to_sympy().to_dok()
176
+ obj = Basic.__new__(cls, Integer(rows), Integer(cols), Dict(smat))
177
+ obj._rows = rows
178
+ obj._cols = cols
179
+ obj._rep = rep
180
+ return obj
181
+
182
+
183
+ @dispatch(ImmutableDenseMatrix, ImmutableDenseMatrix)
184
+ def _eval_is_eq(lhs, rhs): # noqa:F811
185
+ """Helper method for Equality with matrices.sympy.
186
+
187
+ Relational automatically converts matrices to ImmutableDenseMatrix
188
+ instances, so this method only applies here. Returns True if the
189
+ matrices are definitively the same, False if they are definitively
190
+ different, and None if undetermined (e.g. if they contain Symbols).
191
+ Returning None triggers default handling of Equalities.
192
+
193
+ """
194
+ if lhs.shape != rhs.shape:
195
+ return False
196
+ return (lhs - rhs).is_zero_matrix
phi4/lib/python3.10/site-packages/sympy/matrices/inverse.py ADDED
@@ -0,0 +1,524 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.polys.matrices.exceptions import DMNonInvertibleMatrixError
2
+ from sympy.polys.domains import EX
3
+
4
+ from .exceptions import MatrixError, NonSquareMatrixError, NonInvertibleMatrixError
5
+ from .utilities import _iszero
6
+
7
+
8
+ def _pinv_full_rank(M):
9
+ """Subroutine for full row or column rank matrices.
10
+
11
+ For full row rank matrices, inverse of ``A * A.H`` Exists.
12
+ For full column rank matrices, inverse of ``A.H * A`` Exists.
13
+
14
+ This routine can apply for both cases by checking the shape
15
+ and have small decision.
16
+ """
17
+
18
+ if M.is_zero_matrix:
19
+ return M.H
20
+
21
+ if M.rows >= M.cols:
22
+ return M.H.multiply(M).inv().multiply(M.H)
23
+ else:
24
+ return M.H.multiply(M.multiply(M.H).inv())
25
+
26
+ def _pinv_rank_decomposition(M):
27
+ """Subroutine for rank decomposition
28
+
29
+ With rank decompositions, `A` can be decomposed into two full-
30
+ rank matrices, and each matrix can take pseudoinverse
31
+ individually.
32
+ """
33
+
34
+ if M.is_zero_matrix:
35
+ return M.H
36
+
37
+ B, C = M.rank_decomposition()
38
+
39
+ Bp = _pinv_full_rank(B)
40
+ Cp = _pinv_full_rank(C)
41
+
42
+ return Cp.multiply(Bp)
43
+
44
+ def _pinv_diagonalization(M):
45
+ """Subroutine using diagonalization
46
+
47
+ This routine can sometimes fail if SymPy's eigenvalue
48
+ computation is not reliable.
49
+ """
50
+
51
+ if M.is_zero_matrix:
52
+ return M.H
53
+
54
+ A = M
55
+ AH = M.H
56
+
57
+ try:
58
+ if M.rows >= M.cols:
59
+ P, D = AH.multiply(A).diagonalize(normalize=True)
60
+ D_pinv = D.applyfunc(lambda x: 0 if _iszero(x) else 1 / x)
61
+
62
+ return P.multiply(D_pinv).multiply(P.H).multiply(AH)
63
+
64
+ else:
65
+ P, D = A.multiply(AH).diagonalize(
66
+ normalize=True)
67
+ D_pinv = D.applyfunc(lambda x: 0 if _iszero(x) else 1 / x)
68
+
69
+ return AH.multiply(P).multiply(D_pinv).multiply(P.H)
70
+
71
+ except MatrixError:
72
+ raise NotImplementedError(
73
+ 'pinv for rank-deficient matrices where '
74
+ 'diagonalization of A.H*A fails is not supported yet.')
75
+
76
+ def _pinv(M, method='RD'):
77
+ """Calculate the Moore-Penrose pseudoinverse of the matrix.
78
+
79
+ The Moore-Penrose pseudoinverse exists and is unique for any matrix.
80
+ If the matrix is invertible, the pseudoinverse is the same as the
81
+ inverse.
82
+
83
+ Parameters
84
+ ==========
85
+
86
+ method : String, optional
87
+ Specifies the method for computing the pseudoinverse.
88
+
89
+ If ``'RD'``, Rank-Decomposition will be used.
90
+
91
+ If ``'ED'``, Diagonalization will be used.
92
+
93
+ Examples
94
+ ========
95
+
96
+ Computing pseudoinverse by rank decomposition :
97
+
98
+ >>> from sympy import Matrix
99
+ >>> A = Matrix([[1, 2, 3], [4, 5, 6]])
100
+ >>> A.pinv()
101
+ Matrix([
102
+ [-17/18, 4/9],
103
+ [ -1/9, 1/9],
104
+ [ 13/18, -2/9]])
105
+
106
+ Computing pseudoinverse by diagonalization :
107
+
108
+ >>> B = A.pinv(method='ED')
109
+ >>> B.simplify()
110
+ >>> B
111
+ Matrix([
112
+ [-17/18, 4/9],
113
+ [ -1/9, 1/9],
114
+ [ 13/18, -2/9]])
115
+
116
+ See Also
117
+ ========
118
+
119
+ inv
120
+ pinv_solve
121
+
122
+ References
123
+ ==========
124
+
125
+ .. [1] https://en.wikipedia.org/wiki/Moore-Penrose_pseudoinverse
126
+
127
+ """
128
+
129
+ # Trivial case: pseudoinverse of all-zero matrix is its transpose.
130
+ if M.is_zero_matrix:
131
+ return M.H
132
+
133
+ if method == 'RD':
134
+ return _pinv_rank_decomposition(M)
135
+ elif method == 'ED':
136
+ return _pinv_diagonalization(M)
137
+ else:
138
+ raise ValueError('invalid pinv method %s' % repr(method))
139
+
140
+
141
+ def _verify_invertible(M, iszerofunc=_iszero):
142
+ """Initial check to see if a matrix is invertible. Raises or returns
143
+ determinant for use in _inv_ADJ."""
144
+
145
+ if not M.is_square:
146
+ raise NonSquareMatrixError("A Matrix must be square to invert.")
147
+
148
+ d = M.det(method='berkowitz')
149
+ zero = d.equals(0)
150
+
151
+ if zero is None: # if equals() can't decide, will rref be able to?
152
+ ok = M.rref(simplify=True)[0]
153
+ zero = any(iszerofunc(ok[j, j]) for j in range(ok.rows))
154
+
155
+ if zero:
156
+ raise NonInvertibleMatrixError("Matrix det == 0; not invertible.")
157
+
158
+ return d
159
+
160
+ def _inv_ADJ(M, iszerofunc=_iszero):
161
+ """Calculates the inverse using the adjugate matrix and a determinant.
162
+
163
+ See Also
164
+ ========
165
+
166
+ inv
167
+ inverse_GE
168
+ inverse_LU
169
+ inverse_CH
170
+ inverse_LDL
171
+ """
172
+
173
+ d = _verify_invertible(M, iszerofunc=iszerofunc)
174
+
175
+ return M.adjugate() / d
176
+
177
+ def _inv_GE(M, iszerofunc=_iszero):
178
+ """Calculates the inverse using Gaussian elimination.
179
+
180
+ See Also
181
+ ========
182
+
183
+ inv
184
+ inverse_ADJ
185
+ inverse_LU
186
+ inverse_CH
187
+ inverse_LDL
188
+ """
189
+
190
+ from .dense import Matrix
191
+
192
+ if not M.is_square:
193
+ raise NonSquareMatrixError("A Matrix must be square to invert.")
194
+
195
+ big = Matrix.hstack(M.as_mutable(), Matrix.eye(M.rows))
196
+ red = big.rref(iszerofunc=iszerofunc, simplify=True)[0]
197
+
198
+ if any(iszerofunc(red[j, j]) for j in range(red.rows)):
199
+ raise NonInvertibleMatrixError("Matrix det == 0; not invertible.")
200
+
201
+ return M._new(red[:, big.rows:])
202
+
203
+ def _inv_LU(M, iszerofunc=_iszero):
204
+ """Calculates the inverse using LU decomposition.
205
+
206
+ See Also
207
+ ========
208
+
209
+ inv
210
+ inverse_ADJ
211
+ inverse_GE
212
+ inverse_CH
213
+ inverse_LDL
214
+ """
215
+
216
+ if not M.is_square:
217
+ raise NonSquareMatrixError("A Matrix must be square to invert.")
218
+ if M.free_symbols:
219
+ _verify_invertible(M, iszerofunc=iszerofunc)
220
+
221
+ return M.LUsolve(M.eye(M.rows), iszerofunc=_iszero)
222
+
223
+ def _inv_CH(M, iszerofunc=_iszero):
224
+ """Calculates the inverse using cholesky decomposition.
225
+
226
+ See Also
227
+ ========
228
+
229
+ inv
230
+ inverse_ADJ
231
+ inverse_GE
232
+ inverse_LU
233
+ inverse_LDL
234
+ """
235
+
236
+ _verify_invertible(M, iszerofunc=iszerofunc)
237
+
238
+ return M.cholesky_solve(M.eye(M.rows))
239
+
240
+ def _inv_LDL(M, iszerofunc=_iszero):
241
+ """Calculates the inverse using LDL decomposition.
242
+
243
+ See Also
244
+ ========
245
+
246
+ inv
247
+ inverse_ADJ
248
+ inverse_GE
249
+ inverse_LU
250
+ inverse_CH
251
+ """
252
+
253
+ _verify_invertible(M, iszerofunc=iszerofunc)
254
+
255
+ return M.LDLsolve(M.eye(M.rows))
256
+
257
+ def _inv_QR(M, iszerofunc=_iszero):
258
+ """Calculates the inverse using QR decomposition.
259
+
260
+ See Also
261
+ ========
262
+
263
+ inv
264
+ inverse_ADJ
265
+ inverse_GE
266
+ inverse_CH
267
+ inverse_LDL
268
+ """
269
+
270
+ _verify_invertible(M, iszerofunc=iszerofunc)
271
+
272
+ return M.QRsolve(M.eye(M.rows))
273
+
274
+ def _try_DM(M, use_EX=False):
275
+ """Try to convert a matrix to a ``DomainMatrix``."""
276
+ dM = M.to_DM()
277
+ K = dM.domain
278
+
279
+ # Return DomainMatrix if a domain is found. Only use EX if use_EX=True.
280
+ if not use_EX and K.is_EXRAW:
281
+ return None
282
+ elif K.is_EXRAW:
283
+ return dM.convert_to(EX)
284
+ else:
285
+ return dM
286
+
287
+
288
+ def _use_exact_domain(dom):
289
+ """Check whether to convert to an exact domain."""
290
+ # DomainMatrix can handle RR and CC with partial pivoting. Other inexact
291
+ # domains like RR[a,b,...] can only be handled by converting to an exact
292
+ # domain like QQ[a,b,...]
293
+ if dom.is_RR or dom.is_CC:
294
+ return False
295
+ else:
296
+ return not dom.is_Exact
297
+
298
+
299
+ def _inv_DM(dM, cancel=True):
300
+ """Calculates the inverse using ``DomainMatrix``.
301
+
302
+ See Also
303
+ ========
304
+
305
+ inv
306
+ inverse_ADJ
307
+ inverse_GE
308
+ inverse_CH
309
+ inverse_LDL
310
+ sympy.polys.matrices.domainmatrix.DomainMatrix.inv
311
+ """
312
+ m, n = dM.shape
313
+ dom = dM.domain
314
+
315
+ if m != n:
316
+ raise NonSquareMatrixError("A Matrix must be square to invert.")
317
+
318
+ # Convert RR[a,b,...] to QQ[a,b,...]
319
+ use_exact = _use_exact_domain(dom)
320
+
321
+ if use_exact:
322
+ dom_exact = dom.get_exact()
323
+ dM = dM.convert_to(dom_exact)
324
+
325
+ try:
326
+ dMi, den = dM.inv_den()
327
+ except DMNonInvertibleMatrixError:
328
+ raise NonInvertibleMatrixError("Matrix det == 0; not invertible.")
329
+
330
+ if use_exact:
331
+ dMi = dMi.convert_to(dom)
332
+ den = dom.convert_from(den, dom_exact)
333
+
334
+ if cancel:
335
+ # Convert to field and cancel with the denominator.
336
+ if not dMi.domain.is_Field:
337
+ dMi = dMi.to_field()
338
+ Mi = (dMi / den).to_Matrix()
339
+ else:
340
+ # Convert to Matrix and divide without cancelling
341
+ Mi = dMi.to_Matrix() / dMi.domain.to_sympy(den)
342
+
343
+ return Mi
344
+
345
+ def _inv_block(M, iszerofunc=_iszero):
346
+ """Calculates the inverse using BLOCKWISE inversion.
347
+
348
+ See Also
349
+ ========
350
+
351
+ inv
352
+ inverse_ADJ
353
+ inverse_GE
354
+ inverse_CH
355
+ inverse_LDL
356
+ """
357
+ from sympy.matrices.expressions.blockmatrix import BlockMatrix
358
+ i = M.shape[0]
359
+ if i <= 20 :
360
+ return M.inv(method="LU", iszerofunc=_iszero)
361
+ A = M[:i // 2, :i //2]
362
+ B = M[:i // 2, i // 2:]
363
+ C = M[i // 2:, :i // 2]
364
+ D = M[i // 2:, i // 2:]
365
+ try:
366
+ D_inv = _inv_block(D)
367
+ except NonInvertibleMatrixError:
368
+ return M.inv(method="LU", iszerofunc=_iszero)
369
+ B_D_i = B*D_inv
370
+ BDC = B_D_i*C
371
+ A_n = A - BDC
372
+ try:
373
+ A_n = _inv_block(A_n)
374
+ except NonInvertibleMatrixError:
375
+ return M.inv(method="LU", iszerofunc=_iszero)
376
+ B_n = -A_n*B_D_i
377
+ dc = D_inv*C
378
+ C_n = -dc*A_n
379
+ D_n = D_inv + dc*-B_n
380
+ nn = BlockMatrix([[A_n, B_n], [C_n, D_n]]).as_explicit()
381
+ return nn
382
+
383
+ def _inv(M, method=None, iszerofunc=_iszero, try_block_diag=False):
384
+ """
385
+ Return the inverse of a matrix using the method indicated. The default
386
+ is DM if a suitable domain is found or otherwise GE for dense matrices
387
+ LDL for sparse matrices.
388
+
389
+ Parameters
390
+ ==========
391
+
392
+ method : ('DM', 'DMNC', 'GE', 'LU', 'ADJ', 'CH', 'LDL', 'QR')
393
+
394
+ iszerofunc : function, optional
395
+ Zero-testing function to use.
396
+
397
+ try_block_diag : bool, optional
398
+ If True then will try to form block diagonal matrices using the
399
+ method get_diag_blocks(), invert these individually, and then
400
+ reconstruct the full inverse matrix.
401
+
402
+ Examples
403
+ ========
404
+
405
+ >>> from sympy import SparseMatrix, Matrix
406
+ >>> A = SparseMatrix([
407
+ ... [ 2, -1, 0],
408
+ ... [-1, 2, -1],
409
+ ... [ 0, 0, 2]])
410
+ >>> A.inv('CH')
411
+ Matrix([
412
+ [2/3, 1/3, 1/6],
413
+ [1/3, 2/3, 1/3],
414
+ [ 0, 0, 1/2]])
415
+ >>> A.inv(method='LDL') # use of 'method=' is optional
416
+ Matrix([
417
+ [2/3, 1/3, 1/6],
418
+ [1/3, 2/3, 1/3],
419
+ [ 0, 0, 1/2]])
420
+ >>> A * _
421
+ Matrix([
422
+ [1, 0, 0],
423
+ [0, 1, 0],
424
+ [0, 0, 1]])
425
+ >>> A = Matrix(A)
426
+ >>> A.inv('CH')
427
+ Matrix([
428
+ [2/3, 1/3, 1/6],
429
+ [1/3, 2/3, 1/3],
430
+ [ 0, 0, 1/2]])
431
+ >>> A.inv('ADJ') == A.inv('GE') == A.inv('LU') == A.inv('CH') == A.inv('LDL') == A.inv('QR')
432
+ True
433
+
434
+ Notes
435
+ =====
436
+
437
+ According to the ``method`` keyword, it calls the appropriate method:
438
+
439
+ DM .... Use DomainMatrix ``inv_den`` method
440
+ DMNC .... Use DomainMatrix ``inv_den`` method without cancellation
441
+ GE .... inverse_GE(); default for dense matrices
442
+ LU .... inverse_LU()
443
+ ADJ ... inverse_ADJ()
444
+ CH ... inverse_CH()
445
+ LDL ... inverse_LDL(); default for sparse matrices
446
+ QR ... inverse_QR()
447
+
448
+ Note, the GE and LU methods may require the matrix to be simplified
449
+ before it is inverted in order to properly detect zeros during
450
+ pivoting. In difficult cases a custom zero detection function can
451
+ be provided by setting the ``iszerofunc`` argument to a function that
452
+ should return True if its argument is zero. The ADJ routine computes
453
+ the determinant and uses that to detect singular matrices in addition
454
+ to testing for zeros on the diagonal.
455
+
456
+ See Also
457
+ ========
458
+
459
+ inverse_ADJ
460
+ inverse_GE
461
+ inverse_LU
462
+ inverse_CH
463
+ inverse_LDL
464
+
465
+ Raises
466
+ ======
467
+
468
+ ValueError
469
+ If the determinant of the matrix is zero.
470
+ """
471
+
472
+ from sympy.matrices import diag, SparseMatrix
473
+
474
+ if not M.is_square:
475
+ raise NonSquareMatrixError("A Matrix must be square to invert.")
476
+
477
+ if try_block_diag:
478
+ blocks = M.get_diag_blocks()
479
+ r = []
480
+
481
+ for block in blocks:
482
+ r.append(block.inv(method=method, iszerofunc=iszerofunc))
483
+
484
+ return diag(*r)
485
+
486
+ # Default: Use DomainMatrix if the domain is not EX.
487
+ # If DM is requested explicitly then use it even if the domain is EX.
488
+ if method is None and iszerofunc is _iszero:
489
+ dM = _try_DM(M, use_EX=False)
490
+ if dM is not None:
491
+ method = 'DM'
492
+ elif method in ("DM", "DMNC"):
493
+ dM = _try_DM(M, use_EX=True)
494
+
495
+ # A suitable domain was not found, fall back to GE for dense matrices
496
+ # and LDL for sparse matrices.
497
+ if method is None:
498
+ if isinstance(M, SparseMatrix):
499
+ method = 'LDL'
500
+ else:
501
+ method = 'GE'
502
+
503
+ if method == "DM":
504
+ rv = _inv_DM(dM)
505
+ elif method == "DMNC":
506
+ rv = _inv_DM(dM, cancel=False)
507
+ elif method == "GE":
508
+ rv = M.inverse_GE(iszerofunc=iszerofunc)
509
+ elif method == "LU":
510
+ rv = M.inverse_LU(iszerofunc=iszerofunc)
511
+ elif method == "ADJ":
512
+ rv = M.inverse_ADJ(iszerofunc=iszerofunc)
513
+ elif method == "CH":
514
+ rv = M.inverse_CH(iszerofunc=iszerofunc)
515
+ elif method == "LDL":
516
+ rv = M.inverse_LDL(iszerofunc=iszerofunc)
517
+ elif method == "QR":
518
+ rv = M.inverse_QR(iszerofunc=iszerofunc)
519
+ elif method == "BLOCK":
520
+ rv = M.inverse_BLOCK(iszerofunc=iszerofunc)
521
+ else:
522
+ raise ValueError("Inversion method unrecognized")
523
+
524
+ return M._new(rv)
phi4/lib/python3.10/site-packages/sympy/matrices/kind.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # sympy.matrices.kind
2
+
3
+ from sympy.core.kind import Kind, _NumberKind, NumberKind
4
+ from sympy.core.mul import Mul
5
+
6
+
7
+ class MatrixKind(Kind):
8
+ """
9
+ Kind for all matrices in SymPy.
10
+
11
+ Basic class for this kind is ``MatrixBase`` and ``MatrixExpr``,
12
+ but any expression representing the matrix can have this.
13
+
14
+ Parameters
15
+ ==========
16
+
17
+ element_kind : Kind
18
+ Kind of the element. Default is
19
+ :class:`sympy.core.kind.NumberKind`,
20
+ which means that the matrix contains only numbers.
21
+
22
+ Examples
23
+ ========
24
+
25
+ Any instance of matrix class has kind ``MatrixKind``:
26
+
27
+ >>> from sympy import MatrixSymbol
28
+ >>> A = MatrixSymbol('A', 2, 2)
29
+ >>> A.kind
30
+ MatrixKind(NumberKind)
31
+
32
+ An expression representing a matrix may not be an instance of
33
+ the Matrix class, but it will have kind ``MatrixKind``:
34
+
35
+ >>> from sympy import MatrixExpr, Integral
36
+ >>> from sympy.abc import x
37
+ >>> intM = Integral(A, x)
38
+ >>> isinstance(intM, MatrixExpr)
39
+ False
40
+ >>> intM.kind
41
+ MatrixKind(NumberKind)
42
+
43
+ Use ``isinstance()`` to check for ``MatrixKind`` without specifying the
44
+ element kind. Use ``is`` to check the kind including the element kind:
45
+
46
+ >>> from sympy import Matrix
47
+ >>> from sympy.core import NumberKind
48
+ >>> from sympy.matrices import MatrixKind
49
+ >>> M = Matrix([1, 2])
50
+ >>> isinstance(M.kind, MatrixKind)
51
+ True
52
+ >>> M.kind is MatrixKind(NumberKind)
53
+ True
54
+
55
+ See Also
56
+ ========
57
+
58
+ sympy.core.kind.NumberKind
59
+ sympy.core.kind.UndefinedKind
60
+ sympy.core.containers.TupleKind
61
+ sympy.sets.sets.SetKind
62
+
63
+ """
64
+ def __new__(cls, element_kind=NumberKind):
65
+ obj = super().__new__(cls, element_kind)
66
+ obj.element_kind = element_kind
67
+ return obj
68
+
69
+ def __repr__(self):
70
+ return "MatrixKind(%s)" % self.element_kind
71
+
72
+
73
+ @Mul._kind_dispatcher.register(_NumberKind, MatrixKind)
74
+ def num_mat_mul(k1, k2):
75
+ """
76
+ Return MatrixKind. The element kind is selected by recursive dispatching.
77
+ Do not need to dispatch in reversed order because KindDispatcher
78
+ searches for this automatically.
79
+ """
80
+ # Deal with Mul._kind_dispatcher's commutativity
81
+ # XXX: this function is called with either k1 or k2 as MatrixKind because
82
+ # the Mul kind dispatcher is commutative. Maybe it shouldn't be. Need to
83
+ # swap the args here because NumberKind does not have an element_kind
84
+ # attribute.
85
+ if not isinstance(k2, MatrixKind):
86
+ k1, k2 = k2, k1
87
+ elemk = Mul._kind_dispatcher(k1, k2.element_kind)
88
+ return MatrixKind(elemk)
89
+
90
+
91
+ @Mul._kind_dispatcher.register(MatrixKind, MatrixKind)
92
+ def mat_mat_mul(k1, k2):
93
+ """
94
+ Return MatrixKind. The element kind is selected by recursive dispatching.
95
+ """
96
+ elemk = Mul._kind_dispatcher(k1.element_kind, k2.element_kind)
97
+ return MatrixKind(elemk)
phi4/lib/python3.10/site-packages/sympy/matrices/matrices.py ADDED
@@ -0,0 +1,687 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # A module consisting of deprecated matrix classes. New code should not be
3
+ # added here.
4
+ #
5
+ from sympy.core.basic import Basic
6
+ from sympy.core.symbol import Dummy
7
+
8
+ from .common import MatrixCommon
9
+
10
+ from .exceptions import NonSquareMatrixError
11
+
12
+ from .utilities import _iszero, _is_zero_after_expand_mul, _simplify
13
+
14
+ from .determinant import (
15
+ _find_reasonable_pivot, _find_reasonable_pivot_naive,
16
+ _adjugate, _charpoly, _cofactor, _cofactor_matrix, _per,
17
+ _det, _det_bareiss, _det_berkowitz, _det_bird, _det_laplace, _det_LU,
18
+ _minor, _minor_submatrix)
19
+
20
+ from .reductions import _is_echelon, _echelon_form, _rank, _rref
21
+ from .subspaces import _columnspace, _nullspace, _rowspace, _orthogonalize
22
+
23
+ from .eigen import (
24
+ _eigenvals, _eigenvects,
25
+ _bidiagonalize, _bidiagonal_decomposition,
26
+ _is_diagonalizable, _diagonalize,
27
+ _is_positive_definite, _is_positive_semidefinite,
28
+ _is_negative_definite, _is_negative_semidefinite, _is_indefinite,
29
+ _jordan_form, _left_eigenvects, _singular_values)
30
+
31
+
32
+ # This class was previously defined in this module, but was moved to
33
+ # sympy.matrices.matrixbase. We import it here for backwards compatibility in
34
+ # case someone was importing it from here.
35
+ from .matrixbase import MatrixBase
36
+
37
+
38
+ __doctest_requires__ = {
39
+ ('MatrixEigen.is_indefinite',
40
+ 'MatrixEigen.is_negative_definite',
41
+ 'MatrixEigen.is_negative_semidefinite',
42
+ 'MatrixEigen.is_positive_definite',
43
+ 'MatrixEigen.is_positive_semidefinite'): ['matplotlib'],
44
+ }
45
+
46
+
47
+ class MatrixDeterminant(MatrixCommon):
48
+ """Provides basic matrix determinant operations. Should not be instantiated
49
+ directly. See ``determinant.py`` for their implementations."""
50
+
51
+ def _eval_det_bareiss(self, iszerofunc=_is_zero_after_expand_mul):
52
+ return _det_bareiss(self, iszerofunc=iszerofunc)
53
+
54
+ def _eval_det_berkowitz(self):
55
+ return _det_berkowitz(self)
56
+
57
+ def _eval_det_lu(self, iszerofunc=_iszero, simpfunc=None):
58
+ return _det_LU(self, iszerofunc=iszerofunc, simpfunc=simpfunc)
59
+
60
+ def _eval_det_bird(self):
61
+ return _det_bird(self)
62
+
63
+ def _eval_det_laplace(self):
64
+ return _det_laplace(self)
65
+
66
+ def _eval_determinant(self): # for expressions.determinant.Determinant
67
+ return _det(self)
68
+
69
+ def adjugate(self, method="berkowitz"):
70
+ return _adjugate(self, method=method)
71
+
72
+ def charpoly(self, x='lambda', simplify=_simplify):
73
+ return _charpoly(self, x=x, simplify=simplify)
74
+
75
+ def cofactor(self, i, j, method="berkowitz"):
76
+ return _cofactor(self, i, j, method=method)
77
+
78
+ def cofactor_matrix(self, method="berkowitz"):
79
+ return _cofactor_matrix(self, method=method)
80
+
81
+ def det(self, method="bareiss", iszerofunc=None):
82
+ return _det(self, method=method, iszerofunc=iszerofunc)
83
+
84
+ def per(self):
85
+ return _per(self)
86
+
87
+ def minor(self, i, j, method="berkowitz"):
88
+ return _minor(self, i, j, method=method)
89
+
90
+ def minor_submatrix(self, i, j):
91
+ return _minor_submatrix(self, i, j)
92
+
93
+ _find_reasonable_pivot.__doc__ = _find_reasonable_pivot.__doc__
94
+ _find_reasonable_pivot_naive.__doc__ = _find_reasonable_pivot_naive.__doc__
95
+ _eval_det_bareiss.__doc__ = _det_bareiss.__doc__
96
+ _eval_det_berkowitz.__doc__ = _det_berkowitz.__doc__
97
+ _eval_det_bird.__doc__ = _det_bird.__doc__
98
+ _eval_det_laplace.__doc__ = _det_laplace.__doc__
99
+ _eval_det_lu.__doc__ = _det_LU.__doc__
100
+ _eval_determinant.__doc__ = _det.__doc__
101
+ adjugate.__doc__ = _adjugate.__doc__
102
+ charpoly.__doc__ = _charpoly.__doc__
103
+ cofactor.__doc__ = _cofactor.__doc__
104
+ cofactor_matrix.__doc__ = _cofactor_matrix.__doc__
105
+ det.__doc__ = _det.__doc__
106
+ per.__doc__ = _per.__doc__
107
+ minor.__doc__ = _minor.__doc__
108
+ minor_submatrix.__doc__ = _minor_submatrix.__doc__
109
+
110
+
111
+ class MatrixReductions(MatrixDeterminant):
112
+ """Provides basic matrix row/column operations. Should not be instantiated
113
+ directly. See ``reductions.py`` for some of their implementations."""
114
+
115
+ def echelon_form(self, iszerofunc=_iszero, simplify=False, with_pivots=False):
116
+ return _echelon_form(self, iszerofunc=iszerofunc, simplify=simplify,
117
+ with_pivots=with_pivots)
118
+
119
+ @property
120
+ def is_echelon(self):
121
+ return _is_echelon(self)
122
+
123
+ def rank(self, iszerofunc=_iszero, simplify=False):
124
+ return _rank(self, iszerofunc=iszerofunc, simplify=simplify)
125
+
126
+ def rref_rhs(self, rhs):
127
+ """Return reduced row-echelon form of matrix, matrix showing
128
+ rhs after reduction steps. ``rhs`` must have the same number
129
+ of rows as ``self``.
130
+
131
+ Examples
132
+ ========
133
+
134
+ >>> from sympy import Matrix, symbols
135
+ >>> r1, r2 = symbols('r1 r2')
136
+ >>> Matrix([[1, 1], [2, 1]]).rref_rhs(Matrix([r1, r2]))
137
+ (Matrix([
138
+ [1, 0],
139
+ [0, 1]]), Matrix([
140
+ [ -r1 + r2],
141
+ [2*r1 - r2]]))
142
+ """
143
+ r, _ = _rref(self.hstack(self, self.eye(self.rows), rhs))
144
+ return r[:, :self.cols], r[:, -rhs.cols:]
145
+
146
+ def rref(self, iszerofunc=_iszero, simplify=False, pivots=True,
147
+ normalize_last=True):
148
+ return _rref(self, iszerofunc=iszerofunc, simplify=simplify,
149
+ pivots=pivots, normalize_last=normalize_last)
150
+
151
+ echelon_form.__doc__ = _echelon_form.__doc__
152
+ is_echelon.__doc__ = _is_echelon.__doc__
153
+ rank.__doc__ = _rank.__doc__
154
+ rref.__doc__ = _rref.__doc__
155
+
156
+ def _normalize_op_args(self, op, col, k, col1, col2, error_str="col"):
157
+ """Validate the arguments for a row/column operation. ``error_str``
158
+ can be one of "row" or "col" depending on the arguments being parsed."""
159
+ if op not in ["n->kn", "n<->m", "n->n+km"]:
160
+ raise ValueError("Unknown {} operation '{}'. Valid col operations "
161
+ "are 'n->kn', 'n<->m', 'n->n+km'".format(error_str, op))
162
+
163
+ # define self_col according to error_str
164
+ self_cols = self.cols if error_str == 'col' else self.rows
165
+
166
+ # normalize and validate the arguments
167
+ if op == "n->kn":
168
+ col = col if col is not None else col1
169
+ if col is None or k is None:
170
+ raise ValueError("For a {0} operation 'n->kn' you must provide the "
171
+ "kwargs `{0}` and `k`".format(error_str))
172
+ if not 0 <= col < self_cols:
173
+ raise ValueError("This matrix does not have a {} '{}'".format(error_str, col))
174
+
175
+ elif op == "n<->m":
176
+ # we need two cols to swap. It does not matter
177
+ # how they were specified, so gather them together and
178
+ # remove `None`
179
+ cols = {col, k, col1, col2}.difference([None])
180
+ if len(cols) > 2:
181
+ # maybe the user left `k` by mistake?
182
+ cols = {col, col1, col2}.difference([None])
183
+ if len(cols) != 2:
184
+ raise ValueError("For a {0} operation 'n<->m' you must provide the "
185
+ "kwargs `{0}1` and `{0}2`".format(error_str))
186
+ col1, col2 = cols
187
+ if not 0 <= col1 < self_cols:
188
+ raise ValueError("This matrix does not have a {} '{}'".format(error_str, col1))
189
+ if not 0 <= col2 < self_cols:
190
+ raise ValueError("This matrix does not have a {} '{}'".format(error_str, col2))
191
+
192
+ elif op == "n->n+km":
193
+ col = col1 if col is None else col
194
+ col2 = col1 if col2 is None else col2
195
+ if col is None or col2 is None or k is None:
196
+ raise ValueError("For a {0} operation 'n->n+km' you must provide the "
197
+ "kwargs `{0}`, `k`, and `{0}2`".format(error_str))
198
+ if col == col2:
199
+ raise ValueError("For a {0} operation 'n->n+km' `{0}` and `{0}2` must "
200
+ "be different.".format(error_str))
201
+ if not 0 <= col < self_cols:
202
+ raise ValueError("This matrix does not have a {} '{}'".format(error_str, col))
203
+ if not 0 <= col2 < self_cols:
204
+ raise ValueError("This matrix does not have a {} '{}'".format(error_str, col2))
205
+
206
+ else:
207
+ raise ValueError('invalid operation %s' % repr(op))
208
+
209
+ return op, col, k, col1, col2
210
+
211
+ def _eval_col_op_multiply_col_by_const(self, col, k):
212
+ def entry(i, j):
213
+ if j == col:
214
+ return k * self[i, j]
215
+ return self[i, j]
216
+ return self._new(self.rows, self.cols, entry)
217
+
218
+ def _eval_col_op_swap(self, col1, col2):
219
+ def entry(i, j):
220
+ if j == col1:
221
+ return self[i, col2]
222
+ elif j == col2:
223
+ return self[i, col1]
224
+ return self[i, j]
225
+ return self._new(self.rows, self.cols, entry)
226
+
227
+ def _eval_col_op_add_multiple_to_other_col(self, col, k, col2):
228
+ def entry(i, j):
229
+ if j == col:
230
+ return self[i, j] + k * self[i, col2]
231
+ return self[i, j]
232
+ return self._new(self.rows, self.cols, entry)
233
+
234
+ def _eval_row_op_swap(self, row1, row2):
235
+ def entry(i, j):
236
+ if i == row1:
237
+ return self[row2, j]
238
+ elif i == row2:
239
+ return self[row1, j]
240
+ return self[i, j]
241
+ return self._new(self.rows, self.cols, entry)
242
+
243
+ def _eval_row_op_multiply_row_by_const(self, row, k):
244
+ def entry(i, j):
245
+ if i == row:
246
+ return k * self[i, j]
247
+ return self[i, j]
248
+ return self._new(self.rows, self.cols, entry)
249
+
250
+ def _eval_row_op_add_multiple_to_other_row(self, row, k, row2):
251
+ def entry(i, j):
252
+ if i == row:
253
+ return self[i, j] + k * self[row2, j]
254
+ return self[i, j]
255
+ return self._new(self.rows, self.cols, entry)
256
+
257
+ def elementary_col_op(self, op="n->kn", col=None, k=None, col1=None, col2=None):
258
+ """Performs the elementary column operation `op`.
259
+
260
+ `op` may be one of
261
+
262
+ * ``"n->kn"`` (column n goes to k*n)
263
+ * ``"n<->m"`` (swap column n and column m)
264
+ * ``"n->n+km"`` (column n goes to column n + k*column m)
265
+
266
+ Parameters
267
+ ==========
268
+
269
+ op : string; the elementary row operation
270
+ col : the column to apply the column operation
271
+ k : the multiple to apply in the column operation
272
+ col1 : one column of a column swap
273
+ col2 : second column of a column swap or column "m" in the column operation
274
+ "n->n+km"
275
+ """
276
+
277
+ op, col, k, col1, col2 = self._normalize_op_args(op, col, k, col1, col2, "col")
278
+
279
+ # now that we've validated, we're all good to dispatch
280
+ if op == "n->kn":
281
+ return self._eval_col_op_multiply_col_by_const(col, k)
282
+ if op == "n<->m":
283
+ return self._eval_col_op_swap(col1, col2)
284
+ if op == "n->n+km":
285
+ return self._eval_col_op_add_multiple_to_other_col(col, k, col2)
286
+
287
+ def elementary_row_op(self, op="n->kn", row=None, k=None, row1=None, row2=None):
288
+ """Performs the elementary row operation `op`.
289
+
290
+ `op` may be one of
291
+
292
+ * ``"n->kn"`` (row n goes to k*n)
293
+ * ``"n<->m"`` (swap row n and row m)
294
+ * ``"n->n+km"`` (row n goes to row n + k*row m)
295
+
296
+ Parameters
297
+ ==========
298
+
299
+ op : string; the elementary row operation
300
+ row : the row to apply the row operation
301
+ k : the multiple to apply in the row operation
302
+ row1 : one row of a row swap
303
+ row2 : second row of a row swap or row "m" in the row operation
304
+ "n->n+km"
305
+ """
306
+
307
+ op, row, k, row1, row2 = self._normalize_op_args(op, row, k, row1, row2, "row")
308
+
309
+ # now that we've validated, we're all good to dispatch
310
+ if op == "n->kn":
311
+ return self._eval_row_op_multiply_row_by_const(row, k)
312
+ if op == "n<->m":
313
+ return self._eval_row_op_swap(row1, row2)
314
+ if op == "n->n+km":
315
+ return self._eval_row_op_add_multiple_to_other_row(row, k, row2)
316
+
317
+
318
+ class MatrixSubspaces(MatrixReductions):
319
+ """Provides methods relating to the fundamental subspaces of a matrix.
320
+ Should not be instantiated directly. See ``subspaces.py`` for their
321
+ implementations."""
322
+
323
+ def columnspace(self, simplify=False):
324
+ return _columnspace(self, simplify=simplify)
325
+
326
+ def nullspace(self, simplify=False, iszerofunc=_iszero):
327
+ return _nullspace(self, simplify=simplify, iszerofunc=iszerofunc)
328
+
329
+ def rowspace(self, simplify=False):
330
+ return _rowspace(self, simplify=simplify)
331
+
332
+ # This is a classmethod but is converted to such later in order to allow
333
+ # assignment of __doc__ since that does not work for already wrapped
334
+ # classmethods in Python 3.6.
335
+ def orthogonalize(cls, *vecs, **kwargs):
336
+ return _orthogonalize(cls, *vecs, **kwargs)
337
+
338
+ columnspace.__doc__ = _columnspace.__doc__
339
+ nullspace.__doc__ = _nullspace.__doc__
340
+ rowspace.__doc__ = _rowspace.__doc__
341
+ orthogonalize.__doc__ = _orthogonalize.__doc__
342
+
343
+ orthogonalize = classmethod(orthogonalize) # type:ignore
344
+
345
+
346
+ class MatrixEigen(MatrixSubspaces):
347
+ """Provides basic matrix eigenvalue/vector operations.
348
+ Should not be instantiated directly. See ``eigen.py`` for their
349
+ implementations."""
350
+
351
+ def eigenvals(self, error_when_incomplete=True, **flags):
352
+ return _eigenvals(self, error_when_incomplete=error_when_incomplete, **flags)
353
+
354
+ def eigenvects(self, error_when_incomplete=True, iszerofunc=_iszero, **flags):
355
+ return _eigenvects(self, error_when_incomplete=error_when_incomplete,
356
+ iszerofunc=iszerofunc, **flags)
357
+
358
+ def is_diagonalizable(self, reals_only=False, **kwargs):
359
+ return _is_diagonalizable(self, reals_only=reals_only, **kwargs)
360
+
361
+ def diagonalize(self, reals_only=False, sort=False, normalize=False):
362
+ return _diagonalize(self, reals_only=reals_only, sort=sort,
363
+ normalize=normalize)
364
+
365
+ def bidiagonalize(self, upper=True):
366
+ return _bidiagonalize(self, upper=upper)
367
+
368
+ def bidiagonal_decomposition(self, upper=True):
369
+ return _bidiagonal_decomposition(self, upper=upper)
370
+
371
+ @property
372
+ def is_positive_definite(self):
373
+ return _is_positive_definite(self)
374
+
375
+ @property
376
+ def is_positive_semidefinite(self):
377
+ return _is_positive_semidefinite(self)
378
+
379
+ @property
380
+ def is_negative_definite(self):
381
+ return _is_negative_definite(self)
382
+
383
+ @property
384
+ def is_negative_semidefinite(self):
385
+ return _is_negative_semidefinite(self)
386
+
387
+ @property
388
+ def is_indefinite(self):
389
+ return _is_indefinite(self)
390
+
391
+ def jordan_form(self, calc_transform=True, **kwargs):
392
+ return _jordan_form(self, calc_transform=calc_transform, **kwargs)
393
+
394
+ def left_eigenvects(self, **flags):
395
+ return _left_eigenvects(self, **flags)
396
+
397
+ def singular_values(self):
398
+ return _singular_values(self)
399
+
400
+ eigenvals.__doc__ = _eigenvals.__doc__
401
+ eigenvects.__doc__ = _eigenvects.__doc__
402
+ is_diagonalizable.__doc__ = _is_diagonalizable.__doc__
403
+ diagonalize.__doc__ = _diagonalize.__doc__
404
+ is_positive_definite.__doc__ = _is_positive_definite.__doc__
405
+ is_positive_semidefinite.__doc__ = _is_positive_semidefinite.__doc__
406
+ is_negative_definite.__doc__ = _is_negative_definite.__doc__
407
+ is_negative_semidefinite.__doc__ = _is_negative_semidefinite.__doc__
408
+ is_indefinite.__doc__ = _is_indefinite.__doc__
409
+ jordan_form.__doc__ = _jordan_form.__doc__
410
+ left_eigenvects.__doc__ = _left_eigenvects.__doc__
411
+ singular_values.__doc__ = _singular_values.__doc__
412
+ bidiagonalize.__doc__ = _bidiagonalize.__doc__
413
+ bidiagonal_decomposition.__doc__ = _bidiagonal_decomposition.__doc__
414
+
415
+
416
+ class MatrixCalculus(MatrixCommon):
417
+ """Provides calculus-related matrix operations."""
418
+
419
+ def diff(self, *args, evaluate=True, **kwargs):
420
+ """Calculate the derivative of each element in the matrix.
421
+
422
+ Examples
423
+ ========
424
+
425
+ >>> from sympy import Matrix
426
+ >>> from sympy.abc import x, y
427
+ >>> M = Matrix([[x, y], [1, 0]])
428
+ >>> M.diff(x)
429
+ Matrix([
430
+ [1, 0],
431
+ [0, 0]])
432
+
433
+ See Also
434
+ ========
435
+
436
+ integrate
437
+ limit
438
+ """
439
+ # XXX this should be handled here rather than in Derivative
440
+ from sympy.tensor.array.array_derivatives import ArrayDerivative
441
+ deriv = ArrayDerivative(self, *args, evaluate=evaluate)
442
+ # XXX This can rather changed to always return immutable matrix
443
+ if not isinstance(self, Basic) and evaluate:
444
+ return deriv.as_mutable()
445
+ return deriv
446
+
447
+ def _eval_derivative(self, arg):
448
+ return self.applyfunc(lambda x: x.diff(arg))
449
+
450
+ def integrate(self, *args, **kwargs):
451
+ """Integrate each element of the matrix. ``args`` will
452
+ be passed to the ``integrate`` function.
453
+
454
+ Examples
455
+ ========
456
+
457
+ >>> from sympy import Matrix
458
+ >>> from sympy.abc import x, y
459
+ >>> M = Matrix([[x, y], [1, 0]])
460
+ >>> M.integrate((x, ))
461
+ Matrix([
462
+ [x**2/2, x*y],
463
+ [ x, 0]])
464
+ >>> M.integrate((x, 0, 2))
465
+ Matrix([
466
+ [2, 2*y],
467
+ [2, 0]])
468
+
469
+ See Also
470
+ ========
471
+
472
+ limit
473
+ diff
474
+ """
475
+ return self.applyfunc(lambda x: x.integrate(*args, **kwargs))
476
+
477
+ def jacobian(self, X):
478
+ """Calculates the Jacobian matrix (derivative of a vector-valued function).
479
+
480
+ Parameters
481
+ ==========
482
+
483
+ ``self`` : vector of expressions representing functions f_i(x_1, ..., x_n).
484
+ X : set of x_i's in order, it can be a list or a Matrix
485
+
486
+ Both ``self`` and X can be a row or a column matrix in any order
487
+ (i.e., jacobian() should always work).
488
+
489
+ Examples
490
+ ========
491
+
492
+ >>> from sympy import sin, cos, Matrix
493
+ >>> from sympy.abc import rho, phi
494
+ >>> X = Matrix([rho*cos(phi), rho*sin(phi), rho**2])
495
+ >>> Y = Matrix([rho, phi])
496
+ >>> X.jacobian(Y)
497
+ Matrix([
498
+ [cos(phi), -rho*sin(phi)],
499
+ [sin(phi), rho*cos(phi)],
500
+ [ 2*rho, 0]])
501
+ >>> X = Matrix([rho*cos(phi), rho*sin(phi)])
502
+ >>> X.jacobian(Y)
503
+ Matrix([
504
+ [cos(phi), -rho*sin(phi)],
505
+ [sin(phi), rho*cos(phi)]])
506
+
507
+ See Also
508
+ ========
509
+
510
+ hessian
511
+ wronskian
512
+ """
513
+ if not isinstance(X, MatrixBase):
514
+ X = self._new(X)
515
+ # Both X and ``self`` can be a row or a column matrix, so we need to make
516
+ # sure all valid combinations work, but everything else fails:
517
+ if self.shape[0] == 1:
518
+ m = self.shape[1]
519
+ elif self.shape[1] == 1:
520
+ m = self.shape[0]
521
+ else:
522
+ raise TypeError("``self`` must be a row or a column matrix")
523
+ if X.shape[0] == 1:
524
+ n = X.shape[1]
525
+ elif X.shape[1] == 1:
526
+ n = X.shape[0]
527
+ else:
528
+ raise TypeError("X must be a row or a column matrix")
529
+
530
+ # m is the number of functions and n is the number of variables
531
+ # computing the Jacobian is now easy:
532
+ return self._new(m, n, lambda j, i: self[j].diff(X[i]))
533
+
534
+ def limit(self, *args):
535
+ """Calculate the limit of each element in the matrix.
536
+ ``args`` will be passed to the ``limit`` function.
537
+
538
+ Examples
539
+ ========
540
+
541
+ >>> from sympy import Matrix
542
+ >>> from sympy.abc import x, y
543
+ >>> M = Matrix([[x, y], [1, 0]])
544
+ >>> M.limit(x, 2)
545
+ Matrix([
546
+ [2, y],
547
+ [1, 0]])
548
+
549
+ See Also
550
+ ========
551
+
552
+ integrate
553
+ diff
554
+ """
555
+ return self.applyfunc(lambda x: x.limit(*args))
556
+
557
+
558
+ # https://github.com/sympy/sympy/pull/12854
559
+ class MatrixDeprecated(MatrixCommon):
560
+ """A class to house deprecated matrix methods."""
561
+ def berkowitz_charpoly(self, x=Dummy('lambda'), simplify=_simplify):
562
+ return self.charpoly(x=x)
563
+
564
+ def berkowitz_det(self):
565
+ """Computes determinant using Berkowitz method.
566
+
567
+ See Also
568
+ ========
569
+
570
+ det
571
+ berkowitz
572
+ """
573
+ return self.det(method='berkowitz')
574
+
575
+ def berkowitz_eigenvals(self, **flags):
576
+ """Computes eigenvalues of a Matrix using Berkowitz method.
577
+
578
+ See Also
579
+ ========
580
+
581
+ berkowitz
582
+ """
583
+ return self.eigenvals(**flags)
584
+
585
+ def berkowitz_minors(self):
586
+ """Computes principal minors using Berkowitz method.
587
+
588
+ See Also
589
+ ========
590
+
591
+ berkowitz
592
+ """
593
+ sign, minors = self.one, []
594
+
595
+ for poly in self.berkowitz():
596
+ minors.append(sign * poly[-1])
597
+ sign = -sign
598
+
599
+ return tuple(minors)
600
+
601
+ def berkowitz(self):
602
+ from sympy.matrices import zeros
603
+ berk = ((1,),)
604
+ if not self:
605
+ return berk
606
+
607
+ if not self.is_square:
608
+ raise NonSquareMatrixError()
609
+
610
+ A, N = self, self.rows
611
+ transforms = [0] * (N - 1)
612
+
613
+ for n in range(N, 1, -1):
614
+ T, k = zeros(n + 1, n), n - 1
615
+
616
+ R, C = -A[k, :k], A[:k, k]
617
+ A, a = A[:k, :k], -A[k, k]
618
+
619
+ items = [C]
620
+
621
+ for i in range(0, n - 2):
622
+ items.append(A * items[i])
623
+
624
+ for i, B in enumerate(items):
625
+ items[i] = (R * B)[0, 0]
626
+
627
+ items = [self.one, a] + items
628
+
629
+ for i in range(n):
630
+ T[i:, i] = items[:n - i + 1]
631
+
632
+ transforms[k - 1] = T
633
+
634
+ polys = [self._new([self.one, -A[0, 0]])]
635
+
636
+ for i, T in enumerate(transforms):
637
+ polys.append(T * polys[i])
638
+
639
+ return berk + tuple(map(tuple, polys))
640
+
641
+ def cofactorMatrix(self, method="berkowitz"):
642
+ return self.cofactor_matrix(method=method)
643
+
644
+ def det_bareis(self):
645
+ return _det_bareiss(self)
646
+
647
+ def det_LU_decomposition(self):
648
+ """Compute matrix determinant using LU decomposition.
649
+
650
+
651
+ Note that this method fails if the LU decomposition itself
652
+ fails. In particular, if the matrix has no inverse this method
653
+ will fail.
654
+
655
+ TODO: Implement algorithm for sparse matrices (SFF),
656
+ https://www.eecis.udel.edu/~saunders/papers/sffge/it5.ps
657
+
658
+ See Also
659
+ ========
660
+
661
+
662
+ det
663
+ det_bareiss
664
+ berkowitz_det
665
+ """
666
+ return self.det(method='lu')
667
+
668
+ def jordan_cell(self, eigenval, n):
669
+ return self.jordan_block(size=n, eigenvalue=eigenval)
670
+
671
+ def jordan_cells(self, calc_transformation=True):
672
+ P, J = self.jordan_form()
673
+ return P, J.get_diag_blocks()
674
+
675
+ def minorEntry(self, i, j, method="berkowitz"):
676
+ return self.minor(i, j, method=method)
677
+
678
+ def minorMatrix(self, i, j):
679
+ return self.minor_submatrix(i, j)
680
+
681
+ def permuteBkwd(self, perm):
682
+ """Permute the rows of the matrix with the given permutation in reverse."""
683
+ return self.permute_rows(perm, direction='backward')
684
+
685
+ def permuteFwd(self, perm):
686
+ """Permute the rows of the matrix with the given permutation."""
687
+ return self.permute_rows(perm, direction='forward')
phi4/lib/python3.10/site-packages/sympy/matrices/matrixbase.py ADDED
The diff for this file is too large to render. See raw diff
 
phi4/lib/python3.10/site-packages/sympy/matrices/normalforms.py ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''Functions returning normal forms of matrices'''
2
+
3
+ from sympy.polys.domains.integerring import ZZ
4
+ from sympy.polys.polytools import Poly
5
+ from sympy.polys.matrices import DomainMatrix
6
+ from sympy.polys.matrices.normalforms import (
7
+ smith_normal_form as _snf,
8
+ invariant_factors as _invf,
9
+ hermite_normal_form as _hnf,
10
+ )
11
+
12
+
13
+ def _to_domain(m, domain=None):
14
+ """Convert Matrix to DomainMatrix"""
15
+ # XXX: deprecated support for RawMatrix:
16
+ ring = getattr(m, "ring", None)
17
+ m = m.applyfunc(lambda e: e.as_expr() if isinstance(e, Poly) else e)
18
+
19
+ dM = DomainMatrix.from_Matrix(m)
20
+
21
+ domain = domain or ring
22
+ if domain is not None:
23
+ dM = dM.convert_to(domain)
24
+ return dM
25
+
26
+
27
+ def smith_normal_form(m, domain=None):
28
+ '''
29
+ Return the Smith Normal Form of a matrix `m` over the ring `domain`.
30
+ This will only work if the ring is a principal ideal domain.
31
+
32
+ Examples
33
+ ========
34
+
35
+ >>> from sympy import Matrix, ZZ
36
+ >>> from sympy.matrices.normalforms import smith_normal_form
37
+ >>> m = Matrix([[12, 6, 4], [3, 9, 6], [2, 16, 14]])
38
+ >>> print(smith_normal_form(m, domain=ZZ))
39
+ Matrix([[1, 0, 0], [0, 10, 0], [0, 0, -30]])
40
+
41
+ '''
42
+ dM = _to_domain(m, domain)
43
+ return _snf(dM).to_Matrix()
44
+
45
+
46
+ def invariant_factors(m, domain=None):
47
+ '''
48
+ Return the tuple of abelian invariants for a matrix `m`
49
+ (as in the Smith-Normal form)
50
+
51
+ References
52
+ ==========
53
+
54
+ .. [1] https://en.wikipedia.org/wiki/Smith_normal_form#Algorithm
55
+ .. [2] https://web.archive.org/web/20200331143852/https://sierra.nmsu.edu/morandi/notes/SmithNormalForm.pdf
56
+
57
+ '''
58
+ dM = _to_domain(m, domain)
59
+ factors = _invf(dM)
60
+ factors = tuple(dM.domain.to_sympy(f) for f in factors)
61
+ # XXX: deprecated.
62
+ if hasattr(m, "ring"):
63
+ if m.ring.is_PolynomialRing:
64
+ K = m.ring
65
+ to_poly = lambda f: Poly(f, K.symbols, domain=K.domain)
66
+ factors = tuple(to_poly(f) for f in factors)
67
+ return factors
68
+
69
+
70
+ def hermite_normal_form(A, *, D=None, check_rank=False):
71
+ r"""
72
+ Compute the Hermite Normal Form of a Matrix *A* of integers.
73
+
74
+ Examples
75
+ ========
76
+
77
+ >>> from sympy import Matrix
78
+ >>> from sympy.matrices.normalforms import hermite_normal_form
79
+ >>> m = Matrix([[12, 6, 4], [3, 9, 6], [2, 16, 14]])
80
+ >>> print(hermite_normal_form(m))
81
+ Matrix([[10, 0, 2], [0, 15, 3], [0, 0, 2]])
82
+
83
+ Parameters
84
+ ==========
85
+
86
+ A : $m \times n$ ``Matrix`` of integers.
87
+
88
+ D : int, optional
89
+ Let $W$ be the HNF of *A*. If known in advance, a positive integer *D*
90
+ being any multiple of $\det(W)$ may be provided. In this case, if *A*
91
+ also has rank $m$, then we may use an alternative algorithm that works
92
+ mod *D* in order to prevent coefficient explosion.
93
+
94
+ check_rank : boolean, optional (default=False)
95
+ The basic assumption is that, if you pass a value for *D*, then
96
+ you already believe that *A* has rank $m$, so we do not waste time
97
+ checking it for you. If you do want this to be checked (and the
98
+ ordinary, non-modulo *D* algorithm to be used if the check fails), then
99
+ set *check_rank* to ``True``.
100
+
101
+ Returns
102
+ =======
103
+
104
+ ``Matrix``
105
+ The HNF of matrix *A*.
106
+
107
+ Raises
108
+ ======
109
+
110
+ DMDomainError
111
+ If the domain of the matrix is not :ref:`ZZ`.
112
+
113
+ DMShapeError
114
+ If the mod *D* algorithm is used but the matrix has more rows than
115
+ columns.
116
+
117
+ References
118
+ ==========
119
+
120
+ .. [1] Cohen, H. *A Course in Computational Algebraic Number Theory.*
121
+ (See Algorithms 2.4.5 and 2.4.8.)
122
+
123
+ """
124
+ # Accept any of Python int, SymPy Integer, and ZZ itself:
125
+ if D is not None and not ZZ.of_type(D):
126
+ D = ZZ(int(D))
127
+ return _hnf(A._rep, D=D, check_rank=check_rank).to_Matrix()
phi4/lib/python3.10/site-packages/sympy/matrices/reductions.py ADDED
@@ -0,0 +1,387 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from types import FunctionType
2
+
3
+ from sympy.polys.polyerrors import CoercionFailed
4
+ from sympy.polys.domains import ZZ, QQ
5
+
6
+ from .utilities import _get_intermediate_simp, _iszero, _dotprodsimp, _simplify
7
+ from .determinant import _find_reasonable_pivot
8
+
9
+
10
+ def _row_reduce_list(mat, rows, cols, one, iszerofunc, simpfunc,
11
+ normalize_last=True, normalize=True, zero_above=True):
12
+ """Row reduce a flat list representation of a matrix and return a tuple
13
+ (rref_matrix, pivot_cols, swaps) where ``rref_matrix`` is a flat list,
14
+ ``pivot_cols`` are the pivot columns and ``swaps`` are any row swaps that
15
+ were used in the process of row reduction.
16
+
17
+ Parameters
18
+ ==========
19
+
20
+ mat : list
21
+ list of matrix elements, must be ``rows`` * ``cols`` in length
22
+
23
+ rows, cols : integer
24
+ number of rows and columns in flat list representation
25
+
26
+ one : SymPy object
27
+ represents the value one, from ``Matrix.one``
28
+
29
+ iszerofunc : determines if an entry can be used as a pivot
30
+
31
+ simpfunc : used to simplify elements and test if they are
32
+ zero if ``iszerofunc`` returns `None`
33
+
34
+ normalize_last : indicates where all row reduction should
35
+ happen in a fraction-free manner and then the rows are
36
+ normalized (so that the pivots are 1), or whether
37
+ rows should be normalized along the way (like the naive
38
+ row reduction algorithm)
39
+
40
+ normalize : whether pivot rows should be normalized so that
41
+ the pivot value is 1
42
+
43
+ zero_above : whether entries above the pivot should be zeroed.
44
+ If ``zero_above=False``, an echelon matrix will be returned.
45
+ """
46
+
47
+ def get_col(i):
48
+ return mat[i::cols]
49
+
50
+ def row_swap(i, j):
51
+ mat[i*cols:(i + 1)*cols], mat[j*cols:(j + 1)*cols] = \
52
+ mat[j*cols:(j + 1)*cols], mat[i*cols:(i + 1)*cols]
53
+
54
+ def cross_cancel(a, i, b, j):
55
+ """Does the row op row[i] = a*row[i] - b*row[j]"""
56
+ q = (j - i)*cols
57
+ for p in range(i*cols, (i + 1)*cols):
58
+ mat[p] = isimp(a*mat[p] - b*mat[p + q])
59
+
60
+ isimp = _get_intermediate_simp(_dotprodsimp)
61
+ piv_row, piv_col = 0, 0
62
+ pivot_cols = []
63
+ swaps = []
64
+
65
+ # use a fraction free method to zero above and below each pivot
66
+ while piv_col < cols and piv_row < rows:
67
+ pivot_offset, pivot_val, \
68
+ assumed_nonzero, newly_determined = _find_reasonable_pivot(
69
+ get_col(piv_col)[piv_row:], iszerofunc, simpfunc)
70
+
71
+ # _find_reasonable_pivot may have simplified some things
72
+ # in the process. Let's not let them go to waste
73
+ for (offset, val) in newly_determined:
74
+ offset += piv_row
75
+ mat[offset*cols + piv_col] = val
76
+
77
+ if pivot_offset is None:
78
+ piv_col += 1
79
+ continue
80
+
81
+ pivot_cols.append(piv_col)
82
+ if pivot_offset != 0:
83
+ row_swap(piv_row, pivot_offset + piv_row)
84
+ swaps.append((piv_row, pivot_offset + piv_row))
85
+
86
+ # if we aren't normalizing last, we normalize
87
+ # before we zero the other rows
88
+ if normalize_last is False:
89
+ i, j = piv_row, piv_col
90
+ mat[i*cols + j] = one
91
+ for p in range(i*cols + j + 1, (i + 1)*cols):
92
+ mat[p] = isimp(mat[p] / pivot_val)
93
+ # after normalizing, the pivot value is 1
94
+ pivot_val = one
95
+
96
+ # zero above and below the pivot
97
+ for row in range(rows):
98
+ # don't zero our current row
99
+ if row == piv_row:
100
+ continue
101
+ # don't zero above the pivot unless we're told.
102
+ if zero_above is False and row < piv_row:
103
+ continue
104
+ # if we're already a zero, don't do anything
105
+ val = mat[row*cols + piv_col]
106
+ if iszerofunc(val):
107
+ continue
108
+
109
+ cross_cancel(pivot_val, row, val, piv_row)
110
+ piv_row += 1
111
+
112
+ # normalize each row
113
+ if normalize_last is True and normalize is True:
114
+ for piv_i, piv_j in enumerate(pivot_cols):
115
+ pivot_val = mat[piv_i*cols + piv_j]
116
+ mat[piv_i*cols + piv_j] = one
117
+ for p in range(piv_i*cols + piv_j + 1, (piv_i + 1)*cols):
118
+ mat[p] = isimp(mat[p] / pivot_val)
119
+
120
+ return mat, tuple(pivot_cols), tuple(swaps)
121
+
122
+
123
+ # This functions is a candidate for caching if it gets implemented for matrices.
124
+ def _row_reduce(M, iszerofunc, simpfunc, normalize_last=True,
125
+ normalize=True, zero_above=True):
126
+
127
+ mat, pivot_cols, swaps = _row_reduce_list(list(M), M.rows, M.cols, M.one,
128
+ iszerofunc, simpfunc, normalize_last=normalize_last,
129
+ normalize=normalize, zero_above=zero_above)
130
+
131
+ return M._new(M.rows, M.cols, mat), pivot_cols, swaps
132
+
133
+
134
+ def _is_echelon(M, iszerofunc=_iszero):
135
+ """Returns `True` if the matrix is in echelon form. That is, all rows of
136
+ zeros are at the bottom, and below each leading non-zero in a row are
137
+ exclusively zeros."""
138
+
139
+ if M.rows <= 0 or M.cols <= 0:
140
+ return True
141
+
142
+ zeros_below = all(iszerofunc(t) for t in M[1:, 0])
143
+
144
+ if iszerofunc(M[0, 0]):
145
+ return zeros_below and _is_echelon(M[:, 1:], iszerofunc)
146
+
147
+ return zeros_below and _is_echelon(M[1:, 1:], iszerofunc)
148
+
149
+
150
+ def _echelon_form(M, iszerofunc=_iszero, simplify=False, with_pivots=False):
151
+ """Returns a matrix row-equivalent to ``M`` that is in echelon form. Note
152
+ that echelon form of a matrix is *not* unique, however, properties like the
153
+ row space and the null space are preserved.
154
+
155
+ Examples
156
+ ========
157
+
158
+ >>> from sympy import Matrix
159
+ >>> M = Matrix([[1, 2], [3, 4]])
160
+ >>> M.echelon_form()
161
+ Matrix([
162
+ [1, 2],
163
+ [0, -2]])
164
+ """
165
+
166
+ simpfunc = simplify if isinstance(simplify, FunctionType) else _simplify
167
+
168
+ mat, pivots, _ = _row_reduce(M, iszerofunc, simpfunc,
169
+ normalize_last=True, normalize=False, zero_above=False)
170
+
171
+ if with_pivots:
172
+ return mat, pivots
173
+
174
+ return mat
175
+
176
+
177
+ # This functions is a candidate for caching if it gets implemented for matrices.
178
+ def _rank(M, iszerofunc=_iszero, simplify=False):
179
+ """Returns the rank of a matrix.
180
+
181
+ Examples
182
+ ========
183
+
184
+ >>> from sympy import Matrix
185
+ >>> from sympy.abc import x
186
+ >>> m = Matrix([[1, 2], [x, 1 - 1/x]])
187
+ >>> m.rank()
188
+ 2
189
+ >>> n = Matrix(3, 3, range(1, 10))
190
+ >>> n.rank()
191
+ 2
192
+ """
193
+
194
+ def _permute_complexity_right(M, iszerofunc):
195
+ """Permute columns with complicated elements as
196
+ far right as they can go. Since the ``sympy`` row reduction
197
+ algorithms start on the left, having complexity right-shifted
198
+ speeds things up.
199
+
200
+ Returns a tuple (mat, perm) where perm is a permutation
201
+ of the columns to perform to shift the complex columns right, and mat
202
+ is the permuted matrix."""
203
+
204
+ def complexity(i):
205
+ # the complexity of a column will be judged by how many
206
+ # element's zero-ness cannot be determined
207
+ return sum(1 if iszerofunc(e) is None else 0 for e in M[:, i])
208
+
209
+ complex = [(complexity(i), i) for i in range(M.cols)]
210
+ perm = [j for (i, j) in sorted(complex)]
211
+
212
+ return (M.permute(perm, orientation='cols'), perm)
213
+
214
+ simpfunc = simplify if isinstance(simplify, FunctionType) else _simplify
215
+
216
+ # for small matrices, we compute the rank explicitly
217
+ # if is_zero on elements doesn't answer the question
218
+ # for small matrices, we fall back to the full routine.
219
+ if M.rows <= 0 or M.cols <= 0:
220
+ return 0
221
+
222
+ if M.rows <= 1 or M.cols <= 1:
223
+ zeros = [iszerofunc(x) for x in M]
224
+
225
+ if False in zeros:
226
+ return 1
227
+
228
+ if M.rows == 2 and M.cols == 2:
229
+ zeros = [iszerofunc(x) for x in M]
230
+
231
+ if False not in zeros and None not in zeros:
232
+ return 0
233
+
234
+ d = M.det()
235
+
236
+ if iszerofunc(d) and False in zeros:
237
+ return 1
238
+ if iszerofunc(d) is False:
239
+ return 2
240
+
241
+ mat, _ = _permute_complexity_right(M, iszerofunc=iszerofunc)
242
+ _, pivots, _ = _row_reduce(mat, iszerofunc, simpfunc, normalize_last=True,
243
+ normalize=False, zero_above=False)
244
+
245
+ return len(pivots)
246
+
247
+
248
+ def _to_DM_ZZ_QQ(M):
249
+ # We have to test for _rep here because there are tests that otherwise fail
250
+ # with e.g. "AttributeError: 'SubspaceOnlyMatrix' object has no attribute
251
+ # '_rep'." There is almost certainly no value in such tests. The
252
+ # presumption seems to be that someone could create a new class by
253
+ # inheriting some of the Matrix classes and not the full set that is used
254
+ # by the standard Matrix class but if anyone tried that it would fail in
255
+ # many ways.
256
+ if not hasattr(M, '_rep'):
257
+ return None
258
+
259
+ rep = M._rep
260
+ K = rep.domain
261
+
262
+ if K.is_ZZ:
263
+ return rep
264
+ elif K.is_QQ:
265
+ try:
266
+ return rep.convert_to(ZZ)
267
+ except CoercionFailed:
268
+ return rep
269
+ else:
270
+ if not all(e.is_Rational for e in M):
271
+ return None
272
+ try:
273
+ return rep.convert_to(ZZ)
274
+ except CoercionFailed:
275
+ return rep.convert_to(QQ)
276
+
277
+
278
+ def _rref_dm(dM):
279
+ """Compute the reduced row echelon form of a DomainMatrix."""
280
+ K = dM.domain
281
+
282
+ if K.is_ZZ:
283
+ dM_rref, den, pivots = dM.rref_den(keep_domain=False)
284
+ dM_rref = dM_rref.to_field() / den
285
+ elif K.is_QQ:
286
+ dM_rref, pivots = dM.rref()
287
+ else:
288
+ assert False # pragma: no cover
289
+
290
+ M_rref = dM_rref.to_Matrix()
291
+
292
+ return M_rref, pivots
293
+
294
+
295
+ def _rref(M, iszerofunc=_iszero, simplify=False, pivots=True,
296
+ normalize_last=True):
297
+ """Return reduced row-echelon form of matrix and indices
298
+ of pivot vars.
299
+
300
+ Parameters
301
+ ==========
302
+
303
+ iszerofunc : Function
304
+ A function used for detecting whether an element can
305
+ act as a pivot. ``lambda x: x.is_zero`` is used by default.
306
+
307
+ simplify : Function
308
+ A function used to simplify elements when looking for a pivot.
309
+ By default SymPy's ``simplify`` is used.
310
+
311
+ pivots : True or False
312
+ If ``True``, a tuple containing the row-reduced matrix and a tuple
313
+ of pivot columns is returned. If ``False`` just the row-reduced
314
+ matrix is returned.
315
+
316
+ normalize_last : True or False
317
+ If ``True``, no pivots are normalized to `1` until after all
318
+ entries above and below each pivot are zeroed. This means the row
319
+ reduction algorithm is fraction free until the very last step.
320
+ If ``False``, the naive row reduction procedure is used where
321
+ each pivot is normalized to be `1` before row operations are
322
+ used to zero above and below the pivot.
323
+
324
+ Examples
325
+ ========
326
+
327
+ >>> from sympy import Matrix
328
+ >>> from sympy.abc import x
329
+ >>> m = Matrix([[1, 2], [x, 1 - 1/x]])
330
+ >>> m.rref()
331
+ (Matrix([
332
+ [1, 0],
333
+ [0, 1]]), (0, 1))
334
+ >>> rref_matrix, rref_pivots = m.rref()
335
+ >>> rref_matrix
336
+ Matrix([
337
+ [1, 0],
338
+ [0, 1]])
339
+ >>> rref_pivots
340
+ (0, 1)
341
+
342
+ ``iszerofunc`` can correct rounding errors in matrices with float
343
+ values. In the following example, calling ``rref()`` leads to
344
+ floating point errors, incorrectly row reducing the matrix.
345
+ ``iszerofunc= lambda x: abs(x) < 1e-9`` sets sufficiently small numbers
346
+ to zero, avoiding this error.
347
+
348
+ >>> m = Matrix([[0.9, -0.1, -0.2, 0], [-0.8, 0.9, -0.4, 0], [-0.1, -0.8, 0.6, 0]])
349
+ >>> m.rref()
350
+ (Matrix([
351
+ [1, 0, 0, 0],
352
+ [0, 1, 0, 0],
353
+ [0, 0, 1, 0]]), (0, 1, 2))
354
+ >>> m.rref(iszerofunc=lambda x:abs(x)<1e-9)
355
+ (Matrix([
356
+ [1, 0, -0.301369863013699, 0],
357
+ [0, 1, -0.712328767123288, 0],
358
+ [0, 0, 0, 0]]), (0, 1))
359
+
360
+ Notes
361
+ =====
362
+
363
+ The default value of ``normalize_last=True`` can provide significant
364
+ speedup to row reduction, especially on matrices with symbols. However,
365
+ if you depend on the form row reduction algorithm leaves entries
366
+ of the matrix, set ``normalize_last=False``
367
+ """
368
+ # Try to use DomainMatrix for ZZ or QQ
369
+ dM = _to_DM_ZZ_QQ(M)
370
+
371
+ if dM is not None:
372
+ # Use DomainMatrix for ZZ or QQ
373
+ mat, pivot_cols = _rref_dm(dM)
374
+ else:
375
+ # Use the generic Matrix routine.
376
+ if isinstance(simplify, FunctionType):
377
+ simpfunc = simplify
378
+ else:
379
+ simpfunc = _simplify
380
+
381
+ mat, pivot_cols, _ = _row_reduce(M, iszerofunc, simpfunc,
382
+ normalize_last, normalize=True, zero_above=True)
383
+
384
+ if pivots:
385
+ return mat, pivot_cols
386
+ else:
387
+ return mat
phi4/lib/python3.10/site-packages/sympy/matrices/repmatrix.py ADDED
@@ -0,0 +1,1025 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections import defaultdict
2
+
3
+ from operator import index as index_
4
+
5
+ from sympy.core.expr import Expr
6
+ from sympy.core.kind import Kind, NumberKind, UndefinedKind
7
+ from sympy.core.numbers import Integer, Rational
8
+ from sympy.core.sympify import _sympify, SympifyError
9
+ from sympy.core.singleton import S
10
+ from sympy.polys.domains import ZZ, QQ, GF, EXRAW
11
+ from sympy.polys.matrices import DomainMatrix
12
+ from sympy.polys.matrices.exceptions import DMNonInvertibleMatrixError
13
+ from sympy.polys.polyerrors import CoercionFailed
14
+ from sympy.utilities.exceptions import sympy_deprecation_warning
15
+ from sympy.utilities.iterables import is_sequence
16
+ from sympy.utilities.misc import filldedent, as_int
17
+
18
+ from .exceptions import ShapeError, NonSquareMatrixError, NonInvertibleMatrixError
19
+ from .matrixbase import classof, MatrixBase
20
+ from .kind import MatrixKind
21
+
22
+
23
+ class RepMatrix(MatrixBase):
24
+ """Matrix implementation based on DomainMatrix as an internal representation.
25
+
26
+ The RepMatrix class is a superclass for Matrix, ImmutableMatrix,
27
+ SparseMatrix and ImmutableSparseMatrix which are the main usable matrix
28
+ classes in SymPy. Most methods on this class are simply forwarded to
29
+ DomainMatrix.
30
+ """
31
+
32
+ #
33
+ # MatrixBase is the common superclass for all of the usable explicit matrix
34
+ # classes in SymPy. The idea is that MatrixBase is an abstract class though
35
+ # and that subclasses will implement the lower-level methods.
36
+ #
37
+ # RepMatrix is a subclass of MatrixBase that uses DomainMatrix as an
38
+ # internal representation and delegates lower-level methods to
39
+ # DomainMatrix. All of SymPy's standard explicit matrix classes subclass
40
+ # RepMatrix and so use DomainMatrix internally.
41
+ #
42
+ # A RepMatrix uses an internal DomainMatrix with the domain set to ZZ, QQ
43
+ # or EXRAW. The EXRAW domain is equivalent to the previous implementation
44
+ # of Matrix that used Expr for the elements. The ZZ and QQ domains are used
45
+ # when applicable just because they are compatible with the previous
46
+ # implementation but are much more efficient. Other domains such as QQ[x]
47
+ # are not used because they differ from Expr in some way (e.g. automatic
48
+ # expansion of powers and products).
49
+ #
50
+
51
+ _rep: DomainMatrix
52
+
53
+ def __eq__(self, other):
54
+ # Skip sympify for mutable matrices...
55
+ if not isinstance(other, RepMatrix):
56
+ try:
57
+ other = _sympify(other)
58
+ except SympifyError:
59
+ return NotImplemented
60
+ if not isinstance(other, RepMatrix):
61
+ return NotImplemented
62
+
63
+ return self._rep.unify_eq(other._rep)
64
+
65
+ def to_DM(self, domain=None, **kwargs):
66
+ """Convert to a :class:`~.DomainMatrix`.
67
+
68
+ Examples
69
+ ========
70
+
71
+ >>> from sympy import Matrix
72
+ >>> M = Matrix([[1, 2], [3, 4]])
73
+ >>> M.to_DM()
74
+ DomainMatrix({0: {0: 1, 1: 2}, 1: {0: 3, 1: 4}}, (2, 2), ZZ)
75
+
76
+ The :meth:`DomainMatrix.to_Matrix` method can be used to convert back:
77
+
78
+ >>> M.to_DM().to_Matrix() == M
79
+ True
80
+
81
+ The domain can be given explicitly or otherwise it will be chosen by
82
+ :func:`construct_domain`. Any keyword arguments (besides ``domain``)
83
+ are passed to :func:`construct_domain`:
84
+
85
+ >>> from sympy import QQ, symbols
86
+ >>> x = symbols('x')
87
+ >>> M = Matrix([[x, 1], [1, x]])
88
+ >>> M
89
+ Matrix([
90
+ [x, 1],
91
+ [1, x]])
92
+ >>> M.to_DM().domain
93
+ ZZ[x]
94
+ >>> M.to_DM(field=True).domain
95
+ ZZ(x)
96
+ >>> M.to_DM(domain=QQ[x]).domain
97
+ QQ[x]
98
+
99
+ See Also
100
+ ========
101
+
102
+ DomainMatrix
103
+ DomainMatrix.to_Matrix
104
+ DomainMatrix.convert_to
105
+ DomainMatrix.choose_domain
106
+ construct_domain
107
+ """
108
+ if domain is not None:
109
+ if kwargs:
110
+ raise TypeError("Options cannot be used with domain parameter")
111
+ return self._rep.convert_to(domain)
112
+
113
+ rep = self._rep
114
+ dom = rep.domain
115
+
116
+ # If the internal DomainMatrix is already ZZ or QQ then we can maybe
117
+ # bypass calling construct_domain or performing any conversions. Some
118
+ # kwargs might affect this though e.g. field=True (not sure if there
119
+ # are others).
120
+ if not kwargs:
121
+ if dom.is_ZZ:
122
+ return rep.copy()
123
+ elif dom.is_QQ:
124
+ # All elements might be integers
125
+ try:
126
+ return rep.convert_to(ZZ)
127
+ except CoercionFailed:
128
+ pass
129
+ return rep.copy()
130
+
131
+ # Let construct_domain choose a domain
132
+ rep_dom = rep.choose_domain(**kwargs)
133
+
134
+ # XXX: There should be an option to construct_domain to choose EXRAW
135
+ # instead of EX. At least converting to EX does not initially trigger
136
+ # EX.simplify which is what we want here but should probably be
137
+ # considered a bug in EX. Perhaps also this could be handled in
138
+ # DomainMatrix.choose_domain rather than here...
139
+ if rep_dom.domain.is_EX:
140
+ rep_dom = rep_dom.convert_to(EXRAW)
141
+
142
+ return rep_dom
143
+
144
+ @classmethod
145
+ def _unify_element_sympy(cls, rep, element):
146
+ domain = rep.domain
147
+ element = _sympify(element)
148
+
149
+ if domain != EXRAW:
150
+ # The domain can only be ZZ, QQ or EXRAW
151
+ if element.is_Integer:
152
+ new_domain = domain
153
+ elif element.is_Rational:
154
+ new_domain = QQ
155
+ else:
156
+ new_domain = EXRAW
157
+
158
+ # XXX: This converts the domain for all elements in the matrix
159
+ # which can be slow. This happens e.g. if __setitem__ changes one
160
+ # element to something that does not fit in the domain
161
+ if new_domain != domain:
162
+ rep = rep.convert_to(new_domain)
163
+ domain = new_domain
164
+
165
+ if domain != EXRAW:
166
+ element = new_domain.from_sympy(element)
167
+
168
+ if domain == EXRAW and not isinstance(element, Expr):
169
+ sympy_deprecation_warning(
170
+ """
171
+ non-Expr objects in a Matrix is deprecated. Matrix represents
172
+ a mathematical matrix. To represent a container of non-numeric
173
+ entities, Use a list of lists, TableForm, NumPy array, or some
174
+ other data structure instead.
175
+ """,
176
+ deprecated_since_version="1.9",
177
+ active_deprecations_target="deprecated-non-expr-in-matrix",
178
+ stacklevel=4,
179
+ )
180
+
181
+ return rep, element
182
+
183
+ @classmethod
184
+ def _dod_to_DomainMatrix(cls, rows, cols, dod, types):
185
+
186
+ if not all(issubclass(typ, Expr) for typ in types):
187
+ sympy_deprecation_warning(
188
+ """
189
+ non-Expr objects in a Matrix is deprecated. Matrix represents
190
+ a mathematical matrix. To represent a container of non-numeric
191
+ entities, Use a list of lists, TableForm, NumPy array, or some
192
+ other data structure instead.
193
+ """,
194
+ deprecated_since_version="1.9",
195
+ active_deprecations_target="deprecated-non-expr-in-matrix",
196
+ stacklevel=6,
197
+ )
198
+
199
+ rep = DomainMatrix(dod, (rows, cols), EXRAW)
200
+
201
+ if all(issubclass(typ, Rational) for typ in types):
202
+ if all(issubclass(typ, Integer) for typ in types):
203
+ rep = rep.convert_to(ZZ)
204
+ else:
205
+ rep = rep.convert_to(QQ)
206
+
207
+ return rep
208
+
209
+ @classmethod
210
+ def _flat_list_to_DomainMatrix(cls, rows, cols, flat_list):
211
+
212
+ elements_dod = defaultdict(dict)
213
+ for n, element in enumerate(flat_list):
214
+ if element != 0:
215
+ i, j = divmod(n, cols)
216
+ elements_dod[i][j] = element
217
+
218
+ types = set(map(type, flat_list))
219
+
220
+ rep = cls._dod_to_DomainMatrix(rows, cols, elements_dod, types)
221
+ return rep
222
+
223
+ @classmethod
224
+ def _smat_to_DomainMatrix(cls, rows, cols, smat):
225
+
226
+ elements_dod = defaultdict(dict)
227
+ for (i, j), element in smat.items():
228
+ if element != 0:
229
+ elements_dod[i][j] = element
230
+
231
+ types = set(map(type, smat.values()))
232
+
233
+ rep = cls._dod_to_DomainMatrix(rows, cols, elements_dod, types)
234
+ return rep
235
+
236
+ def flat(self):
237
+ return self._rep.to_sympy().to_list_flat()
238
+
239
+ def _eval_tolist(self):
240
+ return self._rep.to_sympy().to_list()
241
+
242
+ def _eval_todok(self):
243
+ return self._rep.to_sympy().to_dok()
244
+
245
+ @classmethod
246
+ def _eval_from_dok(cls, rows, cols, dok):
247
+ return cls._fromrep(cls._smat_to_DomainMatrix(rows, cols, dok))
248
+
249
+ def _eval_values(self):
250
+ return list(self._eval_iter_values())
251
+
252
+ def _eval_iter_values(self):
253
+ rep = self._rep
254
+ K = rep.domain
255
+ values = rep.iter_values()
256
+ if not K.is_EXRAW:
257
+ values = map(K.to_sympy, values)
258
+ return values
259
+
260
+ def _eval_iter_items(self):
261
+ rep = self._rep
262
+ K = rep.domain
263
+ to_sympy = K.to_sympy
264
+ items = rep.iter_items()
265
+ if not K.is_EXRAW:
266
+ items = ((i, to_sympy(v)) for i, v in items)
267
+ return items
268
+
269
+ def copy(self):
270
+ return self._fromrep(self._rep.copy())
271
+
272
+ @property
273
+ def kind(self) -> MatrixKind:
274
+ domain = self._rep.domain
275
+ element_kind: Kind
276
+ if domain in (ZZ, QQ):
277
+ element_kind = NumberKind
278
+ elif domain == EXRAW:
279
+ kinds = {e.kind for e in self.values()}
280
+ if len(kinds) == 1:
281
+ [element_kind] = kinds
282
+ else:
283
+ element_kind = UndefinedKind
284
+ else: # pragma: no cover
285
+ raise RuntimeError("Domain should only be ZZ, QQ or EXRAW")
286
+ return MatrixKind(element_kind)
287
+
288
+ def _eval_has(self, *patterns):
289
+ # if the matrix has any zeros, see if S.Zero
290
+ # has the pattern. If _smat is full length,
291
+ # the matrix has no zeros.
292
+ zhas = False
293
+ dok = self.todok()
294
+ if len(dok) != self.rows*self.cols:
295
+ zhas = S.Zero.has(*patterns)
296
+ return zhas or any(value.has(*patterns) for value in dok.values())
297
+
298
+ def _eval_is_Identity(self):
299
+ if not all(self[i, i] == 1 for i in range(self.rows)):
300
+ return False
301
+ return len(self.todok()) == self.rows
302
+
303
+ def _eval_is_symmetric(self, simpfunc):
304
+ diff = (self - self.T).applyfunc(simpfunc)
305
+ return len(diff.values()) == 0
306
+
307
+ def _eval_transpose(self):
308
+ """Returns the transposed SparseMatrix of this SparseMatrix.
309
+
310
+ Examples
311
+ ========
312
+
313
+ >>> from sympy import SparseMatrix
314
+ >>> a = SparseMatrix(((1, 2), (3, 4)))
315
+ >>> a
316
+ Matrix([
317
+ [1, 2],
318
+ [3, 4]])
319
+ >>> a.T
320
+ Matrix([
321
+ [1, 3],
322
+ [2, 4]])
323
+ """
324
+ return self._fromrep(self._rep.transpose())
325
+
326
+ def _eval_col_join(self, other):
327
+ return self._fromrep(self._rep.vstack(other._rep))
328
+
329
+ def _eval_row_join(self, other):
330
+ return self._fromrep(self._rep.hstack(other._rep))
331
+
332
+ def _eval_extract(self, rowsList, colsList):
333
+ return self._fromrep(self._rep.extract(rowsList, colsList))
334
+
335
+ def __getitem__(self, key):
336
+ return _getitem_RepMatrix(self, key)
337
+
338
+ @classmethod
339
+ def _eval_zeros(cls, rows, cols):
340
+ rep = DomainMatrix.zeros((rows, cols), ZZ)
341
+ return cls._fromrep(rep)
342
+
343
+ @classmethod
344
+ def _eval_eye(cls, rows, cols):
345
+ rep = DomainMatrix.eye((rows, cols), ZZ)
346
+ return cls._fromrep(rep)
347
+
348
+ def _eval_add(self, other):
349
+ return classof(self, other)._fromrep(self._rep + other._rep)
350
+
351
+ def _eval_matrix_mul(self, other):
352
+ return classof(self, other)._fromrep(self._rep * other._rep)
353
+
354
+ def _eval_matrix_mul_elementwise(self, other):
355
+ selfrep, otherrep = self._rep.unify(other._rep)
356
+ newrep = selfrep.mul_elementwise(otherrep)
357
+ return classof(self, other)._fromrep(newrep)
358
+
359
+ def _eval_scalar_mul(self, other):
360
+ rep, other = self._unify_element_sympy(self._rep, other)
361
+ return self._fromrep(rep.scalarmul(other))
362
+
363
+ def _eval_scalar_rmul(self, other):
364
+ rep, other = self._unify_element_sympy(self._rep, other)
365
+ return self._fromrep(rep.rscalarmul(other))
366
+
367
+ def _eval_Abs(self):
368
+ return self._fromrep(self._rep.applyfunc(abs))
369
+
370
+ def _eval_conjugate(self):
371
+ rep = self._rep
372
+ domain = rep.domain
373
+ if domain in (ZZ, QQ):
374
+ return self.copy()
375
+ else:
376
+ return self._fromrep(rep.applyfunc(lambda e: e.conjugate()))
377
+
378
+ def equals(self, other, failing_expression=False):
379
+ """Applies ``equals`` to corresponding elements of the matrices,
380
+ trying to prove that the elements are equivalent, returning True
381
+ if they are, False if any pair is not, and None (or the first
382
+ failing expression if failing_expression is True) if it cannot
383
+ be decided if the expressions are equivalent or not. This is, in
384
+ general, an expensive operation.
385
+
386
+ Examples
387
+ ========
388
+
389
+ >>> from sympy import Matrix
390
+ >>> from sympy.abc import x
391
+ >>> A = Matrix([x*(x - 1), 0])
392
+ >>> B = Matrix([x**2 - x, 0])
393
+ >>> A == B
394
+ False
395
+ >>> A.simplify() == B.simplify()
396
+ True
397
+ >>> A.equals(B)
398
+ True
399
+ >>> A.equals(2)
400
+ False
401
+
402
+ See Also
403
+ ========
404
+ sympy.core.expr.Expr.equals
405
+ """
406
+ if self.shape != getattr(other, 'shape', None):
407
+ return False
408
+
409
+ rv = True
410
+ for i in range(self.rows):
411
+ for j in range(self.cols):
412
+ ans = self[i, j].equals(other[i, j], failing_expression)
413
+ if ans is False:
414
+ return False
415
+ elif ans is not True and rv is True:
416
+ rv = ans
417
+ return rv
418
+
419
+ def inv_mod(M, m):
420
+ r"""
421
+ Returns the inverse of the integer matrix ``M`` modulo ``m``.
422
+
423
+ Examples
424
+ ========
425
+
426
+ >>> from sympy import Matrix
427
+ >>> A = Matrix(2, 2, [1, 2, 3, 4])
428
+ >>> A.inv_mod(5)
429
+ Matrix([
430
+ [3, 1],
431
+ [4, 2]])
432
+ >>> A.inv_mod(3)
433
+ Matrix([
434
+ [1, 1],
435
+ [0, 1]])
436
+
437
+ """
438
+
439
+ if not M.is_square:
440
+ raise NonSquareMatrixError()
441
+
442
+ try:
443
+ m = as_int(m)
444
+ except ValueError:
445
+ raise TypeError("inv_mod: modulus m must be an integer")
446
+
447
+ K = GF(m, symmetric=False)
448
+
449
+ try:
450
+ dM = M.to_DM(K)
451
+ except CoercionFailed:
452
+ raise ValueError("inv_mod: matrix entries must be integers")
453
+
454
+ try:
455
+ dMi = dM.inv()
456
+ except DMNonInvertibleMatrixError as exc:
457
+ msg = f'Matrix is not invertible (mod {m})'
458
+ raise NonInvertibleMatrixError(msg) from exc
459
+
460
+ return dMi.to_Matrix()
461
+
462
+ def lll(self, delta=0.75):
463
+ """LLL-reduced basis for the rowspace of a matrix of integers.
464
+
465
+ Performs the Lenstra–Lenstra–Lovász (LLL) basis reduction algorithm.
466
+
467
+ The implementation is provided by :class:`~DomainMatrix`. See
468
+ :meth:`~DomainMatrix.lll` for more details.
469
+
470
+ Examples
471
+ ========
472
+
473
+ >>> from sympy import Matrix
474
+ >>> M = Matrix([[1, 0, 0, 0, -20160],
475
+ ... [0, 1, 0, 0, 33768],
476
+ ... [0, 0, 1, 0, 39578],
477
+ ... [0, 0, 0, 1, 47757]])
478
+ >>> M.lll()
479
+ Matrix([
480
+ [ 10, -3, -2, 8, -4],
481
+ [ 3, -9, 8, 1, -11],
482
+ [ -3, 13, -9, -3, -9],
483
+ [-12, -7, -11, 9, -1]])
484
+
485
+ See Also
486
+ ========
487
+
488
+ lll_transform
489
+ sympy.polys.matrices.domainmatrix.DomainMatrix.lll
490
+ """
491
+ delta = QQ.from_sympy(_sympify(delta))
492
+ dM = self._rep.convert_to(ZZ)
493
+ basis = dM.lll(delta=delta)
494
+ return self._fromrep(basis)
495
+
496
+ def lll_transform(self, delta=0.75):
497
+ """LLL-reduced basis and transformation matrix.
498
+
499
+ Performs the Lenstra–Lenstra–Lovász (LLL) basis reduction algorithm.
500
+
501
+ The implementation is provided by :class:`~DomainMatrix`. See
502
+ :meth:`~DomainMatrix.lll_transform` for more details.
503
+
504
+ Examples
505
+ ========
506
+
507
+ >>> from sympy import Matrix
508
+ >>> M = Matrix([[1, 0, 0, 0, -20160],
509
+ ... [0, 1, 0, 0, 33768],
510
+ ... [0, 0, 1, 0, 39578],
511
+ ... [0, 0, 0, 1, 47757]])
512
+ >>> B, T = M.lll_transform()
513
+ >>> B
514
+ Matrix([
515
+ [ 10, -3, -2, 8, -4],
516
+ [ 3, -9, 8, 1, -11],
517
+ [ -3, 13, -9, -3, -9],
518
+ [-12, -7, -11, 9, -1]])
519
+ >>> T
520
+ Matrix([
521
+ [ 10, -3, -2, 8],
522
+ [ 3, -9, 8, 1],
523
+ [ -3, 13, -9, -3],
524
+ [-12, -7, -11, 9]])
525
+
526
+ The transformation matrix maps the original basis to the LLL-reduced
527
+ basis:
528
+
529
+ >>> T * M == B
530
+ True
531
+
532
+ See Also
533
+ ========
534
+
535
+ lll
536
+ sympy.polys.matrices.domainmatrix.DomainMatrix.lll_transform
537
+ """
538
+ delta = QQ.from_sympy(_sympify(delta))
539
+ dM = self._rep.convert_to(ZZ)
540
+ basis, transform = dM.lll_transform(delta=delta)
541
+ B = self._fromrep(basis)
542
+ T = self._fromrep(transform)
543
+ return B, T
544
+
545
+
546
+ class MutableRepMatrix(RepMatrix):
547
+ """Mutable matrix based on DomainMatrix as the internal representation"""
548
+
549
+ #
550
+ # MutableRepMatrix is a subclass of RepMatrix that adds/overrides methods
551
+ # to make the instances mutable. MutableRepMatrix is a superclass for both
552
+ # MutableDenseMatrix and MutableSparseMatrix.
553
+ #
554
+
555
+ is_zero = False
556
+
557
+ def __new__(cls, *args, **kwargs):
558
+ return cls._new(*args, **kwargs)
559
+
560
+ @classmethod
561
+ def _new(cls, *args, copy=True, **kwargs):
562
+ if copy is False:
563
+ # The input was rows, cols, [list].
564
+ # It should be used directly without creating a copy.
565
+ if len(args) != 3:
566
+ raise TypeError("'copy=False' requires a matrix be initialized as rows,cols,[list]")
567
+ rows, cols, flat_list = args
568
+ else:
569
+ rows, cols, flat_list = cls._handle_creation_inputs(*args, **kwargs)
570
+ flat_list = list(flat_list) # create a shallow copy
571
+
572
+ rep = cls._flat_list_to_DomainMatrix(rows, cols, flat_list)
573
+
574
+ return cls._fromrep(rep)
575
+
576
+ @classmethod
577
+ def _fromrep(cls, rep):
578
+ obj = super().__new__(cls)
579
+ obj.rows, obj.cols = rep.shape
580
+ obj._rep = rep
581
+ return obj
582
+
583
+ def copy(self):
584
+ return self._fromrep(self._rep.copy())
585
+
586
+ def as_mutable(self):
587
+ return self.copy()
588
+
589
+ def __setitem__(self, key, value):
590
+ """
591
+
592
+ Examples
593
+ ========
594
+
595
+ >>> from sympy import Matrix, I, zeros, ones
596
+ >>> m = Matrix(((1, 2+I), (3, 4)))
597
+ >>> m
598
+ Matrix([
599
+ [1, 2 + I],
600
+ [3, 4]])
601
+ >>> m[1, 0] = 9
602
+ >>> m
603
+ Matrix([
604
+ [1, 2 + I],
605
+ [9, 4]])
606
+ >>> m[1, 0] = [[0, 1]]
607
+
608
+ To replace row r you assign to position r*m where m
609
+ is the number of columns:
610
+
611
+ >>> M = zeros(4)
612
+ >>> m = M.cols
613
+ >>> M[3*m] = ones(1, m)*2; M
614
+ Matrix([
615
+ [0, 0, 0, 0],
616
+ [0, 0, 0, 0],
617
+ [0, 0, 0, 0],
618
+ [2, 2, 2, 2]])
619
+
620
+ And to replace column c you can assign to position c:
621
+
622
+ >>> M[2] = ones(m, 1)*4; M
623
+ Matrix([
624
+ [0, 0, 4, 0],
625
+ [0, 0, 4, 0],
626
+ [0, 0, 4, 0],
627
+ [2, 2, 4, 2]])
628
+ """
629
+ rv = self._setitem(key, value)
630
+ if rv is not None:
631
+ i, j, value = rv
632
+ self._rep, value = self._unify_element_sympy(self._rep, value)
633
+ self._rep.rep.setitem(i, j, value)
634
+
635
+ def _eval_col_del(self, col):
636
+ self._rep = DomainMatrix.hstack(self._rep[:,:col], self._rep[:,col+1:])
637
+ self.cols -= 1
638
+
639
+ def _eval_row_del(self, row):
640
+ self._rep = DomainMatrix.vstack(self._rep[:row,:], self._rep[row+1:, :])
641
+ self.rows -= 1
642
+
643
+ def _eval_col_insert(self, col, other):
644
+ other = self._new(other)
645
+ return self.hstack(self[:,:col], other, self[:,col:])
646
+
647
+ def _eval_row_insert(self, row, other):
648
+ other = self._new(other)
649
+ return self.vstack(self[:row,:], other, self[row:,:])
650
+
651
+ def col_op(self, j, f):
652
+ """In-place operation on col j using two-arg functor whose args are
653
+ interpreted as (self[i, j], i).
654
+
655
+ Examples
656
+ ========
657
+
658
+ >>> from sympy import eye
659
+ >>> M = eye(3)
660
+ >>> M.col_op(1, lambda v, i: v + 2*M[i, 0]); M
661
+ Matrix([
662
+ [1, 2, 0],
663
+ [0, 1, 0],
664
+ [0, 0, 1]])
665
+
666
+ See Also
667
+ ========
668
+ col
669
+ row_op
670
+ """
671
+ for i in range(self.rows):
672
+ self[i, j] = f(self[i, j], i)
673
+
674
+ def col_swap(self, i, j):
675
+ """Swap the two given columns of the matrix in-place.
676
+
677
+ Examples
678
+ ========
679
+
680
+ >>> from sympy import Matrix
681
+ >>> M = Matrix([[1, 0], [1, 0]])
682
+ >>> M
683
+ Matrix([
684
+ [1, 0],
685
+ [1, 0]])
686
+ >>> M.col_swap(0, 1)
687
+ >>> M
688
+ Matrix([
689
+ [0, 1],
690
+ [0, 1]])
691
+
692
+ See Also
693
+ ========
694
+
695
+ col
696
+ row_swap
697
+ """
698
+ for k in range(0, self.rows):
699
+ self[k, i], self[k, j] = self[k, j], self[k, i]
700
+
701
+ def row_op(self, i, f):
702
+ """In-place operation on row ``i`` using two-arg functor whose args are
703
+ interpreted as ``(self[i, j], j)``.
704
+
705
+ Examples
706
+ ========
707
+
708
+ >>> from sympy import eye
709
+ >>> M = eye(3)
710
+ >>> M.row_op(1, lambda v, j: v + 2*M[0, j]); M
711
+ Matrix([
712
+ [1, 0, 0],
713
+ [2, 1, 0],
714
+ [0, 0, 1]])
715
+
716
+ See Also
717
+ ========
718
+ row
719
+ zip_row_op
720
+ col_op
721
+
722
+ """
723
+ for j in range(self.cols):
724
+ self[i, j] = f(self[i, j], j)
725
+
726
+ #The next three methods give direct support for the most common row operations inplace.
727
+ def row_mult(self,i,factor):
728
+ """Multiply the given row by the given factor in-place.
729
+
730
+ Examples
731
+ ========
732
+
733
+ >>> from sympy import eye
734
+ >>> M = eye(3)
735
+ >>> M.row_mult(1,7); M
736
+ Matrix([
737
+ [1, 0, 0],
738
+ [0, 7, 0],
739
+ [0, 0, 1]])
740
+
741
+ """
742
+ for j in range(self.cols):
743
+ self[i,j] *= factor
744
+
745
+ def row_add(self,s,t,k):
746
+ """Add k times row s (source) to row t (target) in place.
747
+
748
+ Examples
749
+ ========
750
+
751
+ >>> from sympy import eye
752
+ >>> M = eye(3)
753
+ >>> M.row_add(0, 2,3); M
754
+ Matrix([
755
+ [1, 0, 0],
756
+ [0, 1, 0],
757
+ [3, 0, 1]])
758
+ """
759
+
760
+ for j in range(self.cols):
761
+ self[t,j] += k*self[s,j]
762
+
763
+ def row_swap(self, i, j):
764
+ """Swap the two given rows of the matrix in-place.
765
+
766
+ Examples
767
+ ========
768
+
769
+ >>> from sympy import Matrix
770
+ >>> M = Matrix([[0, 1], [1, 0]])
771
+ >>> M
772
+ Matrix([
773
+ [0, 1],
774
+ [1, 0]])
775
+ >>> M.row_swap(0, 1)
776
+ >>> M
777
+ Matrix([
778
+ [1, 0],
779
+ [0, 1]])
780
+
781
+ See Also
782
+ ========
783
+
784
+ row
785
+ col_swap
786
+ """
787
+ for k in range(0, self.cols):
788
+ self[i, k], self[j, k] = self[j, k], self[i, k]
789
+
790
+ def zip_row_op(self, i, k, f):
791
+ """In-place operation on row ``i`` using two-arg functor whose args are
792
+ interpreted as ``(self[i, j], self[k, j])``.
793
+
794
+ Examples
795
+ ========
796
+
797
+ >>> from sympy import eye
798
+ >>> M = eye(3)
799
+ >>> M.zip_row_op(1, 0, lambda v, u: v + 2*u); M
800
+ Matrix([
801
+ [1, 0, 0],
802
+ [2, 1, 0],
803
+ [0, 0, 1]])
804
+
805
+ See Also
806
+ ========
807
+ row
808
+ row_op
809
+ col_op
810
+
811
+ """
812
+ for j in range(self.cols):
813
+ self[i, j] = f(self[i, j], self[k, j])
814
+
815
+ def copyin_list(self, key, value):
816
+ """Copy in elements from a list.
817
+
818
+ Parameters
819
+ ==========
820
+
821
+ key : slice
822
+ The section of this matrix to replace.
823
+ value : iterable
824
+ The iterable to copy values from.
825
+
826
+ Examples
827
+ ========
828
+
829
+ >>> from sympy import eye
830
+ >>> I = eye(3)
831
+ >>> I[:2, 0] = [1, 2] # col
832
+ >>> I
833
+ Matrix([
834
+ [1, 0, 0],
835
+ [2, 1, 0],
836
+ [0, 0, 1]])
837
+ >>> I[1, :2] = [[3, 4]]
838
+ >>> I
839
+ Matrix([
840
+ [1, 0, 0],
841
+ [3, 4, 0],
842
+ [0, 0, 1]])
843
+
844
+ See Also
845
+ ========
846
+
847
+ copyin_matrix
848
+ """
849
+ if not is_sequence(value):
850
+ raise TypeError("`value` must be an ordered iterable, not %s." % type(value))
851
+ return self.copyin_matrix(key, type(self)(value))
852
+
853
+ def copyin_matrix(self, key, value):
854
+ """Copy in values from a matrix into the given bounds.
855
+
856
+ Parameters
857
+ ==========
858
+
859
+ key : slice
860
+ The section of this matrix to replace.
861
+ value : Matrix
862
+ The matrix to copy values from.
863
+
864
+ Examples
865
+ ========
866
+
867
+ >>> from sympy import Matrix, eye
868
+ >>> M = Matrix([[0, 1], [2, 3], [4, 5]])
869
+ >>> I = eye(3)
870
+ >>> I[:3, :2] = M
871
+ >>> I
872
+ Matrix([
873
+ [0, 1, 0],
874
+ [2, 3, 0],
875
+ [4, 5, 1]])
876
+ >>> I[0, 1] = M
877
+ >>> I
878
+ Matrix([
879
+ [0, 0, 1],
880
+ [2, 2, 3],
881
+ [4, 4, 5]])
882
+
883
+ See Also
884
+ ========
885
+
886
+ copyin_list
887
+ """
888
+ rlo, rhi, clo, chi = self.key2bounds(key)
889
+ shape = value.shape
890
+ dr, dc = rhi - rlo, chi - clo
891
+ if shape != (dr, dc):
892
+ raise ShapeError(filldedent("The Matrix `value` doesn't have the "
893
+ "same dimensions "
894
+ "as the in sub-Matrix given by `key`."))
895
+
896
+ for i in range(value.rows):
897
+ for j in range(value.cols):
898
+ self[i + rlo, j + clo] = value[i, j]
899
+
900
+ def fill(self, value):
901
+ """Fill self with the given value.
902
+
903
+ Notes
904
+ =====
905
+
906
+ Unless many values are going to be deleted (i.e. set to zero)
907
+ this will create a matrix that is slower than a dense matrix in
908
+ operations.
909
+
910
+ Examples
911
+ ========
912
+
913
+ >>> from sympy import SparseMatrix
914
+ >>> M = SparseMatrix.zeros(3); M
915
+ Matrix([
916
+ [0, 0, 0],
917
+ [0, 0, 0],
918
+ [0, 0, 0]])
919
+ >>> M.fill(1); M
920
+ Matrix([
921
+ [1, 1, 1],
922
+ [1, 1, 1],
923
+ [1, 1, 1]])
924
+
925
+ See Also
926
+ ========
927
+
928
+ zeros
929
+ ones
930
+ """
931
+ value = _sympify(value)
932
+ if not value:
933
+ self._rep = DomainMatrix.zeros(self.shape, EXRAW)
934
+ else:
935
+ elements_dod = {i: dict.fromkeys(range(self.cols), value) for i in range(self.rows)}
936
+ self._rep = DomainMatrix(elements_dod, self.shape, EXRAW)
937
+
938
+
939
+ def _getitem_RepMatrix(self, key):
940
+ """Return portion of self defined by key. If the key involves a slice
941
+ then a list will be returned (if key is a single slice) or a matrix
942
+ (if key was a tuple involving a slice).
943
+
944
+ Examples
945
+ ========
946
+
947
+ >>> from sympy import Matrix, I
948
+ >>> m = Matrix([
949
+ ... [1, 2 + I],
950
+ ... [3, 4 ]])
951
+
952
+ If the key is a tuple that does not involve a slice then that element
953
+ is returned:
954
+
955
+ >>> m[1, 0]
956
+ 3
957
+
958
+ When a tuple key involves a slice, a matrix is returned. Here, the
959
+ first column is selected (all rows, column 0):
960
+
961
+ >>> m[:, 0]
962
+ Matrix([
963
+ [1],
964
+ [3]])
965
+
966
+ If the slice is not a tuple then it selects from the underlying
967
+ list of elements that are arranged in row order and a list is
968
+ returned if a slice is involved:
969
+
970
+ >>> m[0]
971
+ 1
972
+ >>> m[::2]
973
+ [1, 3]
974
+ """
975
+ if isinstance(key, tuple):
976
+ i, j = key
977
+ try:
978
+ return self._rep.getitem_sympy(index_(i), index_(j))
979
+ except (TypeError, IndexError):
980
+ if (isinstance(i, Expr) and not i.is_number) or (isinstance(j, Expr) and not j.is_number):
981
+ if ((j < 0) is True) or ((j >= self.shape[1]) is True) or\
982
+ ((i < 0) is True) or ((i >= self.shape[0]) is True):
983
+ raise ValueError("index out of boundary")
984
+ from sympy.matrices.expressions.matexpr import MatrixElement
985
+ return MatrixElement(self, i, j)
986
+
987
+ if isinstance(i, slice):
988
+ i = range(self.rows)[i]
989
+ elif is_sequence(i):
990
+ pass
991
+ else:
992
+ i = [i]
993
+ if isinstance(j, slice):
994
+ j = range(self.cols)[j]
995
+ elif is_sequence(j):
996
+ pass
997
+ else:
998
+ j = [j]
999
+ return self.extract(i, j)
1000
+
1001
+ else:
1002
+ # Index/slice like a flattened list
1003
+ rows, cols = self.shape
1004
+
1005
+ # Raise the appropriate exception:
1006
+ if not rows * cols:
1007
+ return [][key]
1008
+
1009
+ rep = self._rep.rep
1010
+ domain = rep.domain
1011
+ is_slice = isinstance(key, slice)
1012
+
1013
+ if is_slice:
1014
+ values = [rep.getitem(*divmod(n, cols)) for n in range(rows * cols)[key]]
1015
+ else:
1016
+ values = [rep.getitem(*divmod(index_(key), cols))]
1017
+
1018
+ if domain != EXRAW:
1019
+ to_sympy = domain.to_sympy
1020
+ values = [to_sympy(val) for val in values]
1021
+
1022
+ if is_slice:
1023
+ return values
1024
+ else:
1025
+ return values[0]
phi4/lib/python3.10/site-packages/sympy/matrices/solvers.py ADDED
@@ -0,0 +1,942 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.function import expand_mul
2
+ from sympy.core.symbol import Dummy, uniquely_named_symbol, symbols
3
+ from sympy.utilities.iterables import numbered_symbols
4
+
5
+ from .exceptions import ShapeError, NonSquareMatrixError, NonInvertibleMatrixError
6
+ from .eigen import _fuzzy_positive_definite
7
+ from .utilities import _get_intermediate_simp, _iszero
8
+
9
+
10
+ def _diagonal_solve(M, rhs):
11
+ """Solves ``Ax = B`` efficiently, where A is a diagonal Matrix,
12
+ with non-zero diagonal entries.
13
+
14
+ Examples
15
+ ========
16
+
17
+ >>> from sympy import Matrix, eye
18
+ >>> A = eye(2)*2
19
+ >>> B = Matrix([[1, 2], [3, 4]])
20
+ >>> A.diagonal_solve(B) == B/2
21
+ True
22
+
23
+ See Also
24
+ ========
25
+
26
+ sympy.matrices.dense.DenseMatrix.lower_triangular_solve
27
+ sympy.matrices.dense.DenseMatrix.upper_triangular_solve
28
+ gauss_jordan_solve
29
+ cholesky_solve
30
+ LDLsolve
31
+ LUsolve
32
+ QRsolve
33
+ pinv_solve
34
+ cramer_solve
35
+ """
36
+
37
+ if not M.is_diagonal():
38
+ raise TypeError("Matrix should be diagonal")
39
+ if rhs.rows != M.rows:
40
+ raise TypeError("Size mismatch")
41
+
42
+ return M._new(
43
+ rhs.rows, rhs.cols, lambda i, j: rhs[i, j] / M[i, i])
44
+
45
+
46
+ def _lower_triangular_solve(M, rhs):
47
+ """Solves ``Ax = B``, where A is a lower triangular matrix.
48
+
49
+ See Also
50
+ ========
51
+
52
+ upper_triangular_solve
53
+ gauss_jordan_solve
54
+ cholesky_solve
55
+ diagonal_solve
56
+ LDLsolve
57
+ LUsolve
58
+ QRsolve
59
+ pinv_solve
60
+ cramer_solve
61
+ """
62
+
63
+ from .dense import MutableDenseMatrix
64
+
65
+ if not M.is_square:
66
+ raise NonSquareMatrixError("Matrix must be square.")
67
+ if rhs.rows != M.rows:
68
+ raise ShapeError("Matrices size mismatch.")
69
+ if not M.is_lower:
70
+ raise ValueError("Matrix must be lower triangular.")
71
+
72
+ dps = _get_intermediate_simp()
73
+ X = MutableDenseMatrix.zeros(M.rows, rhs.cols)
74
+
75
+ for j in range(rhs.cols):
76
+ for i in range(M.rows):
77
+ if M[i, i] == 0:
78
+ raise TypeError("Matrix must be non-singular.")
79
+
80
+ X[i, j] = dps((rhs[i, j] - sum(M[i, k]*X[k, j]
81
+ for k in range(i))) / M[i, i])
82
+
83
+ return M._new(X)
84
+
85
+ def _lower_triangular_solve_sparse(M, rhs):
86
+ """Solves ``Ax = B``, where A is a lower triangular matrix.
87
+
88
+ See Also
89
+ ========
90
+
91
+ upper_triangular_solve
92
+ gauss_jordan_solve
93
+ cholesky_solve
94
+ diagonal_solve
95
+ LDLsolve
96
+ LUsolve
97
+ QRsolve
98
+ pinv_solve
99
+ cramer_solve
100
+ """
101
+
102
+ if not M.is_square:
103
+ raise NonSquareMatrixError("Matrix must be square.")
104
+ if rhs.rows != M.rows:
105
+ raise ShapeError("Matrices size mismatch.")
106
+ if not M.is_lower:
107
+ raise ValueError("Matrix must be lower triangular.")
108
+
109
+ dps = _get_intermediate_simp()
110
+ rows = [[] for i in range(M.rows)]
111
+
112
+ for i, j, v in M.row_list():
113
+ if i > j:
114
+ rows[i].append((j, v))
115
+
116
+ X = rhs.as_mutable()
117
+
118
+ for j in range(rhs.cols):
119
+ for i in range(rhs.rows):
120
+ for u, v in rows[i]:
121
+ X[i, j] -= v*X[u, j]
122
+
123
+ X[i, j] = dps(X[i, j] / M[i, i])
124
+
125
+ return M._new(X)
126
+
127
+
128
+ def _upper_triangular_solve(M, rhs):
129
+ """Solves ``Ax = B``, where A is an upper triangular matrix.
130
+
131
+ See Also
132
+ ========
133
+
134
+ lower_triangular_solve
135
+ gauss_jordan_solve
136
+ cholesky_solve
137
+ diagonal_solve
138
+ LDLsolve
139
+ LUsolve
140
+ QRsolve
141
+ pinv_solve
142
+ cramer_solve
143
+ """
144
+
145
+ from .dense import MutableDenseMatrix
146
+
147
+ if not M.is_square:
148
+ raise NonSquareMatrixError("Matrix must be square.")
149
+ if rhs.rows != M.rows:
150
+ raise ShapeError("Matrix size mismatch.")
151
+ if not M.is_upper:
152
+ raise TypeError("Matrix is not upper triangular.")
153
+
154
+ dps = _get_intermediate_simp()
155
+ X = MutableDenseMatrix.zeros(M.rows, rhs.cols)
156
+
157
+ for j in range(rhs.cols):
158
+ for i in reversed(range(M.rows)):
159
+ if M[i, i] == 0:
160
+ raise ValueError("Matrix must be non-singular.")
161
+
162
+ X[i, j] = dps((rhs[i, j] - sum(M[i, k]*X[k, j]
163
+ for k in range(i + 1, M.rows))) / M[i, i])
164
+
165
+ return M._new(X)
166
+
167
+ def _upper_triangular_solve_sparse(M, rhs):
168
+ """Solves ``Ax = B``, where A is an upper triangular matrix.
169
+
170
+ See Also
171
+ ========
172
+
173
+ lower_triangular_solve
174
+ gauss_jordan_solve
175
+ cholesky_solve
176
+ diagonal_solve
177
+ LDLsolve
178
+ LUsolve
179
+ QRsolve
180
+ pinv_solve
181
+ cramer_solve
182
+ """
183
+
184
+ if not M.is_square:
185
+ raise NonSquareMatrixError("Matrix must be square.")
186
+ if rhs.rows != M.rows:
187
+ raise ShapeError("Matrix size mismatch.")
188
+ if not M.is_upper:
189
+ raise TypeError("Matrix is not upper triangular.")
190
+
191
+ dps = _get_intermediate_simp()
192
+ rows = [[] for i in range(M.rows)]
193
+
194
+ for i, j, v in M.row_list():
195
+ if i < j:
196
+ rows[i].append((j, v))
197
+
198
+ X = rhs.as_mutable()
199
+
200
+ for j in range(rhs.cols):
201
+ for i in reversed(range(rhs.rows)):
202
+ for u, v in reversed(rows[i]):
203
+ X[i, j] -= v*X[u, j]
204
+
205
+ X[i, j] = dps(X[i, j] / M[i, i])
206
+
207
+ return M._new(X)
208
+
209
+
210
+ def _cholesky_solve(M, rhs):
211
+ """Solves ``Ax = B`` using Cholesky decomposition,
212
+ for a general square non-singular matrix.
213
+ For a non-square matrix with rows > cols,
214
+ the least squares solution is returned.
215
+
216
+ See Also
217
+ ========
218
+
219
+ sympy.matrices.dense.DenseMatrix.lower_triangular_solve
220
+ sympy.matrices.dense.DenseMatrix.upper_triangular_solve
221
+ gauss_jordan_solve
222
+ diagonal_solve
223
+ LDLsolve
224
+ LUsolve
225
+ QRsolve
226
+ pinv_solve
227
+ cramer_solve
228
+ """
229
+
230
+ if M.rows < M.cols:
231
+ raise NotImplementedError(
232
+ 'Under-determined System. Try M.gauss_jordan_solve(rhs)')
233
+
234
+ hermitian = True
235
+ reform = False
236
+
237
+ if M.is_symmetric():
238
+ hermitian = False
239
+ elif not M.is_hermitian:
240
+ reform = True
241
+
242
+ if reform or _fuzzy_positive_definite(M) is False:
243
+ H = M.H
244
+ M = H.multiply(M)
245
+ rhs = H.multiply(rhs)
246
+ hermitian = not M.is_symmetric()
247
+
248
+ L = M.cholesky(hermitian=hermitian)
249
+ Y = L.lower_triangular_solve(rhs)
250
+
251
+ if hermitian:
252
+ return (L.H).upper_triangular_solve(Y)
253
+ else:
254
+ return (L.T).upper_triangular_solve(Y)
255
+
256
+
257
+ def _LDLsolve(M, rhs):
258
+ """Solves ``Ax = B`` using LDL decomposition,
259
+ for a general square and non-singular matrix.
260
+
261
+ For a non-square matrix with rows > cols,
262
+ the least squares solution is returned.
263
+
264
+ Examples
265
+ ========
266
+
267
+ >>> from sympy import Matrix, eye
268
+ >>> A = eye(2)*2
269
+ >>> B = Matrix([[1, 2], [3, 4]])
270
+ >>> A.LDLsolve(B) == B/2
271
+ True
272
+
273
+ See Also
274
+ ========
275
+
276
+ sympy.matrices.dense.DenseMatrix.LDLdecomposition
277
+ sympy.matrices.dense.DenseMatrix.lower_triangular_solve
278
+ sympy.matrices.dense.DenseMatrix.upper_triangular_solve
279
+ gauss_jordan_solve
280
+ cholesky_solve
281
+ diagonal_solve
282
+ LUsolve
283
+ QRsolve
284
+ pinv_solve
285
+ cramer_solve
286
+ """
287
+
288
+ if M.rows < M.cols:
289
+ raise NotImplementedError(
290
+ 'Under-determined System. Try M.gauss_jordan_solve(rhs)')
291
+
292
+ hermitian = True
293
+ reform = False
294
+
295
+ if M.is_symmetric():
296
+ hermitian = False
297
+ elif not M.is_hermitian:
298
+ reform = True
299
+
300
+ if reform or _fuzzy_positive_definite(M) is False:
301
+ H = M.H
302
+ M = H.multiply(M)
303
+ rhs = H.multiply(rhs)
304
+ hermitian = not M.is_symmetric()
305
+
306
+ L, D = M.LDLdecomposition(hermitian=hermitian)
307
+ Y = L.lower_triangular_solve(rhs)
308
+ Z = D.diagonal_solve(Y)
309
+
310
+ if hermitian:
311
+ return (L.H).upper_triangular_solve(Z)
312
+ else:
313
+ return (L.T).upper_triangular_solve(Z)
314
+
315
+
316
+ def _LUsolve(M, rhs, iszerofunc=_iszero):
317
+ """Solve the linear system ``Ax = rhs`` for ``x`` where ``A = M``.
318
+
319
+ This is for symbolic matrices, for real or complex ones use
320
+ mpmath.lu_solve or mpmath.qr_solve.
321
+
322
+ See Also
323
+ ========
324
+
325
+ sympy.matrices.dense.DenseMatrix.lower_triangular_solve
326
+ sympy.matrices.dense.DenseMatrix.upper_triangular_solve
327
+ gauss_jordan_solve
328
+ cholesky_solve
329
+ diagonal_solve
330
+ LDLsolve
331
+ QRsolve
332
+ pinv_solve
333
+ LUdecomposition
334
+ cramer_solve
335
+ """
336
+
337
+ if rhs.rows != M.rows:
338
+ raise ShapeError(
339
+ "``M`` and ``rhs`` must have the same number of rows.")
340
+
341
+ m = M.rows
342
+ n = M.cols
343
+
344
+ if m < n:
345
+ raise NotImplementedError("Underdetermined systems not supported.")
346
+
347
+ try:
348
+ A, perm = M.LUdecomposition_Simple(
349
+ iszerofunc=iszerofunc, rankcheck=True)
350
+ except ValueError:
351
+ raise NonInvertibleMatrixError("Matrix det == 0; not invertible.")
352
+
353
+ dps = _get_intermediate_simp()
354
+ b = rhs.permute_rows(perm).as_mutable()
355
+
356
+ # forward substitution, all diag entries are scaled to 1
357
+ for i in range(m):
358
+ for j in range(min(i, n)):
359
+ scale = A[i, j]
360
+ b.zip_row_op(i, j, lambda x, y: dps(x - y * scale))
361
+
362
+ # consistency check for overdetermined systems
363
+ if m > n:
364
+ for i in range(n, m):
365
+ for j in range(b.cols):
366
+ if not iszerofunc(b[i, j]):
367
+ raise ValueError("The system is inconsistent.")
368
+
369
+ b = b[0:n, :] # truncate zero rows if consistent
370
+
371
+ # backward substitution
372
+ for i in range(n - 1, -1, -1):
373
+ for j in range(i + 1, n):
374
+ scale = A[i, j]
375
+ b.zip_row_op(i, j, lambda x, y: dps(x - y * scale))
376
+
377
+ scale = A[i, i]
378
+ b.row_op(i, lambda x, _: dps(x / scale))
379
+
380
+ return rhs.__class__(b)
381
+
382
+
383
+ def _QRsolve(M, b):
384
+ """Solve the linear system ``Ax = b``.
385
+
386
+ ``M`` is the matrix ``A``, the method argument is the vector
387
+ ``b``. The method returns the solution vector ``x``. If ``b`` is a
388
+ matrix, the system is solved for each column of ``b`` and the
389
+ return value is a matrix of the same shape as ``b``.
390
+
391
+ This method is slower (approximately by a factor of 2) but
392
+ more stable for floating-point arithmetic than the LUsolve method.
393
+ However, LUsolve usually uses an exact arithmetic, so you do not need
394
+ to use QRsolve.
395
+
396
+ This is mainly for educational purposes and symbolic matrices, for real
397
+ (or complex) matrices use mpmath.qr_solve.
398
+
399
+ See Also
400
+ ========
401
+
402
+ sympy.matrices.dense.DenseMatrix.lower_triangular_solve
403
+ sympy.matrices.dense.DenseMatrix.upper_triangular_solve
404
+ gauss_jordan_solve
405
+ cholesky_solve
406
+ diagonal_solve
407
+ LDLsolve
408
+ LUsolve
409
+ pinv_solve
410
+ QRdecomposition
411
+ cramer_solve
412
+ """
413
+
414
+ dps = _get_intermediate_simp(expand_mul, expand_mul)
415
+ Q, R = M.QRdecomposition()
416
+ y = Q.T * b
417
+
418
+ # back substitution to solve R*x = y:
419
+ # We build up the result "backwards" in the vector 'x' and reverse it
420
+ # only in the end.
421
+ x = []
422
+ n = R.rows
423
+
424
+ for j in range(n - 1, -1, -1):
425
+ tmp = y[j, :]
426
+
427
+ for k in range(j + 1, n):
428
+ tmp -= R[j, k] * x[n - 1 - k]
429
+
430
+ tmp = dps(tmp)
431
+
432
+ x.append(tmp / R[j, j])
433
+
434
+ return M.vstack(*x[::-1])
435
+
436
+
437
+ def _gauss_jordan_solve(M, B, freevar=False):
438
+ """
439
+ Solves ``Ax = B`` using Gauss Jordan elimination.
440
+
441
+ There may be zero, one, or infinite solutions. If one solution
442
+ exists, it will be returned. If infinite solutions exist, it will
443
+ be returned parametrically. If no solutions exist, It will throw
444
+ ValueError.
445
+
446
+ Parameters
447
+ ==========
448
+
449
+ B : Matrix
450
+ The right hand side of the equation to be solved for. Must have
451
+ the same number of rows as matrix A.
452
+
453
+ freevar : boolean, optional
454
+ Flag, when set to `True` will return the indices of the free
455
+ variables in the solutions (column Matrix), for a system that is
456
+ undetermined (e.g. A has more columns than rows), for which
457
+ infinite solutions are possible, in terms of arbitrary
458
+ values of free variables. Default `False`.
459
+
460
+ Returns
461
+ =======
462
+
463
+ x : Matrix
464
+ The matrix that will satisfy ``Ax = B``. Will have as many rows as
465
+ matrix A has columns, and as many columns as matrix B.
466
+
467
+ params : Matrix
468
+ If the system is underdetermined (e.g. A has more columns than
469
+ rows), infinite solutions are possible, in terms of arbitrary
470
+ parameters. These arbitrary parameters are returned as params
471
+ Matrix.
472
+
473
+ free_var_index : List, optional
474
+ If the system is underdetermined (e.g. A has more columns than
475
+ rows), infinite solutions are possible, in terms of arbitrary
476
+ values of free variables. Then the indices of the free variables
477
+ in the solutions (column Matrix) are returned by free_var_index,
478
+ if the flag `freevar` is set to `True`.
479
+
480
+ Examples
481
+ ========
482
+
483
+ >>> from sympy import Matrix
484
+ >>> A = Matrix([[1, 2, 1, 1], [1, 2, 2, -1], [2, 4, 0, 6]])
485
+ >>> B = Matrix([7, 12, 4])
486
+ >>> sol, params = A.gauss_jordan_solve(B)
487
+ >>> sol
488
+ Matrix([
489
+ [-2*tau0 - 3*tau1 + 2],
490
+ [ tau0],
491
+ [ 2*tau1 + 5],
492
+ [ tau1]])
493
+ >>> params
494
+ Matrix([
495
+ [tau0],
496
+ [tau1]])
497
+ >>> taus_zeroes = { tau:0 for tau in params }
498
+ >>> sol_unique = sol.xreplace(taus_zeroes)
499
+ >>> sol_unique
500
+ Matrix([
501
+ [2],
502
+ [0],
503
+ [5],
504
+ [0]])
505
+
506
+
507
+ >>> A = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 10]])
508
+ >>> B = Matrix([3, 6, 9])
509
+ >>> sol, params = A.gauss_jordan_solve(B)
510
+ >>> sol
511
+ Matrix([
512
+ [-1],
513
+ [ 2],
514
+ [ 0]])
515
+ >>> params
516
+ Matrix(0, 1, [])
517
+
518
+ >>> A = Matrix([[2, -7], [-1, 4]])
519
+ >>> B = Matrix([[-21, 3], [12, -2]])
520
+ >>> sol, params = A.gauss_jordan_solve(B)
521
+ >>> sol
522
+ Matrix([
523
+ [0, -2],
524
+ [3, -1]])
525
+ >>> params
526
+ Matrix(0, 2, [])
527
+
528
+
529
+ >>> from sympy import Matrix
530
+ >>> A = Matrix([[1, 2, 1, 1], [1, 2, 2, -1], [2, 4, 0, 6]])
531
+ >>> B = Matrix([7, 12, 4])
532
+ >>> sol, params, freevars = A.gauss_jordan_solve(B, freevar=True)
533
+ >>> sol
534
+ Matrix([
535
+ [-2*tau0 - 3*tau1 + 2],
536
+ [ tau0],
537
+ [ 2*tau1 + 5],
538
+ [ tau1]])
539
+ >>> params
540
+ Matrix([
541
+ [tau0],
542
+ [tau1]])
543
+ >>> freevars
544
+ [1, 3]
545
+
546
+
547
+ See Also
548
+ ========
549
+
550
+ sympy.matrices.dense.DenseMatrix.lower_triangular_solve
551
+ sympy.matrices.dense.DenseMatrix.upper_triangular_solve
552
+ cholesky_solve
553
+ diagonal_solve
554
+ LDLsolve
555
+ LUsolve
556
+ QRsolve
557
+ pinv
558
+
559
+ References
560
+ ==========
561
+
562
+ .. [1] https://en.wikipedia.org/wiki/Gaussian_elimination
563
+
564
+ """
565
+
566
+ from sympy.matrices import Matrix, zeros
567
+
568
+ cls = M.__class__
569
+ aug = M.hstack(M.copy(), B.copy())
570
+ B_cols = B.cols
571
+ row, col = aug[:, :-B_cols].shape
572
+
573
+ # solve by reduced row echelon form
574
+ A, pivots = aug.rref(simplify=True)
575
+ A, v = A[:, :-B_cols], A[:, -B_cols:]
576
+ pivots = list(filter(lambda p: p < col, pivots))
577
+ rank = len(pivots)
578
+
579
+ # Get index of free symbols (free parameters)
580
+ # non-pivots columns are free variables
581
+ free_var_index = [c for c in range(A.cols) if c not in pivots]
582
+
583
+ # Bring to block form
584
+ permutation = Matrix(pivots + free_var_index).T
585
+
586
+ # check for existence of solutions
587
+ # rank of aug Matrix should be equal to rank of coefficient matrix
588
+ if not v[rank:, :].is_zero_matrix:
589
+ raise ValueError("Linear system has no solution")
590
+
591
+ # Free parameters
592
+ # what are current unnumbered free symbol names?
593
+ name = uniquely_named_symbol('tau', [aug],
594
+ compare=lambda i: str(i).rstrip('1234567890'),
595
+ modify=lambda s: '_' + s).name
596
+ gen = numbered_symbols(name)
597
+ tau = Matrix([next(gen) for k in range((col - rank)*B_cols)]).reshape(
598
+ col - rank, B_cols)
599
+
600
+ # Full parametric solution
601
+ V = A[:rank, free_var_index]
602
+ vt = v[:rank, :]
603
+ free_sol = tau.vstack(vt - V * tau, tau)
604
+
605
+ # Undo permutation
606
+ sol = zeros(col, B_cols)
607
+
608
+ for k in range(col):
609
+ sol[permutation[k], :] = free_sol[k,:]
610
+
611
+ sol, tau = cls(sol), cls(tau)
612
+
613
+ if freevar:
614
+ return sol, tau, free_var_index
615
+ else:
616
+ return sol, tau
617
+
618
+
619
+ def _pinv_solve(M, B, arbitrary_matrix=None):
620
+ """Solve ``Ax = B`` using the Moore-Penrose pseudoinverse.
621
+
622
+ There may be zero, one, or infinite solutions. If one solution
623
+ exists, it will be returned. If infinite solutions exist, one will
624
+ be returned based on the value of arbitrary_matrix. If no solutions
625
+ exist, the least-squares solution is returned.
626
+
627
+ Parameters
628
+ ==========
629
+
630
+ B : Matrix
631
+ The right hand side of the equation to be solved for. Must have
632
+ the same number of rows as matrix A.
633
+ arbitrary_matrix : Matrix
634
+ If the system is underdetermined (e.g. A has more columns than
635
+ rows), infinite solutions are possible, in terms of an arbitrary
636
+ matrix. This parameter may be set to a specific matrix to use
637
+ for that purpose; if so, it must be the same shape as x, with as
638
+ many rows as matrix A has columns, and as many columns as matrix
639
+ B. If left as None, an appropriate matrix containing dummy
640
+ symbols in the form of ``wn_m`` will be used, with n and m being
641
+ row and column position of each symbol.
642
+
643
+ Returns
644
+ =======
645
+
646
+ x : Matrix
647
+ The matrix that will satisfy ``Ax = B``. Will have as many rows as
648
+ matrix A has columns, and as many columns as matrix B.
649
+
650
+ Examples
651
+ ========
652
+
653
+ >>> from sympy import Matrix
654
+ >>> A = Matrix([[1, 2, 3], [4, 5, 6]])
655
+ >>> B = Matrix([7, 8])
656
+ >>> A.pinv_solve(B)
657
+ Matrix([
658
+ [ _w0_0/6 - _w1_0/3 + _w2_0/6 - 55/18],
659
+ [-_w0_0/3 + 2*_w1_0/3 - _w2_0/3 + 1/9],
660
+ [ _w0_0/6 - _w1_0/3 + _w2_0/6 + 59/18]])
661
+ >>> A.pinv_solve(B, arbitrary_matrix=Matrix([0, 0, 0]))
662
+ Matrix([
663
+ [-55/18],
664
+ [ 1/9],
665
+ [ 59/18]])
666
+
667
+ See Also
668
+ ========
669
+
670
+ sympy.matrices.dense.DenseMatrix.lower_triangular_solve
671
+ sympy.matrices.dense.DenseMatrix.upper_triangular_solve
672
+ gauss_jordan_solve
673
+ cholesky_solve
674
+ diagonal_solve
675
+ LDLsolve
676
+ LUsolve
677
+ QRsolve
678
+ pinv
679
+
680
+ Notes
681
+ =====
682
+
683
+ This may return either exact solutions or least squares solutions.
684
+ To determine which, check ``A * A.pinv() * B == B``. It will be
685
+ True if exact solutions exist, and False if only a least-squares
686
+ solution exists. Be aware that the left hand side of that equation
687
+ may need to be simplified to correctly compare to the right hand
688
+ side.
689
+
690
+ References
691
+ ==========
692
+
693
+ .. [1] https://en.wikipedia.org/wiki/Moore-Penrose_pseudoinverse#Obtaining_all_solutions_of_a_linear_system
694
+
695
+ """
696
+
697
+ from sympy.matrices import eye
698
+
699
+ A = M
700
+ A_pinv = M.pinv()
701
+
702
+ if arbitrary_matrix is None:
703
+ rows, cols = A.cols, B.cols
704
+ w = symbols('w:{}_:{}'.format(rows, cols), cls=Dummy)
705
+ arbitrary_matrix = M.__class__(cols, rows, w).T
706
+
707
+ return A_pinv.multiply(B) + (eye(A.cols) -
708
+ A_pinv.multiply(A)).multiply(arbitrary_matrix)
709
+
710
+
711
+ def _cramer_solve(M, rhs, det_method="laplace"):
712
+ """Solves system of linear equations using Cramer's rule.
713
+
714
+ This method is relatively inefficient compared to other methods.
715
+ However it only uses a single division, assuming a division-free determinant
716
+ method is provided. This is helpful to minimize the chance of divide-by-zero
717
+ cases in symbolic solutions to linear systems.
718
+
719
+ Parameters
720
+ ==========
721
+ M : Matrix
722
+ The matrix representing the left hand side of the equation.
723
+ rhs : Matrix
724
+ The matrix representing the right hand side of the equation.
725
+ det_method : str or callable
726
+ The method to use to calculate the determinant of the matrix.
727
+ The default is ``'laplace'``. If a callable is passed, it should take a
728
+ single argument, the matrix, and return the determinant of the matrix.
729
+
730
+ Returns
731
+ =======
732
+ x : Matrix
733
+ The matrix that will satisfy ``Ax = B``. Will have as many rows as
734
+ matrix A has columns, and as many columns as matrix B.
735
+
736
+ Examples
737
+ ========
738
+
739
+ >>> from sympy import Matrix
740
+ >>> A = Matrix([[0, -6, 1], [0, -6, -1], [-5, -2, 3]])
741
+ >>> B = Matrix([[-30, -9], [-18, -27], [-26, 46]])
742
+ >>> x = A.cramer_solve(B)
743
+ >>> x
744
+ Matrix([
745
+ [ 0, -5],
746
+ [ 4, 3],
747
+ [-6, 9]])
748
+
749
+ References
750
+ ==========
751
+
752
+ .. [1] https://en.wikipedia.org/wiki/Cramer%27s_rule#Explicit_formulas_for_small_systems
753
+
754
+ """
755
+ from .dense import zeros
756
+
757
+ def entry(i, j):
758
+ return rhs[i, sol] if j == col else M[i, j]
759
+
760
+ if det_method == "bird":
761
+ from .determinant import _det_bird
762
+ det = _det_bird
763
+ elif det_method == "laplace":
764
+ from .determinant import _det_laplace
765
+ det = _det_laplace
766
+ elif isinstance(det_method, str):
767
+ det = lambda matrix: matrix.det(method=det_method)
768
+ else:
769
+ det = det_method
770
+ det_M = det(M)
771
+ x = zeros(*rhs.shape)
772
+ for sol in range(rhs.shape[1]):
773
+ for col in range(rhs.shape[0]):
774
+ x[col, sol] = det(M.__class__(*M.shape, entry)) / det_M
775
+ return M.__class__(x)
776
+
777
+
778
+ def _solve(M, rhs, method='GJ'):
779
+ """Solves linear equation where the unique solution exists.
780
+
781
+ Parameters
782
+ ==========
783
+
784
+ rhs : Matrix
785
+ Vector representing the right hand side of the linear equation.
786
+
787
+ method : string, optional
788
+ If set to ``'GJ'`` or ``'GE'``, the Gauss-Jordan elimination will be
789
+ used, which is implemented in the routine ``gauss_jordan_solve``.
790
+
791
+ If set to ``'LU'``, ``LUsolve`` routine will be used.
792
+
793
+ If set to ``'QR'``, ``QRsolve`` routine will be used.
794
+
795
+ If set to ``'PINV'``, ``pinv_solve`` routine will be used.
796
+
797
+ If set to ``'CRAMER'``, ``cramer_solve`` routine will be used.
798
+
799
+ It also supports the methods available for special linear systems
800
+
801
+ For positive definite systems:
802
+
803
+ If set to ``'CH'``, ``cholesky_solve`` routine will be used.
804
+
805
+ If set to ``'LDL'``, ``LDLsolve`` routine will be used.
806
+
807
+ To use a different method and to compute the solution via the
808
+ inverse, use a method defined in the .inv() docstring.
809
+
810
+ Returns
811
+ =======
812
+
813
+ solutions : Matrix
814
+ Vector representing the solution.
815
+
816
+ Raises
817
+ ======
818
+
819
+ ValueError
820
+ If there is not a unique solution then a ``ValueError`` will be
821
+ raised.
822
+
823
+ If ``M`` is not square, a ``ValueError`` and a different routine
824
+ for solving the system will be suggested.
825
+ """
826
+
827
+ if method in ('GJ', 'GE'):
828
+ try:
829
+ soln, param = M.gauss_jordan_solve(rhs)
830
+
831
+ if param:
832
+ raise NonInvertibleMatrixError("Matrix det == 0; not invertible. "
833
+ "Try ``M.gauss_jordan_solve(rhs)`` to obtain a parametric solution.")
834
+
835
+ except ValueError:
836
+ raise NonInvertibleMatrixError("Matrix det == 0; not invertible.")
837
+
838
+ return soln
839
+
840
+ elif method == 'LU':
841
+ return M.LUsolve(rhs)
842
+ elif method == 'CH':
843
+ return M.cholesky_solve(rhs)
844
+ elif method == 'QR':
845
+ return M.QRsolve(rhs)
846
+ elif method == 'LDL':
847
+ return M.LDLsolve(rhs)
848
+ elif method == 'PINV':
849
+ return M.pinv_solve(rhs)
850
+ elif method == 'CRAMER':
851
+ return M.cramer_solve(rhs)
852
+ else:
853
+ return M.inv(method=method).multiply(rhs)
854
+
855
+
856
+ def _solve_least_squares(M, rhs, method='CH'):
857
+ """Return the least-square fit to the data.
858
+
859
+ Parameters
860
+ ==========
861
+
862
+ rhs : Matrix
863
+ Vector representing the right hand side of the linear equation.
864
+
865
+ method : string or boolean, optional
866
+ If set to ``'CH'``, ``cholesky_solve`` routine will be used.
867
+
868
+ If set to ``'LDL'``, ``LDLsolve`` routine will be used.
869
+
870
+ If set to ``'QR'``, ``QRsolve`` routine will be used.
871
+
872
+ If set to ``'PINV'``, ``pinv_solve`` routine will be used.
873
+
874
+ Otherwise, the conjugate of ``M`` will be used to create a system
875
+ of equations that is passed to ``solve`` along with the hint
876
+ defined by ``method``.
877
+
878
+ Returns
879
+ =======
880
+
881
+ solutions : Matrix
882
+ Vector representing the solution.
883
+
884
+ Examples
885
+ ========
886
+
887
+ >>> from sympy import Matrix, ones
888
+ >>> A = Matrix([1, 2, 3])
889
+ >>> B = Matrix([2, 3, 4])
890
+ >>> S = Matrix(A.row_join(B))
891
+ >>> S
892
+ Matrix([
893
+ [1, 2],
894
+ [2, 3],
895
+ [3, 4]])
896
+
897
+ If each line of S represent coefficients of Ax + By
898
+ and x and y are [2, 3] then S*xy is:
899
+
900
+ >>> r = S*Matrix([2, 3]); r
901
+ Matrix([
902
+ [ 8],
903
+ [13],
904
+ [18]])
905
+
906
+ But let's add 1 to the middle value and then solve for the
907
+ least-squares value of xy:
908
+
909
+ >>> xy = S.solve_least_squares(Matrix([8, 14, 18])); xy
910
+ Matrix([
911
+ [ 5/3],
912
+ [10/3]])
913
+
914
+ The error is given by S*xy - r:
915
+
916
+ >>> S*xy - r
917
+ Matrix([
918
+ [1/3],
919
+ [1/3],
920
+ [1/3]])
921
+ >>> _.norm().n(2)
922
+ 0.58
923
+
924
+ If a different xy is used, the norm will be higher:
925
+
926
+ >>> xy += ones(2, 1)/10
927
+ >>> (S*xy - r).norm().n(2)
928
+ 1.5
929
+
930
+ """
931
+
932
+ if method == 'CH':
933
+ return M.cholesky_solve(rhs)
934
+ elif method == 'QR':
935
+ return M.QRsolve(rhs)
936
+ elif method == 'LDL':
937
+ return M.LDLsolve(rhs)
938
+ elif method == 'PINV':
939
+ return M.pinv_solve(rhs)
940
+ else:
941
+ t = M.H
942
+ return (t * M).solve(t * rhs, method=method)
phi4/lib/python3.10/site-packages/sympy/matrices/sparse.py ADDED
@@ -0,0 +1,473 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections.abc import Callable
2
+
3
+ from sympy.core.containers import Dict
4
+ from sympy.utilities.exceptions import sympy_deprecation_warning
5
+ from sympy.utilities.iterables import is_sequence
6
+ from sympy.utilities.misc import as_int
7
+
8
+ from .matrixbase import MatrixBase
9
+ from .repmatrix import MutableRepMatrix, RepMatrix
10
+
11
+ from .utilities import _iszero
12
+
13
+ from .decompositions import (
14
+ _liupc, _row_structure_symbolic_cholesky, _cholesky_sparse,
15
+ _LDLdecomposition_sparse)
16
+
17
+ from .solvers import (
18
+ _lower_triangular_solve_sparse, _upper_triangular_solve_sparse)
19
+
20
+
21
+ class SparseRepMatrix(RepMatrix):
22
+ """
23
+ A sparse matrix (a matrix with a large number of zero elements).
24
+
25
+ Examples
26
+ ========
27
+
28
+ >>> from sympy import SparseMatrix, ones
29
+ >>> SparseMatrix(2, 2, range(4))
30
+ Matrix([
31
+ [0, 1],
32
+ [2, 3]])
33
+ >>> SparseMatrix(2, 2, {(1, 1): 2})
34
+ Matrix([
35
+ [0, 0],
36
+ [0, 2]])
37
+
38
+ A SparseMatrix can be instantiated from a ragged list of lists:
39
+
40
+ >>> SparseMatrix([[1, 2, 3], [1, 2], [1]])
41
+ Matrix([
42
+ [1, 2, 3],
43
+ [1, 2, 0],
44
+ [1, 0, 0]])
45
+
46
+ For safety, one may include the expected size and then an error
47
+ will be raised if the indices of any element are out of range or
48
+ (for a flat list) if the total number of elements does not match
49
+ the expected shape:
50
+
51
+ >>> SparseMatrix(2, 2, [1, 2])
52
+ Traceback (most recent call last):
53
+ ...
54
+ ValueError: List length (2) != rows*columns (4)
55
+
56
+ Here, an error is not raised because the list is not flat and no
57
+ element is out of range:
58
+
59
+ >>> SparseMatrix(2, 2, [[1, 2]])
60
+ Matrix([
61
+ [1, 2],
62
+ [0, 0]])
63
+
64
+ But adding another element to the first (and only) row will cause
65
+ an error to be raised:
66
+
67
+ >>> SparseMatrix(2, 2, [[1, 2, 3]])
68
+ Traceback (most recent call last):
69
+ ...
70
+ ValueError: The location (0, 2) is out of designated range: (1, 1)
71
+
72
+ To autosize the matrix, pass None for rows:
73
+
74
+ >>> SparseMatrix(None, [[1, 2, 3]])
75
+ Matrix([[1, 2, 3]])
76
+ >>> SparseMatrix(None, {(1, 1): 1, (3, 3): 3})
77
+ Matrix([
78
+ [0, 0, 0, 0],
79
+ [0, 1, 0, 0],
80
+ [0, 0, 0, 0],
81
+ [0, 0, 0, 3]])
82
+
83
+ Values that are themselves a Matrix are automatically expanded:
84
+
85
+ >>> SparseMatrix(4, 4, {(1, 1): ones(2)})
86
+ Matrix([
87
+ [0, 0, 0, 0],
88
+ [0, 1, 1, 0],
89
+ [0, 1, 1, 0],
90
+ [0, 0, 0, 0]])
91
+
92
+ A ValueError is raised if the expanding matrix tries to overwrite
93
+ a different element already present:
94
+
95
+ >>> SparseMatrix(3, 3, {(0, 0): ones(2), (1, 1): 2})
96
+ Traceback (most recent call last):
97
+ ...
98
+ ValueError: collision at (1, 1)
99
+
100
+ See Also
101
+ ========
102
+ DenseMatrix
103
+ MutableSparseMatrix
104
+ ImmutableSparseMatrix
105
+ """
106
+
107
+ @classmethod
108
+ def _handle_creation_inputs(cls, *args, **kwargs):
109
+ if len(args) == 1 and isinstance(args[0], MatrixBase):
110
+ rows = args[0].rows
111
+ cols = args[0].cols
112
+ smat = args[0].todok()
113
+ return rows, cols, smat
114
+
115
+ smat = {}
116
+ # autosizing
117
+ if len(args) == 2 and args[0] is None:
118
+ args = [None, None, args[1]]
119
+
120
+ if len(args) == 3:
121
+ r, c = args[:2]
122
+ if r is c is None:
123
+ rows = cols = None
124
+ elif None in (r, c):
125
+ raise ValueError(
126
+ 'Pass rows=None and no cols for autosizing.')
127
+ else:
128
+ rows, cols = as_int(args[0]), as_int(args[1])
129
+
130
+ if isinstance(args[2], Callable):
131
+ op = args[2]
132
+
133
+ if None in (rows, cols):
134
+ raise ValueError(
135
+ "{} and {} must be integers for this "
136
+ "specification.".format(rows, cols))
137
+
138
+ row_indices = [cls._sympify(i) for i in range(rows)]
139
+ col_indices = [cls._sympify(j) for j in range(cols)]
140
+
141
+ for i in row_indices:
142
+ for j in col_indices:
143
+ value = cls._sympify(op(i, j))
144
+ if value != cls.zero:
145
+ smat[i, j] = value
146
+
147
+ return rows, cols, smat
148
+
149
+ elif isinstance(args[2], (dict, Dict)):
150
+ def update(i, j, v):
151
+ # update smat and make sure there are no collisions
152
+ if v:
153
+ if (i, j) in smat and v != smat[i, j]:
154
+ raise ValueError(
155
+ "There is a collision at {} for {} and {}."
156
+ .format((i, j), v, smat[i, j])
157
+ )
158
+ smat[i, j] = v
159
+
160
+ # manual copy, copy.deepcopy() doesn't work
161
+ for (r, c), v in args[2].items():
162
+ if isinstance(v, MatrixBase):
163
+ for (i, j), vv in v.todok().items():
164
+ update(r + i, c + j, vv)
165
+ elif isinstance(v, (list, tuple)):
166
+ _, _, smat = cls._handle_creation_inputs(v, **kwargs)
167
+ for i, j in smat:
168
+ update(r + i, c + j, smat[i, j])
169
+ else:
170
+ v = cls._sympify(v)
171
+ update(r, c, cls._sympify(v))
172
+
173
+ elif is_sequence(args[2]):
174
+ flat = not any(is_sequence(i) for i in args[2])
175
+ if not flat:
176
+ _, _, smat = \
177
+ cls._handle_creation_inputs(args[2], **kwargs)
178
+ else:
179
+ flat_list = args[2]
180
+ if len(flat_list) != rows * cols:
181
+ raise ValueError(
182
+ "The length of the flat list ({}) does not "
183
+ "match the specified size ({} * {})."
184
+ .format(len(flat_list), rows, cols)
185
+ )
186
+
187
+ for i in range(rows):
188
+ for j in range(cols):
189
+ value = flat_list[i*cols + j]
190
+ value = cls._sympify(value)
191
+ if value != cls.zero:
192
+ smat[i, j] = value
193
+
194
+ if rows is None: # autosizing
195
+ keys = smat.keys()
196
+ rows = max(r for r, _ in keys) + 1 if keys else 0
197
+ cols = max(c for _, c in keys) + 1 if keys else 0
198
+
199
+ else:
200
+ for i, j in smat.keys():
201
+ if i and i >= rows or j and j >= cols:
202
+ raise ValueError(
203
+ "The location {} is out of the designated range"
204
+ "[{}, {}]x[{}, {}]"
205
+ .format((i, j), 0, rows - 1, 0, cols - 1)
206
+ )
207
+
208
+ return rows, cols, smat
209
+
210
+ elif len(args) == 1 and isinstance(args[0], (list, tuple)):
211
+ # list of values or lists
212
+ v = args[0]
213
+ c = 0
214
+ for i, row in enumerate(v):
215
+ if not isinstance(row, (list, tuple)):
216
+ row = [row]
217
+ for j, vv in enumerate(row):
218
+ if vv != cls.zero:
219
+ smat[i, j] = cls._sympify(vv)
220
+ c = max(c, len(row))
221
+ rows = len(v) if c else 0
222
+ cols = c
223
+ return rows, cols, smat
224
+
225
+ else:
226
+ # handle full matrix forms with _handle_creation_inputs
227
+ rows, cols, mat = super()._handle_creation_inputs(*args)
228
+ for i in range(rows):
229
+ for j in range(cols):
230
+ value = mat[cols*i + j]
231
+ if value != cls.zero:
232
+ smat[i, j] = value
233
+
234
+ return rows, cols, smat
235
+
236
+ @property
237
+ def _smat(self):
238
+
239
+ sympy_deprecation_warning(
240
+ """
241
+ The private _smat attribute of SparseMatrix is deprecated. Use the
242
+ .todok() method instead.
243
+ """,
244
+ deprecated_since_version="1.9",
245
+ active_deprecations_target="deprecated-private-matrix-attributes"
246
+ )
247
+
248
+ return self.todok()
249
+
250
+ def _eval_inverse(self, **kwargs):
251
+ return self.inv(method=kwargs.get('method', 'LDL'),
252
+ iszerofunc=kwargs.get('iszerofunc', _iszero),
253
+ try_block_diag=kwargs.get('try_block_diag', False))
254
+
255
+ def applyfunc(self, f):
256
+ """Apply a function to each element of the matrix.
257
+
258
+ Examples
259
+ ========
260
+
261
+ >>> from sympy import SparseMatrix
262
+ >>> m = SparseMatrix(2, 2, lambda i, j: i*2+j)
263
+ >>> m
264
+ Matrix([
265
+ [0, 1],
266
+ [2, 3]])
267
+ >>> m.applyfunc(lambda i: 2*i)
268
+ Matrix([
269
+ [0, 2],
270
+ [4, 6]])
271
+
272
+ """
273
+ if not callable(f):
274
+ raise TypeError("`f` must be callable.")
275
+
276
+ # XXX: This only applies the function to the nonzero elements of the
277
+ # matrix so is inconsistent with DenseMatrix.applyfunc e.g.
278
+ # zeros(2, 2).applyfunc(lambda x: x + 1)
279
+ dok = {}
280
+ for k, v in self.todok().items():
281
+ fv = f(v)
282
+ if fv != 0:
283
+ dok[k] = fv
284
+
285
+ return self._new(self.rows, self.cols, dok)
286
+
287
+ def as_immutable(self):
288
+ """Returns an Immutable version of this Matrix."""
289
+ from .immutable import ImmutableSparseMatrix
290
+ return ImmutableSparseMatrix(self)
291
+
292
+ def as_mutable(self):
293
+ """Returns a mutable version of this matrix.
294
+
295
+ Examples
296
+ ========
297
+
298
+ >>> from sympy import ImmutableMatrix
299
+ >>> X = ImmutableMatrix([[1, 2], [3, 4]])
300
+ >>> Y = X.as_mutable()
301
+ >>> Y[1, 1] = 5 # Can set values in Y
302
+ >>> Y
303
+ Matrix([
304
+ [1, 2],
305
+ [3, 5]])
306
+ """
307
+ return MutableSparseMatrix(self)
308
+
309
+ def col_list(self):
310
+ """Returns a column-sorted list of non-zero elements of the matrix.
311
+
312
+ Examples
313
+ ========
314
+
315
+ >>> from sympy import SparseMatrix
316
+ >>> a=SparseMatrix(((1, 2), (3, 4)))
317
+ >>> a
318
+ Matrix([
319
+ [1, 2],
320
+ [3, 4]])
321
+ >>> a.CL
322
+ [(0, 0, 1), (1, 0, 3), (0, 1, 2), (1, 1, 4)]
323
+
324
+ See Also
325
+ ========
326
+
327
+ sympy.matrices.sparse.SparseMatrix.row_list
328
+ """
329
+ return [tuple(k + (self[k],)) for k in sorted(self.todok().keys(), key=lambda k: list(reversed(k)))]
330
+
331
+ def nnz(self):
332
+ """Returns the number of non-zero elements in Matrix."""
333
+ return len(self.todok())
334
+
335
+ def row_list(self):
336
+ """Returns a row-sorted list of non-zero elements of the matrix.
337
+
338
+ Examples
339
+ ========
340
+
341
+ >>> from sympy import SparseMatrix
342
+ >>> a = SparseMatrix(((1, 2), (3, 4)))
343
+ >>> a
344
+ Matrix([
345
+ [1, 2],
346
+ [3, 4]])
347
+ >>> a.RL
348
+ [(0, 0, 1), (0, 1, 2), (1, 0, 3), (1, 1, 4)]
349
+
350
+ See Also
351
+ ========
352
+
353
+ sympy.matrices.sparse.SparseMatrix.col_list
354
+ """
355
+ return [tuple(k + (self[k],)) for k in
356
+ sorted(self.todok().keys(), key=list)]
357
+
358
+ def scalar_multiply(self, scalar):
359
+ "Scalar element-wise multiplication"
360
+ return scalar * self
361
+
362
+ def solve_least_squares(self, rhs, method='LDL'):
363
+ """Return the least-square fit to the data.
364
+
365
+ By default the cholesky_solve routine is used (method='CH'); other
366
+ methods of matrix inversion can be used. To find out which are
367
+ available, see the docstring of the .inv() method.
368
+
369
+ Examples
370
+ ========
371
+
372
+ >>> from sympy import SparseMatrix, Matrix, ones
373
+ >>> A = Matrix([1, 2, 3])
374
+ >>> B = Matrix([2, 3, 4])
375
+ >>> S = SparseMatrix(A.row_join(B))
376
+ >>> S
377
+ Matrix([
378
+ [1, 2],
379
+ [2, 3],
380
+ [3, 4]])
381
+
382
+ If each line of S represent coefficients of Ax + By
383
+ and x and y are [2, 3] then S*xy is:
384
+
385
+ >>> r = S*Matrix([2, 3]); r
386
+ Matrix([
387
+ [ 8],
388
+ [13],
389
+ [18]])
390
+
391
+ But let's add 1 to the middle value and then solve for the
392
+ least-squares value of xy:
393
+
394
+ >>> xy = S.solve_least_squares(Matrix([8, 14, 18])); xy
395
+ Matrix([
396
+ [ 5/3],
397
+ [10/3]])
398
+
399
+ The error is given by S*xy - r:
400
+
401
+ >>> S*xy - r
402
+ Matrix([
403
+ [1/3],
404
+ [1/3],
405
+ [1/3]])
406
+ >>> _.norm().n(2)
407
+ 0.58
408
+
409
+ If a different xy is used, the norm will be higher:
410
+
411
+ >>> xy += ones(2, 1)/10
412
+ >>> (S*xy - r).norm().n(2)
413
+ 1.5
414
+
415
+ """
416
+ t = self.T
417
+ return (t*self).inv(method=method)*t*rhs
418
+
419
+ def solve(self, rhs, method='LDL'):
420
+ """Return solution to self*soln = rhs using given inversion method.
421
+
422
+ For a list of possible inversion methods, see the .inv() docstring.
423
+ """
424
+ if not self.is_square:
425
+ if self.rows < self.cols:
426
+ raise ValueError('Under-determined system.')
427
+ elif self.rows > self.cols:
428
+ raise ValueError('For over-determined system, M, having '
429
+ 'more rows than columns, try M.solve_least_squares(rhs).')
430
+ else:
431
+ return self.inv(method=method).multiply(rhs)
432
+
433
+ RL = property(row_list, None, None, "Alternate faster representation")
434
+ CL = property(col_list, None, None, "Alternate faster representation")
435
+
436
+ def liupc(self):
437
+ return _liupc(self)
438
+
439
+ def row_structure_symbolic_cholesky(self):
440
+ return _row_structure_symbolic_cholesky(self)
441
+
442
+ def cholesky(self, hermitian=True):
443
+ return _cholesky_sparse(self, hermitian=hermitian)
444
+
445
+ def LDLdecomposition(self, hermitian=True):
446
+ return _LDLdecomposition_sparse(self, hermitian=hermitian)
447
+
448
+ def lower_triangular_solve(self, rhs):
449
+ return _lower_triangular_solve_sparse(self, rhs)
450
+
451
+ def upper_triangular_solve(self, rhs):
452
+ return _upper_triangular_solve_sparse(self, rhs)
453
+
454
+ liupc.__doc__ = _liupc.__doc__
455
+ row_structure_symbolic_cholesky.__doc__ = _row_structure_symbolic_cholesky.__doc__
456
+ cholesky.__doc__ = _cholesky_sparse.__doc__
457
+ LDLdecomposition.__doc__ = _LDLdecomposition_sparse.__doc__
458
+ lower_triangular_solve.__doc__ = lower_triangular_solve.__doc__
459
+ upper_triangular_solve.__doc__ = upper_triangular_solve.__doc__
460
+
461
+
462
+ class MutableSparseMatrix(SparseRepMatrix, MutableRepMatrix):
463
+
464
+ @classmethod
465
+ def _new(cls, *args, **kwargs):
466
+ rows, cols, smat = cls._handle_creation_inputs(*args, **kwargs)
467
+
468
+ rep = cls._smat_to_DomainMatrix(rows, cols, smat)
469
+
470
+ return cls._fromrep(rep)
471
+
472
+
473
+ SparseMatrix = MutableSparseMatrix
phi4/lib/python3.10/site-packages/sympy/matrices/subspaces.py ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .utilities import _iszero
2
+
3
+
4
+ def _columnspace(M, simplify=False):
5
+ """Returns a list of vectors (Matrix objects) that span columnspace of ``M``
6
+
7
+ Examples
8
+ ========
9
+
10
+ >>> from sympy import Matrix
11
+ >>> M = Matrix(3, 3, [1, 3, 0, -2, -6, 0, 3, 9, 6])
12
+ >>> M
13
+ Matrix([
14
+ [ 1, 3, 0],
15
+ [-2, -6, 0],
16
+ [ 3, 9, 6]])
17
+ >>> M.columnspace()
18
+ [Matrix([
19
+ [ 1],
20
+ [-2],
21
+ [ 3]]), Matrix([
22
+ [0],
23
+ [0],
24
+ [6]])]
25
+
26
+ See Also
27
+ ========
28
+
29
+ nullspace
30
+ rowspace
31
+ """
32
+
33
+ reduced, pivots = M.echelon_form(simplify=simplify, with_pivots=True)
34
+
35
+ return [M.col(i) for i in pivots]
36
+
37
+
38
+ def _nullspace(M, simplify=False, iszerofunc=_iszero):
39
+ """Returns list of vectors (Matrix objects) that span nullspace of ``M``
40
+
41
+ Examples
42
+ ========
43
+
44
+ >>> from sympy import Matrix
45
+ >>> M = Matrix(3, 3, [1, 3, 0, -2, -6, 0, 3, 9, 6])
46
+ >>> M
47
+ Matrix([
48
+ [ 1, 3, 0],
49
+ [-2, -6, 0],
50
+ [ 3, 9, 6]])
51
+ >>> M.nullspace()
52
+ [Matrix([
53
+ [-3],
54
+ [ 1],
55
+ [ 0]])]
56
+
57
+ See Also
58
+ ========
59
+
60
+ columnspace
61
+ rowspace
62
+ """
63
+
64
+ reduced, pivots = M.rref(iszerofunc=iszerofunc, simplify=simplify)
65
+
66
+ free_vars = [i for i in range(M.cols) if i not in pivots]
67
+ basis = []
68
+
69
+ for free_var in free_vars:
70
+ # for each free variable, we will set it to 1 and all others
71
+ # to 0. Then, we will use back substitution to solve the system
72
+ vec = [M.zero] * M.cols
73
+ vec[free_var] = M.one
74
+
75
+ for piv_row, piv_col in enumerate(pivots):
76
+ vec[piv_col] -= reduced[piv_row, free_var]
77
+
78
+ basis.append(vec)
79
+
80
+ return [M._new(M.cols, 1, b) for b in basis]
81
+
82
+
83
+ def _rowspace(M, simplify=False):
84
+ """Returns a list of vectors that span the row space of ``M``.
85
+
86
+ Examples
87
+ ========
88
+
89
+ >>> from sympy import Matrix
90
+ >>> M = Matrix(3, 3, [1, 3, 0, -2, -6, 0, 3, 9, 6])
91
+ >>> M
92
+ Matrix([
93
+ [ 1, 3, 0],
94
+ [-2, -6, 0],
95
+ [ 3, 9, 6]])
96
+ >>> M.rowspace()
97
+ [Matrix([[1, 3, 0]]), Matrix([[0, 0, 6]])]
98
+ """
99
+
100
+ reduced, pivots = M.echelon_form(simplify=simplify, with_pivots=True)
101
+
102
+ return [reduced.row(i) for i in range(len(pivots))]
103
+
104
+
105
+ def _orthogonalize(cls, *vecs, normalize=False, rankcheck=False):
106
+ """Apply the Gram-Schmidt orthogonalization procedure
107
+ to vectors supplied in ``vecs``.
108
+
109
+ Parameters
110
+ ==========
111
+
112
+ vecs
113
+ vectors to be made orthogonal
114
+
115
+ normalize : bool
116
+ If ``True``, return an orthonormal basis.
117
+
118
+ rankcheck : bool
119
+ If ``True``, the computation does not stop when encountering
120
+ linearly dependent vectors.
121
+
122
+ If ``False``, it will raise ``ValueError`` when any zero
123
+ or linearly dependent vectors are found.
124
+
125
+ Returns
126
+ =======
127
+
128
+ list
129
+ List of orthogonal (or orthonormal) basis vectors.
130
+
131
+ Examples
132
+ ========
133
+
134
+ >>> from sympy import I, Matrix
135
+ >>> v = [Matrix([1, I]), Matrix([1, -I])]
136
+ >>> Matrix.orthogonalize(*v)
137
+ [Matrix([
138
+ [1],
139
+ [I]]), Matrix([
140
+ [ 1],
141
+ [-I]])]
142
+
143
+ See Also
144
+ ========
145
+
146
+ MatrixBase.QRdecomposition
147
+
148
+ References
149
+ ==========
150
+
151
+ .. [1] https://en.wikipedia.org/wiki/Gram%E2%80%93Schmidt_process
152
+ """
153
+ from .decompositions import _QRdecomposition_optional
154
+
155
+ if not vecs:
156
+ return []
157
+
158
+ all_row_vecs = (vecs[0].rows == 1)
159
+
160
+ vecs = [x.vec() for x in vecs]
161
+ M = cls.hstack(*vecs)
162
+ Q, R = _QRdecomposition_optional(M, normalize=normalize)
163
+
164
+ if rankcheck and Q.cols < len(vecs):
165
+ raise ValueError("GramSchmidt: vector set not linearly independent")
166
+
167
+ ret = []
168
+ for i in range(Q.cols):
169
+ if all_row_vecs:
170
+ col = cls(Q[:, i].T)
171
+ else:
172
+ col = cls(Q[:, i])
173
+ ret.append(col)
174
+ return ret
phi4/lib/python3.10/site-packages/sympy/matrices/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (170 Bytes). View file
 
phi4/lib/python3.10/site-packages/sympy/matrices/tests/__pycache__/test_commonmatrix.cpython-310.pyc ADDED
Binary file (44.7 kB). View file
 
phi4/lib/python3.10/site-packages/sympy/matrices/tests/__pycache__/test_decompositions.cpython-310.pyc ADDED
Binary file (13.4 kB). View file
 
phi4/lib/python3.10/site-packages/sympy/matrices/tests/__pycache__/test_determinant.cpython-310.pyc ADDED
Binary file (10.9 kB). View file