Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- env-llmeval/lib/python3.10/site-packages/sympy/__pycache__/__init__.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/__pycache__/abc.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/__pycache__/conftest.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/__pycache__/galgebra.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/__pycache__/release.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/__pycache__/this.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/core/_print_helpers.py +65 -0
- env-llmeval/lib/python3.10/site-packages/sympy/core/add.py +1287 -0
- env-llmeval/lib/python3.10/site-packages/sympy/core/alphabets.py +4 -0
- env-llmeval/lib/python3.10/site-packages/sympy/core/assumptions_generated.py +1615 -0
- env-llmeval/lib/python3.10/site-packages/sympy/core/decorators.py +238 -0
- env-llmeval/lib/python3.10/site-packages/sympy/core/expr.py +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/core/function.py +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/core/mod.py +238 -0
- env-llmeval/lib/python3.10/site-packages/sympy/core/multidimensional.py +131 -0
- env-llmeval/lib/python3.10/site-packages/sympy/core/power.py +2004 -0
- env-llmeval/lib/python3.10/site-packages/sympy/core/rules.py +66 -0
- env-llmeval/lib/python3.10/site-packages/sympy/core/symbol.py +945 -0
- env-llmeval/lib/python3.10/site-packages/sympy/diffgeom/__init__.py +19 -0
- env-llmeval/lib/python3.10/site-packages/sympy/diffgeom/diffgeom.py +2273 -0
- env-llmeval/lib/python3.10/site-packages/sympy/diffgeom/tests/test_function_diffgeom_book.py +145 -0
- env-llmeval/lib/python3.10/site-packages/sympy/diffgeom/tests/test_hyperbolic_space.py +91 -0
- env-llmeval/lib/python3.10/site-packages/sympy/tensor/array/__pycache__/__init__.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/tensor/array/__pycache__/array_comprehension.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/tensor/array/__pycache__/array_derivatives.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/tensor/array/__pycache__/arrayop.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/tensor/array/__pycache__/dense_ndim_array.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/tensor/array/__pycache__/mutable_ndim_array.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/tensor/array/__pycache__/ndim_array.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/tensor/array/__pycache__/sparse_ndim_array.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/tensor/array/expressions/__pycache__/__init__.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/tensor/array/expressions/__pycache__/array_expressions.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/tensor/array/expressions/__pycache__/arrayexpr_derivatives.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/tensor/array/expressions/__pycache__/conv_array_to_indexed.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/tensor/array/expressions/__pycache__/conv_array_to_matrix.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/tensor/array/expressions/__pycache__/conv_indexed_to_array.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/tensor/array/expressions/__pycache__/conv_matrix_to_array.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/tensor/array/expressions/__pycache__/from_array_to_indexed.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/tensor/array/expressions/__pycache__/from_array_to_matrix.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/tensor/array/expressions/__pycache__/from_indexed_to_array.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/tensor/array/expressions/__pycache__/from_matrix_to_array.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/tensor/array/expressions/__pycache__/utils.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/tensor/array/expressions/array_expressions.py +1967 -0
- env-llmeval/lib/python3.10/site-packages/sympy/tensor/array/expressions/conv_array_to_indexed.py +12 -0
- env-llmeval/lib/python3.10/site-packages/sympy/tensor/array/expressions/conv_array_to_matrix.py +6 -0
- env-llmeval/lib/python3.10/site-packages/sympy/tensor/array/expressions/conv_indexed_to_array.py +4 -0
- env-llmeval/lib/python3.10/site-packages/sympy/tensor/array/expressions/conv_matrix_to_array.py +4 -0
- env-llmeval/lib/python3.10/site-packages/sympy/tensor/array/expressions/from_array_to_indexed.py +84 -0
- env-llmeval/lib/python3.10/site-packages/sympy/tensor/array/expressions/from_array_to_matrix.py +1003 -0
- env-llmeval/lib/python3.10/site-packages/sympy/tensor/array/expressions/from_matrix_to_array.py +87 -0
env-llmeval/lib/python3.10/site-packages/sympy/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (28.1 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/__pycache__/abc.cpython-310.pyc
ADDED
Binary file (3.53 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/__pycache__/conftest.cpython-310.pyc
ADDED
Binary file (2.55 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/__pycache__/galgebra.cpython-310.pyc
ADDED
Binary file (282 Bytes). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/__pycache__/release.cpython-310.pyc
ADDED
Binary file (189 Bytes). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/__pycache__/this.cpython-310.pyc
ADDED
Binary file (730 Bytes). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/core/_print_helpers.py
ADDED
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Base class to provide str and repr hooks that `init_printing` can overwrite.
|
3 |
+
|
4 |
+
This is exposed publicly in the `printing.defaults` module,
|
5 |
+
but cannot be defined there without causing circular imports.
|
6 |
+
"""
|
7 |
+
|
8 |
+
class Printable:
|
9 |
+
"""
|
10 |
+
The default implementation of printing for SymPy classes.
|
11 |
+
|
12 |
+
This implements a hack that allows us to print elements of built-in
|
13 |
+
Python containers in a readable way. Natively Python uses ``repr()``
|
14 |
+
even if ``str()`` was explicitly requested. Mix in this trait into
|
15 |
+
a class to get proper default printing.
|
16 |
+
|
17 |
+
This also adds support for LaTeX printing in jupyter notebooks.
|
18 |
+
"""
|
19 |
+
|
20 |
+
# Since this class is used as a mixin we set empty slots. That means that
|
21 |
+
# instances of any subclasses that use slots will not need to have a
|
22 |
+
# __dict__.
|
23 |
+
__slots__ = ()
|
24 |
+
|
25 |
+
# Note, we always use the default ordering (lex) in __str__ and __repr__,
|
26 |
+
# regardless of the global setting. See issue 5487.
|
27 |
+
def __str__(self):
|
28 |
+
from sympy.printing.str import sstr
|
29 |
+
return sstr(self, order=None)
|
30 |
+
|
31 |
+
__repr__ = __str__
|
32 |
+
|
33 |
+
def _repr_disabled(self):
|
34 |
+
"""
|
35 |
+
No-op repr function used to disable jupyter display hooks.
|
36 |
+
|
37 |
+
When :func:`sympy.init_printing` is used to disable certain display
|
38 |
+
formats, this function is copied into the appropriate ``_repr_*_``
|
39 |
+
attributes.
|
40 |
+
|
41 |
+
While we could just set the attributes to `None``, doing it this way
|
42 |
+
allows derived classes to call `super()`.
|
43 |
+
"""
|
44 |
+
return None
|
45 |
+
|
46 |
+
# We don't implement _repr_png_ here because it would add a large amount of
|
47 |
+
# data to any notebook containing SymPy expressions, without adding
|
48 |
+
# anything useful to the notebook. It can still enabled manually, e.g.,
|
49 |
+
# for the qtconsole, with init_printing().
|
50 |
+
_repr_png_ = _repr_disabled
|
51 |
+
|
52 |
+
_repr_svg_ = _repr_disabled
|
53 |
+
|
54 |
+
def _repr_latex_(self):
|
55 |
+
"""
|
56 |
+
IPython/Jupyter LaTeX printing
|
57 |
+
|
58 |
+
To change the behavior of this (e.g., pass in some settings to LaTeX),
|
59 |
+
use init_printing(). init_printing() will also enable LaTeX printing
|
60 |
+
for built in numeric types like ints and container types that contain
|
61 |
+
SymPy objects, like lists and dictionaries of expressions.
|
62 |
+
"""
|
63 |
+
from sympy.printing.latex import latex
|
64 |
+
s = latex(self, mode='plain')
|
65 |
+
return "$\\displaystyle %s$" % s
|
env-llmeval/lib/python3.10/site-packages/sympy/core/add.py
ADDED
@@ -0,0 +1,1287 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import Tuple as tTuple
|
2 |
+
from collections import defaultdict
|
3 |
+
from functools import cmp_to_key, reduce
|
4 |
+
from operator import attrgetter
|
5 |
+
from .basic import Basic
|
6 |
+
from .parameters import global_parameters
|
7 |
+
from .logic import _fuzzy_group, fuzzy_or, fuzzy_not
|
8 |
+
from .singleton import S
|
9 |
+
from .operations import AssocOp, AssocOpDispatcher
|
10 |
+
from .cache import cacheit
|
11 |
+
from .numbers import ilcm, igcd, equal_valued
|
12 |
+
from .expr import Expr
|
13 |
+
from .kind import UndefinedKind
|
14 |
+
from sympy.utilities.iterables import is_sequence, sift
|
15 |
+
|
16 |
+
# Key for sorting commutative args in canonical order
|
17 |
+
_args_sortkey = cmp_to_key(Basic.compare)
|
18 |
+
|
19 |
+
|
20 |
+
def _could_extract_minus_sign(expr):
|
21 |
+
# assume expr is Add-like
|
22 |
+
# We choose the one with less arguments with minus signs
|
23 |
+
negative_args = sum(1 for i in expr.args
|
24 |
+
if i.could_extract_minus_sign())
|
25 |
+
positive_args = len(expr.args) - negative_args
|
26 |
+
if positive_args > negative_args:
|
27 |
+
return False
|
28 |
+
elif positive_args < negative_args:
|
29 |
+
return True
|
30 |
+
# choose based on .sort_key() to prefer
|
31 |
+
# x - 1 instead of 1 - x and
|
32 |
+
# 3 - sqrt(2) instead of -3 + sqrt(2)
|
33 |
+
return bool(expr.sort_key() < (-expr).sort_key())
|
34 |
+
|
35 |
+
|
36 |
+
def _addsort(args):
|
37 |
+
# in-place sorting of args
|
38 |
+
args.sort(key=_args_sortkey)
|
39 |
+
|
40 |
+
|
41 |
+
def _unevaluated_Add(*args):
|
42 |
+
"""Return a well-formed unevaluated Add: Numbers are collected and
|
43 |
+
put in slot 0 and args are sorted. Use this when args have changed
|
44 |
+
but you still want to return an unevaluated Add.
|
45 |
+
|
46 |
+
Examples
|
47 |
+
========
|
48 |
+
|
49 |
+
>>> from sympy.core.add import _unevaluated_Add as uAdd
|
50 |
+
>>> from sympy import S, Add
|
51 |
+
>>> from sympy.abc import x, y
|
52 |
+
>>> a = uAdd(*[S(1.0), x, S(2)])
|
53 |
+
>>> a.args[0]
|
54 |
+
3.00000000000000
|
55 |
+
>>> a.args[1]
|
56 |
+
x
|
57 |
+
|
58 |
+
Beyond the Number being in slot 0, there is no other assurance of
|
59 |
+
order for the arguments since they are hash sorted. So, for testing
|
60 |
+
purposes, output produced by this in some other function can only
|
61 |
+
be tested against the output of this function or as one of several
|
62 |
+
options:
|
63 |
+
|
64 |
+
>>> opts = (Add(x, y, evaluate=False), Add(y, x, evaluate=False))
|
65 |
+
>>> a = uAdd(x, y)
|
66 |
+
>>> assert a in opts and a == uAdd(x, y)
|
67 |
+
>>> uAdd(x + 1, x + 2)
|
68 |
+
x + x + 3
|
69 |
+
"""
|
70 |
+
args = list(args)
|
71 |
+
newargs = []
|
72 |
+
co = S.Zero
|
73 |
+
while args:
|
74 |
+
a = args.pop()
|
75 |
+
if a.is_Add:
|
76 |
+
# this will keep nesting from building up
|
77 |
+
# so that x + (x + 1) -> x + x + 1 (3 args)
|
78 |
+
args.extend(a.args)
|
79 |
+
elif a.is_Number:
|
80 |
+
co += a
|
81 |
+
else:
|
82 |
+
newargs.append(a)
|
83 |
+
_addsort(newargs)
|
84 |
+
if co:
|
85 |
+
newargs.insert(0, co)
|
86 |
+
return Add._from_args(newargs)
|
87 |
+
|
88 |
+
|
89 |
+
class Add(Expr, AssocOp):
|
90 |
+
"""
|
91 |
+
Expression representing addition operation for algebraic group.
|
92 |
+
|
93 |
+
.. deprecated:: 1.7
|
94 |
+
|
95 |
+
Using arguments that aren't subclasses of :class:`~.Expr` in core
|
96 |
+
operators (:class:`~.Mul`, :class:`~.Add`, and :class:`~.Pow`) is
|
97 |
+
deprecated. See :ref:`non-expr-args-deprecated` for details.
|
98 |
+
|
99 |
+
Every argument of ``Add()`` must be ``Expr``. Infix operator ``+``
|
100 |
+
on most scalar objects in SymPy calls this class.
|
101 |
+
|
102 |
+
Another use of ``Add()`` is to represent the structure of abstract
|
103 |
+
addition so that its arguments can be substituted to return different
|
104 |
+
class. Refer to examples section for this.
|
105 |
+
|
106 |
+
``Add()`` evaluates the argument unless ``evaluate=False`` is passed.
|
107 |
+
The evaluation logic includes:
|
108 |
+
|
109 |
+
1. Flattening
|
110 |
+
``Add(x, Add(y, z))`` -> ``Add(x, y, z)``
|
111 |
+
|
112 |
+
2. Identity removing
|
113 |
+
``Add(x, 0, y)`` -> ``Add(x, y)``
|
114 |
+
|
115 |
+
3. Coefficient collecting by ``.as_coeff_Mul()``
|
116 |
+
``Add(x, 2*x)`` -> ``Mul(3, x)``
|
117 |
+
|
118 |
+
4. Term sorting
|
119 |
+
``Add(y, x, 2)`` -> ``Add(2, x, y)``
|
120 |
+
|
121 |
+
If no argument is passed, identity element 0 is returned. If single
|
122 |
+
element is passed, that element is returned.
|
123 |
+
|
124 |
+
Note that ``Add(*args)`` is more efficient than ``sum(args)`` because
|
125 |
+
it flattens the arguments. ``sum(a, b, c, ...)`` recursively adds the
|
126 |
+
arguments as ``a + (b + (c + ...))``, which has quadratic complexity.
|
127 |
+
On the other hand, ``Add(a, b, c, d)`` does not assume nested
|
128 |
+
structure, making the complexity linear.
|
129 |
+
|
130 |
+
Since addition is group operation, every argument should have the
|
131 |
+
same :obj:`sympy.core.kind.Kind()`.
|
132 |
+
|
133 |
+
Examples
|
134 |
+
========
|
135 |
+
|
136 |
+
>>> from sympy import Add, I
|
137 |
+
>>> from sympy.abc import x, y
|
138 |
+
>>> Add(x, 1)
|
139 |
+
x + 1
|
140 |
+
>>> Add(x, x)
|
141 |
+
2*x
|
142 |
+
>>> 2*x**2 + 3*x + I*y + 2*y + 2*x/5 + 1.0*y + 1
|
143 |
+
2*x**2 + 17*x/5 + 3.0*y + I*y + 1
|
144 |
+
|
145 |
+
If ``evaluate=False`` is passed, result is not evaluated.
|
146 |
+
|
147 |
+
>>> Add(1, 2, evaluate=False)
|
148 |
+
1 + 2
|
149 |
+
>>> Add(x, x, evaluate=False)
|
150 |
+
x + x
|
151 |
+
|
152 |
+
``Add()`` also represents the general structure of addition operation.
|
153 |
+
|
154 |
+
>>> from sympy import MatrixSymbol
|
155 |
+
>>> A,B = MatrixSymbol('A', 2,2), MatrixSymbol('B', 2,2)
|
156 |
+
>>> expr = Add(x,y).subs({x:A, y:B})
|
157 |
+
>>> expr
|
158 |
+
A + B
|
159 |
+
>>> type(expr)
|
160 |
+
<class 'sympy.matrices.expressions.matadd.MatAdd'>
|
161 |
+
|
162 |
+
Note that the printers do not display in args order.
|
163 |
+
|
164 |
+
>>> Add(x, 1)
|
165 |
+
x + 1
|
166 |
+
>>> Add(x, 1).args
|
167 |
+
(1, x)
|
168 |
+
|
169 |
+
See Also
|
170 |
+
========
|
171 |
+
|
172 |
+
MatAdd
|
173 |
+
|
174 |
+
"""
|
175 |
+
|
176 |
+
__slots__ = ()
|
177 |
+
|
178 |
+
args: tTuple[Expr, ...]
|
179 |
+
|
180 |
+
is_Add = True
|
181 |
+
|
182 |
+
_args_type = Expr
|
183 |
+
|
184 |
+
@classmethod
|
185 |
+
def flatten(cls, seq):
|
186 |
+
"""
|
187 |
+
Takes the sequence "seq" of nested Adds and returns a flatten list.
|
188 |
+
|
189 |
+
Returns: (commutative_part, noncommutative_part, order_symbols)
|
190 |
+
|
191 |
+
Applies associativity, all terms are commutable with respect to
|
192 |
+
addition.
|
193 |
+
|
194 |
+
NB: the removal of 0 is already handled by AssocOp.__new__
|
195 |
+
|
196 |
+
See Also
|
197 |
+
========
|
198 |
+
|
199 |
+
sympy.core.mul.Mul.flatten
|
200 |
+
|
201 |
+
"""
|
202 |
+
from sympy.calculus.accumulationbounds import AccumBounds
|
203 |
+
from sympy.matrices.expressions import MatrixExpr
|
204 |
+
from sympy.tensor.tensor import TensExpr
|
205 |
+
rv = None
|
206 |
+
if len(seq) == 2:
|
207 |
+
a, b = seq
|
208 |
+
if b.is_Rational:
|
209 |
+
a, b = b, a
|
210 |
+
if a.is_Rational:
|
211 |
+
if b.is_Mul:
|
212 |
+
rv = [a, b], [], None
|
213 |
+
if rv:
|
214 |
+
if all(s.is_commutative for s in rv[0]):
|
215 |
+
return rv
|
216 |
+
return [], rv[0], None
|
217 |
+
|
218 |
+
terms = {} # term -> coeff
|
219 |
+
# e.g. x**2 -> 5 for ... + 5*x**2 + ...
|
220 |
+
|
221 |
+
coeff = S.Zero # coefficient (Number or zoo) to always be in slot 0
|
222 |
+
# e.g. 3 + ...
|
223 |
+
order_factors = []
|
224 |
+
|
225 |
+
extra = []
|
226 |
+
|
227 |
+
for o in seq:
|
228 |
+
|
229 |
+
# O(x)
|
230 |
+
if o.is_Order:
|
231 |
+
if o.expr.is_zero:
|
232 |
+
continue
|
233 |
+
for o1 in order_factors:
|
234 |
+
if o1.contains(o):
|
235 |
+
o = None
|
236 |
+
break
|
237 |
+
if o is None:
|
238 |
+
continue
|
239 |
+
order_factors = [o] + [
|
240 |
+
o1 for o1 in order_factors if not o.contains(o1)]
|
241 |
+
continue
|
242 |
+
|
243 |
+
# 3 or NaN
|
244 |
+
elif o.is_Number:
|
245 |
+
if (o is S.NaN or coeff is S.ComplexInfinity and
|
246 |
+
o.is_finite is False) and not extra:
|
247 |
+
# we know for sure the result will be nan
|
248 |
+
return [S.NaN], [], None
|
249 |
+
if coeff.is_Number or isinstance(coeff, AccumBounds):
|
250 |
+
coeff += o
|
251 |
+
if coeff is S.NaN and not extra:
|
252 |
+
# we know for sure the result will be nan
|
253 |
+
return [S.NaN], [], None
|
254 |
+
continue
|
255 |
+
|
256 |
+
elif isinstance(o, AccumBounds):
|
257 |
+
coeff = o.__add__(coeff)
|
258 |
+
continue
|
259 |
+
|
260 |
+
elif isinstance(o, MatrixExpr):
|
261 |
+
# can't add 0 to Matrix so make sure coeff is not 0
|
262 |
+
extra.append(o)
|
263 |
+
continue
|
264 |
+
|
265 |
+
elif isinstance(o, TensExpr):
|
266 |
+
coeff = o.__add__(coeff) if coeff else o
|
267 |
+
continue
|
268 |
+
|
269 |
+
elif o is S.ComplexInfinity:
|
270 |
+
if coeff.is_finite is False and not extra:
|
271 |
+
# we know for sure the result will be nan
|
272 |
+
return [S.NaN], [], None
|
273 |
+
coeff = S.ComplexInfinity
|
274 |
+
continue
|
275 |
+
|
276 |
+
# Add([...])
|
277 |
+
elif o.is_Add:
|
278 |
+
# NB: here we assume Add is always commutative
|
279 |
+
seq.extend(o.args) # TODO zerocopy?
|
280 |
+
continue
|
281 |
+
|
282 |
+
# Mul([...])
|
283 |
+
elif o.is_Mul:
|
284 |
+
c, s = o.as_coeff_Mul()
|
285 |
+
|
286 |
+
# check for unevaluated Pow, e.g. 2**3 or 2**(-1/2)
|
287 |
+
elif o.is_Pow:
|
288 |
+
b, e = o.as_base_exp()
|
289 |
+
if b.is_Number and (e.is_Integer or
|
290 |
+
(e.is_Rational and e.is_negative)):
|
291 |
+
seq.append(b**e)
|
292 |
+
continue
|
293 |
+
c, s = S.One, o
|
294 |
+
|
295 |
+
else:
|
296 |
+
# everything else
|
297 |
+
c = S.One
|
298 |
+
s = o
|
299 |
+
|
300 |
+
# now we have:
|
301 |
+
# o = c*s, where
|
302 |
+
#
|
303 |
+
# c is a Number
|
304 |
+
# s is an expression with number factor extracted
|
305 |
+
# let's collect terms with the same s, so e.g.
|
306 |
+
# 2*x**2 + 3*x**2 -> 5*x**2
|
307 |
+
if s in terms:
|
308 |
+
terms[s] += c
|
309 |
+
if terms[s] is S.NaN and not extra:
|
310 |
+
# we know for sure the result will be nan
|
311 |
+
return [S.NaN], [], None
|
312 |
+
else:
|
313 |
+
terms[s] = c
|
314 |
+
|
315 |
+
# now let's construct new args:
|
316 |
+
# [2*x**2, x**3, 7*x**4, pi, ...]
|
317 |
+
newseq = []
|
318 |
+
noncommutative = False
|
319 |
+
for s, c in terms.items():
|
320 |
+
# 0*s
|
321 |
+
if c.is_zero:
|
322 |
+
continue
|
323 |
+
# 1*s
|
324 |
+
elif c is S.One:
|
325 |
+
newseq.append(s)
|
326 |
+
# c*s
|
327 |
+
else:
|
328 |
+
if s.is_Mul:
|
329 |
+
# Mul, already keeps its arguments in perfect order.
|
330 |
+
# so we can simply put c in slot0 and go the fast way.
|
331 |
+
cs = s._new_rawargs(*((c,) + s.args))
|
332 |
+
newseq.append(cs)
|
333 |
+
elif s.is_Add:
|
334 |
+
# we just re-create the unevaluated Mul
|
335 |
+
newseq.append(Mul(c, s, evaluate=False))
|
336 |
+
else:
|
337 |
+
# alternatively we have to call all Mul's machinery (slow)
|
338 |
+
newseq.append(Mul(c, s))
|
339 |
+
|
340 |
+
noncommutative = noncommutative or not s.is_commutative
|
341 |
+
|
342 |
+
# oo, -oo
|
343 |
+
if coeff is S.Infinity:
|
344 |
+
newseq = [f for f in newseq if not (f.is_extended_nonnegative or f.is_real)]
|
345 |
+
|
346 |
+
elif coeff is S.NegativeInfinity:
|
347 |
+
newseq = [f for f in newseq if not (f.is_extended_nonpositive or f.is_real)]
|
348 |
+
|
349 |
+
if coeff is S.ComplexInfinity:
|
350 |
+
# zoo might be
|
351 |
+
# infinite_real + finite_im
|
352 |
+
# finite_real + infinite_im
|
353 |
+
# infinite_real + infinite_im
|
354 |
+
# addition of a finite real or imaginary number won't be able to
|
355 |
+
# change the zoo nature; adding an infinite qualtity would result
|
356 |
+
# in a NaN condition if it had sign opposite of the infinite
|
357 |
+
# portion of zoo, e.g., infinite_real - infinite_real.
|
358 |
+
newseq = [c for c in newseq if not (c.is_finite and
|
359 |
+
c.is_extended_real is not None)]
|
360 |
+
|
361 |
+
# process O(x)
|
362 |
+
if order_factors:
|
363 |
+
newseq2 = []
|
364 |
+
for t in newseq:
|
365 |
+
for o in order_factors:
|
366 |
+
# x + O(x) -> O(x)
|
367 |
+
if o.contains(t):
|
368 |
+
t = None
|
369 |
+
break
|
370 |
+
# x + O(x**2) -> x + O(x**2)
|
371 |
+
if t is not None:
|
372 |
+
newseq2.append(t)
|
373 |
+
newseq = newseq2 + order_factors
|
374 |
+
# 1 + O(1) -> O(1)
|
375 |
+
for o in order_factors:
|
376 |
+
if o.contains(coeff):
|
377 |
+
coeff = S.Zero
|
378 |
+
break
|
379 |
+
|
380 |
+
# order args canonically
|
381 |
+
_addsort(newseq)
|
382 |
+
|
383 |
+
# current code expects coeff to be first
|
384 |
+
if coeff is not S.Zero:
|
385 |
+
newseq.insert(0, coeff)
|
386 |
+
|
387 |
+
if extra:
|
388 |
+
newseq += extra
|
389 |
+
noncommutative = True
|
390 |
+
|
391 |
+
# we are done
|
392 |
+
if noncommutative:
|
393 |
+
return [], newseq, None
|
394 |
+
else:
|
395 |
+
return newseq, [], None
|
396 |
+
|
397 |
+
@classmethod
|
398 |
+
def class_key(cls):
|
399 |
+
return 3, 1, cls.__name__
|
400 |
+
|
401 |
+
@property
|
402 |
+
def kind(self):
|
403 |
+
k = attrgetter('kind')
|
404 |
+
kinds = map(k, self.args)
|
405 |
+
kinds = frozenset(kinds)
|
406 |
+
if len(kinds) != 1:
|
407 |
+
# Since addition is group operator, kind must be same.
|
408 |
+
# We know that this is unexpected signature, so return this.
|
409 |
+
result = UndefinedKind
|
410 |
+
else:
|
411 |
+
result, = kinds
|
412 |
+
return result
|
413 |
+
|
414 |
+
def could_extract_minus_sign(self):
|
415 |
+
return _could_extract_minus_sign(self)
|
416 |
+
|
417 |
+
@cacheit
|
418 |
+
def as_coeff_add(self, *deps):
|
419 |
+
"""
|
420 |
+
Returns a tuple (coeff, args) where self is treated as an Add and coeff
|
421 |
+
is the Number term and args is a tuple of all other terms.
|
422 |
+
|
423 |
+
Examples
|
424 |
+
========
|
425 |
+
|
426 |
+
>>> from sympy.abc import x
|
427 |
+
>>> (7 + 3*x).as_coeff_add()
|
428 |
+
(7, (3*x,))
|
429 |
+
>>> (7*x).as_coeff_add()
|
430 |
+
(0, (7*x,))
|
431 |
+
"""
|
432 |
+
if deps:
|
433 |
+
l1, l2 = sift(self.args, lambda x: x.has_free(*deps), binary=True)
|
434 |
+
return self._new_rawargs(*l2), tuple(l1)
|
435 |
+
coeff, notrat = self.args[0].as_coeff_add()
|
436 |
+
if coeff is not S.Zero:
|
437 |
+
return coeff, notrat + self.args[1:]
|
438 |
+
return S.Zero, self.args
|
439 |
+
|
440 |
+
def as_coeff_Add(self, rational=False, deps=None):
|
441 |
+
"""
|
442 |
+
Efficiently extract the coefficient of a summation.
|
443 |
+
"""
|
444 |
+
coeff, args = self.args[0], self.args[1:]
|
445 |
+
|
446 |
+
if coeff.is_Number and not rational or coeff.is_Rational:
|
447 |
+
return coeff, self._new_rawargs(*args)
|
448 |
+
return S.Zero, self
|
449 |
+
|
450 |
+
# Note, we intentionally do not implement Add.as_coeff_mul(). Rather, we
|
451 |
+
# let Expr.as_coeff_mul() just always return (S.One, self) for an Add. See
|
452 |
+
# issue 5524.
|
453 |
+
|
454 |
+
def _eval_power(self, e):
|
455 |
+
from .evalf import pure_complex
|
456 |
+
from .relational import is_eq
|
457 |
+
if len(self.args) == 2 and any(_.is_infinite for _ in self.args):
|
458 |
+
if e.is_zero is False and is_eq(e, S.One) is False:
|
459 |
+
# looking for literal a + I*b
|
460 |
+
a, b = self.args
|
461 |
+
if a.coeff(S.ImaginaryUnit):
|
462 |
+
a, b = b, a
|
463 |
+
ico = b.coeff(S.ImaginaryUnit)
|
464 |
+
if ico and ico.is_extended_real and a.is_extended_real:
|
465 |
+
if e.is_extended_negative:
|
466 |
+
return S.Zero
|
467 |
+
if e.is_extended_positive:
|
468 |
+
return S.ComplexInfinity
|
469 |
+
return
|
470 |
+
if e.is_Rational and self.is_number:
|
471 |
+
ri = pure_complex(self)
|
472 |
+
if ri:
|
473 |
+
r, i = ri
|
474 |
+
if e.q == 2:
|
475 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
476 |
+
D = sqrt(r**2 + i**2)
|
477 |
+
if D.is_Rational:
|
478 |
+
from .exprtools import factor_terms
|
479 |
+
from sympy.functions.elementary.complexes import sign
|
480 |
+
from .function import expand_multinomial
|
481 |
+
# (r, i, D) is a Pythagorean triple
|
482 |
+
root = sqrt(factor_terms((D - r)/2))**e.p
|
483 |
+
return root*expand_multinomial((
|
484 |
+
# principle value
|
485 |
+
(D + r)/abs(i) + sign(i)*S.ImaginaryUnit)**e.p)
|
486 |
+
elif e == -1:
|
487 |
+
return _unevaluated_Mul(
|
488 |
+
r - i*S.ImaginaryUnit,
|
489 |
+
1/(r**2 + i**2))
|
490 |
+
elif e.is_Number and abs(e) != 1:
|
491 |
+
# handle the Float case: (2.0 + 4*x)**e -> 4**e*(0.5 + x)**e
|
492 |
+
c, m = zip(*[i.as_coeff_Mul() for i in self.args])
|
493 |
+
if any(i.is_Float for i in c): # XXX should this always be done?
|
494 |
+
big = -1
|
495 |
+
for i in c:
|
496 |
+
if abs(i) >= big:
|
497 |
+
big = abs(i)
|
498 |
+
if big > 0 and not equal_valued(big, 1):
|
499 |
+
from sympy.functions.elementary.complexes import sign
|
500 |
+
bigs = (big, -big)
|
501 |
+
c = [sign(i) if i in bigs else i/big for i in c]
|
502 |
+
addpow = Add(*[c*m for c, m in zip(c, m)])**e
|
503 |
+
return big**e*addpow
|
504 |
+
|
505 |
+
@cacheit
|
506 |
+
def _eval_derivative(self, s):
|
507 |
+
return self.func(*[a.diff(s) for a in self.args])
|
508 |
+
|
509 |
+
def _eval_nseries(self, x, n, logx, cdir=0):
|
510 |
+
terms = [t.nseries(x, n=n, logx=logx, cdir=cdir) for t in self.args]
|
511 |
+
return self.func(*terms)
|
512 |
+
|
513 |
+
def _matches_simple(self, expr, repl_dict):
|
514 |
+
# handle (w+3).matches('x+5') -> {w: x+2}
|
515 |
+
coeff, terms = self.as_coeff_add()
|
516 |
+
if len(terms) == 1:
|
517 |
+
return terms[0].matches(expr - coeff, repl_dict)
|
518 |
+
return
|
519 |
+
|
520 |
+
def matches(self, expr, repl_dict=None, old=False):
|
521 |
+
return self._matches_commutative(expr, repl_dict, old)
|
522 |
+
|
523 |
+
@staticmethod
|
524 |
+
def _combine_inverse(lhs, rhs):
|
525 |
+
"""
|
526 |
+
Returns lhs - rhs, but treats oo like a symbol so oo - oo
|
527 |
+
returns 0, instead of a nan.
|
528 |
+
"""
|
529 |
+
from sympy.simplify.simplify import signsimp
|
530 |
+
inf = (S.Infinity, S.NegativeInfinity)
|
531 |
+
if lhs.has(*inf) or rhs.has(*inf):
|
532 |
+
from .symbol import Dummy
|
533 |
+
oo = Dummy('oo')
|
534 |
+
reps = {
|
535 |
+
S.Infinity: oo,
|
536 |
+
S.NegativeInfinity: -oo}
|
537 |
+
ireps = {v: k for k, v in reps.items()}
|
538 |
+
eq = lhs.xreplace(reps) - rhs.xreplace(reps)
|
539 |
+
if eq.has(oo):
|
540 |
+
eq = eq.replace(
|
541 |
+
lambda x: x.is_Pow and x.base is oo,
|
542 |
+
lambda x: x.base)
|
543 |
+
rv = eq.xreplace(ireps)
|
544 |
+
else:
|
545 |
+
rv = lhs - rhs
|
546 |
+
srv = signsimp(rv)
|
547 |
+
return srv if srv.is_Number else rv
|
548 |
+
|
549 |
+
@cacheit
|
550 |
+
def as_two_terms(self):
|
551 |
+
"""Return head and tail of self.
|
552 |
+
|
553 |
+
This is the most efficient way to get the head and tail of an
|
554 |
+
expression.
|
555 |
+
|
556 |
+
- if you want only the head, use self.args[0];
|
557 |
+
- if you want to process the arguments of the tail then use
|
558 |
+
self.as_coef_add() which gives the head and a tuple containing
|
559 |
+
the arguments of the tail when treated as an Add.
|
560 |
+
- if you want the coefficient when self is treated as a Mul
|
561 |
+
then use self.as_coeff_mul()[0]
|
562 |
+
|
563 |
+
>>> from sympy.abc import x, y
|
564 |
+
>>> (3*x - 2*y + 5).as_two_terms()
|
565 |
+
(5, 3*x - 2*y)
|
566 |
+
"""
|
567 |
+
return self.args[0], self._new_rawargs(*self.args[1:])
|
568 |
+
|
569 |
+
def as_numer_denom(self):
|
570 |
+
"""
|
571 |
+
Decomposes an expression to its numerator part and its
|
572 |
+
denominator part.
|
573 |
+
|
574 |
+
Examples
|
575 |
+
========
|
576 |
+
|
577 |
+
>>> from sympy.abc import x, y, z
|
578 |
+
>>> (x*y/z).as_numer_denom()
|
579 |
+
(x*y, z)
|
580 |
+
>>> (x*(y + 1)/y**7).as_numer_denom()
|
581 |
+
(x*(y + 1), y**7)
|
582 |
+
|
583 |
+
See Also
|
584 |
+
========
|
585 |
+
|
586 |
+
sympy.core.expr.Expr.as_numer_denom
|
587 |
+
"""
|
588 |
+
# clear rational denominator
|
589 |
+
content, expr = self.primitive()
|
590 |
+
if not isinstance(expr, Add):
|
591 |
+
return Mul(content, expr, evaluate=False).as_numer_denom()
|
592 |
+
ncon, dcon = content.as_numer_denom()
|
593 |
+
|
594 |
+
# collect numerators and denominators of the terms
|
595 |
+
nd = defaultdict(list)
|
596 |
+
for f in expr.args:
|
597 |
+
ni, di = f.as_numer_denom()
|
598 |
+
nd[di].append(ni)
|
599 |
+
|
600 |
+
# check for quick exit
|
601 |
+
if len(nd) == 1:
|
602 |
+
d, n = nd.popitem()
|
603 |
+
return self.func(
|
604 |
+
*[_keep_coeff(ncon, ni) for ni in n]), _keep_coeff(dcon, d)
|
605 |
+
|
606 |
+
# sum up the terms having a common denominator
|
607 |
+
for d, n in nd.items():
|
608 |
+
if len(n) == 1:
|
609 |
+
nd[d] = n[0]
|
610 |
+
else:
|
611 |
+
nd[d] = self.func(*n)
|
612 |
+
|
613 |
+
# assemble single numerator and denominator
|
614 |
+
denoms, numers = [list(i) for i in zip(*iter(nd.items()))]
|
615 |
+
n, d = self.func(*[Mul(*(denoms[:i] + [numers[i]] + denoms[i + 1:]))
|
616 |
+
for i in range(len(numers))]), Mul(*denoms)
|
617 |
+
|
618 |
+
return _keep_coeff(ncon, n), _keep_coeff(dcon, d)
|
619 |
+
|
620 |
+
def _eval_is_polynomial(self, syms):
|
621 |
+
return all(term._eval_is_polynomial(syms) for term in self.args)
|
622 |
+
|
623 |
+
def _eval_is_rational_function(self, syms):
|
624 |
+
return all(term._eval_is_rational_function(syms) for term in self.args)
|
625 |
+
|
626 |
+
def _eval_is_meromorphic(self, x, a):
|
627 |
+
return _fuzzy_group((arg.is_meromorphic(x, a) for arg in self.args),
|
628 |
+
quick_exit=True)
|
629 |
+
|
630 |
+
def _eval_is_algebraic_expr(self, syms):
|
631 |
+
return all(term._eval_is_algebraic_expr(syms) for term in self.args)
|
632 |
+
|
633 |
+
# assumption methods
|
634 |
+
_eval_is_real = lambda self: _fuzzy_group(
|
635 |
+
(a.is_real for a in self.args), quick_exit=True)
|
636 |
+
_eval_is_extended_real = lambda self: _fuzzy_group(
|
637 |
+
(a.is_extended_real for a in self.args), quick_exit=True)
|
638 |
+
_eval_is_complex = lambda self: _fuzzy_group(
|
639 |
+
(a.is_complex for a in self.args), quick_exit=True)
|
640 |
+
_eval_is_antihermitian = lambda self: _fuzzy_group(
|
641 |
+
(a.is_antihermitian for a in self.args), quick_exit=True)
|
642 |
+
_eval_is_finite = lambda self: _fuzzy_group(
|
643 |
+
(a.is_finite for a in self.args), quick_exit=True)
|
644 |
+
_eval_is_hermitian = lambda self: _fuzzy_group(
|
645 |
+
(a.is_hermitian for a in self.args), quick_exit=True)
|
646 |
+
_eval_is_integer = lambda self: _fuzzy_group(
|
647 |
+
(a.is_integer for a in self.args), quick_exit=True)
|
648 |
+
_eval_is_rational = lambda self: _fuzzy_group(
|
649 |
+
(a.is_rational for a in self.args), quick_exit=True)
|
650 |
+
_eval_is_algebraic = lambda self: _fuzzy_group(
|
651 |
+
(a.is_algebraic for a in self.args), quick_exit=True)
|
652 |
+
_eval_is_commutative = lambda self: _fuzzy_group(
|
653 |
+
a.is_commutative for a in self.args)
|
654 |
+
|
655 |
+
def _eval_is_infinite(self):
|
656 |
+
sawinf = False
|
657 |
+
for a in self.args:
|
658 |
+
ainf = a.is_infinite
|
659 |
+
if ainf is None:
|
660 |
+
return None
|
661 |
+
elif ainf is True:
|
662 |
+
# infinite+infinite might not be infinite
|
663 |
+
if sawinf is True:
|
664 |
+
return None
|
665 |
+
sawinf = True
|
666 |
+
return sawinf
|
667 |
+
|
668 |
+
def _eval_is_imaginary(self):
|
669 |
+
nz = []
|
670 |
+
im_I = []
|
671 |
+
for a in self.args:
|
672 |
+
if a.is_extended_real:
|
673 |
+
if a.is_zero:
|
674 |
+
pass
|
675 |
+
elif a.is_zero is False:
|
676 |
+
nz.append(a)
|
677 |
+
else:
|
678 |
+
return
|
679 |
+
elif a.is_imaginary:
|
680 |
+
im_I.append(a*S.ImaginaryUnit)
|
681 |
+
elif a.is_Mul and S.ImaginaryUnit in a.args:
|
682 |
+
coeff, ai = a.as_coeff_mul(S.ImaginaryUnit)
|
683 |
+
if ai == (S.ImaginaryUnit,) and coeff.is_extended_real:
|
684 |
+
im_I.append(-coeff)
|
685 |
+
else:
|
686 |
+
return
|
687 |
+
else:
|
688 |
+
return
|
689 |
+
b = self.func(*nz)
|
690 |
+
if b != self:
|
691 |
+
if b.is_zero:
|
692 |
+
return fuzzy_not(self.func(*im_I).is_zero)
|
693 |
+
elif b.is_zero is False:
|
694 |
+
return False
|
695 |
+
|
696 |
+
def _eval_is_zero(self):
|
697 |
+
if self.is_commutative is False:
|
698 |
+
# issue 10528: there is no way to know if a nc symbol
|
699 |
+
# is zero or not
|
700 |
+
return
|
701 |
+
nz = []
|
702 |
+
z = 0
|
703 |
+
im_or_z = False
|
704 |
+
im = 0
|
705 |
+
for a in self.args:
|
706 |
+
if a.is_extended_real:
|
707 |
+
if a.is_zero:
|
708 |
+
z += 1
|
709 |
+
elif a.is_zero is False:
|
710 |
+
nz.append(a)
|
711 |
+
else:
|
712 |
+
return
|
713 |
+
elif a.is_imaginary:
|
714 |
+
im += 1
|
715 |
+
elif a.is_Mul and S.ImaginaryUnit in a.args:
|
716 |
+
coeff, ai = a.as_coeff_mul(S.ImaginaryUnit)
|
717 |
+
if ai == (S.ImaginaryUnit,) and coeff.is_extended_real:
|
718 |
+
im_or_z = True
|
719 |
+
else:
|
720 |
+
return
|
721 |
+
else:
|
722 |
+
return
|
723 |
+
if z == len(self.args):
|
724 |
+
return True
|
725 |
+
if len(nz) in [0, len(self.args)]:
|
726 |
+
return None
|
727 |
+
b = self.func(*nz)
|
728 |
+
if b.is_zero:
|
729 |
+
if not im_or_z:
|
730 |
+
if im == 0:
|
731 |
+
return True
|
732 |
+
elif im == 1:
|
733 |
+
return False
|
734 |
+
if b.is_zero is False:
|
735 |
+
return False
|
736 |
+
|
737 |
+
def _eval_is_odd(self):
|
738 |
+
l = [f for f in self.args if not (f.is_even is True)]
|
739 |
+
if not l:
|
740 |
+
return False
|
741 |
+
if l[0].is_odd:
|
742 |
+
return self._new_rawargs(*l[1:]).is_even
|
743 |
+
|
744 |
+
def _eval_is_irrational(self):
|
745 |
+
for t in self.args:
|
746 |
+
a = t.is_irrational
|
747 |
+
if a:
|
748 |
+
others = list(self.args)
|
749 |
+
others.remove(t)
|
750 |
+
if all(x.is_rational is True for x in others):
|
751 |
+
return True
|
752 |
+
return None
|
753 |
+
if a is None:
|
754 |
+
return
|
755 |
+
return False
|
756 |
+
|
757 |
+
def _all_nonneg_or_nonppos(self):
|
758 |
+
nn = np = 0
|
759 |
+
for a in self.args:
|
760 |
+
if a.is_nonnegative:
|
761 |
+
if np:
|
762 |
+
return False
|
763 |
+
nn = 1
|
764 |
+
elif a.is_nonpositive:
|
765 |
+
if nn:
|
766 |
+
return False
|
767 |
+
np = 1
|
768 |
+
else:
|
769 |
+
break
|
770 |
+
else:
|
771 |
+
return True
|
772 |
+
|
773 |
+
def _eval_is_extended_positive(self):
|
774 |
+
if self.is_number:
|
775 |
+
return super()._eval_is_extended_positive()
|
776 |
+
c, a = self.as_coeff_Add()
|
777 |
+
if not c.is_zero:
|
778 |
+
from .exprtools import _monotonic_sign
|
779 |
+
v = _monotonic_sign(a)
|
780 |
+
if v is not None:
|
781 |
+
s = v + c
|
782 |
+
if s != self and s.is_extended_positive and a.is_extended_nonnegative:
|
783 |
+
return True
|
784 |
+
if len(self.free_symbols) == 1:
|
785 |
+
v = _monotonic_sign(self)
|
786 |
+
if v is not None and v != self and v.is_extended_positive:
|
787 |
+
return True
|
788 |
+
pos = nonneg = nonpos = unknown_sign = False
|
789 |
+
saw_INF = set()
|
790 |
+
args = [a for a in self.args if not a.is_zero]
|
791 |
+
if not args:
|
792 |
+
return False
|
793 |
+
for a in args:
|
794 |
+
ispos = a.is_extended_positive
|
795 |
+
infinite = a.is_infinite
|
796 |
+
if infinite:
|
797 |
+
saw_INF.add(fuzzy_or((ispos, a.is_extended_nonnegative)))
|
798 |
+
if True in saw_INF and False in saw_INF:
|
799 |
+
return
|
800 |
+
if ispos:
|
801 |
+
pos = True
|
802 |
+
continue
|
803 |
+
elif a.is_extended_nonnegative:
|
804 |
+
nonneg = True
|
805 |
+
continue
|
806 |
+
elif a.is_extended_nonpositive:
|
807 |
+
nonpos = True
|
808 |
+
continue
|
809 |
+
|
810 |
+
if infinite is None:
|
811 |
+
return
|
812 |
+
unknown_sign = True
|
813 |
+
|
814 |
+
if saw_INF:
|
815 |
+
if len(saw_INF) > 1:
|
816 |
+
return
|
817 |
+
return saw_INF.pop()
|
818 |
+
elif unknown_sign:
|
819 |
+
return
|
820 |
+
elif not nonpos and not nonneg and pos:
|
821 |
+
return True
|
822 |
+
elif not nonpos and pos:
|
823 |
+
return True
|
824 |
+
elif not pos and not nonneg:
|
825 |
+
return False
|
826 |
+
|
827 |
+
def _eval_is_extended_nonnegative(self):
|
828 |
+
if not self.is_number:
|
829 |
+
c, a = self.as_coeff_Add()
|
830 |
+
if not c.is_zero and a.is_extended_nonnegative:
|
831 |
+
from .exprtools import _monotonic_sign
|
832 |
+
v = _monotonic_sign(a)
|
833 |
+
if v is not None:
|
834 |
+
s = v + c
|
835 |
+
if s != self and s.is_extended_nonnegative:
|
836 |
+
return True
|
837 |
+
if len(self.free_symbols) == 1:
|
838 |
+
v = _monotonic_sign(self)
|
839 |
+
if v is not None and v != self and v.is_extended_nonnegative:
|
840 |
+
return True
|
841 |
+
|
842 |
+
def _eval_is_extended_nonpositive(self):
|
843 |
+
if not self.is_number:
|
844 |
+
c, a = self.as_coeff_Add()
|
845 |
+
if not c.is_zero and a.is_extended_nonpositive:
|
846 |
+
from .exprtools import _monotonic_sign
|
847 |
+
v = _monotonic_sign(a)
|
848 |
+
if v is not None:
|
849 |
+
s = v + c
|
850 |
+
if s != self and s.is_extended_nonpositive:
|
851 |
+
return True
|
852 |
+
if len(self.free_symbols) == 1:
|
853 |
+
v = _monotonic_sign(self)
|
854 |
+
if v is not None and v != self and v.is_extended_nonpositive:
|
855 |
+
return True
|
856 |
+
|
857 |
+
def _eval_is_extended_negative(self):
|
858 |
+
if self.is_number:
|
859 |
+
return super()._eval_is_extended_negative()
|
860 |
+
c, a = self.as_coeff_Add()
|
861 |
+
if not c.is_zero:
|
862 |
+
from .exprtools import _monotonic_sign
|
863 |
+
v = _monotonic_sign(a)
|
864 |
+
if v is not None:
|
865 |
+
s = v + c
|
866 |
+
if s != self and s.is_extended_negative and a.is_extended_nonpositive:
|
867 |
+
return True
|
868 |
+
if len(self.free_symbols) == 1:
|
869 |
+
v = _monotonic_sign(self)
|
870 |
+
if v is not None and v != self and v.is_extended_negative:
|
871 |
+
return True
|
872 |
+
neg = nonpos = nonneg = unknown_sign = False
|
873 |
+
saw_INF = set()
|
874 |
+
args = [a for a in self.args if not a.is_zero]
|
875 |
+
if not args:
|
876 |
+
return False
|
877 |
+
for a in args:
|
878 |
+
isneg = a.is_extended_negative
|
879 |
+
infinite = a.is_infinite
|
880 |
+
if infinite:
|
881 |
+
saw_INF.add(fuzzy_or((isneg, a.is_extended_nonpositive)))
|
882 |
+
if True in saw_INF and False in saw_INF:
|
883 |
+
return
|
884 |
+
if isneg:
|
885 |
+
neg = True
|
886 |
+
continue
|
887 |
+
elif a.is_extended_nonpositive:
|
888 |
+
nonpos = True
|
889 |
+
continue
|
890 |
+
elif a.is_extended_nonnegative:
|
891 |
+
nonneg = True
|
892 |
+
continue
|
893 |
+
|
894 |
+
if infinite is None:
|
895 |
+
return
|
896 |
+
unknown_sign = True
|
897 |
+
|
898 |
+
if saw_INF:
|
899 |
+
if len(saw_INF) > 1:
|
900 |
+
return
|
901 |
+
return saw_INF.pop()
|
902 |
+
elif unknown_sign:
|
903 |
+
return
|
904 |
+
elif not nonneg and not nonpos and neg:
|
905 |
+
return True
|
906 |
+
elif not nonneg and neg:
|
907 |
+
return True
|
908 |
+
elif not neg and not nonpos:
|
909 |
+
return False
|
910 |
+
|
911 |
+
def _eval_subs(self, old, new):
|
912 |
+
if not old.is_Add:
|
913 |
+
if old is S.Infinity and -old in self.args:
|
914 |
+
# foo - oo is foo + (-oo) internally
|
915 |
+
return self.xreplace({-old: -new})
|
916 |
+
return None
|
917 |
+
|
918 |
+
coeff_self, terms_self = self.as_coeff_Add()
|
919 |
+
coeff_old, terms_old = old.as_coeff_Add()
|
920 |
+
|
921 |
+
if coeff_self.is_Rational and coeff_old.is_Rational:
|
922 |
+
if terms_self == terms_old: # (2 + a).subs( 3 + a, y) -> -1 + y
|
923 |
+
return self.func(new, coeff_self, -coeff_old)
|
924 |
+
if terms_self == -terms_old: # (2 + a).subs(-3 - a, y) -> -1 - y
|
925 |
+
return self.func(-new, coeff_self, coeff_old)
|
926 |
+
|
927 |
+
if coeff_self.is_Rational and coeff_old.is_Rational \
|
928 |
+
or coeff_self == coeff_old:
|
929 |
+
args_old, args_self = self.func.make_args(
|
930 |
+
terms_old), self.func.make_args(terms_self)
|
931 |
+
if len(args_old) < len(args_self): # (a+b+c).subs(b+c,x) -> a+x
|
932 |
+
self_set = set(args_self)
|
933 |
+
old_set = set(args_old)
|
934 |
+
|
935 |
+
if old_set < self_set:
|
936 |
+
ret_set = self_set - old_set
|
937 |
+
return self.func(new, coeff_self, -coeff_old,
|
938 |
+
*[s._subs(old, new) for s in ret_set])
|
939 |
+
|
940 |
+
args_old = self.func.make_args(
|
941 |
+
-terms_old) # (a+b+c+d).subs(-b-c,x) -> a-x+d
|
942 |
+
old_set = set(args_old)
|
943 |
+
if old_set < self_set:
|
944 |
+
ret_set = self_set - old_set
|
945 |
+
return self.func(-new, coeff_self, coeff_old,
|
946 |
+
*[s._subs(old, new) for s in ret_set])
|
947 |
+
|
948 |
+
def removeO(self):
|
949 |
+
args = [a for a in self.args if not a.is_Order]
|
950 |
+
return self._new_rawargs(*args)
|
951 |
+
|
952 |
+
def getO(self):
|
953 |
+
args = [a for a in self.args if a.is_Order]
|
954 |
+
if args:
|
955 |
+
return self._new_rawargs(*args)
|
956 |
+
|
957 |
+
@cacheit
|
958 |
+
def extract_leading_order(self, symbols, point=None):
|
959 |
+
"""
|
960 |
+
Returns the leading term and its order.
|
961 |
+
|
962 |
+
Examples
|
963 |
+
========
|
964 |
+
|
965 |
+
>>> from sympy.abc import x
|
966 |
+
>>> (x + 1 + 1/x**5).extract_leading_order(x)
|
967 |
+
((x**(-5), O(x**(-5))),)
|
968 |
+
>>> (1 + x).extract_leading_order(x)
|
969 |
+
((1, O(1)),)
|
970 |
+
>>> (x + x**2).extract_leading_order(x)
|
971 |
+
((x, O(x)),)
|
972 |
+
|
973 |
+
"""
|
974 |
+
from sympy.series.order import Order
|
975 |
+
lst = []
|
976 |
+
symbols = list(symbols if is_sequence(symbols) else [symbols])
|
977 |
+
if not point:
|
978 |
+
point = [0]*len(symbols)
|
979 |
+
seq = [(f, Order(f, *zip(symbols, point))) for f in self.args]
|
980 |
+
for ef, of in seq:
|
981 |
+
for e, o in lst:
|
982 |
+
if o.contains(of) and o != of:
|
983 |
+
of = None
|
984 |
+
break
|
985 |
+
if of is None:
|
986 |
+
continue
|
987 |
+
new_lst = [(ef, of)]
|
988 |
+
for e, o in lst:
|
989 |
+
if of.contains(o) and o != of:
|
990 |
+
continue
|
991 |
+
new_lst.append((e, o))
|
992 |
+
lst = new_lst
|
993 |
+
return tuple(lst)
|
994 |
+
|
995 |
+
def as_real_imag(self, deep=True, **hints):
|
996 |
+
"""
|
997 |
+
Return a tuple representing a complex number.
|
998 |
+
|
999 |
+
Examples
|
1000 |
+
========
|
1001 |
+
|
1002 |
+
>>> from sympy import I
|
1003 |
+
>>> (7 + 9*I).as_real_imag()
|
1004 |
+
(7, 9)
|
1005 |
+
>>> ((1 + I)/(1 - I)).as_real_imag()
|
1006 |
+
(0, 1)
|
1007 |
+
>>> ((1 + 2*I)*(1 + 3*I)).as_real_imag()
|
1008 |
+
(-5, 5)
|
1009 |
+
"""
|
1010 |
+
sargs = self.args
|
1011 |
+
re_part, im_part = [], []
|
1012 |
+
for term in sargs:
|
1013 |
+
re, im = term.as_real_imag(deep=deep)
|
1014 |
+
re_part.append(re)
|
1015 |
+
im_part.append(im)
|
1016 |
+
return (self.func(*re_part), self.func(*im_part))
|
1017 |
+
|
1018 |
+
def _eval_as_leading_term(self, x, logx=None, cdir=0):
|
1019 |
+
from sympy.core.symbol import Dummy, Symbol
|
1020 |
+
from sympy.series.order import Order
|
1021 |
+
from sympy.functions.elementary.exponential import log
|
1022 |
+
from sympy.functions.elementary.piecewise import Piecewise, piecewise_fold
|
1023 |
+
from .function import expand_mul
|
1024 |
+
|
1025 |
+
o = self.getO()
|
1026 |
+
if o is None:
|
1027 |
+
o = Order(0)
|
1028 |
+
old = self.removeO()
|
1029 |
+
|
1030 |
+
if old.has(Piecewise):
|
1031 |
+
old = piecewise_fold(old)
|
1032 |
+
|
1033 |
+
# This expansion is the last part of expand_log. expand_log also calls
|
1034 |
+
# expand_mul with factor=True, which would be more expensive
|
1035 |
+
if any(isinstance(a, log) for a in self.args):
|
1036 |
+
logflags = {"deep": True, "log": True, "mul": False, "power_exp": False,
|
1037 |
+
"power_base": False, "multinomial": False, "basic": False, "force": False,
|
1038 |
+
"factor": False}
|
1039 |
+
old = old.expand(**logflags)
|
1040 |
+
expr = expand_mul(old)
|
1041 |
+
|
1042 |
+
if not expr.is_Add:
|
1043 |
+
return expr.as_leading_term(x, logx=logx, cdir=cdir)
|
1044 |
+
|
1045 |
+
infinite = [t for t in expr.args if t.is_infinite]
|
1046 |
+
|
1047 |
+
_logx = Dummy('logx') if logx is None else logx
|
1048 |
+
leading_terms = [t.as_leading_term(x, logx=_logx, cdir=cdir) for t in expr.args]
|
1049 |
+
|
1050 |
+
min, new_expr = Order(0), 0
|
1051 |
+
|
1052 |
+
try:
|
1053 |
+
for term in leading_terms:
|
1054 |
+
order = Order(term, x)
|
1055 |
+
if not min or order not in min:
|
1056 |
+
min = order
|
1057 |
+
new_expr = term
|
1058 |
+
elif min in order:
|
1059 |
+
new_expr += term
|
1060 |
+
|
1061 |
+
except TypeError:
|
1062 |
+
return expr
|
1063 |
+
|
1064 |
+
if logx is None:
|
1065 |
+
new_expr = new_expr.subs(_logx, log(x))
|
1066 |
+
|
1067 |
+
is_zero = new_expr.is_zero
|
1068 |
+
if is_zero is None:
|
1069 |
+
new_expr = new_expr.trigsimp().cancel()
|
1070 |
+
is_zero = new_expr.is_zero
|
1071 |
+
if is_zero is True:
|
1072 |
+
# simple leading term analysis gave us cancelled terms but we have to send
|
1073 |
+
# back a term, so compute the leading term (via series)
|
1074 |
+
try:
|
1075 |
+
n0 = min.getn()
|
1076 |
+
except NotImplementedError:
|
1077 |
+
n0 = S.One
|
1078 |
+
if n0.has(Symbol):
|
1079 |
+
n0 = S.One
|
1080 |
+
res = Order(1)
|
1081 |
+
incr = S.One
|
1082 |
+
while res.is_Order:
|
1083 |
+
res = old._eval_nseries(x, n=n0+incr, logx=logx, cdir=cdir).cancel().powsimp().trigsimp()
|
1084 |
+
incr *= 2
|
1085 |
+
return res.as_leading_term(x, logx=logx, cdir=cdir)
|
1086 |
+
|
1087 |
+
elif new_expr is S.NaN:
|
1088 |
+
return old.func._from_args(infinite) + o
|
1089 |
+
|
1090 |
+
else:
|
1091 |
+
return new_expr
|
1092 |
+
|
1093 |
+
def _eval_adjoint(self):
|
1094 |
+
return self.func(*[t.adjoint() for t in self.args])
|
1095 |
+
|
1096 |
+
def _eval_conjugate(self):
|
1097 |
+
return self.func(*[t.conjugate() for t in self.args])
|
1098 |
+
|
1099 |
+
def _eval_transpose(self):
|
1100 |
+
return self.func(*[t.transpose() for t in self.args])
|
1101 |
+
|
1102 |
+
def primitive(self):
|
1103 |
+
"""
|
1104 |
+
Return ``(R, self/R)`` where ``R``` is the Rational GCD of ``self```.
|
1105 |
+
|
1106 |
+
``R`` is collected only from the leading coefficient of each term.
|
1107 |
+
|
1108 |
+
Examples
|
1109 |
+
========
|
1110 |
+
|
1111 |
+
>>> from sympy.abc import x, y
|
1112 |
+
|
1113 |
+
>>> (2*x + 4*y).primitive()
|
1114 |
+
(2, x + 2*y)
|
1115 |
+
|
1116 |
+
>>> (2*x/3 + 4*y/9).primitive()
|
1117 |
+
(2/9, 3*x + 2*y)
|
1118 |
+
|
1119 |
+
>>> (2*x/3 + 4.2*y).primitive()
|
1120 |
+
(1/3, 2*x + 12.6*y)
|
1121 |
+
|
1122 |
+
No subprocessing of term factors is performed:
|
1123 |
+
|
1124 |
+
>>> ((2 + 2*x)*x + 2).primitive()
|
1125 |
+
(1, x*(2*x + 2) + 2)
|
1126 |
+
|
1127 |
+
Recursive processing can be done with the ``as_content_primitive()``
|
1128 |
+
method:
|
1129 |
+
|
1130 |
+
>>> ((2 + 2*x)*x + 2).as_content_primitive()
|
1131 |
+
(2, x*(x + 1) + 1)
|
1132 |
+
|
1133 |
+
See also: primitive() function in polytools.py
|
1134 |
+
|
1135 |
+
"""
|
1136 |
+
|
1137 |
+
terms = []
|
1138 |
+
inf = False
|
1139 |
+
for a in self.args:
|
1140 |
+
c, m = a.as_coeff_Mul()
|
1141 |
+
if not c.is_Rational:
|
1142 |
+
c = S.One
|
1143 |
+
m = a
|
1144 |
+
inf = inf or m is S.ComplexInfinity
|
1145 |
+
terms.append((c.p, c.q, m))
|
1146 |
+
|
1147 |
+
if not inf:
|
1148 |
+
ngcd = reduce(igcd, [t[0] for t in terms], 0)
|
1149 |
+
dlcm = reduce(ilcm, [t[1] for t in terms], 1)
|
1150 |
+
else:
|
1151 |
+
ngcd = reduce(igcd, [t[0] for t in terms if t[1]], 0)
|
1152 |
+
dlcm = reduce(ilcm, [t[1] for t in terms if t[1]], 1)
|
1153 |
+
|
1154 |
+
if ngcd == dlcm == 1:
|
1155 |
+
return S.One, self
|
1156 |
+
if not inf:
|
1157 |
+
for i, (p, q, term) in enumerate(terms):
|
1158 |
+
terms[i] = _keep_coeff(Rational((p//ngcd)*(dlcm//q)), term)
|
1159 |
+
else:
|
1160 |
+
for i, (p, q, term) in enumerate(terms):
|
1161 |
+
if q:
|
1162 |
+
terms[i] = _keep_coeff(Rational((p//ngcd)*(dlcm//q)), term)
|
1163 |
+
else:
|
1164 |
+
terms[i] = _keep_coeff(Rational(p, q), term)
|
1165 |
+
|
1166 |
+
# we don't need a complete re-flattening since no new terms will join
|
1167 |
+
# so we just use the same sort as is used in Add.flatten. When the
|
1168 |
+
# coefficient changes, the ordering of terms may change, e.g.
|
1169 |
+
# (3*x, 6*y) -> (2*y, x)
|
1170 |
+
#
|
1171 |
+
# We do need to make sure that term[0] stays in position 0, however.
|
1172 |
+
#
|
1173 |
+
if terms[0].is_Number or terms[0] is S.ComplexInfinity:
|
1174 |
+
c = terms.pop(0)
|
1175 |
+
else:
|
1176 |
+
c = None
|
1177 |
+
_addsort(terms)
|
1178 |
+
if c:
|
1179 |
+
terms.insert(0, c)
|
1180 |
+
return Rational(ngcd, dlcm), self._new_rawargs(*terms)
|
1181 |
+
|
1182 |
+
def as_content_primitive(self, radical=False, clear=True):
|
1183 |
+
"""Return the tuple (R, self/R) where R is the positive Rational
|
1184 |
+
extracted from self. If radical is True (default is False) then
|
1185 |
+
common radicals will be removed and included as a factor of the
|
1186 |
+
primitive expression.
|
1187 |
+
|
1188 |
+
Examples
|
1189 |
+
========
|
1190 |
+
|
1191 |
+
>>> from sympy import sqrt
|
1192 |
+
>>> (3 + 3*sqrt(2)).as_content_primitive()
|
1193 |
+
(3, 1 + sqrt(2))
|
1194 |
+
|
1195 |
+
Radical content can also be factored out of the primitive:
|
1196 |
+
|
1197 |
+
>>> (2*sqrt(2) + 4*sqrt(10)).as_content_primitive(radical=True)
|
1198 |
+
(2, sqrt(2)*(1 + 2*sqrt(5)))
|
1199 |
+
|
1200 |
+
See docstring of Expr.as_content_primitive for more examples.
|
1201 |
+
"""
|
1202 |
+
con, prim = self.func(*[_keep_coeff(*a.as_content_primitive(
|
1203 |
+
radical=radical, clear=clear)) for a in self.args]).primitive()
|
1204 |
+
if not clear and not con.is_Integer and prim.is_Add:
|
1205 |
+
con, d = con.as_numer_denom()
|
1206 |
+
_p = prim/d
|
1207 |
+
if any(a.as_coeff_Mul()[0].is_Integer for a in _p.args):
|
1208 |
+
prim = _p
|
1209 |
+
else:
|
1210 |
+
con /= d
|
1211 |
+
if radical and prim.is_Add:
|
1212 |
+
# look for common radicals that can be removed
|
1213 |
+
args = prim.args
|
1214 |
+
rads = []
|
1215 |
+
common_q = None
|
1216 |
+
for m in args:
|
1217 |
+
term_rads = defaultdict(list)
|
1218 |
+
for ai in Mul.make_args(m):
|
1219 |
+
if ai.is_Pow:
|
1220 |
+
b, e = ai.as_base_exp()
|
1221 |
+
if e.is_Rational and b.is_Integer:
|
1222 |
+
term_rads[e.q].append(abs(int(b))**e.p)
|
1223 |
+
if not term_rads:
|
1224 |
+
break
|
1225 |
+
if common_q is None:
|
1226 |
+
common_q = set(term_rads.keys())
|
1227 |
+
else:
|
1228 |
+
common_q = common_q & set(term_rads.keys())
|
1229 |
+
if not common_q:
|
1230 |
+
break
|
1231 |
+
rads.append(term_rads)
|
1232 |
+
else:
|
1233 |
+
# process rads
|
1234 |
+
# keep only those in common_q
|
1235 |
+
for r in rads:
|
1236 |
+
for q in list(r.keys()):
|
1237 |
+
if q not in common_q:
|
1238 |
+
r.pop(q)
|
1239 |
+
for q in r:
|
1240 |
+
r[q] = Mul(*r[q])
|
1241 |
+
# find the gcd of bases for each q
|
1242 |
+
G = []
|
1243 |
+
for q in common_q:
|
1244 |
+
g = reduce(igcd, [r[q] for r in rads], 0)
|
1245 |
+
if g != 1:
|
1246 |
+
G.append(g**Rational(1, q))
|
1247 |
+
if G:
|
1248 |
+
G = Mul(*G)
|
1249 |
+
args = [ai/G for ai in args]
|
1250 |
+
prim = G*prim.func(*args)
|
1251 |
+
|
1252 |
+
return con, prim
|
1253 |
+
|
1254 |
+
@property
|
1255 |
+
def _sorted_args(self):
|
1256 |
+
from .sorting import default_sort_key
|
1257 |
+
return tuple(sorted(self.args, key=default_sort_key))
|
1258 |
+
|
1259 |
+
def _eval_difference_delta(self, n, step):
|
1260 |
+
from sympy.series.limitseq import difference_delta as dd
|
1261 |
+
return self.func(*[dd(a, n, step) for a in self.args])
|
1262 |
+
|
1263 |
+
@property
|
1264 |
+
def _mpc_(self):
|
1265 |
+
"""
|
1266 |
+
Convert self to an mpmath mpc if possible
|
1267 |
+
"""
|
1268 |
+
from .numbers import Float
|
1269 |
+
re_part, rest = self.as_coeff_Add()
|
1270 |
+
im_part, imag_unit = rest.as_coeff_Mul()
|
1271 |
+
if not imag_unit == S.ImaginaryUnit:
|
1272 |
+
# ValueError may seem more reasonable but since it's a @property,
|
1273 |
+
# we need to use AttributeError to keep from confusing things like
|
1274 |
+
# hasattr.
|
1275 |
+
raise AttributeError("Cannot convert Add to mpc. Must be of the form Number + Number*I")
|
1276 |
+
|
1277 |
+
return (Float(re_part)._mpf_, Float(im_part)._mpf_)
|
1278 |
+
|
1279 |
+
def __neg__(self):
|
1280 |
+
if not global_parameters.distribute:
|
1281 |
+
return super().__neg__()
|
1282 |
+
return Mul(S.NegativeOne, self)
|
1283 |
+
|
1284 |
+
add = AssocOpDispatcher('add')
|
1285 |
+
|
1286 |
+
from .mul import Mul, _keep_coeff, _unevaluated_Mul
|
1287 |
+
from .numbers import Rational
|
env-llmeval/lib/python3.10/site-packages/sympy/core/alphabets.py
ADDED
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
1 |
+
greeks = ('alpha', 'beta', 'gamma', 'delta', 'epsilon', 'zeta',
|
2 |
+
'eta', 'theta', 'iota', 'kappa', 'lambda', 'mu', 'nu',
|
3 |
+
'xi', 'omicron', 'pi', 'rho', 'sigma', 'tau', 'upsilon',
|
4 |
+
'phi', 'chi', 'psi', 'omega')
|
env-llmeval/lib/python3.10/site-packages/sympy/core/assumptions_generated.py
ADDED
@@ -0,0 +1,1615 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Do NOT manually edit this file.
|
3 |
+
Instead, run ./bin/ask_update.py.
|
4 |
+
"""
|
5 |
+
|
6 |
+
defined_facts = [
|
7 |
+
'algebraic',
|
8 |
+
'antihermitian',
|
9 |
+
'commutative',
|
10 |
+
'complex',
|
11 |
+
'composite',
|
12 |
+
'even',
|
13 |
+
'extended_negative',
|
14 |
+
'extended_nonnegative',
|
15 |
+
'extended_nonpositive',
|
16 |
+
'extended_nonzero',
|
17 |
+
'extended_positive',
|
18 |
+
'extended_real',
|
19 |
+
'finite',
|
20 |
+
'hermitian',
|
21 |
+
'imaginary',
|
22 |
+
'infinite',
|
23 |
+
'integer',
|
24 |
+
'irrational',
|
25 |
+
'negative',
|
26 |
+
'noninteger',
|
27 |
+
'nonnegative',
|
28 |
+
'nonpositive',
|
29 |
+
'nonzero',
|
30 |
+
'odd',
|
31 |
+
'positive',
|
32 |
+
'prime',
|
33 |
+
'rational',
|
34 |
+
'real',
|
35 |
+
'transcendental',
|
36 |
+
'zero',
|
37 |
+
] # defined_facts
|
38 |
+
|
39 |
+
|
40 |
+
full_implications = dict( [
|
41 |
+
# Implications of algebraic = True:
|
42 |
+
(('algebraic', True), set( (
|
43 |
+
('commutative', True),
|
44 |
+
('complex', True),
|
45 |
+
('finite', True),
|
46 |
+
('infinite', False),
|
47 |
+
('transcendental', False),
|
48 |
+
) ),
|
49 |
+
),
|
50 |
+
# Implications of algebraic = False:
|
51 |
+
(('algebraic', False), set( (
|
52 |
+
('composite', False),
|
53 |
+
('even', False),
|
54 |
+
('integer', False),
|
55 |
+
('odd', False),
|
56 |
+
('prime', False),
|
57 |
+
('rational', False),
|
58 |
+
('zero', False),
|
59 |
+
) ),
|
60 |
+
),
|
61 |
+
# Implications of antihermitian = True:
|
62 |
+
(('antihermitian', True), set( (
|
63 |
+
) ),
|
64 |
+
),
|
65 |
+
# Implications of antihermitian = False:
|
66 |
+
(('antihermitian', False), set( (
|
67 |
+
('imaginary', False),
|
68 |
+
) ),
|
69 |
+
),
|
70 |
+
# Implications of commutative = True:
|
71 |
+
(('commutative', True), set( (
|
72 |
+
) ),
|
73 |
+
),
|
74 |
+
# Implications of commutative = False:
|
75 |
+
(('commutative', False), set( (
|
76 |
+
('algebraic', False),
|
77 |
+
('complex', False),
|
78 |
+
('composite', False),
|
79 |
+
('even', False),
|
80 |
+
('extended_negative', False),
|
81 |
+
('extended_nonnegative', False),
|
82 |
+
('extended_nonpositive', False),
|
83 |
+
('extended_nonzero', False),
|
84 |
+
('extended_positive', False),
|
85 |
+
('extended_real', False),
|
86 |
+
('imaginary', False),
|
87 |
+
('integer', False),
|
88 |
+
('irrational', False),
|
89 |
+
('negative', False),
|
90 |
+
('noninteger', False),
|
91 |
+
('nonnegative', False),
|
92 |
+
('nonpositive', False),
|
93 |
+
('nonzero', False),
|
94 |
+
('odd', False),
|
95 |
+
('positive', False),
|
96 |
+
('prime', False),
|
97 |
+
('rational', False),
|
98 |
+
('real', False),
|
99 |
+
('transcendental', False),
|
100 |
+
('zero', False),
|
101 |
+
) ),
|
102 |
+
),
|
103 |
+
# Implications of complex = True:
|
104 |
+
(('complex', True), set( (
|
105 |
+
('commutative', True),
|
106 |
+
('finite', True),
|
107 |
+
('infinite', False),
|
108 |
+
) ),
|
109 |
+
),
|
110 |
+
# Implications of complex = False:
|
111 |
+
(('complex', False), set( (
|
112 |
+
('algebraic', False),
|
113 |
+
('composite', False),
|
114 |
+
('even', False),
|
115 |
+
('imaginary', False),
|
116 |
+
('integer', False),
|
117 |
+
('irrational', False),
|
118 |
+
('negative', False),
|
119 |
+
('nonnegative', False),
|
120 |
+
('nonpositive', False),
|
121 |
+
('nonzero', False),
|
122 |
+
('odd', False),
|
123 |
+
('positive', False),
|
124 |
+
('prime', False),
|
125 |
+
('rational', False),
|
126 |
+
('real', False),
|
127 |
+
('transcendental', False),
|
128 |
+
('zero', False),
|
129 |
+
) ),
|
130 |
+
),
|
131 |
+
# Implications of composite = True:
|
132 |
+
(('composite', True), set( (
|
133 |
+
('algebraic', True),
|
134 |
+
('commutative', True),
|
135 |
+
('complex', True),
|
136 |
+
('extended_negative', False),
|
137 |
+
('extended_nonnegative', True),
|
138 |
+
('extended_nonpositive', False),
|
139 |
+
('extended_nonzero', True),
|
140 |
+
('extended_positive', True),
|
141 |
+
('extended_real', True),
|
142 |
+
('finite', True),
|
143 |
+
('hermitian', True),
|
144 |
+
('imaginary', False),
|
145 |
+
('infinite', False),
|
146 |
+
('integer', True),
|
147 |
+
('irrational', False),
|
148 |
+
('negative', False),
|
149 |
+
('noninteger', False),
|
150 |
+
('nonnegative', True),
|
151 |
+
('nonpositive', False),
|
152 |
+
('nonzero', True),
|
153 |
+
('positive', True),
|
154 |
+
('prime', False),
|
155 |
+
('rational', True),
|
156 |
+
('real', True),
|
157 |
+
('transcendental', False),
|
158 |
+
('zero', False),
|
159 |
+
) ),
|
160 |
+
),
|
161 |
+
# Implications of composite = False:
|
162 |
+
(('composite', False), set( (
|
163 |
+
) ),
|
164 |
+
),
|
165 |
+
# Implications of even = True:
|
166 |
+
(('even', True), set( (
|
167 |
+
('algebraic', True),
|
168 |
+
('commutative', True),
|
169 |
+
('complex', True),
|
170 |
+
('extended_real', True),
|
171 |
+
('finite', True),
|
172 |
+
('hermitian', True),
|
173 |
+
('imaginary', False),
|
174 |
+
('infinite', False),
|
175 |
+
('integer', True),
|
176 |
+
('irrational', False),
|
177 |
+
('noninteger', False),
|
178 |
+
('odd', False),
|
179 |
+
('rational', True),
|
180 |
+
('real', True),
|
181 |
+
('transcendental', False),
|
182 |
+
) ),
|
183 |
+
),
|
184 |
+
# Implications of even = False:
|
185 |
+
(('even', False), set( (
|
186 |
+
('zero', False),
|
187 |
+
) ),
|
188 |
+
),
|
189 |
+
# Implications of extended_negative = True:
|
190 |
+
(('extended_negative', True), set( (
|
191 |
+
('commutative', True),
|
192 |
+
('composite', False),
|
193 |
+
('extended_nonnegative', False),
|
194 |
+
('extended_nonpositive', True),
|
195 |
+
('extended_nonzero', True),
|
196 |
+
('extended_positive', False),
|
197 |
+
('extended_real', True),
|
198 |
+
('imaginary', False),
|
199 |
+
('nonnegative', False),
|
200 |
+
('positive', False),
|
201 |
+
('prime', False),
|
202 |
+
('zero', False),
|
203 |
+
) ),
|
204 |
+
),
|
205 |
+
# Implications of extended_negative = False:
|
206 |
+
(('extended_negative', False), set( (
|
207 |
+
('negative', False),
|
208 |
+
) ),
|
209 |
+
),
|
210 |
+
# Implications of extended_nonnegative = True:
|
211 |
+
(('extended_nonnegative', True), set( (
|
212 |
+
('commutative', True),
|
213 |
+
('extended_negative', False),
|
214 |
+
('extended_real', True),
|
215 |
+
('imaginary', False),
|
216 |
+
('negative', False),
|
217 |
+
) ),
|
218 |
+
),
|
219 |
+
# Implications of extended_nonnegative = False:
|
220 |
+
(('extended_nonnegative', False), set( (
|
221 |
+
('composite', False),
|
222 |
+
('extended_positive', False),
|
223 |
+
('nonnegative', False),
|
224 |
+
('positive', False),
|
225 |
+
('prime', False),
|
226 |
+
('zero', False),
|
227 |
+
) ),
|
228 |
+
),
|
229 |
+
# Implications of extended_nonpositive = True:
|
230 |
+
(('extended_nonpositive', True), set( (
|
231 |
+
('commutative', True),
|
232 |
+
('composite', False),
|
233 |
+
('extended_positive', False),
|
234 |
+
('extended_real', True),
|
235 |
+
('imaginary', False),
|
236 |
+
('positive', False),
|
237 |
+
('prime', False),
|
238 |
+
) ),
|
239 |
+
),
|
240 |
+
# Implications of extended_nonpositive = False:
|
241 |
+
(('extended_nonpositive', False), set( (
|
242 |
+
('extended_negative', False),
|
243 |
+
('negative', False),
|
244 |
+
('nonpositive', False),
|
245 |
+
('zero', False),
|
246 |
+
) ),
|
247 |
+
),
|
248 |
+
# Implications of extended_nonzero = True:
|
249 |
+
(('extended_nonzero', True), set( (
|
250 |
+
('commutative', True),
|
251 |
+
('extended_real', True),
|
252 |
+
('imaginary', False),
|
253 |
+
('zero', False),
|
254 |
+
) ),
|
255 |
+
),
|
256 |
+
# Implications of extended_nonzero = False:
|
257 |
+
(('extended_nonzero', False), set( (
|
258 |
+
('composite', False),
|
259 |
+
('extended_negative', False),
|
260 |
+
('extended_positive', False),
|
261 |
+
('negative', False),
|
262 |
+
('nonzero', False),
|
263 |
+
('positive', False),
|
264 |
+
('prime', False),
|
265 |
+
) ),
|
266 |
+
),
|
267 |
+
# Implications of extended_positive = True:
|
268 |
+
(('extended_positive', True), set( (
|
269 |
+
('commutative', True),
|
270 |
+
('extended_negative', False),
|
271 |
+
('extended_nonnegative', True),
|
272 |
+
('extended_nonpositive', False),
|
273 |
+
('extended_nonzero', True),
|
274 |
+
('extended_real', True),
|
275 |
+
('imaginary', False),
|
276 |
+
('negative', False),
|
277 |
+
('nonpositive', False),
|
278 |
+
('zero', False),
|
279 |
+
) ),
|
280 |
+
),
|
281 |
+
# Implications of extended_positive = False:
|
282 |
+
(('extended_positive', False), set( (
|
283 |
+
('composite', False),
|
284 |
+
('positive', False),
|
285 |
+
('prime', False),
|
286 |
+
) ),
|
287 |
+
),
|
288 |
+
# Implications of extended_real = True:
|
289 |
+
(('extended_real', True), set( (
|
290 |
+
('commutative', True),
|
291 |
+
('imaginary', False),
|
292 |
+
) ),
|
293 |
+
),
|
294 |
+
# Implications of extended_real = False:
|
295 |
+
(('extended_real', False), set( (
|
296 |
+
('composite', False),
|
297 |
+
('even', False),
|
298 |
+
('extended_negative', False),
|
299 |
+
('extended_nonnegative', False),
|
300 |
+
('extended_nonpositive', False),
|
301 |
+
('extended_nonzero', False),
|
302 |
+
('extended_positive', False),
|
303 |
+
('integer', False),
|
304 |
+
('irrational', False),
|
305 |
+
('negative', False),
|
306 |
+
('noninteger', False),
|
307 |
+
('nonnegative', False),
|
308 |
+
('nonpositive', False),
|
309 |
+
('nonzero', False),
|
310 |
+
('odd', False),
|
311 |
+
('positive', False),
|
312 |
+
('prime', False),
|
313 |
+
('rational', False),
|
314 |
+
('real', False),
|
315 |
+
('zero', False),
|
316 |
+
) ),
|
317 |
+
),
|
318 |
+
# Implications of finite = True:
|
319 |
+
(('finite', True), set( (
|
320 |
+
('infinite', False),
|
321 |
+
) ),
|
322 |
+
),
|
323 |
+
# Implications of finite = False:
|
324 |
+
(('finite', False), set( (
|
325 |
+
('algebraic', False),
|
326 |
+
('complex', False),
|
327 |
+
('composite', False),
|
328 |
+
('even', False),
|
329 |
+
('imaginary', False),
|
330 |
+
('infinite', True),
|
331 |
+
('integer', False),
|
332 |
+
('irrational', False),
|
333 |
+
('negative', False),
|
334 |
+
('nonnegative', False),
|
335 |
+
('nonpositive', False),
|
336 |
+
('nonzero', False),
|
337 |
+
('odd', False),
|
338 |
+
('positive', False),
|
339 |
+
('prime', False),
|
340 |
+
('rational', False),
|
341 |
+
('real', False),
|
342 |
+
('transcendental', False),
|
343 |
+
('zero', False),
|
344 |
+
) ),
|
345 |
+
),
|
346 |
+
# Implications of hermitian = True:
|
347 |
+
(('hermitian', True), set( (
|
348 |
+
) ),
|
349 |
+
),
|
350 |
+
# Implications of hermitian = False:
|
351 |
+
(('hermitian', False), set( (
|
352 |
+
('composite', False),
|
353 |
+
('even', False),
|
354 |
+
('integer', False),
|
355 |
+
('irrational', False),
|
356 |
+
('negative', False),
|
357 |
+
('nonnegative', False),
|
358 |
+
('nonpositive', False),
|
359 |
+
('nonzero', False),
|
360 |
+
('odd', False),
|
361 |
+
('positive', False),
|
362 |
+
('prime', False),
|
363 |
+
('rational', False),
|
364 |
+
('real', False),
|
365 |
+
('zero', False),
|
366 |
+
) ),
|
367 |
+
),
|
368 |
+
# Implications of imaginary = True:
|
369 |
+
(('imaginary', True), set( (
|
370 |
+
('antihermitian', True),
|
371 |
+
('commutative', True),
|
372 |
+
('complex', True),
|
373 |
+
('composite', False),
|
374 |
+
('even', False),
|
375 |
+
('extended_negative', False),
|
376 |
+
('extended_nonnegative', False),
|
377 |
+
('extended_nonpositive', False),
|
378 |
+
('extended_nonzero', False),
|
379 |
+
('extended_positive', False),
|
380 |
+
('extended_real', False),
|
381 |
+
('finite', True),
|
382 |
+
('infinite', False),
|
383 |
+
('integer', False),
|
384 |
+
('irrational', False),
|
385 |
+
('negative', False),
|
386 |
+
('noninteger', False),
|
387 |
+
('nonnegative', False),
|
388 |
+
('nonpositive', False),
|
389 |
+
('nonzero', False),
|
390 |
+
('odd', False),
|
391 |
+
('positive', False),
|
392 |
+
('prime', False),
|
393 |
+
('rational', False),
|
394 |
+
('real', False),
|
395 |
+
('zero', False),
|
396 |
+
) ),
|
397 |
+
),
|
398 |
+
# Implications of imaginary = False:
|
399 |
+
(('imaginary', False), set( (
|
400 |
+
) ),
|
401 |
+
),
|
402 |
+
# Implications of infinite = True:
|
403 |
+
(('infinite', True), set( (
|
404 |
+
('algebraic', False),
|
405 |
+
('complex', False),
|
406 |
+
('composite', False),
|
407 |
+
('even', False),
|
408 |
+
('finite', False),
|
409 |
+
('imaginary', False),
|
410 |
+
('integer', False),
|
411 |
+
('irrational', False),
|
412 |
+
('negative', False),
|
413 |
+
('nonnegative', False),
|
414 |
+
('nonpositive', False),
|
415 |
+
('nonzero', False),
|
416 |
+
('odd', False),
|
417 |
+
('positive', False),
|
418 |
+
('prime', False),
|
419 |
+
('rational', False),
|
420 |
+
('real', False),
|
421 |
+
('transcendental', False),
|
422 |
+
('zero', False),
|
423 |
+
) ),
|
424 |
+
),
|
425 |
+
# Implications of infinite = False:
|
426 |
+
(('infinite', False), set( (
|
427 |
+
('finite', True),
|
428 |
+
) ),
|
429 |
+
),
|
430 |
+
# Implications of integer = True:
|
431 |
+
(('integer', True), set( (
|
432 |
+
('algebraic', True),
|
433 |
+
('commutative', True),
|
434 |
+
('complex', True),
|
435 |
+
('extended_real', True),
|
436 |
+
('finite', True),
|
437 |
+
('hermitian', True),
|
438 |
+
('imaginary', False),
|
439 |
+
('infinite', False),
|
440 |
+
('irrational', False),
|
441 |
+
('noninteger', False),
|
442 |
+
('rational', True),
|
443 |
+
('real', True),
|
444 |
+
('transcendental', False),
|
445 |
+
) ),
|
446 |
+
),
|
447 |
+
# Implications of integer = False:
|
448 |
+
(('integer', False), set( (
|
449 |
+
('composite', False),
|
450 |
+
('even', False),
|
451 |
+
('odd', False),
|
452 |
+
('prime', False),
|
453 |
+
('zero', False),
|
454 |
+
) ),
|
455 |
+
),
|
456 |
+
# Implications of irrational = True:
|
457 |
+
(('irrational', True), set( (
|
458 |
+
('commutative', True),
|
459 |
+
('complex', True),
|
460 |
+
('composite', False),
|
461 |
+
('even', False),
|
462 |
+
('extended_nonzero', True),
|
463 |
+
('extended_real', True),
|
464 |
+
('finite', True),
|
465 |
+
('hermitian', True),
|
466 |
+
('imaginary', False),
|
467 |
+
('infinite', False),
|
468 |
+
('integer', False),
|
469 |
+
('noninteger', True),
|
470 |
+
('nonzero', True),
|
471 |
+
('odd', False),
|
472 |
+
('prime', False),
|
473 |
+
('rational', False),
|
474 |
+
('real', True),
|
475 |
+
('zero', False),
|
476 |
+
) ),
|
477 |
+
),
|
478 |
+
# Implications of irrational = False:
|
479 |
+
(('irrational', False), set( (
|
480 |
+
) ),
|
481 |
+
),
|
482 |
+
# Implications of negative = True:
|
483 |
+
(('negative', True), set( (
|
484 |
+
('commutative', True),
|
485 |
+
('complex', True),
|
486 |
+
('composite', False),
|
487 |
+
('extended_negative', True),
|
488 |
+
('extended_nonnegative', False),
|
489 |
+
('extended_nonpositive', True),
|
490 |
+
('extended_nonzero', True),
|
491 |
+
('extended_positive', False),
|
492 |
+
('extended_real', True),
|
493 |
+
('finite', True),
|
494 |
+
('hermitian', True),
|
495 |
+
('imaginary', False),
|
496 |
+
('infinite', False),
|
497 |
+
('nonnegative', False),
|
498 |
+
('nonpositive', True),
|
499 |
+
('nonzero', True),
|
500 |
+
('positive', False),
|
501 |
+
('prime', False),
|
502 |
+
('real', True),
|
503 |
+
('zero', False),
|
504 |
+
) ),
|
505 |
+
),
|
506 |
+
# Implications of negative = False:
|
507 |
+
(('negative', False), set( (
|
508 |
+
) ),
|
509 |
+
),
|
510 |
+
# Implications of noninteger = True:
|
511 |
+
(('noninteger', True), set( (
|
512 |
+
('commutative', True),
|
513 |
+
('composite', False),
|
514 |
+
('even', False),
|
515 |
+
('extended_nonzero', True),
|
516 |
+
('extended_real', True),
|
517 |
+
('imaginary', False),
|
518 |
+
('integer', False),
|
519 |
+
('odd', False),
|
520 |
+
('prime', False),
|
521 |
+
('zero', False),
|
522 |
+
) ),
|
523 |
+
),
|
524 |
+
# Implications of noninteger = False:
|
525 |
+
(('noninteger', False), set( (
|
526 |
+
) ),
|
527 |
+
),
|
528 |
+
# Implications of nonnegative = True:
|
529 |
+
(('nonnegative', True), set( (
|
530 |
+
('commutative', True),
|
531 |
+
('complex', True),
|
532 |
+
('extended_negative', False),
|
533 |
+
('extended_nonnegative', True),
|
534 |
+
('extended_real', True),
|
535 |
+
('finite', True),
|
536 |
+
('hermitian', True),
|
537 |
+
('imaginary', False),
|
538 |
+
('infinite', False),
|
539 |
+
('negative', False),
|
540 |
+
('real', True),
|
541 |
+
) ),
|
542 |
+
),
|
543 |
+
# Implications of nonnegative = False:
|
544 |
+
(('nonnegative', False), set( (
|
545 |
+
('composite', False),
|
546 |
+
('positive', False),
|
547 |
+
('prime', False),
|
548 |
+
('zero', False),
|
549 |
+
) ),
|
550 |
+
),
|
551 |
+
# Implications of nonpositive = True:
|
552 |
+
(('nonpositive', True), set( (
|
553 |
+
('commutative', True),
|
554 |
+
('complex', True),
|
555 |
+
('composite', False),
|
556 |
+
('extended_nonpositive', True),
|
557 |
+
('extended_positive', False),
|
558 |
+
('extended_real', True),
|
559 |
+
('finite', True),
|
560 |
+
('hermitian', True),
|
561 |
+
('imaginary', False),
|
562 |
+
('infinite', False),
|
563 |
+
('positive', False),
|
564 |
+
('prime', False),
|
565 |
+
('real', True),
|
566 |
+
) ),
|
567 |
+
),
|
568 |
+
# Implications of nonpositive = False:
|
569 |
+
(('nonpositive', False), set( (
|
570 |
+
('negative', False),
|
571 |
+
('zero', False),
|
572 |
+
) ),
|
573 |
+
),
|
574 |
+
# Implications of nonzero = True:
|
575 |
+
(('nonzero', True), set( (
|
576 |
+
('commutative', True),
|
577 |
+
('complex', True),
|
578 |
+
('extended_nonzero', True),
|
579 |
+
('extended_real', True),
|
580 |
+
('finite', True),
|
581 |
+
('hermitian', True),
|
582 |
+
('imaginary', False),
|
583 |
+
('infinite', False),
|
584 |
+
('real', True),
|
585 |
+
('zero', False),
|
586 |
+
) ),
|
587 |
+
),
|
588 |
+
# Implications of nonzero = False:
|
589 |
+
(('nonzero', False), set( (
|
590 |
+
('composite', False),
|
591 |
+
('negative', False),
|
592 |
+
('positive', False),
|
593 |
+
('prime', False),
|
594 |
+
) ),
|
595 |
+
),
|
596 |
+
# Implications of odd = True:
|
597 |
+
(('odd', True), set( (
|
598 |
+
('algebraic', True),
|
599 |
+
('commutative', True),
|
600 |
+
('complex', True),
|
601 |
+
('even', False),
|
602 |
+
('extended_nonzero', True),
|
603 |
+
('extended_real', True),
|
604 |
+
('finite', True),
|
605 |
+
('hermitian', True),
|
606 |
+
('imaginary', False),
|
607 |
+
('infinite', False),
|
608 |
+
('integer', True),
|
609 |
+
('irrational', False),
|
610 |
+
('noninteger', False),
|
611 |
+
('nonzero', True),
|
612 |
+
('rational', True),
|
613 |
+
('real', True),
|
614 |
+
('transcendental', False),
|
615 |
+
('zero', False),
|
616 |
+
) ),
|
617 |
+
),
|
618 |
+
# Implications of odd = False:
|
619 |
+
(('odd', False), set( (
|
620 |
+
) ),
|
621 |
+
),
|
622 |
+
# Implications of positive = True:
|
623 |
+
(('positive', True), set( (
|
624 |
+
('commutative', True),
|
625 |
+
('complex', True),
|
626 |
+
('extended_negative', False),
|
627 |
+
('extended_nonnegative', True),
|
628 |
+
('extended_nonpositive', False),
|
629 |
+
('extended_nonzero', True),
|
630 |
+
('extended_positive', True),
|
631 |
+
('extended_real', True),
|
632 |
+
('finite', True),
|
633 |
+
('hermitian', True),
|
634 |
+
('imaginary', False),
|
635 |
+
('infinite', False),
|
636 |
+
('negative', False),
|
637 |
+
('nonnegative', True),
|
638 |
+
('nonpositive', False),
|
639 |
+
('nonzero', True),
|
640 |
+
('real', True),
|
641 |
+
('zero', False),
|
642 |
+
) ),
|
643 |
+
),
|
644 |
+
# Implications of positive = False:
|
645 |
+
(('positive', False), set( (
|
646 |
+
('composite', False),
|
647 |
+
('prime', False),
|
648 |
+
) ),
|
649 |
+
),
|
650 |
+
# Implications of prime = True:
|
651 |
+
(('prime', True), set( (
|
652 |
+
('algebraic', True),
|
653 |
+
('commutative', True),
|
654 |
+
('complex', True),
|
655 |
+
('composite', False),
|
656 |
+
('extended_negative', False),
|
657 |
+
('extended_nonnegative', True),
|
658 |
+
('extended_nonpositive', False),
|
659 |
+
('extended_nonzero', True),
|
660 |
+
('extended_positive', True),
|
661 |
+
('extended_real', True),
|
662 |
+
('finite', True),
|
663 |
+
('hermitian', True),
|
664 |
+
('imaginary', False),
|
665 |
+
('infinite', False),
|
666 |
+
('integer', True),
|
667 |
+
('irrational', False),
|
668 |
+
('negative', False),
|
669 |
+
('noninteger', False),
|
670 |
+
('nonnegative', True),
|
671 |
+
('nonpositive', False),
|
672 |
+
('nonzero', True),
|
673 |
+
('positive', True),
|
674 |
+
('rational', True),
|
675 |
+
('real', True),
|
676 |
+
('transcendental', False),
|
677 |
+
('zero', False),
|
678 |
+
) ),
|
679 |
+
),
|
680 |
+
# Implications of prime = False:
|
681 |
+
(('prime', False), set( (
|
682 |
+
) ),
|
683 |
+
),
|
684 |
+
# Implications of rational = True:
|
685 |
+
(('rational', True), set( (
|
686 |
+
('algebraic', True),
|
687 |
+
('commutative', True),
|
688 |
+
('complex', True),
|
689 |
+
('extended_real', True),
|
690 |
+
('finite', True),
|
691 |
+
('hermitian', True),
|
692 |
+
('imaginary', False),
|
693 |
+
('infinite', False),
|
694 |
+
('irrational', False),
|
695 |
+
('real', True),
|
696 |
+
('transcendental', False),
|
697 |
+
) ),
|
698 |
+
),
|
699 |
+
# Implications of rational = False:
|
700 |
+
(('rational', False), set( (
|
701 |
+
('composite', False),
|
702 |
+
('even', False),
|
703 |
+
('integer', False),
|
704 |
+
('odd', False),
|
705 |
+
('prime', False),
|
706 |
+
('zero', False),
|
707 |
+
) ),
|
708 |
+
),
|
709 |
+
# Implications of real = True:
|
710 |
+
(('real', True), set( (
|
711 |
+
('commutative', True),
|
712 |
+
('complex', True),
|
713 |
+
('extended_real', True),
|
714 |
+
('finite', True),
|
715 |
+
('hermitian', True),
|
716 |
+
('imaginary', False),
|
717 |
+
('infinite', False),
|
718 |
+
) ),
|
719 |
+
),
|
720 |
+
# Implications of real = False:
|
721 |
+
(('real', False), set( (
|
722 |
+
('composite', False),
|
723 |
+
('even', False),
|
724 |
+
('integer', False),
|
725 |
+
('irrational', False),
|
726 |
+
('negative', False),
|
727 |
+
('nonnegative', False),
|
728 |
+
('nonpositive', False),
|
729 |
+
('nonzero', False),
|
730 |
+
('odd', False),
|
731 |
+
('positive', False),
|
732 |
+
('prime', False),
|
733 |
+
('rational', False),
|
734 |
+
('zero', False),
|
735 |
+
) ),
|
736 |
+
),
|
737 |
+
# Implications of transcendental = True:
|
738 |
+
(('transcendental', True), set( (
|
739 |
+
('algebraic', False),
|
740 |
+
('commutative', True),
|
741 |
+
('complex', True),
|
742 |
+
('composite', False),
|
743 |
+
('even', False),
|
744 |
+
('finite', True),
|
745 |
+
('infinite', False),
|
746 |
+
('integer', False),
|
747 |
+
('odd', False),
|
748 |
+
('prime', False),
|
749 |
+
('rational', False),
|
750 |
+
('zero', False),
|
751 |
+
) ),
|
752 |
+
),
|
753 |
+
# Implications of transcendental = False:
|
754 |
+
(('transcendental', False), set( (
|
755 |
+
) ),
|
756 |
+
),
|
757 |
+
# Implications of zero = True:
|
758 |
+
(('zero', True), set( (
|
759 |
+
('algebraic', True),
|
760 |
+
('commutative', True),
|
761 |
+
('complex', True),
|
762 |
+
('composite', False),
|
763 |
+
('even', True),
|
764 |
+
('extended_negative', False),
|
765 |
+
('extended_nonnegative', True),
|
766 |
+
('extended_nonpositive', True),
|
767 |
+
('extended_nonzero', False),
|
768 |
+
('extended_positive', False),
|
769 |
+
('extended_real', True),
|
770 |
+
('finite', True),
|
771 |
+
('hermitian', True),
|
772 |
+
('imaginary', False),
|
773 |
+
('infinite', False),
|
774 |
+
('integer', True),
|
775 |
+
('irrational', False),
|
776 |
+
('negative', False),
|
777 |
+
('noninteger', False),
|
778 |
+
('nonnegative', True),
|
779 |
+
('nonpositive', True),
|
780 |
+
('nonzero', False),
|
781 |
+
('odd', False),
|
782 |
+
('positive', False),
|
783 |
+
('prime', False),
|
784 |
+
('rational', True),
|
785 |
+
('real', True),
|
786 |
+
('transcendental', False),
|
787 |
+
) ),
|
788 |
+
),
|
789 |
+
# Implications of zero = False:
|
790 |
+
(('zero', False), set( (
|
791 |
+
) ),
|
792 |
+
),
|
793 |
+
] ) # full_implications
|
794 |
+
|
795 |
+
|
796 |
+
prereq = {
|
797 |
+
|
798 |
+
# facts that could determine the value of algebraic
|
799 |
+
'algebraic': {
|
800 |
+
'commutative',
|
801 |
+
'complex',
|
802 |
+
'composite',
|
803 |
+
'even',
|
804 |
+
'finite',
|
805 |
+
'infinite',
|
806 |
+
'integer',
|
807 |
+
'odd',
|
808 |
+
'prime',
|
809 |
+
'rational',
|
810 |
+
'transcendental',
|
811 |
+
'zero',
|
812 |
+
},
|
813 |
+
|
814 |
+
# facts that could determine the value of antihermitian
|
815 |
+
'antihermitian': {
|
816 |
+
'imaginary',
|
817 |
+
},
|
818 |
+
|
819 |
+
# facts that could determine the value of commutative
|
820 |
+
'commutative': {
|
821 |
+
'algebraic',
|
822 |
+
'complex',
|
823 |
+
'composite',
|
824 |
+
'even',
|
825 |
+
'extended_negative',
|
826 |
+
'extended_nonnegative',
|
827 |
+
'extended_nonpositive',
|
828 |
+
'extended_nonzero',
|
829 |
+
'extended_positive',
|
830 |
+
'extended_real',
|
831 |
+
'imaginary',
|
832 |
+
'integer',
|
833 |
+
'irrational',
|
834 |
+
'negative',
|
835 |
+
'noninteger',
|
836 |
+
'nonnegative',
|
837 |
+
'nonpositive',
|
838 |
+
'nonzero',
|
839 |
+
'odd',
|
840 |
+
'positive',
|
841 |
+
'prime',
|
842 |
+
'rational',
|
843 |
+
'real',
|
844 |
+
'transcendental',
|
845 |
+
'zero',
|
846 |
+
},
|
847 |
+
|
848 |
+
# facts that could determine the value of complex
|
849 |
+
'complex': {
|
850 |
+
'algebraic',
|
851 |
+
'commutative',
|
852 |
+
'composite',
|
853 |
+
'even',
|
854 |
+
'finite',
|
855 |
+
'imaginary',
|
856 |
+
'infinite',
|
857 |
+
'integer',
|
858 |
+
'irrational',
|
859 |
+
'negative',
|
860 |
+
'nonnegative',
|
861 |
+
'nonpositive',
|
862 |
+
'nonzero',
|
863 |
+
'odd',
|
864 |
+
'positive',
|
865 |
+
'prime',
|
866 |
+
'rational',
|
867 |
+
'real',
|
868 |
+
'transcendental',
|
869 |
+
'zero',
|
870 |
+
},
|
871 |
+
|
872 |
+
# facts that could determine the value of composite
|
873 |
+
'composite': {
|
874 |
+
'algebraic',
|
875 |
+
'commutative',
|
876 |
+
'complex',
|
877 |
+
'extended_negative',
|
878 |
+
'extended_nonnegative',
|
879 |
+
'extended_nonpositive',
|
880 |
+
'extended_nonzero',
|
881 |
+
'extended_positive',
|
882 |
+
'extended_real',
|
883 |
+
'finite',
|
884 |
+
'hermitian',
|
885 |
+
'imaginary',
|
886 |
+
'infinite',
|
887 |
+
'integer',
|
888 |
+
'irrational',
|
889 |
+
'negative',
|
890 |
+
'noninteger',
|
891 |
+
'nonnegative',
|
892 |
+
'nonpositive',
|
893 |
+
'nonzero',
|
894 |
+
'positive',
|
895 |
+
'prime',
|
896 |
+
'rational',
|
897 |
+
'real',
|
898 |
+
'transcendental',
|
899 |
+
'zero',
|
900 |
+
},
|
901 |
+
|
902 |
+
# facts that could determine the value of even
|
903 |
+
'even': {
|
904 |
+
'algebraic',
|
905 |
+
'commutative',
|
906 |
+
'complex',
|
907 |
+
'extended_real',
|
908 |
+
'finite',
|
909 |
+
'hermitian',
|
910 |
+
'imaginary',
|
911 |
+
'infinite',
|
912 |
+
'integer',
|
913 |
+
'irrational',
|
914 |
+
'noninteger',
|
915 |
+
'odd',
|
916 |
+
'rational',
|
917 |
+
'real',
|
918 |
+
'transcendental',
|
919 |
+
'zero',
|
920 |
+
},
|
921 |
+
|
922 |
+
# facts that could determine the value of extended_negative
|
923 |
+
'extended_negative': {
|
924 |
+
'commutative',
|
925 |
+
'composite',
|
926 |
+
'extended_nonnegative',
|
927 |
+
'extended_nonpositive',
|
928 |
+
'extended_nonzero',
|
929 |
+
'extended_positive',
|
930 |
+
'extended_real',
|
931 |
+
'imaginary',
|
932 |
+
'negative',
|
933 |
+
'nonnegative',
|
934 |
+
'positive',
|
935 |
+
'prime',
|
936 |
+
'zero',
|
937 |
+
},
|
938 |
+
|
939 |
+
# facts that could determine the value of extended_nonnegative
|
940 |
+
'extended_nonnegative': {
|
941 |
+
'commutative',
|
942 |
+
'composite',
|
943 |
+
'extended_negative',
|
944 |
+
'extended_positive',
|
945 |
+
'extended_real',
|
946 |
+
'imaginary',
|
947 |
+
'negative',
|
948 |
+
'nonnegative',
|
949 |
+
'positive',
|
950 |
+
'prime',
|
951 |
+
'zero',
|
952 |
+
},
|
953 |
+
|
954 |
+
# facts that could determine the value of extended_nonpositive
|
955 |
+
'extended_nonpositive': {
|
956 |
+
'commutative',
|
957 |
+
'composite',
|
958 |
+
'extended_negative',
|
959 |
+
'extended_positive',
|
960 |
+
'extended_real',
|
961 |
+
'imaginary',
|
962 |
+
'negative',
|
963 |
+
'nonpositive',
|
964 |
+
'positive',
|
965 |
+
'prime',
|
966 |
+
'zero',
|
967 |
+
},
|
968 |
+
|
969 |
+
# facts that could determine the value of extended_nonzero
|
970 |
+
'extended_nonzero': {
|
971 |
+
'commutative',
|
972 |
+
'composite',
|
973 |
+
'extended_negative',
|
974 |
+
'extended_positive',
|
975 |
+
'extended_real',
|
976 |
+
'imaginary',
|
977 |
+
'irrational',
|
978 |
+
'negative',
|
979 |
+
'noninteger',
|
980 |
+
'nonzero',
|
981 |
+
'odd',
|
982 |
+
'positive',
|
983 |
+
'prime',
|
984 |
+
'zero',
|
985 |
+
},
|
986 |
+
|
987 |
+
# facts that could determine the value of extended_positive
|
988 |
+
'extended_positive': {
|
989 |
+
'commutative',
|
990 |
+
'composite',
|
991 |
+
'extended_negative',
|
992 |
+
'extended_nonnegative',
|
993 |
+
'extended_nonpositive',
|
994 |
+
'extended_nonzero',
|
995 |
+
'extended_real',
|
996 |
+
'imaginary',
|
997 |
+
'negative',
|
998 |
+
'nonpositive',
|
999 |
+
'positive',
|
1000 |
+
'prime',
|
1001 |
+
'zero',
|
1002 |
+
},
|
1003 |
+
|
1004 |
+
# facts that could determine the value of extended_real
|
1005 |
+
'extended_real': {
|
1006 |
+
'commutative',
|
1007 |
+
'composite',
|
1008 |
+
'even',
|
1009 |
+
'extended_negative',
|
1010 |
+
'extended_nonnegative',
|
1011 |
+
'extended_nonpositive',
|
1012 |
+
'extended_nonzero',
|
1013 |
+
'extended_positive',
|
1014 |
+
'imaginary',
|
1015 |
+
'integer',
|
1016 |
+
'irrational',
|
1017 |
+
'negative',
|
1018 |
+
'noninteger',
|
1019 |
+
'nonnegative',
|
1020 |
+
'nonpositive',
|
1021 |
+
'nonzero',
|
1022 |
+
'odd',
|
1023 |
+
'positive',
|
1024 |
+
'prime',
|
1025 |
+
'rational',
|
1026 |
+
'real',
|
1027 |
+
'zero',
|
1028 |
+
},
|
1029 |
+
|
1030 |
+
# facts that could determine the value of finite
|
1031 |
+
'finite': {
|
1032 |
+
'algebraic',
|
1033 |
+
'complex',
|
1034 |
+
'composite',
|
1035 |
+
'even',
|
1036 |
+
'imaginary',
|
1037 |
+
'infinite',
|
1038 |
+
'integer',
|
1039 |
+
'irrational',
|
1040 |
+
'negative',
|
1041 |
+
'nonnegative',
|
1042 |
+
'nonpositive',
|
1043 |
+
'nonzero',
|
1044 |
+
'odd',
|
1045 |
+
'positive',
|
1046 |
+
'prime',
|
1047 |
+
'rational',
|
1048 |
+
'real',
|
1049 |
+
'transcendental',
|
1050 |
+
'zero',
|
1051 |
+
},
|
1052 |
+
|
1053 |
+
# facts that could determine the value of hermitian
|
1054 |
+
'hermitian': {
|
1055 |
+
'composite',
|
1056 |
+
'even',
|
1057 |
+
'integer',
|
1058 |
+
'irrational',
|
1059 |
+
'negative',
|
1060 |
+
'nonnegative',
|
1061 |
+
'nonpositive',
|
1062 |
+
'nonzero',
|
1063 |
+
'odd',
|
1064 |
+
'positive',
|
1065 |
+
'prime',
|
1066 |
+
'rational',
|
1067 |
+
'real',
|
1068 |
+
'zero',
|
1069 |
+
},
|
1070 |
+
|
1071 |
+
# facts that could determine the value of imaginary
|
1072 |
+
'imaginary': {
|
1073 |
+
'antihermitian',
|
1074 |
+
'commutative',
|
1075 |
+
'complex',
|
1076 |
+
'composite',
|
1077 |
+
'even',
|
1078 |
+
'extended_negative',
|
1079 |
+
'extended_nonnegative',
|
1080 |
+
'extended_nonpositive',
|
1081 |
+
'extended_nonzero',
|
1082 |
+
'extended_positive',
|
1083 |
+
'extended_real',
|
1084 |
+
'finite',
|
1085 |
+
'infinite',
|
1086 |
+
'integer',
|
1087 |
+
'irrational',
|
1088 |
+
'negative',
|
1089 |
+
'noninteger',
|
1090 |
+
'nonnegative',
|
1091 |
+
'nonpositive',
|
1092 |
+
'nonzero',
|
1093 |
+
'odd',
|
1094 |
+
'positive',
|
1095 |
+
'prime',
|
1096 |
+
'rational',
|
1097 |
+
'real',
|
1098 |
+
'zero',
|
1099 |
+
},
|
1100 |
+
|
1101 |
+
# facts that could determine the value of infinite
|
1102 |
+
'infinite': {
|
1103 |
+
'algebraic',
|
1104 |
+
'complex',
|
1105 |
+
'composite',
|
1106 |
+
'even',
|
1107 |
+
'finite',
|
1108 |
+
'imaginary',
|
1109 |
+
'integer',
|
1110 |
+
'irrational',
|
1111 |
+
'negative',
|
1112 |
+
'nonnegative',
|
1113 |
+
'nonpositive',
|
1114 |
+
'nonzero',
|
1115 |
+
'odd',
|
1116 |
+
'positive',
|
1117 |
+
'prime',
|
1118 |
+
'rational',
|
1119 |
+
'real',
|
1120 |
+
'transcendental',
|
1121 |
+
'zero',
|
1122 |
+
},
|
1123 |
+
|
1124 |
+
# facts that could determine the value of integer
|
1125 |
+
'integer': {
|
1126 |
+
'algebraic',
|
1127 |
+
'commutative',
|
1128 |
+
'complex',
|
1129 |
+
'composite',
|
1130 |
+
'even',
|
1131 |
+
'extended_real',
|
1132 |
+
'finite',
|
1133 |
+
'hermitian',
|
1134 |
+
'imaginary',
|
1135 |
+
'infinite',
|
1136 |
+
'irrational',
|
1137 |
+
'noninteger',
|
1138 |
+
'odd',
|
1139 |
+
'prime',
|
1140 |
+
'rational',
|
1141 |
+
'real',
|
1142 |
+
'transcendental',
|
1143 |
+
'zero',
|
1144 |
+
},
|
1145 |
+
|
1146 |
+
# facts that could determine the value of irrational
|
1147 |
+
'irrational': {
|
1148 |
+
'commutative',
|
1149 |
+
'complex',
|
1150 |
+
'composite',
|
1151 |
+
'even',
|
1152 |
+
'extended_real',
|
1153 |
+
'finite',
|
1154 |
+
'hermitian',
|
1155 |
+
'imaginary',
|
1156 |
+
'infinite',
|
1157 |
+
'integer',
|
1158 |
+
'odd',
|
1159 |
+
'prime',
|
1160 |
+
'rational',
|
1161 |
+
'real',
|
1162 |
+
'zero',
|
1163 |
+
},
|
1164 |
+
|
1165 |
+
# facts that could determine the value of negative
|
1166 |
+
'negative': {
|
1167 |
+
'commutative',
|
1168 |
+
'complex',
|
1169 |
+
'composite',
|
1170 |
+
'extended_negative',
|
1171 |
+
'extended_nonnegative',
|
1172 |
+
'extended_nonpositive',
|
1173 |
+
'extended_nonzero',
|
1174 |
+
'extended_positive',
|
1175 |
+
'extended_real',
|
1176 |
+
'finite',
|
1177 |
+
'hermitian',
|
1178 |
+
'imaginary',
|
1179 |
+
'infinite',
|
1180 |
+
'nonnegative',
|
1181 |
+
'nonpositive',
|
1182 |
+
'nonzero',
|
1183 |
+
'positive',
|
1184 |
+
'prime',
|
1185 |
+
'real',
|
1186 |
+
'zero',
|
1187 |
+
},
|
1188 |
+
|
1189 |
+
# facts that could determine the value of noninteger
|
1190 |
+
'noninteger': {
|
1191 |
+
'commutative',
|
1192 |
+
'composite',
|
1193 |
+
'even',
|
1194 |
+
'extended_real',
|
1195 |
+
'imaginary',
|
1196 |
+
'integer',
|
1197 |
+
'irrational',
|
1198 |
+
'odd',
|
1199 |
+
'prime',
|
1200 |
+
'zero',
|
1201 |
+
},
|
1202 |
+
|
1203 |
+
# facts that could determine the value of nonnegative
|
1204 |
+
'nonnegative': {
|
1205 |
+
'commutative',
|
1206 |
+
'complex',
|
1207 |
+
'composite',
|
1208 |
+
'extended_negative',
|
1209 |
+
'extended_nonnegative',
|
1210 |
+
'extended_real',
|
1211 |
+
'finite',
|
1212 |
+
'hermitian',
|
1213 |
+
'imaginary',
|
1214 |
+
'infinite',
|
1215 |
+
'negative',
|
1216 |
+
'positive',
|
1217 |
+
'prime',
|
1218 |
+
'real',
|
1219 |
+
'zero',
|
1220 |
+
},
|
1221 |
+
|
1222 |
+
# facts that could determine the value of nonpositive
|
1223 |
+
'nonpositive': {
|
1224 |
+
'commutative',
|
1225 |
+
'complex',
|
1226 |
+
'composite',
|
1227 |
+
'extended_nonpositive',
|
1228 |
+
'extended_positive',
|
1229 |
+
'extended_real',
|
1230 |
+
'finite',
|
1231 |
+
'hermitian',
|
1232 |
+
'imaginary',
|
1233 |
+
'infinite',
|
1234 |
+
'negative',
|
1235 |
+
'positive',
|
1236 |
+
'prime',
|
1237 |
+
'real',
|
1238 |
+
'zero',
|
1239 |
+
},
|
1240 |
+
|
1241 |
+
# facts that could determine the value of nonzero
|
1242 |
+
'nonzero': {
|
1243 |
+
'commutative',
|
1244 |
+
'complex',
|
1245 |
+
'composite',
|
1246 |
+
'extended_nonzero',
|
1247 |
+
'extended_real',
|
1248 |
+
'finite',
|
1249 |
+
'hermitian',
|
1250 |
+
'imaginary',
|
1251 |
+
'infinite',
|
1252 |
+
'irrational',
|
1253 |
+
'negative',
|
1254 |
+
'odd',
|
1255 |
+
'positive',
|
1256 |
+
'prime',
|
1257 |
+
'real',
|
1258 |
+
'zero',
|
1259 |
+
},
|
1260 |
+
|
1261 |
+
# facts that could determine the value of odd
|
1262 |
+
'odd': {
|
1263 |
+
'algebraic',
|
1264 |
+
'commutative',
|
1265 |
+
'complex',
|
1266 |
+
'even',
|
1267 |
+
'extended_real',
|
1268 |
+
'finite',
|
1269 |
+
'hermitian',
|
1270 |
+
'imaginary',
|
1271 |
+
'infinite',
|
1272 |
+
'integer',
|
1273 |
+
'irrational',
|
1274 |
+
'noninteger',
|
1275 |
+
'rational',
|
1276 |
+
'real',
|
1277 |
+
'transcendental',
|
1278 |
+
'zero',
|
1279 |
+
},
|
1280 |
+
|
1281 |
+
# facts that could determine the value of positive
|
1282 |
+
'positive': {
|
1283 |
+
'commutative',
|
1284 |
+
'complex',
|
1285 |
+
'composite',
|
1286 |
+
'extended_negative',
|
1287 |
+
'extended_nonnegative',
|
1288 |
+
'extended_nonpositive',
|
1289 |
+
'extended_nonzero',
|
1290 |
+
'extended_positive',
|
1291 |
+
'extended_real',
|
1292 |
+
'finite',
|
1293 |
+
'hermitian',
|
1294 |
+
'imaginary',
|
1295 |
+
'infinite',
|
1296 |
+
'negative',
|
1297 |
+
'nonnegative',
|
1298 |
+
'nonpositive',
|
1299 |
+
'nonzero',
|
1300 |
+
'prime',
|
1301 |
+
'real',
|
1302 |
+
'zero',
|
1303 |
+
},
|
1304 |
+
|
1305 |
+
# facts that could determine the value of prime
|
1306 |
+
'prime': {
|
1307 |
+
'algebraic',
|
1308 |
+
'commutative',
|
1309 |
+
'complex',
|
1310 |
+
'composite',
|
1311 |
+
'extended_negative',
|
1312 |
+
'extended_nonnegative',
|
1313 |
+
'extended_nonpositive',
|
1314 |
+
'extended_nonzero',
|
1315 |
+
'extended_positive',
|
1316 |
+
'extended_real',
|
1317 |
+
'finite',
|
1318 |
+
'hermitian',
|
1319 |
+
'imaginary',
|
1320 |
+
'infinite',
|
1321 |
+
'integer',
|
1322 |
+
'irrational',
|
1323 |
+
'negative',
|
1324 |
+
'noninteger',
|
1325 |
+
'nonnegative',
|
1326 |
+
'nonpositive',
|
1327 |
+
'nonzero',
|
1328 |
+
'positive',
|
1329 |
+
'rational',
|
1330 |
+
'real',
|
1331 |
+
'transcendental',
|
1332 |
+
'zero',
|
1333 |
+
},
|
1334 |
+
|
1335 |
+
# facts that could determine the value of rational
|
1336 |
+
'rational': {
|
1337 |
+
'algebraic',
|
1338 |
+
'commutative',
|
1339 |
+
'complex',
|
1340 |
+
'composite',
|
1341 |
+
'even',
|
1342 |
+
'extended_real',
|
1343 |
+
'finite',
|
1344 |
+
'hermitian',
|
1345 |
+
'imaginary',
|
1346 |
+
'infinite',
|
1347 |
+
'integer',
|
1348 |
+
'irrational',
|
1349 |
+
'odd',
|
1350 |
+
'prime',
|
1351 |
+
'real',
|
1352 |
+
'transcendental',
|
1353 |
+
'zero',
|
1354 |
+
},
|
1355 |
+
|
1356 |
+
# facts that could determine the value of real
|
1357 |
+
'real': {
|
1358 |
+
'commutative',
|
1359 |
+
'complex',
|
1360 |
+
'composite',
|
1361 |
+
'even',
|
1362 |
+
'extended_real',
|
1363 |
+
'finite',
|
1364 |
+
'hermitian',
|
1365 |
+
'imaginary',
|
1366 |
+
'infinite',
|
1367 |
+
'integer',
|
1368 |
+
'irrational',
|
1369 |
+
'negative',
|
1370 |
+
'nonnegative',
|
1371 |
+
'nonpositive',
|
1372 |
+
'nonzero',
|
1373 |
+
'odd',
|
1374 |
+
'positive',
|
1375 |
+
'prime',
|
1376 |
+
'rational',
|
1377 |
+
'zero',
|
1378 |
+
},
|
1379 |
+
|
1380 |
+
# facts that could determine the value of transcendental
|
1381 |
+
'transcendental': {
|
1382 |
+
'algebraic',
|
1383 |
+
'commutative',
|
1384 |
+
'complex',
|
1385 |
+
'composite',
|
1386 |
+
'even',
|
1387 |
+
'finite',
|
1388 |
+
'infinite',
|
1389 |
+
'integer',
|
1390 |
+
'odd',
|
1391 |
+
'prime',
|
1392 |
+
'rational',
|
1393 |
+
'zero',
|
1394 |
+
},
|
1395 |
+
|
1396 |
+
# facts that could determine the value of zero
|
1397 |
+
'zero': {
|
1398 |
+
'algebraic',
|
1399 |
+
'commutative',
|
1400 |
+
'complex',
|
1401 |
+
'composite',
|
1402 |
+
'even',
|
1403 |
+
'extended_negative',
|
1404 |
+
'extended_nonnegative',
|
1405 |
+
'extended_nonpositive',
|
1406 |
+
'extended_nonzero',
|
1407 |
+
'extended_positive',
|
1408 |
+
'extended_real',
|
1409 |
+
'finite',
|
1410 |
+
'hermitian',
|
1411 |
+
'imaginary',
|
1412 |
+
'infinite',
|
1413 |
+
'integer',
|
1414 |
+
'irrational',
|
1415 |
+
'negative',
|
1416 |
+
'noninteger',
|
1417 |
+
'nonnegative',
|
1418 |
+
'nonpositive',
|
1419 |
+
'nonzero',
|
1420 |
+
'odd',
|
1421 |
+
'positive',
|
1422 |
+
'prime',
|
1423 |
+
'rational',
|
1424 |
+
'real',
|
1425 |
+
'transcendental',
|
1426 |
+
},
|
1427 |
+
|
1428 |
+
} # prereq
|
1429 |
+
|
1430 |
+
|
1431 |
+
# Note: the order of the beta rules is used in the beta_triggers
|
1432 |
+
beta_rules = [
|
1433 |
+
|
1434 |
+
# Rules implying composite = True
|
1435 |
+
({('even', True), ('positive', True), ('prime', False)},
|
1436 |
+
('composite', True)),
|
1437 |
+
|
1438 |
+
# Rules implying even = False
|
1439 |
+
({('composite', False), ('positive', True), ('prime', False)},
|
1440 |
+
('even', False)),
|
1441 |
+
|
1442 |
+
# Rules implying even = True
|
1443 |
+
({('integer', True), ('odd', False)},
|
1444 |
+
('even', True)),
|
1445 |
+
|
1446 |
+
# Rules implying extended_negative = True
|
1447 |
+
({('extended_positive', False), ('extended_real', True), ('zero', False)},
|
1448 |
+
('extended_negative', True)),
|
1449 |
+
({('extended_nonpositive', True), ('extended_nonzero', True)},
|
1450 |
+
('extended_negative', True)),
|
1451 |
+
|
1452 |
+
# Rules implying extended_nonnegative = True
|
1453 |
+
({('extended_negative', False), ('extended_real', True)},
|
1454 |
+
('extended_nonnegative', True)),
|
1455 |
+
|
1456 |
+
# Rules implying extended_nonpositive = True
|
1457 |
+
({('extended_positive', False), ('extended_real', True)},
|
1458 |
+
('extended_nonpositive', True)),
|
1459 |
+
|
1460 |
+
# Rules implying extended_nonzero = True
|
1461 |
+
({('extended_real', True), ('zero', False)},
|
1462 |
+
('extended_nonzero', True)),
|
1463 |
+
|
1464 |
+
# Rules implying extended_positive = True
|
1465 |
+
({('extended_negative', False), ('extended_real', True), ('zero', False)},
|
1466 |
+
('extended_positive', True)),
|
1467 |
+
({('extended_nonnegative', True), ('extended_nonzero', True)},
|
1468 |
+
('extended_positive', True)),
|
1469 |
+
|
1470 |
+
# Rules implying extended_real = False
|
1471 |
+
({('infinite', False), ('real', False)},
|
1472 |
+
('extended_real', False)),
|
1473 |
+
({('extended_negative', False), ('extended_positive', False), ('zero', False)},
|
1474 |
+
('extended_real', False)),
|
1475 |
+
|
1476 |
+
# Rules implying infinite = True
|
1477 |
+
({('extended_real', True), ('real', False)},
|
1478 |
+
('infinite', True)),
|
1479 |
+
|
1480 |
+
# Rules implying irrational = True
|
1481 |
+
({('rational', False), ('real', True)},
|
1482 |
+
('irrational', True)),
|
1483 |
+
|
1484 |
+
# Rules implying negative = True
|
1485 |
+
({('positive', False), ('real', True), ('zero', False)},
|
1486 |
+
('negative', True)),
|
1487 |
+
({('nonpositive', True), ('nonzero', True)},
|
1488 |
+
('negative', True)),
|
1489 |
+
({('extended_negative', True), ('finite', True)},
|
1490 |
+
('negative', True)),
|
1491 |
+
|
1492 |
+
# Rules implying noninteger = True
|
1493 |
+
({('extended_real', True), ('integer', False)},
|
1494 |
+
('noninteger', True)),
|
1495 |
+
|
1496 |
+
# Rules implying nonnegative = True
|
1497 |
+
({('negative', False), ('real', True)},
|
1498 |
+
('nonnegative', True)),
|
1499 |
+
({('extended_nonnegative', True), ('finite', True)},
|
1500 |
+
('nonnegative', True)),
|
1501 |
+
|
1502 |
+
# Rules implying nonpositive = True
|
1503 |
+
({('positive', False), ('real', True)},
|
1504 |
+
('nonpositive', True)),
|
1505 |
+
({('extended_nonpositive', True), ('finite', True)},
|
1506 |
+
('nonpositive', True)),
|
1507 |
+
|
1508 |
+
# Rules implying nonzero = True
|
1509 |
+
({('extended_nonzero', True), ('finite', True)},
|
1510 |
+
('nonzero', True)),
|
1511 |
+
|
1512 |
+
# Rules implying odd = True
|
1513 |
+
({('even', False), ('integer', True)},
|
1514 |
+
('odd', True)),
|
1515 |
+
|
1516 |
+
# Rules implying positive = False
|
1517 |
+
({('composite', False), ('even', True), ('prime', False)},
|
1518 |
+
('positive', False)),
|
1519 |
+
|
1520 |
+
# Rules implying positive = True
|
1521 |
+
({('negative', False), ('real', True), ('zero', False)},
|
1522 |
+
('positive', True)),
|
1523 |
+
({('nonnegative', True), ('nonzero', True)},
|
1524 |
+
('positive', True)),
|
1525 |
+
({('extended_positive', True), ('finite', True)},
|
1526 |
+
('positive', True)),
|
1527 |
+
|
1528 |
+
# Rules implying prime = True
|
1529 |
+
({('composite', False), ('even', True), ('positive', True)},
|
1530 |
+
('prime', True)),
|
1531 |
+
|
1532 |
+
# Rules implying real = False
|
1533 |
+
({('negative', False), ('positive', False), ('zero', False)},
|
1534 |
+
('real', False)),
|
1535 |
+
|
1536 |
+
# Rules implying real = True
|
1537 |
+
({('extended_real', True), ('infinite', False)},
|
1538 |
+
('real', True)),
|
1539 |
+
({('extended_real', True), ('finite', True)},
|
1540 |
+
('real', True)),
|
1541 |
+
|
1542 |
+
# Rules implying transcendental = True
|
1543 |
+
({('algebraic', False), ('complex', True)},
|
1544 |
+
('transcendental', True)),
|
1545 |
+
|
1546 |
+
# Rules implying zero = True
|
1547 |
+
({('extended_negative', False), ('extended_positive', False), ('extended_real', True)},
|
1548 |
+
('zero', True)),
|
1549 |
+
({('negative', False), ('positive', False), ('real', True)},
|
1550 |
+
('zero', True)),
|
1551 |
+
({('extended_nonnegative', True), ('extended_nonpositive', True)},
|
1552 |
+
('zero', True)),
|
1553 |
+
({('nonnegative', True), ('nonpositive', True)},
|
1554 |
+
('zero', True)),
|
1555 |
+
|
1556 |
+
] # beta_rules
|
1557 |
+
beta_triggers = {
|
1558 |
+
('algebraic', False): [32, 11, 3, 8, 29, 14, 25, 13, 17, 7],
|
1559 |
+
('algebraic', True): [10, 30, 31, 27, 16, 21, 19, 22],
|
1560 |
+
('antihermitian', False): [],
|
1561 |
+
('commutative', False): [],
|
1562 |
+
('complex', False): [10, 12, 11, 3, 8, 17, 7],
|
1563 |
+
('complex', True): [32, 10, 30, 31, 27, 16, 21, 19, 22],
|
1564 |
+
('composite', False): [1, 28, 24],
|
1565 |
+
('composite', True): [23, 2],
|
1566 |
+
('even', False): [23, 11, 3, 8, 29, 14, 25, 7],
|
1567 |
+
('even', True): [3, 33, 8, 6, 5, 14, 34, 25, 20, 18, 27, 16, 21, 19, 22, 0, 28, 24, 7],
|
1568 |
+
('extended_negative', False): [11, 33, 8, 5, 29, 34, 25, 18],
|
1569 |
+
('extended_negative', True): [30, 12, 31, 29, 14, 20, 16, 21, 22, 17],
|
1570 |
+
('extended_nonnegative', False): [11, 3, 6, 29, 14, 20, 7],
|
1571 |
+
('extended_nonnegative', True): [30, 12, 31, 33, 8, 9, 6, 29, 34, 25, 18, 19, 35, 17, 7],
|
1572 |
+
('extended_nonpositive', False): [11, 8, 5, 29, 25, 18, 7],
|
1573 |
+
('extended_nonpositive', True): [30, 12, 31, 3, 33, 4, 5, 29, 14, 34, 20, 21, 35, 17, 7],
|
1574 |
+
('extended_nonzero', False): [11, 33, 6, 5, 29, 34, 20, 18],
|
1575 |
+
('extended_nonzero', True): [30, 12, 31, 3, 8, 4, 9, 6, 5, 29, 14, 25, 22, 17],
|
1576 |
+
('extended_positive', False): [11, 3, 33, 6, 29, 14, 34, 20],
|
1577 |
+
('extended_positive', True): [30, 12, 31, 29, 25, 18, 27, 19, 22, 17],
|
1578 |
+
('extended_real', False): [],
|
1579 |
+
('extended_real', True): [30, 12, 31, 3, 33, 8, 6, 5, 17, 7],
|
1580 |
+
('finite', False): [11, 3, 8, 17, 7],
|
1581 |
+
('finite', True): [10, 30, 31, 27, 16, 21, 19, 22],
|
1582 |
+
('hermitian', False): [10, 12, 11, 3, 8, 17, 7],
|
1583 |
+
('imaginary', True): [32],
|
1584 |
+
('infinite', False): [10, 30, 31, 27, 16, 21, 19, 22],
|
1585 |
+
('infinite', True): [11, 3, 8, 17, 7],
|
1586 |
+
('integer', False): [11, 3, 8, 29, 14, 25, 17, 7],
|
1587 |
+
('integer', True): [23, 2, 3, 33, 8, 6, 5, 14, 34, 25, 20, 18, 27, 16, 21, 19, 22, 7],
|
1588 |
+
('irrational', True): [32, 3, 8, 4, 9, 6, 5, 14, 25, 15, 26, 20, 18, 27, 16, 21, 19],
|
1589 |
+
('negative', False): [29, 34, 25, 18],
|
1590 |
+
('negative', True): [32, 13, 17],
|
1591 |
+
('noninteger', True): [30, 12, 31, 3, 8, 4, 9, 6, 5, 29, 14, 25, 22],
|
1592 |
+
('nonnegative', False): [11, 3, 8, 29, 14, 20, 7],
|
1593 |
+
('nonnegative', True): [32, 33, 8, 9, 6, 34, 25, 26, 20, 27, 21, 22, 35, 36, 13, 17, 7],
|
1594 |
+
('nonpositive', False): [11, 3, 8, 29, 25, 18, 7],
|
1595 |
+
('nonpositive', True): [32, 3, 33, 4, 5, 14, 34, 15, 18, 16, 19, 22, 35, 36, 13, 17, 7],
|
1596 |
+
('nonzero', False): [29, 34, 20, 18],
|
1597 |
+
('nonzero', True): [32, 3, 8, 4, 9, 6, 5, 14, 25, 15, 26, 20, 18, 27, 16, 21, 19, 13, 17],
|
1598 |
+
('odd', False): [2],
|
1599 |
+
('odd', True): [3, 8, 4, 9, 6, 5, 14, 25, 15, 26, 20, 18, 27, 16, 21, 19],
|
1600 |
+
('positive', False): [29, 14, 34, 20],
|
1601 |
+
('positive', True): [32, 0, 1, 28, 13, 17],
|
1602 |
+
('prime', False): [0, 1, 24],
|
1603 |
+
('prime', True): [23, 2],
|
1604 |
+
('rational', False): [11, 3, 8, 29, 14, 25, 13, 17, 7],
|
1605 |
+
('rational', True): [3, 33, 8, 6, 5, 14, 34, 25, 20, 18, 27, 16, 21, 19, 22, 17, 7],
|
1606 |
+
('real', False): [10, 12, 11, 3, 8, 17, 7],
|
1607 |
+
('real', True): [32, 3, 33, 8, 6, 5, 14, 34, 25, 20, 18, 27, 16, 21, 19, 22, 13, 17, 7],
|
1608 |
+
('transcendental', True): [10, 30, 31, 11, 3, 8, 29, 14, 25, 27, 16, 21, 19, 22, 13, 17, 7],
|
1609 |
+
('zero', False): [11, 3, 8, 29, 14, 25, 7],
|
1610 |
+
('zero', True): [],
|
1611 |
+
} # beta_triggers
|
1612 |
+
|
1613 |
+
|
1614 |
+
generated_assumptions = {'defined_facts': defined_facts, 'full_implications': full_implications,
|
1615 |
+
'prereq': prereq, 'beta_rules': beta_rules, 'beta_triggers': beta_triggers}
|
env-llmeval/lib/python3.10/site-packages/sympy/core/decorators.py
ADDED
@@ -0,0 +1,238 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
SymPy core decorators.
|
3 |
+
|
4 |
+
The purpose of this module is to expose decorators without any other
|
5 |
+
dependencies, so that they can be easily imported anywhere in sympy/core.
|
6 |
+
"""
|
7 |
+
|
8 |
+
from functools import wraps
|
9 |
+
from .sympify import SympifyError, sympify
|
10 |
+
|
11 |
+
|
12 |
+
def _sympifyit(arg, retval=None):
|
13 |
+
"""
|
14 |
+
decorator to smartly _sympify function arguments
|
15 |
+
|
16 |
+
Explanation
|
17 |
+
===========
|
18 |
+
|
19 |
+
@_sympifyit('other', NotImplemented)
|
20 |
+
def add(self, other):
|
21 |
+
...
|
22 |
+
|
23 |
+
In add, other can be thought of as already being a SymPy object.
|
24 |
+
|
25 |
+
If it is not, the code is likely to catch an exception, then other will
|
26 |
+
be explicitly _sympified, and the whole code restarted.
|
27 |
+
|
28 |
+
if _sympify(arg) fails, NotImplemented will be returned
|
29 |
+
|
30 |
+
See also
|
31 |
+
========
|
32 |
+
|
33 |
+
__sympifyit
|
34 |
+
"""
|
35 |
+
def deco(func):
|
36 |
+
return __sympifyit(func, arg, retval)
|
37 |
+
|
38 |
+
return deco
|
39 |
+
|
40 |
+
|
41 |
+
def __sympifyit(func, arg, retval=None):
|
42 |
+
"""Decorator to _sympify `arg` argument for function `func`.
|
43 |
+
|
44 |
+
Do not use directly -- use _sympifyit instead.
|
45 |
+
"""
|
46 |
+
|
47 |
+
# we support f(a,b) only
|
48 |
+
if not func.__code__.co_argcount:
|
49 |
+
raise LookupError("func not found")
|
50 |
+
# only b is _sympified
|
51 |
+
assert func.__code__.co_varnames[1] == arg
|
52 |
+
if retval is None:
|
53 |
+
@wraps(func)
|
54 |
+
def __sympifyit_wrapper(a, b):
|
55 |
+
return func(a, sympify(b, strict=True))
|
56 |
+
|
57 |
+
else:
|
58 |
+
@wraps(func)
|
59 |
+
def __sympifyit_wrapper(a, b):
|
60 |
+
try:
|
61 |
+
# If an external class has _op_priority, it knows how to deal
|
62 |
+
# with SymPy objects. Otherwise, it must be converted.
|
63 |
+
if not hasattr(b, '_op_priority'):
|
64 |
+
b = sympify(b, strict=True)
|
65 |
+
return func(a, b)
|
66 |
+
except SympifyError:
|
67 |
+
return retval
|
68 |
+
|
69 |
+
return __sympifyit_wrapper
|
70 |
+
|
71 |
+
|
72 |
+
def call_highest_priority(method_name):
|
73 |
+
"""A decorator for binary special methods to handle _op_priority.
|
74 |
+
|
75 |
+
Explanation
|
76 |
+
===========
|
77 |
+
|
78 |
+
Binary special methods in Expr and its subclasses use a special attribute
|
79 |
+
'_op_priority' to determine whose special method will be called to
|
80 |
+
handle the operation. In general, the object having the highest value of
|
81 |
+
'_op_priority' will handle the operation. Expr and subclasses that define
|
82 |
+
custom binary special methods (__mul__, etc.) should decorate those
|
83 |
+
methods with this decorator to add the priority logic.
|
84 |
+
|
85 |
+
The ``method_name`` argument is the name of the method of the other class
|
86 |
+
that will be called. Use this decorator in the following manner::
|
87 |
+
|
88 |
+
# Call other.__rmul__ if other._op_priority > self._op_priority
|
89 |
+
@call_highest_priority('__rmul__')
|
90 |
+
def __mul__(self, other):
|
91 |
+
...
|
92 |
+
|
93 |
+
# Call other.__mul__ if other._op_priority > self._op_priority
|
94 |
+
@call_highest_priority('__mul__')
|
95 |
+
def __rmul__(self, other):
|
96 |
+
...
|
97 |
+
"""
|
98 |
+
def priority_decorator(func):
|
99 |
+
@wraps(func)
|
100 |
+
def binary_op_wrapper(self, other):
|
101 |
+
if hasattr(other, '_op_priority'):
|
102 |
+
if other._op_priority > self._op_priority:
|
103 |
+
f = getattr(other, method_name, None)
|
104 |
+
if f is not None:
|
105 |
+
return f(self)
|
106 |
+
return func(self, other)
|
107 |
+
return binary_op_wrapper
|
108 |
+
return priority_decorator
|
109 |
+
|
110 |
+
|
111 |
+
def sympify_method_args(cls):
|
112 |
+
'''Decorator for a class with methods that sympify arguments.
|
113 |
+
|
114 |
+
Explanation
|
115 |
+
===========
|
116 |
+
|
117 |
+
The sympify_method_args decorator is to be used with the sympify_return
|
118 |
+
decorator for automatic sympification of method arguments. This is
|
119 |
+
intended for the common idiom of writing a class like :
|
120 |
+
|
121 |
+
Examples
|
122 |
+
========
|
123 |
+
|
124 |
+
>>> from sympy import Basic, SympifyError, S
|
125 |
+
>>> from sympy.core.sympify import _sympify
|
126 |
+
|
127 |
+
>>> class MyTuple(Basic):
|
128 |
+
... def __add__(self, other):
|
129 |
+
... try:
|
130 |
+
... other = _sympify(other)
|
131 |
+
... except SympifyError:
|
132 |
+
... return NotImplemented
|
133 |
+
... if not isinstance(other, MyTuple):
|
134 |
+
... return NotImplemented
|
135 |
+
... return MyTuple(*(self.args + other.args))
|
136 |
+
|
137 |
+
>>> MyTuple(S(1), S(2)) + MyTuple(S(3), S(4))
|
138 |
+
MyTuple(1, 2, 3, 4)
|
139 |
+
|
140 |
+
In the above it is important that we return NotImplemented when other is
|
141 |
+
not sympifiable and also when the sympified result is not of the expected
|
142 |
+
type. This allows the MyTuple class to be used cooperatively with other
|
143 |
+
classes that overload __add__ and want to do something else in combination
|
144 |
+
with instance of Tuple.
|
145 |
+
|
146 |
+
Using this decorator the above can be written as
|
147 |
+
|
148 |
+
>>> from sympy.core.decorators import sympify_method_args, sympify_return
|
149 |
+
|
150 |
+
>>> @sympify_method_args
|
151 |
+
... class MyTuple(Basic):
|
152 |
+
... @sympify_return([('other', 'MyTuple')], NotImplemented)
|
153 |
+
... def __add__(self, other):
|
154 |
+
... return MyTuple(*(self.args + other.args))
|
155 |
+
|
156 |
+
>>> MyTuple(S(1), S(2)) + MyTuple(S(3), S(4))
|
157 |
+
MyTuple(1, 2, 3, 4)
|
158 |
+
|
159 |
+
The idea here is that the decorators take care of the boiler-plate code
|
160 |
+
for making this happen in each method that potentially needs to accept
|
161 |
+
unsympified arguments. Then the body of e.g. the __add__ method can be
|
162 |
+
written without needing to worry about calling _sympify or checking the
|
163 |
+
type of the resulting object.
|
164 |
+
|
165 |
+
The parameters for sympify_return are a list of tuples of the form
|
166 |
+
(parameter_name, expected_type) and the value to return (e.g.
|
167 |
+
NotImplemented). The expected_type parameter can be a type e.g. Tuple or a
|
168 |
+
string 'Tuple'. Using a string is useful for specifying a Type within its
|
169 |
+
class body (as in the above example).
|
170 |
+
|
171 |
+
Notes: Currently sympify_return only works for methods that take a single
|
172 |
+
argument (not including self). Specifying an expected_type as a string
|
173 |
+
only works for the class in which the method is defined.
|
174 |
+
'''
|
175 |
+
# Extract the wrapped methods from each of the wrapper objects created by
|
176 |
+
# the sympify_return decorator. Doing this here allows us to provide the
|
177 |
+
# cls argument which is used for forward string referencing.
|
178 |
+
for attrname, obj in cls.__dict__.items():
|
179 |
+
if isinstance(obj, _SympifyWrapper):
|
180 |
+
setattr(cls, attrname, obj.make_wrapped(cls))
|
181 |
+
return cls
|
182 |
+
|
183 |
+
|
184 |
+
def sympify_return(*args):
|
185 |
+
'''Function/method decorator to sympify arguments automatically
|
186 |
+
|
187 |
+
See the docstring of sympify_method_args for explanation.
|
188 |
+
'''
|
189 |
+
# Store a wrapper object for the decorated method
|
190 |
+
def wrapper(func):
|
191 |
+
return _SympifyWrapper(func, args)
|
192 |
+
return wrapper
|
193 |
+
|
194 |
+
|
195 |
+
class _SympifyWrapper:
|
196 |
+
'''Internal class used by sympify_return and sympify_method_args'''
|
197 |
+
|
198 |
+
def __init__(self, func, args):
|
199 |
+
self.func = func
|
200 |
+
self.args = args
|
201 |
+
|
202 |
+
def make_wrapped(self, cls):
|
203 |
+
func = self.func
|
204 |
+
parameters, retval = self.args
|
205 |
+
|
206 |
+
# XXX: Handle more than one parameter?
|
207 |
+
[(parameter, expectedcls)] = parameters
|
208 |
+
|
209 |
+
# Handle forward references to the current class using strings
|
210 |
+
if expectedcls == cls.__name__:
|
211 |
+
expectedcls = cls
|
212 |
+
|
213 |
+
# Raise RuntimeError since this is a failure at import time and should
|
214 |
+
# not be recoverable.
|
215 |
+
nargs = func.__code__.co_argcount
|
216 |
+
# we support f(a, b) only
|
217 |
+
if nargs != 2:
|
218 |
+
raise RuntimeError('sympify_return can only be used with 2 argument functions')
|
219 |
+
# only b is _sympified
|
220 |
+
if func.__code__.co_varnames[1] != parameter:
|
221 |
+
raise RuntimeError('parameter name mismatch "%s" in %s' %
|
222 |
+
(parameter, func.__name__))
|
223 |
+
|
224 |
+
@wraps(func)
|
225 |
+
def _func(self, other):
|
226 |
+
# XXX: The check for _op_priority here should be removed. It is
|
227 |
+
# needed to stop mutable matrices from being sympified to
|
228 |
+
# immutable matrices which breaks things in quantum...
|
229 |
+
if not hasattr(other, '_op_priority'):
|
230 |
+
try:
|
231 |
+
other = sympify(other, strict=True)
|
232 |
+
except SympifyError:
|
233 |
+
return retval
|
234 |
+
if not isinstance(other, expectedcls):
|
235 |
+
return retval
|
236 |
+
return func(self, other)
|
237 |
+
|
238 |
+
return _func
|
env-llmeval/lib/python3.10/site-packages/sympy/core/expr.py
ADDED
The diff for this file is too large to render.
See raw diff
|
|
env-llmeval/lib/python3.10/site-packages/sympy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
|
|
|
|
|
|
|
|
|
|
1 |
+
from .add import Add
|
2 |
+
from .exprtools import gcd_terms
|
3 |
+
from .function import Function
|
4 |
+
from .kind import NumberKind
|
5 |
+
from .logic import fuzzy_and, fuzzy_not
|
6 |
+
from .mul import Mul
|
7 |
+
from .numbers import equal_valued
|
8 |
+
from .singleton import S
|
9 |
+
|
10 |
+
|
11 |
+
class Mod(Function):
|
12 |
+
"""Represents a modulo operation on symbolic expressions.
|
13 |
+
|
14 |
+
Parameters
|
15 |
+
==========
|
16 |
+
|
17 |
+
p : Expr
|
18 |
+
Dividend.
|
19 |
+
|
20 |
+
q : Expr
|
21 |
+
Divisor.
|
22 |
+
|
23 |
+
Notes
|
24 |
+
=====
|
25 |
+
|
26 |
+
The convention used is the same as Python's: the remainder always has the
|
27 |
+
same sign as the divisor.
|
28 |
+
|
29 |
+
Examples
|
30 |
+
========
|
31 |
+
|
32 |
+
>>> from sympy.abc import x, y
|
33 |
+
>>> x**2 % y
|
34 |
+
Mod(x**2, y)
|
35 |
+
>>> _.subs({x: 5, y: 6})
|
36 |
+
1
|
37 |
+
|
38 |
+
"""
|
39 |
+
|
40 |
+
kind = NumberKind
|
41 |
+
|
42 |
+
@classmethod
|
43 |
+
def eval(cls, p, q):
|
44 |
+
def number_eval(p, q):
|
45 |
+
"""Try to return p % q if both are numbers or +/-p is known
|
46 |
+
to be less than or equal q.
|
47 |
+
"""
|
48 |
+
|
49 |
+
if q.is_zero:
|
50 |
+
raise ZeroDivisionError("Modulo by zero")
|
51 |
+
if p is S.NaN or q is S.NaN or p.is_finite is False or q.is_finite is False:
|
52 |
+
return S.NaN
|
53 |
+
if p is S.Zero or p in (q, -q) or (p.is_integer and q == 1):
|
54 |
+
return S.Zero
|
55 |
+
|
56 |
+
if q.is_Number:
|
57 |
+
if p.is_Number:
|
58 |
+
return p%q
|
59 |
+
if q == 2:
|
60 |
+
if p.is_even:
|
61 |
+
return S.Zero
|
62 |
+
elif p.is_odd:
|
63 |
+
return S.One
|
64 |
+
|
65 |
+
if hasattr(p, '_eval_Mod'):
|
66 |
+
rv = getattr(p, '_eval_Mod')(q)
|
67 |
+
if rv is not None:
|
68 |
+
return rv
|
69 |
+
|
70 |
+
# by ratio
|
71 |
+
r = p/q
|
72 |
+
if r.is_integer:
|
73 |
+
return S.Zero
|
74 |
+
try:
|
75 |
+
d = int(r)
|
76 |
+
except TypeError:
|
77 |
+
pass
|
78 |
+
else:
|
79 |
+
if isinstance(d, int):
|
80 |
+
rv = p - d*q
|
81 |
+
if (rv*q < 0) == True:
|
82 |
+
rv += q
|
83 |
+
return rv
|
84 |
+
|
85 |
+
# by difference
|
86 |
+
# -2|q| < p < 2|q|
|
87 |
+
d = abs(p)
|
88 |
+
for _ in range(2):
|
89 |
+
d -= abs(q)
|
90 |
+
if d.is_negative:
|
91 |
+
if q.is_positive:
|
92 |
+
if p.is_positive:
|
93 |
+
return d + q
|
94 |
+
elif p.is_negative:
|
95 |
+
return -d
|
96 |
+
elif q.is_negative:
|
97 |
+
if p.is_positive:
|
98 |
+
return d
|
99 |
+
elif p.is_negative:
|
100 |
+
return -d + q
|
101 |
+
break
|
102 |
+
|
103 |
+
rv = number_eval(p, q)
|
104 |
+
if rv is not None:
|
105 |
+
return rv
|
106 |
+
|
107 |
+
# denest
|
108 |
+
if isinstance(p, cls):
|
109 |
+
qinner = p.args[1]
|
110 |
+
if qinner % q == 0:
|
111 |
+
return cls(p.args[0], q)
|
112 |
+
elif (qinner*(q - qinner)).is_nonnegative:
|
113 |
+
# |qinner| < |q| and have same sign
|
114 |
+
return p
|
115 |
+
elif isinstance(-p, cls):
|
116 |
+
qinner = (-p).args[1]
|
117 |
+
if qinner % q == 0:
|
118 |
+
return cls(-(-p).args[0], q)
|
119 |
+
elif (qinner*(q + qinner)).is_nonpositive:
|
120 |
+
# |qinner| < |q| and have different sign
|
121 |
+
return p
|
122 |
+
elif isinstance(p, Add):
|
123 |
+
# separating into modulus and non modulus
|
124 |
+
both_l = non_mod_l, mod_l = [], []
|
125 |
+
for arg in p.args:
|
126 |
+
both_l[isinstance(arg, cls)].append(arg)
|
127 |
+
# if q same for all
|
128 |
+
if mod_l and all(inner.args[1] == q for inner in mod_l):
|
129 |
+
net = Add(*non_mod_l) + Add(*[i.args[0] for i in mod_l])
|
130 |
+
return cls(net, q)
|
131 |
+
|
132 |
+
elif isinstance(p, Mul):
|
133 |
+
# separating into modulus and non modulus
|
134 |
+
both_l = non_mod_l, mod_l = [], []
|
135 |
+
for arg in p.args:
|
136 |
+
both_l[isinstance(arg, cls)].append(arg)
|
137 |
+
|
138 |
+
if mod_l and all(inner.args[1] == q for inner in mod_l) and all(t.is_integer for t in p.args) and q.is_integer:
|
139 |
+
# finding distributive term
|
140 |
+
non_mod_l = [cls(x, q) for x in non_mod_l]
|
141 |
+
mod = []
|
142 |
+
non_mod = []
|
143 |
+
for j in non_mod_l:
|
144 |
+
if isinstance(j, cls):
|
145 |
+
mod.append(j.args[0])
|
146 |
+
else:
|
147 |
+
non_mod.append(j)
|
148 |
+
prod_mod = Mul(*mod)
|
149 |
+
prod_non_mod = Mul(*non_mod)
|
150 |
+
prod_mod1 = Mul(*[i.args[0] for i in mod_l])
|
151 |
+
net = prod_mod1*prod_mod
|
152 |
+
return prod_non_mod*cls(net, q)
|
153 |
+
|
154 |
+
if q.is_Integer and q is not S.One:
|
155 |
+
non_mod_l = [i % q if i.is_Integer and (i % q is not S.Zero) else i for
|
156 |
+
i in non_mod_l]
|
157 |
+
|
158 |
+
p = Mul(*(non_mod_l + mod_l))
|
159 |
+
|
160 |
+
# XXX other possibilities?
|
161 |
+
|
162 |
+
from sympy.polys.polyerrors import PolynomialError
|
163 |
+
from sympy.polys.polytools import gcd
|
164 |
+
|
165 |
+
# extract gcd; any further simplification should be done by the user
|
166 |
+
try:
|
167 |
+
G = gcd(p, q)
|
168 |
+
if not equal_valued(G, 1):
|
169 |
+
p, q = [gcd_terms(i/G, clear=False, fraction=False)
|
170 |
+
for i in (p, q)]
|
171 |
+
except PolynomialError: # issue 21373
|
172 |
+
G = S.One
|
173 |
+
pwas, qwas = p, q
|
174 |
+
|
175 |
+
# simplify terms
|
176 |
+
# (x + y + 2) % x -> Mod(y + 2, x)
|
177 |
+
if p.is_Add:
|
178 |
+
args = []
|
179 |
+
for i in p.args:
|
180 |
+
a = cls(i, q)
|
181 |
+
if a.count(cls) > i.count(cls):
|
182 |
+
args.append(i)
|
183 |
+
else:
|
184 |
+
args.append(a)
|
185 |
+
if args != list(p.args):
|
186 |
+
p = Add(*args)
|
187 |
+
|
188 |
+
else:
|
189 |
+
# handle coefficients if they are not Rational
|
190 |
+
# since those are not handled by factor_terms
|
191 |
+
# e.g. Mod(.6*x, .3*y) -> 0.3*Mod(2*x, y)
|
192 |
+
cp, p = p.as_coeff_Mul()
|
193 |
+
cq, q = q.as_coeff_Mul()
|
194 |
+
ok = False
|
195 |
+
if not cp.is_Rational or not cq.is_Rational:
|
196 |
+
r = cp % cq
|
197 |
+
if equal_valued(r, 0):
|
198 |
+
G *= cq
|
199 |
+
p *= int(cp/cq)
|
200 |
+
ok = True
|
201 |
+
if not ok:
|
202 |
+
p = cp*p
|
203 |
+
q = cq*q
|
204 |
+
|
205 |
+
# simple -1 extraction
|
206 |
+
if p.could_extract_minus_sign() and q.could_extract_minus_sign():
|
207 |
+
G, p, q = [-i for i in (G, p, q)]
|
208 |
+
|
209 |
+
# check again to see if p and q can now be handled as numbers
|
210 |
+
rv = number_eval(p, q)
|
211 |
+
if rv is not None:
|
212 |
+
return rv*G
|
213 |
+
|
214 |
+
# put 1.0 from G on inside
|
215 |
+
if G.is_Float and equal_valued(G, 1):
|
216 |
+
p *= G
|
217 |
+
return cls(p, q, evaluate=False)
|
218 |
+
elif G.is_Mul and G.args[0].is_Float and equal_valued(G.args[0], 1):
|
219 |
+
p = G.args[0]*p
|
220 |
+
G = Mul._from_args(G.args[1:])
|
221 |
+
return G*cls(p, q, evaluate=(p, q) != (pwas, qwas))
|
222 |
+
|
223 |
+
def _eval_is_integer(self):
|
224 |
+
p, q = self.args
|
225 |
+
if fuzzy_and([p.is_integer, q.is_integer, fuzzy_not(q.is_zero)]):
|
226 |
+
return True
|
227 |
+
|
228 |
+
def _eval_is_nonnegative(self):
|
229 |
+
if self.args[1].is_positive:
|
230 |
+
return True
|
231 |
+
|
232 |
+
def _eval_is_nonpositive(self):
|
233 |
+
if self.args[1].is_negative:
|
234 |
+
return True
|
235 |
+
|
236 |
+
def _eval_rewrite_as_floor(self, a, b, **kwargs):
|
237 |
+
from sympy.functions.elementary.integers import floor
|
238 |
+
return a - b*floor(a/b)
|
env-llmeval/lib/python3.10/site-packages/sympy/core/multidimensional.py
ADDED
@@ -0,0 +1,131 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Provides functionality for multidimensional usage of scalar-functions.
|
3 |
+
|
4 |
+
Read the vectorize docstring for more details.
|
5 |
+
"""
|
6 |
+
|
7 |
+
from functools import wraps
|
8 |
+
|
9 |
+
|
10 |
+
def apply_on_element(f, args, kwargs, n):
|
11 |
+
"""
|
12 |
+
Returns a structure with the same dimension as the specified argument,
|
13 |
+
where each basic element is replaced by the function f applied on it. All
|
14 |
+
other arguments stay the same.
|
15 |
+
"""
|
16 |
+
# Get the specified argument.
|
17 |
+
if isinstance(n, int):
|
18 |
+
structure = args[n]
|
19 |
+
is_arg = True
|
20 |
+
elif isinstance(n, str):
|
21 |
+
structure = kwargs[n]
|
22 |
+
is_arg = False
|
23 |
+
|
24 |
+
# Define reduced function that is only dependent on the specified argument.
|
25 |
+
def f_reduced(x):
|
26 |
+
if hasattr(x, "__iter__"):
|
27 |
+
return list(map(f_reduced, x))
|
28 |
+
else:
|
29 |
+
if is_arg:
|
30 |
+
args[n] = x
|
31 |
+
else:
|
32 |
+
kwargs[n] = x
|
33 |
+
return f(*args, **kwargs)
|
34 |
+
|
35 |
+
# f_reduced will call itself recursively so that in the end f is applied to
|
36 |
+
# all basic elements.
|
37 |
+
return list(map(f_reduced, structure))
|
38 |
+
|
39 |
+
|
40 |
+
def iter_copy(structure):
|
41 |
+
"""
|
42 |
+
Returns a copy of an iterable object (also copying all embedded iterables).
|
43 |
+
"""
|
44 |
+
return [iter_copy(i) if hasattr(i, "__iter__") else i for i in structure]
|
45 |
+
|
46 |
+
|
47 |
+
def structure_copy(structure):
|
48 |
+
"""
|
49 |
+
Returns a copy of the given structure (numpy-array, list, iterable, ..).
|
50 |
+
"""
|
51 |
+
if hasattr(structure, "copy"):
|
52 |
+
return structure.copy()
|
53 |
+
return iter_copy(structure)
|
54 |
+
|
55 |
+
|
56 |
+
class vectorize:
|
57 |
+
"""
|
58 |
+
Generalizes a function taking scalars to accept multidimensional arguments.
|
59 |
+
|
60 |
+
Examples
|
61 |
+
========
|
62 |
+
|
63 |
+
>>> from sympy import vectorize, diff, sin, symbols, Function
|
64 |
+
>>> x, y, z = symbols('x y z')
|
65 |
+
>>> f, g, h = list(map(Function, 'fgh'))
|
66 |
+
|
67 |
+
>>> @vectorize(0)
|
68 |
+
... def vsin(x):
|
69 |
+
... return sin(x)
|
70 |
+
|
71 |
+
>>> vsin([1, x, y])
|
72 |
+
[sin(1), sin(x), sin(y)]
|
73 |
+
|
74 |
+
>>> @vectorize(0, 1)
|
75 |
+
... def vdiff(f, y):
|
76 |
+
... return diff(f, y)
|
77 |
+
|
78 |
+
>>> vdiff([f(x, y, z), g(x, y, z), h(x, y, z)], [x, y, z])
|
79 |
+
[[Derivative(f(x, y, z), x), Derivative(f(x, y, z), y), Derivative(f(x, y, z), z)], [Derivative(g(x, y, z), x), Derivative(g(x, y, z), y), Derivative(g(x, y, z), z)], [Derivative(h(x, y, z), x), Derivative(h(x, y, z), y), Derivative(h(x, y, z), z)]]
|
80 |
+
"""
|
81 |
+
def __init__(self, *mdargs):
|
82 |
+
"""
|
83 |
+
The given numbers and strings characterize the arguments that will be
|
84 |
+
treated as data structures, where the decorated function will be applied
|
85 |
+
to every single element.
|
86 |
+
If no argument is given, everything is treated multidimensional.
|
87 |
+
"""
|
88 |
+
for a in mdargs:
|
89 |
+
if not isinstance(a, (int, str)):
|
90 |
+
raise TypeError("a is of invalid type")
|
91 |
+
self.mdargs = mdargs
|
92 |
+
|
93 |
+
def __call__(self, f):
|
94 |
+
"""
|
95 |
+
Returns a wrapper for the one-dimensional function that can handle
|
96 |
+
multidimensional arguments.
|
97 |
+
"""
|
98 |
+
@wraps(f)
|
99 |
+
def wrapper(*args, **kwargs):
|
100 |
+
# Get arguments that should be treated multidimensional
|
101 |
+
if self.mdargs:
|
102 |
+
mdargs = self.mdargs
|
103 |
+
else:
|
104 |
+
mdargs = range(len(args)) + kwargs.keys()
|
105 |
+
|
106 |
+
arglength = len(args)
|
107 |
+
|
108 |
+
for n in mdargs:
|
109 |
+
if isinstance(n, int):
|
110 |
+
if n >= arglength:
|
111 |
+
continue
|
112 |
+
entry = args[n]
|
113 |
+
is_arg = True
|
114 |
+
elif isinstance(n, str):
|
115 |
+
try:
|
116 |
+
entry = kwargs[n]
|
117 |
+
except KeyError:
|
118 |
+
continue
|
119 |
+
is_arg = False
|
120 |
+
if hasattr(entry, "__iter__"):
|
121 |
+
# Create now a copy of the given array and manipulate then
|
122 |
+
# the entries directly.
|
123 |
+
if is_arg:
|
124 |
+
args = list(args)
|
125 |
+
args[n] = structure_copy(entry)
|
126 |
+
else:
|
127 |
+
kwargs[n] = structure_copy(entry)
|
128 |
+
result = apply_on_element(wrapper, args, kwargs, n)
|
129 |
+
return result
|
130 |
+
return f(*args, **kwargs)
|
131 |
+
return wrapper
|
env-llmeval/lib/python3.10/site-packages/sympy/core/power.py
ADDED
@@ -0,0 +1,2004 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from __future__ import annotations
|
2 |
+
from typing import Callable
|
3 |
+
from math import log as _log, sqrt as _sqrt
|
4 |
+
from itertools import product
|
5 |
+
|
6 |
+
from .sympify import _sympify
|
7 |
+
from .cache import cacheit
|
8 |
+
from .singleton import S
|
9 |
+
from .expr import Expr
|
10 |
+
from .evalf import PrecisionExhausted
|
11 |
+
from .function import (expand_complex, expand_multinomial,
|
12 |
+
expand_mul, _mexpand, PoleError)
|
13 |
+
from .logic import fuzzy_bool, fuzzy_not, fuzzy_and, fuzzy_or
|
14 |
+
from .parameters import global_parameters
|
15 |
+
from .relational import is_gt, is_lt
|
16 |
+
from .kind import NumberKind, UndefinedKind
|
17 |
+
from sympy.external.gmpy import HAS_GMPY, gmpy
|
18 |
+
from sympy.utilities.iterables import sift
|
19 |
+
from sympy.utilities.exceptions import sympy_deprecation_warning
|
20 |
+
from sympy.utilities.misc import as_int
|
21 |
+
from sympy.multipledispatch import Dispatcher
|
22 |
+
|
23 |
+
from mpmath.libmp import sqrtrem as mpmath_sqrtrem
|
24 |
+
|
25 |
+
|
26 |
+
|
27 |
+
def isqrt(n):
|
28 |
+
"""Return the largest integer less than or equal to sqrt(n)."""
|
29 |
+
if n < 0:
|
30 |
+
raise ValueError("n must be nonnegative")
|
31 |
+
n = int(n)
|
32 |
+
|
33 |
+
# Fast path: with IEEE 754 binary64 floats and a correctly-rounded
|
34 |
+
# math.sqrt, int(math.sqrt(n)) works for any integer n satisfying 0 <= n <
|
35 |
+
# 4503599761588224 = 2**52 + 2**27. But Python doesn't guarantee either
|
36 |
+
# IEEE 754 format floats *or* correct rounding of math.sqrt, so check the
|
37 |
+
# answer and fall back to the slow method if necessary.
|
38 |
+
if n < 4503599761588224:
|
39 |
+
s = int(_sqrt(n))
|
40 |
+
if 0 <= n - s*s <= 2*s:
|
41 |
+
return s
|
42 |
+
|
43 |
+
return integer_nthroot(n, 2)[0]
|
44 |
+
|
45 |
+
|
46 |
+
def integer_nthroot(y, n):
|
47 |
+
"""
|
48 |
+
Return a tuple containing x = floor(y**(1/n))
|
49 |
+
and a boolean indicating whether the result is exact (that is,
|
50 |
+
whether x**n == y).
|
51 |
+
|
52 |
+
Examples
|
53 |
+
========
|
54 |
+
|
55 |
+
>>> from sympy import integer_nthroot
|
56 |
+
>>> integer_nthroot(16, 2)
|
57 |
+
(4, True)
|
58 |
+
>>> integer_nthroot(26, 2)
|
59 |
+
(5, False)
|
60 |
+
|
61 |
+
To simply determine if a number is a perfect square, the is_square
|
62 |
+
function should be used:
|
63 |
+
|
64 |
+
>>> from sympy.ntheory.primetest import is_square
|
65 |
+
>>> is_square(26)
|
66 |
+
False
|
67 |
+
|
68 |
+
See Also
|
69 |
+
========
|
70 |
+
sympy.ntheory.primetest.is_square
|
71 |
+
integer_log
|
72 |
+
"""
|
73 |
+
y, n = as_int(y), as_int(n)
|
74 |
+
if y < 0:
|
75 |
+
raise ValueError("y must be nonnegative")
|
76 |
+
if n < 1:
|
77 |
+
raise ValueError("n must be positive")
|
78 |
+
if HAS_GMPY and n < 2**63:
|
79 |
+
# Currently it works only for n < 2**63, else it produces TypeError
|
80 |
+
# sympy issue: https://github.com/sympy/sympy/issues/18374
|
81 |
+
# gmpy2 issue: https://github.com/aleaxit/gmpy/issues/257
|
82 |
+
if HAS_GMPY >= 2:
|
83 |
+
x, t = gmpy.iroot(y, n)
|
84 |
+
else:
|
85 |
+
x, t = gmpy.root(y, n)
|
86 |
+
return as_int(x), bool(t)
|
87 |
+
return _integer_nthroot_python(y, n)
|
88 |
+
|
89 |
+
def _integer_nthroot_python(y, n):
|
90 |
+
if y in (0, 1):
|
91 |
+
return y, True
|
92 |
+
if n == 1:
|
93 |
+
return y, True
|
94 |
+
if n == 2:
|
95 |
+
x, rem = mpmath_sqrtrem(y)
|
96 |
+
return int(x), not rem
|
97 |
+
if n >= y.bit_length():
|
98 |
+
return 1, False
|
99 |
+
# Get initial estimate for Newton's method. Care must be taken to
|
100 |
+
# avoid overflow
|
101 |
+
try:
|
102 |
+
guess = int(y**(1./n) + 0.5)
|
103 |
+
except OverflowError:
|
104 |
+
exp = _log(y, 2)/n
|
105 |
+
if exp > 53:
|
106 |
+
shift = int(exp - 53)
|
107 |
+
guess = int(2.0**(exp - shift) + 1) << shift
|
108 |
+
else:
|
109 |
+
guess = int(2.0**exp)
|
110 |
+
if guess > 2**50:
|
111 |
+
# Newton iteration
|
112 |
+
xprev, x = -1, guess
|
113 |
+
while 1:
|
114 |
+
t = x**(n - 1)
|
115 |
+
xprev, x = x, ((n - 1)*x + y//t)//n
|
116 |
+
if abs(x - xprev) < 2:
|
117 |
+
break
|
118 |
+
else:
|
119 |
+
x = guess
|
120 |
+
# Compensate
|
121 |
+
t = x**n
|
122 |
+
while t < y:
|
123 |
+
x += 1
|
124 |
+
t = x**n
|
125 |
+
while t > y:
|
126 |
+
x -= 1
|
127 |
+
t = x**n
|
128 |
+
return int(x), t == y # int converts long to int if possible
|
129 |
+
|
130 |
+
|
131 |
+
def integer_log(y, x):
|
132 |
+
r"""
|
133 |
+
Returns ``(e, bool)`` where e is the largest nonnegative integer
|
134 |
+
such that :math:`|y| \geq |x^e|` and ``bool`` is True if $y = x^e$.
|
135 |
+
|
136 |
+
Examples
|
137 |
+
========
|
138 |
+
|
139 |
+
>>> from sympy import integer_log
|
140 |
+
>>> integer_log(125, 5)
|
141 |
+
(3, True)
|
142 |
+
>>> integer_log(17, 9)
|
143 |
+
(1, False)
|
144 |
+
>>> integer_log(4, -2)
|
145 |
+
(2, True)
|
146 |
+
>>> integer_log(-125,-5)
|
147 |
+
(3, True)
|
148 |
+
|
149 |
+
See Also
|
150 |
+
========
|
151 |
+
integer_nthroot
|
152 |
+
sympy.ntheory.primetest.is_square
|
153 |
+
sympy.ntheory.factor_.multiplicity
|
154 |
+
sympy.ntheory.factor_.perfect_power
|
155 |
+
"""
|
156 |
+
if x == 1:
|
157 |
+
raise ValueError('x cannot take value as 1')
|
158 |
+
if y == 0:
|
159 |
+
raise ValueError('y cannot take value as 0')
|
160 |
+
|
161 |
+
if x in (-2, 2):
|
162 |
+
x = int(x)
|
163 |
+
y = as_int(y)
|
164 |
+
e = y.bit_length() - 1
|
165 |
+
return e, x**e == y
|
166 |
+
if x < 0:
|
167 |
+
n, b = integer_log(y if y > 0 else -y, -x)
|
168 |
+
return n, b and bool(n % 2 if y < 0 else not n % 2)
|
169 |
+
|
170 |
+
x = as_int(x)
|
171 |
+
y = as_int(y)
|
172 |
+
r = e = 0
|
173 |
+
while y >= x:
|
174 |
+
d = x
|
175 |
+
m = 1
|
176 |
+
while y >= d:
|
177 |
+
y, rem = divmod(y, d)
|
178 |
+
r = r or rem
|
179 |
+
e += m
|
180 |
+
if y > d:
|
181 |
+
d *= d
|
182 |
+
m *= 2
|
183 |
+
return e, r == 0 and y == 1
|
184 |
+
|
185 |
+
|
186 |
+
class Pow(Expr):
|
187 |
+
"""
|
188 |
+
Defines the expression x**y as "x raised to a power y"
|
189 |
+
|
190 |
+
.. deprecated:: 1.7
|
191 |
+
|
192 |
+
Using arguments that aren't subclasses of :class:`~.Expr` in core
|
193 |
+
operators (:class:`~.Mul`, :class:`~.Add`, and :class:`~.Pow`) is
|
194 |
+
deprecated. See :ref:`non-expr-args-deprecated` for details.
|
195 |
+
|
196 |
+
Singleton definitions involving (0, 1, -1, oo, -oo, I, -I):
|
197 |
+
|
198 |
+
+--------------+---------+-----------------------------------------------+
|
199 |
+
| expr | value | reason |
|
200 |
+
+==============+=========+===============================================+
|
201 |
+
| z**0 | 1 | Although arguments over 0**0 exist, see [2]. |
|
202 |
+
+--------------+---------+-----------------------------------------------+
|
203 |
+
| z**1 | z | |
|
204 |
+
+--------------+---------+-----------------------------------------------+
|
205 |
+
| (-oo)**(-1) | 0 | |
|
206 |
+
+--------------+---------+-----------------------------------------------+
|
207 |
+
| (-1)**-1 | -1 | |
|
208 |
+
+--------------+---------+-----------------------------------------------+
|
209 |
+
| S.Zero**-1 | zoo | This is not strictly true, as 0**-1 may be |
|
210 |
+
| | | undefined, but is convenient in some contexts |
|
211 |
+
| | | where the base is assumed to be positive. |
|
212 |
+
+--------------+---------+-----------------------------------------------+
|
213 |
+
| 1**-1 | 1 | |
|
214 |
+
+--------------+---------+-----------------------------------------------+
|
215 |
+
| oo**-1 | 0 | |
|
216 |
+
+--------------+---------+-----------------------------------------------+
|
217 |
+
| 0**oo | 0 | Because for all complex numbers z near |
|
218 |
+
| | | 0, z**oo -> 0. |
|
219 |
+
+--------------+---------+-----------------------------------------------+
|
220 |
+
| 0**-oo | zoo | This is not strictly true, as 0**oo may be |
|
221 |
+
| | | oscillating between positive and negative |
|
222 |
+
| | | values or rotating in the complex plane. |
|
223 |
+
| | | It is convenient, however, when the base |
|
224 |
+
| | | is positive. |
|
225 |
+
+--------------+---------+-----------------------------------------------+
|
226 |
+
| 1**oo | nan | Because there are various cases where |
|
227 |
+
| 1**-oo | | lim(x(t),t)=1, lim(y(t),t)=oo (or -oo), |
|
228 |
+
| | | but lim( x(t)**y(t), t) != 1. See [3]. |
|
229 |
+
+--------------+---------+-----------------------------------------------+
|
230 |
+
| b**zoo | nan | Because b**z has no limit as z -> zoo |
|
231 |
+
+--------------+---------+-----------------------------------------------+
|
232 |
+
| (-1)**oo | nan | Because of oscillations in the limit. |
|
233 |
+
| (-1)**(-oo) | | |
|
234 |
+
+--------------+---------+-----------------------------------------------+
|
235 |
+
| oo**oo | oo | |
|
236 |
+
+--------------+---------+-----------------------------------------------+
|
237 |
+
| oo**-oo | 0 | |
|
238 |
+
+--------------+---------+-----------------------------------------------+
|
239 |
+
| (-oo)**oo | nan | |
|
240 |
+
| (-oo)**-oo | | |
|
241 |
+
+--------------+---------+-----------------------------------------------+
|
242 |
+
| oo**I | nan | oo**e could probably be best thought of as |
|
243 |
+
| (-oo)**I | | the limit of x**e for real x as x tends to |
|
244 |
+
| | | oo. If e is I, then the limit does not exist |
|
245 |
+
| | | and nan is used to indicate that. |
|
246 |
+
+--------------+---------+-----------------------------------------------+
|
247 |
+
| oo**(1+I) | zoo | If the real part of e is positive, then the |
|
248 |
+
| (-oo)**(1+I) | | limit of abs(x**e) is oo. So the limit value |
|
249 |
+
| | | is zoo. |
|
250 |
+
+--------------+---------+-----------------------------------------------+
|
251 |
+
| oo**(-1+I) | 0 | If the real part of e is negative, then the |
|
252 |
+
| -oo**(-1+I) | | limit is 0. |
|
253 |
+
+--------------+---------+-----------------------------------------------+
|
254 |
+
|
255 |
+
Because symbolic computations are more flexible than floating point
|
256 |
+
calculations and we prefer to never return an incorrect answer,
|
257 |
+
we choose not to conform to all IEEE 754 conventions. This helps
|
258 |
+
us avoid extra test-case code in the calculation of limits.
|
259 |
+
|
260 |
+
See Also
|
261 |
+
========
|
262 |
+
|
263 |
+
sympy.core.numbers.Infinity
|
264 |
+
sympy.core.numbers.NegativeInfinity
|
265 |
+
sympy.core.numbers.NaN
|
266 |
+
|
267 |
+
References
|
268 |
+
==========
|
269 |
+
|
270 |
+
.. [1] https://en.wikipedia.org/wiki/Exponentiation
|
271 |
+
.. [2] https://en.wikipedia.org/wiki/Zero_to_the_power_of_zero
|
272 |
+
.. [3] https://en.wikipedia.org/wiki/Indeterminate_forms
|
273 |
+
|
274 |
+
"""
|
275 |
+
is_Pow = True
|
276 |
+
|
277 |
+
__slots__ = ('is_commutative',)
|
278 |
+
|
279 |
+
args: tuple[Expr, Expr]
|
280 |
+
_args: tuple[Expr, Expr]
|
281 |
+
|
282 |
+
@cacheit
|
283 |
+
def __new__(cls, b, e, evaluate=None):
|
284 |
+
if evaluate is None:
|
285 |
+
evaluate = global_parameters.evaluate
|
286 |
+
|
287 |
+
b = _sympify(b)
|
288 |
+
e = _sympify(e)
|
289 |
+
|
290 |
+
# XXX: This can be removed when non-Expr args are disallowed rather
|
291 |
+
# than deprecated.
|
292 |
+
from .relational import Relational
|
293 |
+
if isinstance(b, Relational) or isinstance(e, Relational):
|
294 |
+
raise TypeError('Relational cannot be used in Pow')
|
295 |
+
|
296 |
+
# XXX: This should raise TypeError once deprecation period is over:
|
297 |
+
for arg in [b, e]:
|
298 |
+
if not isinstance(arg, Expr):
|
299 |
+
sympy_deprecation_warning(
|
300 |
+
f"""
|
301 |
+
Using non-Expr arguments in Pow is deprecated (in this case, one of the
|
302 |
+
arguments is of type {type(arg).__name__!r}).
|
303 |
+
|
304 |
+
If you really did intend to construct a power with this base, use the **
|
305 |
+
operator instead.""",
|
306 |
+
deprecated_since_version="1.7",
|
307 |
+
active_deprecations_target="non-expr-args-deprecated",
|
308 |
+
stacklevel=4,
|
309 |
+
)
|
310 |
+
|
311 |
+
if evaluate:
|
312 |
+
if e is S.ComplexInfinity:
|
313 |
+
return S.NaN
|
314 |
+
if e is S.Infinity:
|
315 |
+
if is_gt(b, S.One):
|
316 |
+
return S.Infinity
|
317 |
+
if is_gt(b, S.NegativeOne) and is_lt(b, S.One):
|
318 |
+
return S.Zero
|
319 |
+
if is_lt(b, S.NegativeOne):
|
320 |
+
if b.is_finite:
|
321 |
+
return S.ComplexInfinity
|
322 |
+
if b.is_finite is False:
|
323 |
+
return S.NaN
|
324 |
+
if e is S.Zero:
|
325 |
+
return S.One
|
326 |
+
elif e is S.One:
|
327 |
+
return b
|
328 |
+
elif e == -1 and not b:
|
329 |
+
return S.ComplexInfinity
|
330 |
+
elif e.__class__.__name__ == "AccumulationBounds":
|
331 |
+
if b == S.Exp1:
|
332 |
+
from sympy.calculus.accumulationbounds import AccumBounds
|
333 |
+
return AccumBounds(Pow(b, e.min), Pow(b, e.max))
|
334 |
+
# autosimplification if base is a number and exp odd/even
|
335 |
+
# if base is Number then the base will end up positive; we
|
336 |
+
# do not do this with arbitrary expressions since symbolic
|
337 |
+
# cancellation might occur as in (x - 1)/(1 - x) -> -1. If
|
338 |
+
# we returned Piecewise((-1, Ne(x, 1))) for such cases then
|
339 |
+
# we could do this...but we don't
|
340 |
+
elif (e.is_Symbol and e.is_integer or e.is_Integer
|
341 |
+
) and (b.is_number and b.is_Mul or b.is_Number
|
342 |
+
) and b.could_extract_minus_sign():
|
343 |
+
if e.is_even:
|
344 |
+
b = -b
|
345 |
+
elif e.is_odd:
|
346 |
+
return -Pow(-b, e)
|
347 |
+
if S.NaN in (b, e): # XXX S.NaN**x -> S.NaN under assumption that x != 0
|
348 |
+
return S.NaN
|
349 |
+
elif b is S.One:
|
350 |
+
if abs(e).is_infinite:
|
351 |
+
return S.NaN
|
352 |
+
return S.One
|
353 |
+
else:
|
354 |
+
# recognize base as E
|
355 |
+
from sympy.functions.elementary.exponential import exp_polar
|
356 |
+
if not e.is_Atom and b is not S.Exp1 and not isinstance(b, exp_polar):
|
357 |
+
from .exprtools import factor_terms
|
358 |
+
from sympy.functions.elementary.exponential import log
|
359 |
+
from sympy.simplify.radsimp import fraction
|
360 |
+
c, ex = factor_terms(e, sign=False).as_coeff_Mul()
|
361 |
+
num, den = fraction(ex)
|
362 |
+
if isinstance(den, log) and den.args[0] == b:
|
363 |
+
return S.Exp1**(c*num)
|
364 |
+
elif den.is_Add:
|
365 |
+
from sympy.functions.elementary.complexes import sign, im
|
366 |
+
s = sign(im(b))
|
367 |
+
if s.is_Number and s and den == \
|
368 |
+
log(-factor_terms(b, sign=False)) + s*S.ImaginaryUnit*S.Pi:
|
369 |
+
return S.Exp1**(c*num)
|
370 |
+
|
371 |
+
obj = b._eval_power(e)
|
372 |
+
if obj is not None:
|
373 |
+
return obj
|
374 |
+
obj = Expr.__new__(cls, b, e)
|
375 |
+
obj = cls._exec_constructor_postprocessors(obj)
|
376 |
+
if not isinstance(obj, Pow):
|
377 |
+
return obj
|
378 |
+
obj.is_commutative = (b.is_commutative and e.is_commutative)
|
379 |
+
return obj
|
380 |
+
|
381 |
+
def inverse(self, argindex=1):
|
382 |
+
if self.base == S.Exp1:
|
383 |
+
from sympy.functions.elementary.exponential import log
|
384 |
+
return log
|
385 |
+
return None
|
386 |
+
|
387 |
+
@property
|
388 |
+
def base(self) -> Expr:
|
389 |
+
return self._args[0]
|
390 |
+
|
391 |
+
@property
|
392 |
+
def exp(self) -> Expr:
|
393 |
+
return self._args[1]
|
394 |
+
|
395 |
+
@property
|
396 |
+
def kind(self):
|
397 |
+
if self.exp.kind is NumberKind:
|
398 |
+
return self.base.kind
|
399 |
+
else:
|
400 |
+
return UndefinedKind
|
401 |
+
|
402 |
+
@classmethod
|
403 |
+
def class_key(cls):
|
404 |
+
return 3, 2, cls.__name__
|
405 |
+
|
406 |
+
def _eval_refine(self, assumptions):
|
407 |
+
from sympy.assumptions.ask import ask, Q
|
408 |
+
b, e = self.as_base_exp()
|
409 |
+
if ask(Q.integer(e), assumptions) and b.could_extract_minus_sign():
|
410 |
+
if ask(Q.even(e), assumptions):
|
411 |
+
return Pow(-b, e)
|
412 |
+
elif ask(Q.odd(e), assumptions):
|
413 |
+
return -Pow(-b, e)
|
414 |
+
|
415 |
+
def _eval_power(self, other):
|
416 |
+
b, e = self.as_base_exp()
|
417 |
+
if b is S.NaN:
|
418 |
+
return (b**e)**other # let __new__ handle it
|
419 |
+
|
420 |
+
s = None
|
421 |
+
if other.is_integer:
|
422 |
+
s = 1
|
423 |
+
elif b.is_polar: # e.g. exp_polar, besselj, var('p', polar=True)...
|
424 |
+
s = 1
|
425 |
+
elif e.is_extended_real is not None:
|
426 |
+
from sympy.functions.elementary.complexes import arg, im, re, sign
|
427 |
+
from sympy.functions.elementary.exponential import exp, log
|
428 |
+
from sympy.functions.elementary.integers import floor
|
429 |
+
# helper functions ===========================
|
430 |
+
def _half(e):
|
431 |
+
"""Return True if the exponent has a literal 2 as the
|
432 |
+
denominator, else None."""
|
433 |
+
if getattr(e, 'q', None) == 2:
|
434 |
+
return True
|
435 |
+
n, d = e.as_numer_denom()
|
436 |
+
if n.is_integer and d == 2:
|
437 |
+
return True
|
438 |
+
def _n2(e):
|
439 |
+
"""Return ``e`` evaluated to a Number with 2 significant
|
440 |
+
digits, else None."""
|
441 |
+
try:
|
442 |
+
rv = e.evalf(2, strict=True)
|
443 |
+
if rv.is_Number:
|
444 |
+
return rv
|
445 |
+
except PrecisionExhausted:
|
446 |
+
pass
|
447 |
+
# ===================================================
|
448 |
+
if e.is_extended_real:
|
449 |
+
# we need _half(other) with constant floor or
|
450 |
+
# floor(S.Half - e*arg(b)/2/pi) == 0
|
451 |
+
|
452 |
+
|
453 |
+
# handle -1 as special case
|
454 |
+
if e == -1:
|
455 |
+
# floor arg. is 1/2 + arg(b)/2/pi
|
456 |
+
if _half(other):
|
457 |
+
if b.is_negative is True:
|
458 |
+
return S.NegativeOne**other*Pow(-b, e*other)
|
459 |
+
elif b.is_negative is False: # XXX ok if im(b) != 0?
|
460 |
+
return Pow(b, -other)
|
461 |
+
elif e.is_even:
|
462 |
+
if b.is_extended_real:
|
463 |
+
b = abs(b)
|
464 |
+
if b.is_imaginary:
|
465 |
+
b = abs(im(b))*S.ImaginaryUnit
|
466 |
+
|
467 |
+
if (abs(e) < 1) == True or e == 1:
|
468 |
+
s = 1 # floor = 0
|
469 |
+
elif b.is_extended_nonnegative:
|
470 |
+
s = 1 # floor = 0
|
471 |
+
elif re(b).is_extended_nonnegative and (abs(e) < 2) == True:
|
472 |
+
s = 1 # floor = 0
|
473 |
+
elif _half(other):
|
474 |
+
s = exp(2*S.Pi*S.ImaginaryUnit*other*floor(
|
475 |
+
S.Half - e*arg(b)/(2*S.Pi)))
|
476 |
+
if s.is_extended_real and _n2(sign(s) - s) == 0:
|
477 |
+
s = sign(s)
|
478 |
+
else:
|
479 |
+
s = None
|
480 |
+
else:
|
481 |
+
# e.is_extended_real is False requires:
|
482 |
+
# _half(other) with constant floor or
|
483 |
+
# floor(S.Half - im(e*log(b))/2/pi) == 0
|
484 |
+
try:
|
485 |
+
s = exp(2*S.ImaginaryUnit*S.Pi*other*
|
486 |
+
floor(S.Half - im(e*log(b))/2/S.Pi))
|
487 |
+
# be careful to test that s is -1 or 1 b/c sign(I) == I:
|
488 |
+
# so check that s is real
|
489 |
+
if s.is_extended_real and _n2(sign(s) - s) == 0:
|
490 |
+
s = sign(s)
|
491 |
+
else:
|
492 |
+
s = None
|
493 |
+
except PrecisionExhausted:
|
494 |
+
s = None
|
495 |
+
|
496 |
+
if s is not None:
|
497 |
+
return s*Pow(b, e*other)
|
498 |
+
|
499 |
+
def _eval_Mod(self, q):
|
500 |
+
r"""A dispatched function to compute `b^e \bmod q`, dispatched
|
501 |
+
by ``Mod``.
|
502 |
+
|
503 |
+
Notes
|
504 |
+
=====
|
505 |
+
|
506 |
+
Algorithms:
|
507 |
+
|
508 |
+
1. For unevaluated integer power, use built-in ``pow`` function
|
509 |
+
with 3 arguments, if powers are not too large wrt base.
|
510 |
+
|
511 |
+
2. For very large powers, use totient reduction if $e \ge \log(m)$.
|
512 |
+
Bound on m, is for safe factorization memory wise i.e. $m^{1/4}$.
|
513 |
+
For pollard-rho to be faster than built-in pow $\log(e) > m^{1/4}$
|
514 |
+
check is added.
|
515 |
+
|
516 |
+
3. For any unevaluated power found in `b` or `e`, the step 2
|
517 |
+
will be recursed down to the base and the exponent
|
518 |
+
such that the $b \bmod q$ becomes the new base and
|
519 |
+
$\phi(q) + e \bmod \phi(q)$ becomes the new exponent, and then
|
520 |
+
the computation for the reduced expression can be done.
|
521 |
+
"""
|
522 |
+
|
523 |
+
base, exp = self.base, self.exp
|
524 |
+
|
525 |
+
if exp.is_integer and exp.is_positive:
|
526 |
+
if q.is_integer and base % q == 0:
|
527 |
+
return S.Zero
|
528 |
+
|
529 |
+
from sympy.ntheory.factor_ import totient
|
530 |
+
|
531 |
+
if base.is_Integer and exp.is_Integer and q.is_Integer:
|
532 |
+
b, e, m = int(base), int(exp), int(q)
|
533 |
+
mb = m.bit_length()
|
534 |
+
if mb <= 80 and e >= mb and e.bit_length()**4 >= m:
|
535 |
+
phi = int(totient(m))
|
536 |
+
return Integer(pow(b, phi + e%phi, m))
|
537 |
+
return Integer(pow(b, e, m))
|
538 |
+
|
539 |
+
from .mod import Mod
|
540 |
+
|
541 |
+
if isinstance(base, Pow) and base.is_integer and base.is_number:
|
542 |
+
base = Mod(base, q)
|
543 |
+
return Mod(Pow(base, exp, evaluate=False), q)
|
544 |
+
|
545 |
+
if isinstance(exp, Pow) and exp.is_integer and exp.is_number:
|
546 |
+
bit_length = int(q).bit_length()
|
547 |
+
# XXX Mod-Pow actually attempts to do a hanging evaluation
|
548 |
+
# if this dispatched function returns None.
|
549 |
+
# May need some fixes in the dispatcher itself.
|
550 |
+
if bit_length <= 80:
|
551 |
+
phi = totient(q)
|
552 |
+
exp = phi + Mod(exp, phi)
|
553 |
+
return Mod(Pow(base, exp, evaluate=False), q)
|
554 |
+
|
555 |
+
def _eval_is_even(self):
|
556 |
+
if self.exp.is_integer and self.exp.is_positive:
|
557 |
+
return self.base.is_even
|
558 |
+
|
559 |
+
def _eval_is_negative(self):
|
560 |
+
ext_neg = Pow._eval_is_extended_negative(self)
|
561 |
+
if ext_neg is True:
|
562 |
+
return self.is_finite
|
563 |
+
return ext_neg
|
564 |
+
|
565 |
+
def _eval_is_extended_positive(self):
|
566 |
+
if self.base == self.exp:
|
567 |
+
if self.base.is_extended_nonnegative:
|
568 |
+
return True
|
569 |
+
elif self.base.is_positive:
|
570 |
+
if self.exp.is_real:
|
571 |
+
return True
|
572 |
+
elif self.base.is_extended_negative:
|
573 |
+
if self.exp.is_even:
|
574 |
+
return True
|
575 |
+
if self.exp.is_odd:
|
576 |
+
return False
|
577 |
+
elif self.base.is_zero:
|
578 |
+
if self.exp.is_extended_real:
|
579 |
+
return self.exp.is_zero
|
580 |
+
elif self.base.is_extended_nonpositive:
|
581 |
+
if self.exp.is_odd:
|
582 |
+
return False
|
583 |
+
elif self.base.is_imaginary:
|
584 |
+
if self.exp.is_integer:
|
585 |
+
m = self.exp % 4
|
586 |
+
if m.is_zero:
|
587 |
+
return True
|
588 |
+
if m.is_integer and m.is_zero is False:
|
589 |
+
return False
|
590 |
+
if self.exp.is_imaginary:
|
591 |
+
from sympy.functions.elementary.exponential import log
|
592 |
+
return log(self.base).is_imaginary
|
593 |
+
|
594 |
+
def _eval_is_extended_negative(self):
|
595 |
+
if self.exp is S.Half:
|
596 |
+
if self.base.is_complex or self.base.is_extended_real:
|
597 |
+
return False
|
598 |
+
if self.base.is_extended_negative:
|
599 |
+
if self.exp.is_odd and self.base.is_finite:
|
600 |
+
return True
|
601 |
+
if self.exp.is_even:
|
602 |
+
return False
|
603 |
+
elif self.base.is_extended_positive:
|
604 |
+
if self.exp.is_extended_real:
|
605 |
+
return False
|
606 |
+
elif self.base.is_zero:
|
607 |
+
if self.exp.is_extended_real:
|
608 |
+
return False
|
609 |
+
elif self.base.is_extended_nonnegative:
|
610 |
+
if self.exp.is_extended_nonnegative:
|
611 |
+
return False
|
612 |
+
elif self.base.is_extended_nonpositive:
|
613 |
+
if self.exp.is_even:
|
614 |
+
return False
|
615 |
+
elif self.base.is_extended_real:
|
616 |
+
if self.exp.is_even:
|
617 |
+
return False
|
618 |
+
|
619 |
+
def _eval_is_zero(self):
|
620 |
+
if self.base.is_zero:
|
621 |
+
if self.exp.is_extended_positive:
|
622 |
+
return True
|
623 |
+
elif self.exp.is_extended_nonpositive:
|
624 |
+
return False
|
625 |
+
elif self.base == S.Exp1:
|
626 |
+
return self.exp is S.NegativeInfinity
|
627 |
+
elif self.base.is_zero is False:
|
628 |
+
if self.base.is_finite and self.exp.is_finite:
|
629 |
+
return False
|
630 |
+
elif self.exp.is_negative:
|
631 |
+
return self.base.is_infinite
|
632 |
+
elif self.exp.is_nonnegative:
|
633 |
+
return False
|
634 |
+
elif self.exp.is_infinite and self.exp.is_extended_real:
|
635 |
+
if (1 - abs(self.base)).is_extended_positive:
|
636 |
+
return self.exp.is_extended_positive
|
637 |
+
elif (1 - abs(self.base)).is_extended_negative:
|
638 |
+
return self.exp.is_extended_negative
|
639 |
+
elif self.base.is_finite and self.exp.is_negative:
|
640 |
+
# when self.base.is_zero is None
|
641 |
+
return False
|
642 |
+
|
643 |
+
def _eval_is_integer(self):
|
644 |
+
b, e = self.args
|
645 |
+
if b.is_rational:
|
646 |
+
if b.is_integer is False and e.is_positive:
|
647 |
+
return False # rat**nonneg
|
648 |
+
if b.is_integer and e.is_integer:
|
649 |
+
if b is S.NegativeOne:
|
650 |
+
return True
|
651 |
+
if e.is_nonnegative or e.is_positive:
|
652 |
+
return True
|
653 |
+
if b.is_integer and e.is_negative and (e.is_finite or e.is_integer):
|
654 |
+
if fuzzy_not((b - 1).is_zero) and fuzzy_not((b + 1).is_zero):
|
655 |
+
return False
|
656 |
+
if b.is_Number and e.is_Number:
|
657 |
+
check = self.func(*self.args)
|
658 |
+
return check.is_Integer
|
659 |
+
if e.is_negative and b.is_positive and (b - 1).is_positive:
|
660 |
+
return False
|
661 |
+
if e.is_negative and b.is_negative and (b + 1).is_negative:
|
662 |
+
return False
|
663 |
+
|
664 |
+
def _eval_is_extended_real(self):
|
665 |
+
if self.base is S.Exp1:
|
666 |
+
if self.exp.is_extended_real:
|
667 |
+
return True
|
668 |
+
elif self.exp.is_imaginary:
|
669 |
+
return (2*S.ImaginaryUnit*self.exp/S.Pi).is_even
|
670 |
+
|
671 |
+
from sympy.functions.elementary.exponential import log, exp
|
672 |
+
real_b = self.base.is_extended_real
|
673 |
+
if real_b is None:
|
674 |
+
if self.base.func == exp and self.base.exp.is_imaginary:
|
675 |
+
return self.exp.is_imaginary
|
676 |
+
if self.base.func == Pow and self.base.base is S.Exp1 and self.base.exp.is_imaginary:
|
677 |
+
return self.exp.is_imaginary
|
678 |
+
return
|
679 |
+
real_e = self.exp.is_extended_real
|
680 |
+
if real_e is None:
|
681 |
+
return
|
682 |
+
if real_b and real_e:
|
683 |
+
if self.base.is_extended_positive:
|
684 |
+
return True
|
685 |
+
elif self.base.is_extended_nonnegative and self.exp.is_extended_nonnegative:
|
686 |
+
return True
|
687 |
+
elif self.exp.is_integer and self.base.is_extended_nonzero:
|
688 |
+
return True
|
689 |
+
elif self.exp.is_integer and self.exp.is_nonnegative:
|
690 |
+
return True
|
691 |
+
elif self.base.is_extended_negative:
|
692 |
+
if self.exp.is_Rational:
|
693 |
+
return False
|
694 |
+
if real_e and self.exp.is_extended_negative and self.base.is_zero is False:
|
695 |
+
return Pow(self.base, -self.exp).is_extended_real
|
696 |
+
im_b = self.base.is_imaginary
|
697 |
+
im_e = self.exp.is_imaginary
|
698 |
+
if im_b:
|
699 |
+
if self.exp.is_integer:
|
700 |
+
if self.exp.is_even:
|
701 |
+
return True
|
702 |
+
elif self.exp.is_odd:
|
703 |
+
return False
|
704 |
+
elif im_e and log(self.base).is_imaginary:
|
705 |
+
return True
|
706 |
+
elif self.exp.is_Add:
|
707 |
+
c, a = self.exp.as_coeff_Add()
|
708 |
+
if c and c.is_Integer:
|
709 |
+
return Mul(
|
710 |
+
self.base**c, self.base**a, evaluate=False).is_extended_real
|
711 |
+
elif self.base in (-S.ImaginaryUnit, S.ImaginaryUnit):
|
712 |
+
if (self.exp/2).is_integer is False:
|
713 |
+
return False
|
714 |
+
if real_b and im_e:
|
715 |
+
if self.base is S.NegativeOne:
|
716 |
+
return True
|
717 |
+
c = self.exp.coeff(S.ImaginaryUnit)
|
718 |
+
if c:
|
719 |
+
if self.base.is_rational and c.is_rational:
|
720 |
+
if self.base.is_nonzero and (self.base - 1).is_nonzero and c.is_nonzero:
|
721 |
+
return False
|
722 |
+
ok = (c*log(self.base)/S.Pi).is_integer
|
723 |
+
if ok is not None:
|
724 |
+
return ok
|
725 |
+
|
726 |
+
if real_b is False and real_e: # we already know it's not imag
|
727 |
+
from sympy.functions.elementary.complexes import arg
|
728 |
+
i = arg(self.base)*self.exp/S.Pi
|
729 |
+
if i.is_complex: # finite
|
730 |
+
return i.is_integer
|
731 |
+
|
732 |
+
def _eval_is_complex(self):
|
733 |
+
|
734 |
+
if self.base == S.Exp1:
|
735 |
+
return fuzzy_or([self.exp.is_complex, self.exp.is_extended_negative])
|
736 |
+
|
737 |
+
if all(a.is_complex for a in self.args) and self._eval_is_finite():
|
738 |
+
return True
|
739 |
+
|
740 |
+
def _eval_is_imaginary(self):
|
741 |
+
if self.base.is_commutative is False:
|
742 |
+
return False
|
743 |
+
|
744 |
+
if self.base.is_imaginary:
|
745 |
+
if self.exp.is_integer:
|
746 |
+
odd = self.exp.is_odd
|
747 |
+
if odd is not None:
|
748 |
+
return odd
|
749 |
+
return
|
750 |
+
|
751 |
+
if self.base == S.Exp1:
|
752 |
+
f = 2 * self.exp / (S.Pi*S.ImaginaryUnit)
|
753 |
+
# exp(pi*integer) = 1 or -1, so not imaginary
|
754 |
+
if f.is_even:
|
755 |
+
return False
|
756 |
+
# exp(pi*integer + pi/2) = I or -I, so it is imaginary
|
757 |
+
if f.is_odd:
|
758 |
+
return True
|
759 |
+
return None
|
760 |
+
|
761 |
+
if self.exp.is_imaginary:
|
762 |
+
from sympy.functions.elementary.exponential import log
|
763 |
+
imlog = log(self.base).is_imaginary
|
764 |
+
if imlog is not None:
|
765 |
+
return False # I**i -> real; (2*I)**i -> complex ==> not imaginary
|
766 |
+
|
767 |
+
if self.base.is_extended_real and self.exp.is_extended_real:
|
768 |
+
if self.base.is_positive:
|
769 |
+
return False
|
770 |
+
else:
|
771 |
+
rat = self.exp.is_rational
|
772 |
+
if not rat:
|
773 |
+
return rat
|
774 |
+
if self.exp.is_integer:
|
775 |
+
return False
|
776 |
+
else:
|
777 |
+
half = (2*self.exp).is_integer
|
778 |
+
if half:
|
779 |
+
return self.base.is_negative
|
780 |
+
return half
|
781 |
+
|
782 |
+
if self.base.is_extended_real is False: # we already know it's not imag
|
783 |
+
from sympy.functions.elementary.complexes import arg
|
784 |
+
i = arg(self.base)*self.exp/S.Pi
|
785 |
+
isodd = (2*i).is_odd
|
786 |
+
if isodd is not None:
|
787 |
+
return isodd
|
788 |
+
|
789 |
+
def _eval_is_odd(self):
|
790 |
+
if self.exp.is_integer:
|
791 |
+
if self.exp.is_positive:
|
792 |
+
return self.base.is_odd
|
793 |
+
elif self.exp.is_nonnegative and self.base.is_odd:
|
794 |
+
return True
|
795 |
+
elif self.base is S.NegativeOne:
|
796 |
+
return True
|
797 |
+
|
798 |
+
def _eval_is_finite(self):
|
799 |
+
if self.exp.is_negative:
|
800 |
+
if self.base.is_zero:
|
801 |
+
return False
|
802 |
+
if self.base.is_infinite or self.base.is_nonzero:
|
803 |
+
return True
|
804 |
+
c1 = self.base.is_finite
|
805 |
+
if c1 is None:
|
806 |
+
return
|
807 |
+
c2 = self.exp.is_finite
|
808 |
+
if c2 is None:
|
809 |
+
return
|
810 |
+
if c1 and c2:
|
811 |
+
if self.exp.is_nonnegative or fuzzy_not(self.base.is_zero):
|
812 |
+
return True
|
813 |
+
|
814 |
+
def _eval_is_prime(self):
|
815 |
+
'''
|
816 |
+
An integer raised to the n(>=2)-th power cannot be a prime.
|
817 |
+
'''
|
818 |
+
if self.base.is_integer and self.exp.is_integer and (self.exp - 1).is_positive:
|
819 |
+
return False
|
820 |
+
|
821 |
+
def _eval_is_composite(self):
|
822 |
+
"""
|
823 |
+
A power is composite if both base and exponent are greater than 1
|
824 |
+
"""
|
825 |
+
if (self.base.is_integer and self.exp.is_integer and
|
826 |
+
((self.base - 1).is_positive and (self.exp - 1).is_positive or
|
827 |
+
(self.base + 1).is_negative and self.exp.is_positive and self.exp.is_even)):
|
828 |
+
return True
|
829 |
+
|
830 |
+
def _eval_is_polar(self):
|
831 |
+
return self.base.is_polar
|
832 |
+
|
833 |
+
def _eval_subs(self, old, new):
|
834 |
+
from sympy.calculus.accumulationbounds import AccumBounds
|
835 |
+
|
836 |
+
if isinstance(self.exp, AccumBounds):
|
837 |
+
b = self.base.subs(old, new)
|
838 |
+
e = self.exp.subs(old, new)
|
839 |
+
if isinstance(e, AccumBounds):
|
840 |
+
return e.__rpow__(b)
|
841 |
+
return self.func(b, e)
|
842 |
+
|
843 |
+
from sympy.functions.elementary.exponential import exp, log
|
844 |
+
|
845 |
+
def _check(ct1, ct2, old):
|
846 |
+
"""Return (bool, pow, remainder_pow) where, if bool is True, then the
|
847 |
+
exponent of Pow `old` will combine with `pow` so the substitution
|
848 |
+
is valid, otherwise bool will be False.
|
849 |
+
|
850 |
+
For noncommutative objects, `pow` will be an integer, and a factor
|
851 |
+
`Pow(old.base, remainder_pow)` needs to be included. If there is
|
852 |
+
no such factor, None is returned. For commutative objects,
|
853 |
+
remainder_pow is always None.
|
854 |
+
|
855 |
+
cti are the coefficient and terms of an exponent of self or old
|
856 |
+
In this _eval_subs routine a change like (b**(2*x)).subs(b**x, y)
|
857 |
+
will give y**2 since (b**x)**2 == b**(2*x); if that equality does
|
858 |
+
not hold then the substitution should not occur so `bool` will be
|
859 |
+
False.
|
860 |
+
|
861 |
+
"""
|
862 |
+
coeff1, terms1 = ct1
|
863 |
+
coeff2, terms2 = ct2
|
864 |
+
if terms1 == terms2:
|
865 |
+
if old.is_commutative:
|
866 |
+
# Allow fractional powers for commutative objects
|
867 |
+
pow = coeff1/coeff2
|
868 |
+
try:
|
869 |
+
as_int(pow, strict=False)
|
870 |
+
combines = True
|
871 |
+
except ValueError:
|
872 |
+
b, e = old.as_base_exp()
|
873 |
+
# These conditions ensure that (b**e)**f == b**(e*f) for any f
|
874 |
+
combines = b.is_positive and e.is_real or b.is_nonnegative and e.is_nonnegative
|
875 |
+
|
876 |
+
return combines, pow, None
|
877 |
+
else:
|
878 |
+
# With noncommutative symbols, substitute only integer powers
|
879 |
+
if not isinstance(terms1, tuple):
|
880 |
+
terms1 = (terms1,)
|
881 |
+
if not all(term.is_integer for term in terms1):
|
882 |
+
return False, None, None
|
883 |
+
|
884 |
+
try:
|
885 |
+
# Round pow toward zero
|
886 |
+
pow, remainder = divmod(as_int(coeff1), as_int(coeff2))
|
887 |
+
if pow < 0 and remainder != 0:
|
888 |
+
pow += 1
|
889 |
+
remainder -= as_int(coeff2)
|
890 |
+
|
891 |
+
if remainder == 0:
|
892 |
+
remainder_pow = None
|
893 |
+
else:
|
894 |
+
remainder_pow = Mul(remainder, *terms1)
|
895 |
+
|
896 |
+
return True, pow, remainder_pow
|
897 |
+
except ValueError:
|
898 |
+
# Can't substitute
|
899 |
+
pass
|
900 |
+
|
901 |
+
return False, None, None
|
902 |
+
|
903 |
+
if old == self.base or (old == exp and self.base == S.Exp1):
|
904 |
+
if new.is_Function and isinstance(new, Callable):
|
905 |
+
return new(self.exp._subs(old, new))
|
906 |
+
else:
|
907 |
+
return new**self.exp._subs(old, new)
|
908 |
+
|
909 |
+
# issue 10829: (4**x - 3*y + 2).subs(2**x, y) -> y**2 - 3*y + 2
|
910 |
+
if isinstance(old, self.func) and self.exp == old.exp:
|
911 |
+
l = log(self.base, old.base)
|
912 |
+
if l.is_Number:
|
913 |
+
return Pow(new, l)
|
914 |
+
|
915 |
+
if isinstance(old, self.func) and self.base == old.base:
|
916 |
+
if self.exp.is_Add is False:
|
917 |
+
ct1 = self.exp.as_independent(Symbol, as_Add=False)
|
918 |
+
ct2 = old.exp.as_independent(Symbol, as_Add=False)
|
919 |
+
ok, pow, remainder_pow = _check(ct1, ct2, old)
|
920 |
+
if ok:
|
921 |
+
# issue 5180: (x**(6*y)).subs(x**(3*y),z)->z**2
|
922 |
+
result = self.func(new, pow)
|
923 |
+
if remainder_pow is not None:
|
924 |
+
result = Mul(result, Pow(old.base, remainder_pow))
|
925 |
+
return result
|
926 |
+
else: # b**(6*x + a).subs(b**(3*x), y) -> y**2 * b**a
|
927 |
+
# exp(exp(x) + exp(x**2)).subs(exp(exp(x)), w) -> w * exp(exp(x**2))
|
928 |
+
oarg = old.exp
|
929 |
+
new_l = []
|
930 |
+
o_al = []
|
931 |
+
ct2 = oarg.as_coeff_mul()
|
932 |
+
for a in self.exp.args:
|
933 |
+
newa = a._subs(old, new)
|
934 |
+
ct1 = newa.as_coeff_mul()
|
935 |
+
ok, pow, remainder_pow = _check(ct1, ct2, old)
|
936 |
+
if ok:
|
937 |
+
new_l.append(new**pow)
|
938 |
+
if remainder_pow is not None:
|
939 |
+
o_al.append(remainder_pow)
|
940 |
+
continue
|
941 |
+
elif not old.is_commutative and not newa.is_integer:
|
942 |
+
# If any term in the exponent is non-integer,
|
943 |
+
# we do not do any substitutions in the noncommutative case
|
944 |
+
return
|
945 |
+
o_al.append(newa)
|
946 |
+
if new_l:
|
947 |
+
expo = Add(*o_al)
|
948 |
+
new_l.append(Pow(self.base, expo, evaluate=False) if expo != 1 else self.base)
|
949 |
+
return Mul(*new_l)
|
950 |
+
|
951 |
+
if (isinstance(old, exp) or (old.is_Pow and old.base is S.Exp1)) and self.exp.is_extended_real and self.base.is_positive:
|
952 |
+
ct1 = old.exp.as_independent(Symbol, as_Add=False)
|
953 |
+
ct2 = (self.exp*log(self.base)).as_independent(
|
954 |
+
Symbol, as_Add=False)
|
955 |
+
ok, pow, remainder_pow = _check(ct1, ct2, old)
|
956 |
+
if ok:
|
957 |
+
result = self.func(new, pow) # (2**x).subs(exp(x*log(2)), z) -> z
|
958 |
+
if remainder_pow is not None:
|
959 |
+
result = Mul(result, Pow(old.base, remainder_pow))
|
960 |
+
return result
|
961 |
+
|
962 |
+
def as_base_exp(self):
|
963 |
+
"""Return base and exp of self.
|
964 |
+
|
965 |
+
Explanation
|
966 |
+
===========
|
967 |
+
|
968 |
+
If base a Rational less than 1, then return 1/Rational, -exp.
|
969 |
+
If this extra processing is not needed, the base and exp
|
970 |
+
properties will give the raw arguments.
|
971 |
+
|
972 |
+
Examples
|
973 |
+
========
|
974 |
+
|
975 |
+
>>> from sympy import Pow, S
|
976 |
+
>>> p = Pow(S.Half, 2, evaluate=False)
|
977 |
+
>>> p.as_base_exp()
|
978 |
+
(2, -2)
|
979 |
+
>>> p.args
|
980 |
+
(1/2, 2)
|
981 |
+
>>> p.base, p.exp
|
982 |
+
(1/2, 2)
|
983 |
+
|
984 |
+
"""
|
985 |
+
|
986 |
+
b, e = self.args
|
987 |
+
if b.is_Rational and b.p < b.q and b.p > 0:
|
988 |
+
return 1/b, -e
|
989 |
+
return b, e
|
990 |
+
|
991 |
+
def _eval_adjoint(self):
|
992 |
+
from sympy.functions.elementary.complexes import adjoint
|
993 |
+
i, p = self.exp.is_integer, self.base.is_positive
|
994 |
+
if i:
|
995 |
+
return adjoint(self.base)**self.exp
|
996 |
+
if p:
|
997 |
+
return self.base**adjoint(self.exp)
|
998 |
+
if i is False and p is False:
|
999 |
+
expanded = expand_complex(self)
|
1000 |
+
if expanded != self:
|
1001 |
+
return adjoint(expanded)
|
1002 |
+
|
1003 |
+
def _eval_conjugate(self):
|
1004 |
+
from sympy.functions.elementary.complexes import conjugate as c
|
1005 |
+
i, p = self.exp.is_integer, self.base.is_positive
|
1006 |
+
if i:
|
1007 |
+
return c(self.base)**self.exp
|
1008 |
+
if p:
|
1009 |
+
return self.base**c(self.exp)
|
1010 |
+
if i is False and p is False:
|
1011 |
+
expanded = expand_complex(self)
|
1012 |
+
if expanded != self:
|
1013 |
+
return c(expanded)
|
1014 |
+
if self.is_extended_real:
|
1015 |
+
return self
|
1016 |
+
|
1017 |
+
def _eval_transpose(self):
|
1018 |
+
from sympy.functions.elementary.complexes import transpose
|
1019 |
+
if self.base == S.Exp1:
|
1020 |
+
return self.func(S.Exp1, self.exp.transpose())
|
1021 |
+
i, p = self.exp.is_integer, (self.base.is_complex or self.base.is_infinite)
|
1022 |
+
if p:
|
1023 |
+
return self.base**self.exp
|
1024 |
+
if i:
|
1025 |
+
return transpose(self.base)**self.exp
|
1026 |
+
if i is False and p is False:
|
1027 |
+
expanded = expand_complex(self)
|
1028 |
+
if expanded != self:
|
1029 |
+
return transpose(expanded)
|
1030 |
+
|
1031 |
+
def _eval_expand_power_exp(self, **hints):
|
1032 |
+
"""a**(n + m) -> a**n*a**m"""
|
1033 |
+
b = self.base
|
1034 |
+
e = self.exp
|
1035 |
+
if b == S.Exp1:
|
1036 |
+
from sympy.concrete.summations import Sum
|
1037 |
+
if isinstance(e, Sum) and e.is_commutative:
|
1038 |
+
from sympy.concrete.products import Product
|
1039 |
+
return Product(self.func(b, e.function), *e.limits)
|
1040 |
+
if e.is_Add and (hints.get('force', False) or
|
1041 |
+
b.is_zero is False or e._all_nonneg_or_nonppos()):
|
1042 |
+
if e.is_commutative:
|
1043 |
+
return Mul(*[self.func(b, x) for x in e.args])
|
1044 |
+
if b.is_commutative:
|
1045 |
+
c, nc = sift(e.args, lambda x: x.is_commutative, binary=True)
|
1046 |
+
if c:
|
1047 |
+
return Mul(*[self.func(b, x) for x in c]
|
1048 |
+
)*b**Add._from_args(nc)
|
1049 |
+
return self
|
1050 |
+
|
1051 |
+
def _eval_expand_power_base(self, **hints):
|
1052 |
+
"""(a*b)**n -> a**n * b**n"""
|
1053 |
+
force = hints.get('force', False)
|
1054 |
+
|
1055 |
+
b = self.base
|
1056 |
+
e = self.exp
|
1057 |
+
if not b.is_Mul:
|
1058 |
+
return self
|
1059 |
+
|
1060 |
+
cargs, nc = b.args_cnc(split_1=False)
|
1061 |
+
|
1062 |
+
# expand each term - this is top-level-only
|
1063 |
+
# expansion but we have to watch out for things
|
1064 |
+
# that don't have an _eval_expand method
|
1065 |
+
if nc:
|
1066 |
+
nc = [i._eval_expand_power_base(**hints)
|
1067 |
+
if hasattr(i, '_eval_expand_power_base') else i
|
1068 |
+
for i in nc]
|
1069 |
+
|
1070 |
+
if e.is_Integer:
|
1071 |
+
if e.is_positive:
|
1072 |
+
rv = Mul(*nc*e)
|
1073 |
+
else:
|
1074 |
+
rv = Mul(*[i**-1 for i in nc[::-1]]*-e)
|
1075 |
+
if cargs:
|
1076 |
+
rv *= Mul(*cargs)**e
|
1077 |
+
return rv
|
1078 |
+
|
1079 |
+
if not cargs:
|
1080 |
+
return self.func(Mul(*nc), e, evaluate=False)
|
1081 |
+
|
1082 |
+
nc = [Mul(*nc)]
|
1083 |
+
|
1084 |
+
# sift the commutative bases
|
1085 |
+
other, maybe_real = sift(cargs, lambda x: x.is_extended_real is False,
|
1086 |
+
binary=True)
|
1087 |
+
def pred(x):
|
1088 |
+
if x is S.ImaginaryUnit:
|
1089 |
+
return S.ImaginaryUnit
|
1090 |
+
polar = x.is_polar
|
1091 |
+
if polar:
|
1092 |
+
return True
|
1093 |
+
if polar is None:
|
1094 |
+
return fuzzy_bool(x.is_extended_nonnegative)
|
1095 |
+
sifted = sift(maybe_real, pred)
|
1096 |
+
nonneg = sifted[True]
|
1097 |
+
other += sifted[None]
|
1098 |
+
neg = sifted[False]
|
1099 |
+
imag = sifted[S.ImaginaryUnit]
|
1100 |
+
if imag:
|
1101 |
+
I = S.ImaginaryUnit
|
1102 |
+
i = len(imag) % 4
|
1103 |
+
if i == 0:
|
1104 |
+
pass
|
1105 |
+
elif i == 1:
|
1106 |
+
other.append(I)
|
1107 |
+
elif i == 2:
|
1108 |
+
if neg:
|
1109 |
+
nonn = -neg.pop()
|
1110 |
+
if nonn is not S.One:
|
1111 |
+
nonneg.append(nonn)
|
1112 |
+
else:
|
1113 |
+
neg.append(S.NegativeOne)
|
1114 |
+
else:
|
1115 |
+
if neg:
|
1116 |
+
nonn = -neg.pop()
|
1117 |
+
if nonn is not S.One:
|
1118 |
+
nonneg.append(nonn)
|
1119 |
+
else:
|
1120 |
+
neg.append(S.NegativeOne)
|
1121 |
+
other.append(I)
|
1122 |
+
del imag
|
1123 |
+
|
1124 |
+
# bring out the bases that can be separated from the base
|
1125 |
+
|
1126 |
+
if force or e.is_integer:
|
1127 |
+
# treat all commutatives the same and put nc in other
|
1128 |
+
cargs = nonneg + neg + other
|
1129 |
+
other = nc
|
1130 |
+
else:
|
1131 |
+
# this is just like what is happening automatically, except
|
1132 |
+
# that now we are doing it for an arbitrary exponent for which
|
1133 |
+
# no automatic expansion is done
|
1134 |
+
|
1135 |
+
assert not e.is_Integer
|
1136 |
+
|
1137 |
+
# handle negatives by making them all positive and putting
|
1138 |
+
# the residual -1 in other
|
1139 |
+
if len(neg) > 1:
|
1140 |
+
o = S.One
|
1141 |
+
if not other and neg[0].is_Number:
|
1142 |
+
o *= neg.pop(0)
|
1143 |
+
if len(neg) % 2:
|
1144 |
+
o = -o
|
1145 |
+
for n in neg:
|
1146 |
+
nonneg.append(-n)
|
1147 |
+
if o is not S.One:
|
1148 |
+
other.append(o)
|
1149 |
+
elif neg and other:
|
1150 |
+
if neg[0].is_Number and neg[0] is not S.NegativeOne:
|
1151 |
+
other.append(S.NegativeOne)
|
1152 |
+
nonneg.append(-neg[0])
|
1153 |
+
else:
|
1154 |
+
other.extend(neg)
|
1155 |
+
else:
|
1156 |
+
other.extend(neg)
|
1157 |
+
del neg
|
1158 |
+
|
1159 |
+
cargs = nonneg
|
1160 |
+
other += nc
|
1161 |
+
|
1162 |
+
rv = S.One
|
1163 |
+
if cargs:
|
1164 |
+
if e.is_Rational:
|
1165 |
+
npow, cargs = sift(cargs, lambda x: x.is_Pow and
|
1166 |
+
x.exp.is_Rational and x.base.is_number,
|
1167 |
+
binary=True)
|
1168 |
+
rv = Mul(*[self.func(b.func(*b.args), e) for b in npow])
|
1169 |
+
rv *= Mul(*[self.func(b, e, evaluate=False) for b in cargs])
|
1170 |
+
if other:
|
1171 |
+
rv *= self.func(Mul(*other), e, evaluate=False)
|
1172 |
+
return rv
|
1173 |
+
|
1174 |
+
def _eval_expand_multinomial(self, **hints):
|
1175 |
+
"""(a + b + ..)**n -> a**n + n*a**(n-1)*b + .., n is nonzero integer"""
|
1176 |
+
|
1177 |
+
base, exp = self.args
|
1178 |
+
result = self
|
1179 |
+
|
1180 |
+
if exp.is_Rational and exp.p > 0 and base.is_Add:
|
1181 |
+
if not exp.is_Integer:
|
1182 |
+
n = Integer(exp.p // exp.q)
|
1183 |
+
|
1184 |
+
if not n:
|
1185 |
+
return result
|
1186 |
+
else:
|
1187 |
+
radical, result = self.func(base, exp - n), []
|
1188 |
+
|
1189 |
+
expanded_base_n = self.func(base, n)
|
1190 |
+
if expanded_base_n.is_Pow:
|
1191 |
+
expanded_base_n = \
|
1192 |
+
expanded_base_n._eval_expand_multinomial()
|
1193 |
+
for term in Add.make_args(expanded_base_n):
|
1194 |
+
result.append(term*radical)
|
1195 |
+
|
1196 |
+
return Add(*result)
|
1197 |
+
|
1198 |
+
n = int(exp)
|
1199 |
+
|
1200 |
+
if base.is_commutative:
|
1201 |
+
order_terms, other_terms = [], []
|
1202 |
+
|
1203 |
+
for b in base.args:
|
1204 |
+
if b.is_Order:
|
1205 |
+
order_terms.append(b)
|
1206 |
+
else:
|
1207 |
+
other_terms.append(b)
|
1208 |
+
|
1209 |
+
if order_terms:
|
1210 |
+
# (f(x) + O(x^n))^m -> f(x)^m + m*f(x)^{m-1} *O(x^n)
|
1211 |
+
f = Add(*other_terms)
|
1212 |
+
o = Add(*order_terms)
|
1213 |
+
|
1214 |
+
if n == 2:
|
1215 |
+
return expand_multinomial(f**n, deep=False) + n*f*o
|
1216 |
+
else:
|
1217 |
+
g = expand_multinomial(f**(n - 1), deep=False)
|
1218 |
+
return expand_mul(f*g, deep=False) + n*g*o
|
1219 |
+
|
1220 |
+
if base.is_number:
|
1221 |
+
# Efficiently expand expressions of the form (a + b*I)**n
|
1222 |
+
# where 'a' and 'b' are real numbers and 'n' is integer.
|
1223 |
+
a, b = base.as_real_imag()
|
1224 |
+
|
1225 |
+
if a.is_Rational and b.is_Rational:
|
1226 |
+
if not a.is_Integer:
|
1227 |
+
if not b.is_Integer:
|
1228 |
+
k = self.func(a.q * b.q, n)
|
1229 |
+
a, b = a.p*b.q, a.q*b.p
|
1230 |
+
else:
|
1231 |
+
k = self.func(a.q, n)
|
1232 |
+
a, b = a.p, a.q*b
|
1233 |
+
elif not b.is_Integer:
|
1234 |
+
k = self.func(b.q, n)
|
1235 |
+
a, b = a*b.q, b.p
|
1236 |
+
else:
|
1237 |
+
k = 1
|
1238 |
+
|
1239 |
+
a, b, c, d = int(a), int(b), 1, 0
|
1240 |
+
|
1241 |
+
while n:
|
1242 |
+
if n & 1:
|
1243 |
+
c, d = a*c - b*d, b*c + a*d
|
1244 |
+
n -= 1
|
1245 |
+
a, b = a*a - b*b, 2*a*b
|
1246 |
+
n //= 2
|
1247 |
+
|
1248 |
+
I = S.ImaginaryUnit
|
1249 |
+
|
1250 |
+
if k == 1:
|
1251 |
+
return c + I*d
|
1252 |
+
else:
|
1253 |
+
return Integer(c)/k + I*d/k
|
1254 |
+
|
1255 |
+
p = other_terms
|
1256 |
+
# (x + y)**3 -> x**3 + 3*x**2*y + 3*x*y**2 + y**3
|
1257 |
+
# in this particular example:
|
1258 |
+
# p = [x,y]; n = 3
|
1259 |
+
# so now it's easy to get the correct result -- we get the
|
1260 |
+
# coefficients first:
|
1261 |
+
from sympy.ntheory.multinomial import multinomial_coefficients
|
1262 |
+
from sympy.polys.polyutils import basic_from_dict
|
1263 |
+
expansion_dict = multinomial_coefficients(len(p), n)
|
1264 |
+
# in our example: {(3, 0): 1, (1, 2): 3, (0, 3): 1, (2, 1): 3}
|
1265 |
+
# and now construct the expression.
|
1266 |
+
return basic_from_dict(expansion_dict, *p)
|
1267 |
+
else:
|
1268 |
+
if n == 2:
|
1269 |
+
return Add(*[f*g for f in base.args for g in base.args])
|
1270 |
+
else:
|
1271 |
+
multi = (base**(n - 1))._eval_expand_multinomial()
|
1272 |
+
if multi.is_Add:
|
1273 |
+
return Add(*[f*g for f in base.args
|
1274 |
+
for g in multi.args])
|
1275 |
+
else:
|
1276 |
+
# XXX can this ever happen if base was an Add?
|
1277 |
+
return Add(*[f*multi for f in base.args])
|
1278 |
+
elif (exp.is_Rational and exp.p < 0 and base.is_Add and
|
1279 |
+
abs(exp.p) > exp.q):
|
1280 |
+
return 1 / self.func(base, -exp)._eval_expand_multinomial()
|
1281 |
+
elif exp.is_Add and base.is_Number and (hints.get('force', False) or
|
1282 |
+
base.is_zero is False or exp._all_nonneg_or_nonppos()):
|
1283 |
+
# a + b a b
|
1284 |
+
# n --> n n, where n, a, b are Numbers
|
1285 |
+
# XXX should be in expand_power_exp?
|
1286 |
+
coeff, tail = [], []
|
1287 |
+
for term in exp.args:
|
1288 |
+
if term.is_Number:
|
1289 |
+
coeff.append(self.func(base, term))
|
1290 |
+
else:
|
1291 |
+
tail.append(term)
|
1292 |
+
return Mul(*(coeff + [self.func(base, Add._from_args(tail))]))
|
1293 |
+
else:
|
1294 |
+
return result
|
1295 |
+
|
1296 |
+
def as_real_imag(self, deep=True, **hints):
|
1297 |
+
if self.exp.is_Integer:
|
1298 |
+
from sympy.polys.polytools import poly
|
1299 |
+
|
1300 |
+
exp = self.exp
|
1301 |
+
re_e, im_e = self.base.as_real_imag(deep=deep)
|
1302 |
+
if not im_e:
|
1303 |
+
return self, S.Zero
|
1304 |
+
a, b = symbols('a b', cls=Dummy)
|
1305 |
+
if exp >= 0:
|
1306 |
+
if re_e.is_Number and im_e.is_Number:
|
1307 |
+
# We can be more efficient in this case
|
1308 |
+
expr = expand_multinomial(self.base**exp)
|
1309 |
+
if expr != self:
|
1310 |
+
return expr.as_real_imag()
|
1311 |
+
|
1312 |
+
expr = poly(
|
1313 |
+
(a + b)**exp) # a = re, b = im; expr = (a + b*I)**exp
|
1314 |
+
else:
|
1315 |
+
mag = re_e**2 + im_e**2
|
1316 |
+
re_e, im_e = re_e/mag, -im_e/mag
|
1317 |
+
if re_e.is_Number and im_e.is_Number:
|
1318 |
+
# We can be more efficient in this case
|
1319 |
+
expr = expand_multinomial((re_e + im_e*S.ImaginaryUnit)**-exp)
|
1320 |
+
if expr != self:
|
1321 |
+
return expr.as_real_imag()
|
1322 |
+
|
1323 |
+
expr = poly((a + b)**-exp)
|
1324 |
+
|
1325 |
+
# Terms with even b powers will be real
|
1326 |
+
r = [i for i in expr.terms() if not i[0][1] % 2]
|
1327 |
+
re_part = Add(*[cc*a**aa*b**bb for (aa, bb), cc in r])
|
1328 |
+
# Terms with odd b powers will be imaginary
|
1329 |
+
r = [i for i in expr.terms() if i[0][1] % 4 == 1]
|
1330 |
+
im_part1 = Add(*[cc*a**aa*b**bb for (aa, bb), cc in r])
|
1331 |
+
r = [i for i in expr.terms() if i[0][1] % 4 == 3]
|
1332 |
+
im_part3 = Add(*[cc*a**aa*b**bb for (aa, bb), cc in r])
|
1333 |
+
|
1334 |
+
return (re_part.subs({a: re_e, b: S.ImaginaryUnit*im_e}),
|
1335 |
+
im_part1.subs({a: re_e, b: im_e}) + im_part3.subs({a: re_e, b: -im_e}))
|
1336 |
+
|
1337 |
+
from sympy.functions.elementary.trigonometric import atan2, cos, sin
|
1338 |
+
|
1339 |
+
if self.exp.is_Rational:
|
1340 |
+
re_e, im_e = self.base.as_real_imag(deep=deep)
|
1341 |
+
|
1342 |
+
if im_e.is_zero and self.exp is S.Half:
|
1343 |
+
if re_e.is_extended_nonnegative:
|
1344 |
+
return self, S.Zero
|
1345 |
+
if re_e.is_extended_nonpositive:
|
1346 |
+
return S.Zero, (-self.base)**self.exp
|
1347 |
+
|
1348 |
+
# XXX: This is not totally correct since for x**(p/q) with
|
1349 |
+
# x being imaginary there are actually q roots, but
|
1350 |
+
# only a single one is returned from here.
|
1351 |
+
r = self.func(self.func(re_e, 2) + self.func(im_e, 2), S.Half)
|
1352 |
+
|
1353 |
+
t = atan2(im_e, re_e)
|
1354 |
+
|
1355 |
+
rp, tp = self.func(r, self.exp), t*self.exp
|
1356 |
+
|
1357 |
+
return rp*cos(tp), rp*sin(tp)
|
1358 |
+
elif self.base is S.Exp1:
|
1359 |
+
from sympy.functions.elementary.exponential import exp
|
1360 |
+
re_e, im_e = self.exp.as_real_imag()
|
1361 |
+
if deep:
|
1362 |
+
re_e = re_e.expand(deep, **hints)
|
1363 |
+
im_e = im_e.expand(deep, **hints)
|
1364 |
+
c, s = cos(im_e), sin(im_e)
|
1365 |
+
return exp(re_e)*c, exp(re_e)*s
|
1366 |
+
else:
|
1367 |
+
from sympy.functions.elementary.complexes import im, re
|
1368 |
+
if deep:
|
1369 |
+
hints['complex'] = False
|
1370 |
+
|
1371 |
+
expanded = self.expand(deep, **hints)
|
1372 |
+
if hints.get('ignore') == expanded:
|
1373 |
+
return None
|
1374 |
+
else:
|
1375 |
+
return (re(expanded), im(expanded))
|
1376 |
+
else:
|
1377 |
+
return re(self), im(self)
|
1378 |
+
|
1379 |
+
def _eval_derivative(self, s):
|
1380 |
+
from sympy.functions.elementary.exponential import log
|
1381 |
+
dbase = self.base.diff(s)
|
1382 |
+
dexp = self.exp.diff(s)
|
1383 |
+
return self * (dexp * log(self.base) + dbase * self.exp/self.base)
|
1384 |
+
|
1385 |
+
def _eval_evalf(self, prec):
|
1386 |
+
base, exp = self.as_base_exp()
|
1387 |
+
if base == S.Exp1:
|
1388 |
+
# Use mpmath function associated to class "exp":
|
1389 |
+
from sympy.functions.elementary.exponential import exp as exp_function
|
1390 |
+
return exp_function(self.exp, evaluate=False)._eval_evalf(prec)
|
1391 |
+
base = base._evalf(prec)
|
1392 |
+
if not exp.is_Integer:
|
1393 |
+
exp = exp._evalf(prec)
|
1394 |
+
if exp.is_negative and base.is_number and base.is_extended_real is False:
|
1395 |
+
base = base.conjugate() / (base * base.conjugate())._evalf(prec)
|
1396 |
+
exp = -exp
|
1397 |
+
return self.func(base, exp).expand()
|
1398 |
+
return self.func(base, exp)
|
1399 |
+
|
1400 |
+
def _eval_is_polynomial(self, syms):
|
1401 |
+
if self.exp.has(*syms):
|
1402 |
+
return False
|
1403 |
+
|
1404 |
+
if self.base.has(*syms):
|
1405 |
+
return bool(self.base._eval_is_polynomial(syms) and
|
1406 |
+
self.exp.is_Integer and (self.exp >= 0))
|
1407 |
+
else:
|
1408 |
+
return True
|
1409 |
+
|
1410 |
+
def _eval_is_rational(self):
|
1411 |
+
# The evaluation of self.func below can be very expensive in the case
|
1412 |
+
# of integer**integer if the exponent is large. We should try to exit
|
1413 |
+
# before that if possible:
|
1414 |
+
if (self.exp.is_integer and self.base.is_rational
|
1415 |
+
and fuzzy_not(fuzzy_and([self.exp.is_negative, self.base.is_zero]))):
|
1416 |
+
return True
|
1417 |
+
p = self.func(*self.as_base_exp()) # in case it's unevaluated
|
1418 |
+
if not p.is_Pow:
|
1419 |
+
return p.is_rational
|
1420 |
+
b, e = p.as_base_exp()
|
1421 |
+
if e.is_Rational and b.is_Rational:
|
1422 |
+
# we didn't check that e is not an Integer
|
1423 |
+
# because Rational**Integer autosimplifies
|
1424 |
+
return False
|
1425 |
+
if e.is_integer:
|
1426 |
+
if b.is_rational:
|
1427 |
+
if fuzzy_not(b.is_zero) or e.is_nonnegative:
|
1428 |
+
return True
|
1429 |
+
if b == e: # always rational, even for 0**0
|
1430 |
+
return True
|
1431 |
+
elif b.is_irrational:
|
1432 |
+
return e.is_zero
|
1433 |
+
if b is S.Exp1:
|
1434 |
+
if e.is_rational and e.is_nonzero:
|
1435 |
+
return False
|
1436 |
+
|
1437 |
+
def _eval_is_algebraic(self):
|
1438 |
+
def _is_one(expr):
|
1439 |
+
try:
|
1440 |
+
return (expr - 1).is_zero
|
1441 |
+
except ValueError:
|
1442 |
+
# when the operation is not allowed
|
1443 |
+
return False
|
1444 |
+
|
1445 |
+
if self.base.is_zero or _is_one(self.base):
|
1446 |
+
return True
|
1447 |
+
elif self.base is S.Exp1:
|
1448 |
+
s = self.func(*self.args)
|
1449 |
+
if s.func == self.func:
|
1450 |
+
if self.exp.is_nonzero:
|
1451 |
+
if self.exp.is_algebraic:
|
1452 |
+
return False
|
1453 |
+
elif (self.exp/S.Pi).is_rational:
|
1454 |
+
return False
|
1455 |
+
elif (self.exp/(S.ImaginaryUnit*S.Pi)).is_rational:
|
1456 |
+
return True
|
1457 |
+
else:
|
1458 |
+
return s.is_algebraic
|
1459 |
+
elif self.exp.is_rational:
|
1460 |
+
if self.base.is_algebraic is False:
|
1461 |
+
return self.exp.is_zero
|
1462 |
+
if self.base.is_zero is False:
|
1463 |
+
if self.exp.is_nonzero:
|
1464 |
+
return self.base.is_algebraic
|
1465 |
+
elif self.base.is_algebraic:
|
1466 |
+
return True
|
1467 |
+
if self.exp.is_positive:
|
1468 |
+
return self.base.is_algebraic
|
1469 |
+
elif self.base.is_algebraic and self.exp.is_algebraic:
|
1470 |
+
if ((fuzzy_not(self.base.is_zero)
|
1471 |
+
and fuzzy_not(_is_one(self.base)))
|
1472 |
+
or self.base.is_integer is False
|
1473 |
+
or self.base.is_irrational):
|
1474 |
+
return self.exp.is_rational
|
1475 |
+
|
1476 |
+
def _eval_is_rational_function(self, syms):
|
1477 |
+
if self.exp.has(*syms):
|
1478 |
+
return False
|
1479 |
+
|
1480 |
+
if self.base.has(*syms):
|
1481 |
+
return self.base._eval_is_rational_function(syms) and \
|
1482 |
+
self.exp.is_Integer
|
1483 |
+
else:
|
1484 |
+
return True
|
1485 |
+
|
1486 |
+
def _eval_is_meromorphic(self, x, a):
|
1487 |
+
# f**g is meromorphic if g is an integer and f is meromorphic.
|
1488 |
+
# E**(log(f)*g) is meromorphic if log(f)*g is meromorphic
|
1489 |
+
# and finite.
|
1490 |
+
base_merom = self.base._eval_is_meromorphic(x, a)
|
1491 |
+
exp_integer = self.exp.is_Integer
|
1492 |
+
if exp_integer:
|
1493 |
+
return base_merom
|
1494 |
+
|
1495 |
+
exp_merom = self.exp._eval_is_meromorphic(x, a)
|
1496 |
+
if base_merom is False:
|
1497 |
+
# f**g = E**(log(f)*g) may be meromorphic if the
|
1498 |
+
# singularities of log(f) and g cancel each other,
|
1499 |
+
# for example, if g = 1/log(f). Hence,
|
1500 |
+
return False if exp_merom else None
|
1501 |
+
elif base_merom is None:
|
1502 |
+
return None
|
1503 |
+
|
1504 |
+
b = self.base.subs(x, a)
|
1505 |
+
# b is extended complex as base is meromorphic.
|
1506 |
+
# log(base) is finite and meromorphic when b != 0, zoo.
|
1507 |
+
b_zero = b.is_zero
|
1508 |
+
if b_zero:
|
1509 |
+
log_defined = False
|
1510 |
+
else:
|
1511 |
+
log_defined = fuzzy_and((b.is_finite, fuzzy_not(b_zero)))
|
1512 |
+
|
1513 |
+
if log_defined is False: # zero or pole of base
|
1514 |
+
return exp_integer # False or None
|
1515 |
+
elif log_defined is None:
|
1516 |
+
return None
|
1517 |
+
|
1518 |
+
if not exp_merom:
|
1519 |
+
return exp_merom # False or None
|
1520 |
+
|
1521 |
+
return self.exp.subs(x, a).is_finite
|
1522 |
+
|
1523 |
+
def _eval_is_algebraic_expr(self, syms):
|
1524 |
+
if self.exp.has(*syms):
|
1525 |
+
return False
|
1526 |
+
|
1527 |
+
if self.base.has(*syms):
|
1528 |
+
return self.base._eval_is_algebraic_expr(syms) and \
|
1529 |
+
self.exp.is_Rational
|
1530 |
+
else:
|
1531 |
+
return True
|
1532 |
+
|
1533 |
+
def _eval_rewrite_as_exp(self, base, expo, **kwargs):
|
1534 |
+
from sympy.functions.elementary.exponential import exp, log
|
1535 |
+
|
1536 |
+
if base.is_zero or base.has(exp) or expo.has(exp):
|
1537 |
+
return base**expo
|
1538 |
+
|
1539 |
+
if base.has(Symbol):
|
1540 |
+
# delay evaluation if expo is non symbolic
|
1541 |
+
# (as exp(x*log(5)) automatically reduces to x**5)
|
1542 |
+
if global_parameters.exp_is_pow:
|
1543 |
+
return Pow(S.Exp1, log(base)*expo, evaluate=expo.has(Symbol))
|
1544 |
+
else:
|
1545 |
+
return exp(log(base)*expo, evaluate=expo.has(Symbol))
|
1546 |
+
|
1547 |
+
else:
|
1548 |
+
from sympy.functions.elementary.complexes import arg, Abs
|
1549 |
+
return exp((log(Abs(base)) + S.ImaginaryUnit*arg(base))*expo)
|
1550 |
+
|
1551 |
+
def as_numer_denom(self):
|
1552 |
+
if not self.is_commutative:
|
1553 |
+
return self, S.One
|
1554 |
+
base, exp = self.as_base_exp()
|
1555 |
+
n, d = base.as_numer_denom()
|
1556 |
+
# this should be the same as ExpBase.as_numer_denom wrt
|
1557 |
+
# exponent handling
|
1558 |
+
neg_exp = exp.is_negative
|
1559 |
+
if exp.is_Mul and not neg_exp and not exp.is_positive:
|
1560 |
+
neg_exp = exp.could_extract_minus_sign()
|
1561 |
+
int_exp = exp.is_integer
|
1562 |
+
# the denominator cannot be separated from the numerator if
|
1563 |
+
# its sign is unknown unless the exponent is an integer, e.g.
|
1564 |
+
# sqrt(a/b) != sqrt(a)/sqrt(b) when a=1 and b=-1. But if the
|
1565 |
+
# denominator is negative the numerator and denominator can
|
1566 |
+
# be negated and the denominator (now positive) separated.
|
1567 |
+
if not (d.is_extended_real or int_exp):
|
1568 |
+
n = base
|
1569 |
+
d = S.One
|
1570 |
+
dnonpos = d.is_nonpositive
|
1571 |
+
if dnonpos:
|
1572 |
+
n, d = -n, -d
|
1573 |
+
elif dnonpos is None and not int_exp:
|
1574 |
+
n = base
|
1575 |
+
d = S.One
|
1576 |
+
if neg_exp:
|
1577 |
+
n, d = d, n
|
1578 |
+
exp = -exp
|
1579 |
+
if exp.is_infinite:
|
1580 |
+
if n is S.One and d is not S.One:
|
1581 |
+
return n, self.func(d, exp)
|
1582 |
+
if n is not S.One and d is S.One:
|
1583 |
+
return self.func(n, exp), d
|
1584 |
+
return self.func(n, exp), self.func(d, exp)
|
1585 |
+
|
1586 |
+
def matches(self, expr, repl_dict=None, old=False):
|
1587 |
+
expr = _sympify(expr)
|
1588 |
+
if repl_dict is None:
|
1589 |
+
repl_dict = {}
|
1590 |
+
|
1591 |
+
# special case, pattern = 1 and expr.exp can match to 0
|
1592 |
+
if expr is S.One:
|
1593 |
+
d = self.exp.matches(S.Zero, repl_dict)
|
1594 |
+
if d is not None:
|
1595 |
+
return d
|
1596 |
+
|
1597 |
+
# make sure the expression to be matched is an Expr
|
1598 |
+
if not isinstance(expr, Expr):
|
1599 |
+
return None
|
1600 |
+
|
1601 |
+
b, e = expr.as_base_exp()
|
1602 |
+
|
1603 |
+
# special case number
|
1604 |
+
sb, se = self.as_base_exp()
|
1605 |
+
if sb.is_Symbol and se.is_Integer and expr:
|
1606 |
+
if e.is_rational:
|
1607 |
+
return sb.matches(b**(e/se), repl_dict)
|
1608 |
+
return sb.matches(expr**(1/se), repl_dict)
|
1609 |
+
|
1610 |
+
d = repl_dict.copy()
|
1611 |
+
d = self.base.matches(b, d)
|
1612 |
+
if d is None:
|
1613 |
+
return None
|
1614 |
+
|
1615 |
+
d = self.exp.xreplace(d).matches(e, d)
|
1616 |
+
if d is None:
|
1617 |
+
return Expr.matches(self, expr, repl_dict)
|
1618 |
+
return d
|
1619 |
+
|
1620 |
+
def _eval_nseries(self, x, n, logx, cdir=0):
|
1621 |
+
# NOTE! This function is an important part of the gruntz algorithm
|
1622 |
+
# for computing limits. It has to return a generalized power
|
1623 |
+
# series with coefficients in C(log, log(x)). In more detail:
|
1624 |
+
# It has to return an expression
|
1625 |
+
# c_0*x**e_0 + c_1*x**e_1 + ... (finitely many terms)
|
1626 |
+
# where e_i are numbers (not necessarily integers) and c_i are
|
1627 |
+
# expressions involving only numbers, the log function, and log(x).
|
1628 |
+
# The series expansion of b**e is computed as follows:
|
1629 |
+
# 1) We express b as f*(1 + g) where f is the leading term of b.
|
1630 |
+
# g has order O(x**d) where d is strictly positive.
|
1631 |
+
# 2) Then b**e = (f**e)*((1 + g)**e).
|
1632 |
+
# (1 + g)**e is computed using binomial series.
|
1633 |
+
from sympy.functions.elementary.exponential import exp, log
|
1634 |
+
from sympy.series.limits import limit
|
1635 |
+
from sympy.series.order import Order
|
1636 |
+
from sympy.core.sympify import sympify
|
1637 |
+
if self.base is S.Exp1:
|
1638 |
+
e_series = self.exp.nseries(x, n=n, logx=logx)
|
1639 |
+
if e_series.is_Order:
|
1640 |
+
return 1 + e_series
|
1641 |
+
e0 = limit(e_series.removeO(), x, 0)
|
1642 |
+
if e0 is S.NegativeInfinity:
|
1643 |
+
return Order(x**n, x)
|
1644 |
+
if e0 is S.Infinity:
|
1645 |
+
return self
|
1646 |
+
t = e_series - e0
|
1647 |
+
exp_series = term = exp(e0)
|
1648 |
+
# series of exp(e0 + t) in t
|
1649 |
+
for i in range(1, n):
|
1650 |
+
term *= t/i
|
1651 |
+
term = term.nseries(x, n=n, logx=logx)
|
1652 |
+
exp_series += term
|
1653 |
+
exp_series += Order(t**n, x)
|
1654 |
+
from sympy.simplify.powsimp import powsimp
|
1655 |
+
return powsimp(exp_series, deep=True, combine='exp')
|
1656 |
+
from sympy.simplify.powsimp import powdenest
|
1657 |
+
from .numbers import _illegal
|
1658 |
+
self = powdenest(self, force=True).trigsimp()
|
1659 |
+
b, e = self.as_base_exp()
|
1660 |
+
|
1661 |
+
if e.has(*_illegal):
|
1662 |
+
raise PoleError()
|
1663 |
+
|
1664 |
+
if e.has(x):
|
1665 |
+
return exp(e*log(b))._eval_nseries(x, n=n, logx=logx, cdir=cdir)
|
1666 |
+
|
1667 |
+
if logx is not None and b.has(log):
|
1668 |
+
from .symbol import Wild
|
1669 |
+
c, ex = symbols('c, ex', cls=Wild, exclude=[x])
|
1670 |
+
b = b.replace(log(c*x**ex), log(c) + ex*logx)
|
1671 |
+
self = b**e
|
1672 |
+
|
1673 |
+
b = b.removeO()
|
1674 |
+
try:
|
1675 |
+
from sympy.functions.special.gamma_functions import polygamma
|
1676 |
+
if b.has(polygamma, S.EulerGamma) and logx is not None:
|
1677 |
+
raise ValueError()
|
1678 |
+
_, m = b.leadterm(x)
|
1679 |
+
except (ValueError, NotImplementedError, PoleError):
|
1680 |
+
b = b._eval_nseries(x, n=max(2, n), logx=logx, cdir=cdir).removeO()
|
1681 |
+
if b.has(S.NaN, S.ComplexInfinity):
|
1682 |
+
raise NotImplementedError()
|
1683 |
+
_, m = b.leadterm(x)
|
1684 |
+
|
1685 |
+
if e.has(log):
|
1686 |
+
from sympy.simplify.simplify import logcombine
|
1687 |
+
e = logcombine(e).cancel()
|
1688 |
+
|
1689 |
+
if not (m.is_zero or e.is_number and e.is_real):
|
1690 |
+
if self == self._eval_as_leading_term(x, logx=logx, cdir=cdir):
|
1691 |
+
res = exp(e*log(b))._eval_nseries(x, n=n, logx=logx, cdir=cdir)
|
1692 |
+
if res == exp(e*log(b)):
|
1693 |
+
return self
|
1694 |
+
return res
|
1695 |
+
|
1696 |
+
f = b.as_leading_term(x, logx=logx)
|
1697 |
+
g = (b/f - S.One).cancel(expand=False)
|
1698 |
+
if not m.is_number:
|
1699 |
+
raise NotImplementedError()
|
1700 |
+
maxpow = n - m*e
|
1701 |
+
if maxpow.has(Symbol):
|
1702 |
+
maxpow = sympify(n)
|
1703 |
+
|
1704 |
+
if maxpow.is_negative:
|
1705 |
+
return Order(x**(m*e), x)
|
1706 |
+
|
1707 |
+
if g.is_zero:
|
1708 |
+
r = f**e
|
1709 |
+
if r != self:
|
1710 |
+
r += Order(x**n, x)
|
1711 |
+
return r
|
1712 |
+
|
1713 |
+
def coeff_exp(term, x):
|
1714 |
+
coeff, exp = S.One, S.Zero
|
1715 |
+
for factor in Mul.make_args(term):
|
1716 |
+
if factor.has(x):
|
1717 |
+
base, exp = factor.as_base_exp()
|
1718 |
+
if base != x:
|
1719 |
+
try:
|
1720 |
+
return term.leadterm(x)
|
1721 |
+
except ValueError:
|
1722 |
+
return term, S.Zero
|
1723 |
+
else:
|
1724 |
+
coeff *= factor
|
1725 |
+
return coeff, exp
|
1726 |
+
|
1727 |
+
def mul(d1, d2):
|
1728 |
+
res = {}
|
1729 |
+
for e1, e2 in product(d1, d2):
|
1730 |
+
ex = e1 + e2
|
1731 |
+
if ex < maxpow:
|
1732 |
+
res[ex] = res.get(ex, S.Zero) + d1[e1]*d2[e2]
|
1733 |
+
return res
|
1734 |
+
|
1735 |
+
try:
|
1736 |
+
c, d = g.leadterm(x, logx=logx)
|
1737 |
+
except (ValueError, NotImplementedError):
|
1738 |
+
if limit(g/x**maxpow, x, 0) == 0:
|
1739 |
+
# g has higher order zero
|
1740 |
+
return f**e + e*f**e*g # first term of binomial series
|
1741 |
+
else:
|
1742 |
+
raise NotImplementedError()
|
1743 |
+
if c.is_Float and d == S.Zero:
|
1744 |
+
# Convert floats like 0.5 to exact SymPy numbers like S.Half, to
|
1745 |
+
# prevent rounding errors which can induce wrong values of d leading
|
1746 |
+
# to a NotImplementedError being returned from the block below.
|
1747 |
+
from sympy.simplify.simplify import nsimplify
|
1748 |
+
_, d = nsimplify(g).leadterm(x, logx=logx)
|
1749 |
+
if not d.is_positive:
|
1750 |
+
g = g.simplify()
|
1751 |
+
if g.is_zero:
|
1752 |
+
return f**e
|
1753 |
+
_, d = g.leadterm(x, logx=logx)
|
1754 |
+
if not d.is_positive:
|
1755 |
+
g = ((b - f)/f).expand()
|
1756 |
+
_, d = g.leadterm(x, logx=logx)
|
1757 |
+
if not d.is_positive:
|
1758 |
+
raise NotImplementedError()
|
1759 |
+
|
1760 |
+
from sympy.functions.elementary.integers import ceiling
|
1761 |
+
gpoly = g._eval_nseries(x, n=ceiling(maxpow), logx=logx, cdir=cdir).removeO()
|
1762 |
+
gterms = {}
|
1763 |
+
|
1764 |
+
for term in Add.make_args(gpoly):
|
1765 |
+
co1, e1 = coeff_exp(term, x)
|
1766 |
+
gterms[e1] = gterms.get(e1, S.Zero) + co1
|
1767 |
+
|
1768 |
+
k = S.One
|
1769 |
+
terms = {S.Zero: S.One}
|
1770 |
+
tk = gterms
|
1771 |
+
|
1772 |
+
from sympy.functions.combinatorial.factorials import factorial, ff
|
1773 |
+
|
1774 |
+
while (k*d - maxpow).is_negative:
|
1775 |
+
coeff = ff(e, k)/factorial(k)
|
1776 |
+
for ex in tk:
|
1777 |
+
terms[ex] = terms.get(ex, S.Zero) + coeff*tk[ex]
|
1778 |
+
tk = mul(tk, gterms)
|
1779 |
+
k += S.One
|
1780 |
+
|
1781 |
+
from sympy.functions.elementary.complexes import im
|
1782 |
+
|
1783 |
+
if not e.is_integer and m.is_zero and f.is_negative:
|
1784 |
+
ndir = (b - f).dir(x, cdir)
|
1785 |
+
if im(ndir).is_negative:
|
1786 |
+
inco, inex = coeff_exp(f**e*(-1)**(-2*e), x)
|
1787 |
+
elif im(ndir).is_zero:
|
1788 |
+
inco, inex = coeff_exp(exp(e*log(b)).as_leading_term(x, logx=logx, cdir=cdir), x)
|
1789 |
+
else:
|
1790 |
+
inco, inex = coeff_exp(f**e, x)
|
1791 |
+
else:
|
1792 |
+
inco, inex = coeff_exp(f**e, x)
|
1793 |
+
res = S.Zero
|
1794 |
+
|
1795 |
+
for e1 in terms:
|
1796 |
+
ex = e1 + inex
|
1797 |
+
res += terms[e1]*inco*x**(ex)
|
1798 |
+
|
1799 |
+
if not (e.is_integer and e.is_positive and (e*d - n).is_nonpositive and
|
1800 |
+
res == _mexpand(self)):
|
1801 |
+
try:
|
1802 |
+
res += Order(x**n, x)
|
1803 |
+
except NotImplementedError:
|
1804 |
+
return exp(e*log(b))._eval_nseries(x, n=n, logx=logx, cdir=cdir)
|
1805 |
+
return res
|
1806 |
+
|
1807 |
+
def _eval_as_leading_term(self, x, logx=None, cdir=0):
|
1808 |
+
from sympy.functions.elementary.exponential import exp, log
|
1809 |
+
e = self.exp
|
1810 |
+
b = self.base
|
1811 |
+
if self.base is S.Exp1:
|
1812 |
+
arg = e.as_leading_term(x, logx=logx)
|
1813 |
+
arg0 = arg.subs(x, 0)
|
1814 |
+
if arg0 is S.NaN:
|
1815 |
+
arg0 = arg.limit(x, 0)
|
1816 |
+
if arg0.is_infinite is False:
|
1817 |
+
return S.Exp1**arg0
|
1818 |
+
raise PoleError("Cannot expand %s around 0" % (self))
|
1819 |
+
elif e.has(x):
|
1820 |
+
lt = exp(e * log(b))
|
1821 |
+
return lt.as_leading_term(x, logx=logx, cdir=cdir)
|
1822 |
+
else:
|
1823 |
+
from sympy.functions.elementary.complexes import im
|
1824 |
+
try:
|
1825 |
+
f = b.as_leading_term(x, logx=logx, cdir=cdir)
|
1826 |
+
except PoleError:
|
1827 |
+
return self
|
1828 |
+
if not e.is_integer and f.is_negative and not f.has(x):
|
1829 |
+
ndir = (b - f).dir(x, cdir)
|
1830 |
+
if im(ndir).is_negative:
|
1831 |
+
# Normally, f**e would evaluate to exp(e*log(f)) but on branch cuts
|
1832 |
+
# an other value is expected through the following computation
|
1833 |
+
# exp(e*(log(f) - 2*pi*I)) == f**e*exp(-2*e*pi*I) == f**e*(-1)**(-2*e).
|
1834 |
+
return self.func(f, e) * (-1)**(-2*e)
|
1835 |
+
elif im(ndir).is_zero:
|
1836 |
+
log_leadterm = log(b)._eval_as_leading_term(x, logx=logx, cdir=cdir)
|
1837 |
+
if log_leadterm.is_infinite is False:
|
1838 |
+
return exp(e*log_leadterm)
|
1839 |
+
return self.func(f, e)
|
1840 |
+
|
1841 |
+
@cacheit
|
1842 |
+
def _taylor_term(self, n, x, *previous_terms): # of (1 + x)**e
|
1843 |
+
from sympy.functions.combinatorial.factorials import binomial
|
1844 |
+
return binomial(self.exp, n) * self.func(x, n)
|
1845 |
+
|
1846 |
+
def taylor_term(self, n, x, *previous_terms):
|
1847 |
+
if self.base is not S.Exp1:
|
1848 |
+
return super().taylor_term(n, x, *previous_terms)
|
1849 |
+
if n < 0:
|
1850 |
+
return S.Zero
|
1851 |
+
if n == 0:
|
1852 |
+
return S.One
|
1853 |
+
from .sympify import sympify
|
1854 |
+
x = sympify(x)
|
1855 |
+
if previous_terms:
|
1856 |
+
p = previous_terms[-1]
|
1857 |
+
if p is not None:
|
1858 |
+
return p * x / n
|
1859 |
+
from sympy.functions.combinatorial.factorials import factorial
|
1860 |
+
return x**n/factorial(n)
|
1861 |
+
|
1862 |
+
def _eval_rewrite_as_sin(self, base, exp):
|
1863 |
+
if self.base is S.Exp1:
|
1864 |
+
from sympy.functions.elementary.trigonometric import sin
|
1865 |
+
return sin(S.ImaginaryUnit*self.exp + S.Pi/2) - S.ImaginaryUnit*sin(S.ImaginaryUnit*self.exp)
|
1866 |
+
|
1867 |
+
def _eval_rewrite_as_cos(self, base, exp):
|
1868 |
+
if self.base is S.Exp1:
|
1869 |
+
from sympy.functions.elementary.trigonometric import cos
|
1870 |
+
return cos(S.ImaginaryUnit*self.exp) + S.ImaginaryUnit*cos(S.ImaginaryUnit*self.exp + S.Pi/2)
|
1871 |
+
|
1872 |
+
def _eval_rewrite_as_tanh(self, base, exp):
|
1873 |
+
if self.base is S.Exp1:
|
1874 |
+
from sympy.functions.elementary.hyperbolic import tanh
|
1875 |
+
return (1 + tanh(self.exp/2))/(1 - tanh(self.exp/2))
|
1876 |
+
|
1877 |
+
def _eval_rewrite_as_sqrt(self, base, exp, **kwargs):
|
1878 |
+
from sympy.functions.elementary.trigonometric import sin, cos
|
1879 |
+
if base is not S.Exp1:
|
1880 |
+
return None
|
1881 |
+
if exp.is_Mul:
|
1882 |
+
coeff = exp.coeff(S.Pi * S.ImaginaryUnit)
|
1883 |
+
if coeff and coeff.is_number:
|
1884 |
+
cosine, sine = cos(S.Pi*coeff), sin(S.Pi*coeff)
|
1885 |
+
if not isinstance(cosine, cos) and not isinstance (sine, sin):
|
1886 |
+
return cosine + S.ImaginaryUnit*sine
|
1887 |
+
|
1888 |
+
def as_content_primitive(self, radical=False, clear=True):
|
1889 |
+
"""Return the tuple (R, self/R) where R is the positive Rational
|
1890 |
+
extracted from self.
|
1891 |
+
|
1892 |
+
Examples
|
1893 |
+
========
|
1894 |
+
|
1895 |
+
>>> from sympy import sqrt
|
1896 |
+
>>> sqrt(4 + 4*sqrt(2)).as_content_primitive()
|
1897 |
+
(2, sqrt(1 + sqrt(2)))
|
1898 |
+
>>> sqrt(3 + 3*sqrt(2)).as_content_primitive()
|
1899 |
+
(1, sqrt(3)*sqrt(1 + sqrt(2)))
|
1900 |
+
|
1901 |
+
>>> from sympy import expand_power_base, powsimp, Mul
|
1902 |
+
>>> from sympy.abc import x, y
|
1903 |
+
|
1904 |
+
>>> ((2*x + 2)**2).as_content_primitive()
|
1905 |
+
(4, (x + 1)**2)
|
1906 |
+
>>> (4**((1 + y)/2)).as_content_primitive()
|
1907 |
+
(2, 4**(y/2))
|
1908 |
+
>>> (3**((1 + y)/2)).as_content_primitive()
|
1909 |
+
(1, 3**((y + 1)/2))
|
1910 |
+
>>> (3**((5 + y)/2)).as_content_primitive()
|
1911 |
+
(9, 3**((y + 1)/2))
|
1912 |
+
>>> eq = 3**(2 + 2*x)
|
1913 |
+
>>> powsimp(eq) == eq
|
1914 |
+
True
|
1915 |
+
>>> eq.as_content_primitive()
|
1916 |
+
(9, 3**(2*x))
|
1917 |
+
>>> powsimp(Mul(*_))
|
1918 |
+
3**(2*x + 2)
|
1919 |
+
|
1920 |
+
>>> eq = (2 + 2*x)**y
|
1921 |
+
>>> s = expand_power_base(eq); s.is_Mul, s
|
1922 |
+
(False, (2*x + 2)**y)
|
1923 |
+
>>> eq.as_content_primitive()
|
1924 |
+
(1, (2*(x + 1))**y)
|
1925 |
+
>>> s = expand_power_base(_[1]); s.is_Mul, s
|
1926 |
+
(True, 2**y*(x + 1)**y)
|
1927 |
+
|
1928 |
+
See docstring of Expr.as_content_primitive for more examples.
|
1929 |
+
"""
|
1930 |
+
|
1931 |
+
b, e = self.as_base_exp()
|
1932 |
+
b = _keep_coeff(*b.as_content_primitive(radical=radical, clear=clear))
|
1933 |
+
ce, pe = e.as_content_primitive(radical=radical, clear=clear)
|
1934 |
+
if b.is_Rational:
|
1935 |
+
#e
|
1936 |
+
#= ce*pe
|
1937 |
+
#= ce*(h + t)
|
1938 |
+
#= ce*h + ce*t
|
1939 |
+
#=> self
|
1940 |
+
#= b**(ce*h)*b**(ce*t)
|
1941 |
+
#= b**(cehp/cehq)*b**(ce*t)
|
1942 |
+
#= b**(iceh + r/cehq)*b**(ce*t)
|
1943 |
+
#= b**(iceh)*b**(r/cehq)*b**(ce*t)
|
1944 |
+
#= b**(iceh)*b**(ce*t + r/cehq)
|
1945 |
+
h, t = pe.as_coeff_Add()
|
1946 |
+
if h.is_Rational and b != S.Zero:
|
1947 |
+
ceh = ce*h
|
1948 |
+
c = self.func(b, ceh)
|
1949 |
+
r = S.Zero
|
1950 |
+
if not c.is_Rational:
|
1951 |
+
iceh, r = divmod(ceh.p, ceh.q)
|
1952 |
+
c = self.func(b, iceh)
|
1953 |
+
return c, self.func(b, _keep_coeff(ce, t + r/ce/ceh.q))
|
1954 |
+
e = _keep_coeff(ce, pe)
|
1955 |
+
# b**e = (h*t)**e = h**e*t**e = c*m*t**e
|
1956 |
+
if e.is_Rational and b.is_Mul:
|
1957 |
+
h, t = b.as_content_primitive(radical=radical, clear=clear) # h is positive
|
1958 |
+
c, m = self.func(h, e).as_coeff_Mul() # so c is positive
|
1959 |
+
m, me = m.as_base_exp()
|
1960 |
+
if m is S.One or me == e: # probably always true
|
1961 |
+
# return the following, not return c, m*Pow(t, e)
|
1962 |
+
# which would change Pow into Mul; we let SymPy
|
1963 |
+
# decide what to do by using the unevaluated Mul, e.g
|
1964 |
+
# should it stay as sqrt(2 + 2*sqrt(5)) or become
|
1965 |
+
# sqrt(2)*sqrt(1 + sqrt(5))
|
1966 |
+
return c, self.func(_keep_coeff(m, t), e)
|
1967 |
+
return S.One, self.func(b, e)
|
1968 |
+
|
1969 |
+
def is_constant(self, *wrt, **flags):
|
1970 |
+
expr = self
|
1971 |
+
if flags.get('simplify', True):
|
1972 |
+
expr = expr.simplify()
|
1973 |
+
b, e = expr.as_base_exp()
|
1974 |
+
bz = b.equals(0)
|
1975 |
+
if bz: # recalculate with assumptions in case it's unevaluated
|
1976 |
+
new = b**e
|
1977 |
+
if new != expr:
|
1978 |
+
return new.is_constant()
|
1979 |
+
econ = e.is_constant(*wrt)
|
1980 |
+
bcon = b.is_constant(*wrt)
|
1981 |
+
if bcon:
|
1982 |
+
if econ:
|
1983 |
+
return True
|
1984 |
+
bz = b.equals(0)
|
1985 |
+
if bz is False:
|
1986 |
+
return False
|
1987 |
+
elif bcon is None:
|
1988 |
+
return None
|
1989 |
+
|
1990 |
+
return e.equals(0)
|
1991 |
+
|
1992 |
+
def _eval_difference_delta(self, n, step):
|
1993 |
+
b, e = self.args
|
1994 |
+
if e.has(n) and not b.has(n):
|
1995 |
+
new_e = e.subs(n, n + step)
|
1996 |
+
return (b**(new_e - e) - 1) * self
|
1997 |
+
|
1998 |
+
power = Dispatcher('power')
|
1999 |
+
power.add((object, object), Pow)
|
2000 |
+
|
2001 |
+
from .add import Add
|
2002 |
+
from .numbers import Integer
|
2003 |
+
from .mul import Mul, _keep_coeff
|
2004 |
+
from .symbol import Symbol, Dummy, symbols
|
env-llmeval/lib/python3.10/site-packages/sympy/core/rules.py
ADDED
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Replacement rules.
|
3 |
+
"""
|
4 |
+
|
5 |
+
class Transform:
|
6 |
+
"""
|
7 |
+
Immutable mapping that can be used as a generic transformation rule.
|
8 |
+
|
9 |
+
Parameters
|
10 |
+
==========
|
11 |
+
|
12 |
+
transform : callable
|
13 |
+
Computes the value corresponding to any key.
|
14 |
+
|
15 |
+
filter : callable, optional
|
16 |
+
If supplied, specifies which objects are in the mapping.
|
17 |
+
|
18 |
+
Examples
|
19 |
+
========
|
20 |
+
|
21 |
+
>>> from sympy.core.rules import Transform
|
22 |
+
>>> from sympy.abc import x
|
23 |
+
|
24 |
+
This Transform will return, as a value, one more than the key:
|
25 |
+
|
26 |
+
>>> add1 = Transform(lambda x: x + 1)
|
27 |
+
>>> add1[1]
|
28 |
+
2
|
29 |
+
>>> add1[x]
|
30 |
+
x + 1
|
31 |
+
|
32 |
+
By default, all values are considered to be in the dictionary. If a filter
|
33 |
+
is supplied, only the objects for which it returns True are considered as
|
34 |
+
being in the dictionary:
|
35 |
+
|
36 |
+
>>> add1_odd = Transform(lambda x: x + 1, lambda x: x%2 == 1)
|
37 |
+
>>> 2 in add1_odd
|
38 |
+
False
|
39 |
+
>>> add1_odd.get(2, 0)
|
40 |
+
0
|
41 |
+
>>> 3 in add1_odd
|
42 |
+
True
|
43 |
+
>>> add1_odd[3]
|
44 |
+
4
|
45 |
+
>>> add1_odd.get(3, 0)
|
46 |
+
4
|
47 |
+
"""
|
48 |
+
|
49 |
+
def __init__(self, transform, filter=lambda x: True):
|
50 |
+
self._transform = transform
|
51 |
+
self._filter = filter
|
52 |
+
|
53 |
+
def __contains__(self, item):
|
54 |
+
return self._filter(item)
|
55 |
+
|
56 |
+
def __getitem__(self, key):
|
57 |
+
if self._filter(key):
|
58 |
+
return self._transform(key)
|
59 |
+
else:
|
60 |
+
raise KeyError(key)
|
61 |
+
|
62 |
+
def get(self, item, default=None):
|
63 |
+
if item in self:
|
64 |
+
return self[item]
|
65 |
+
else:
|
66 |
+
return default
|
env-llmeval/lib/python3.10/site-packages/sympy/core/symbol.py
ADDED
@@ -0,0 +1,945 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
from __future__ import annotations
|
2 |
+
|
3 |
+
from .assumptions import StdFactKB, _assume_defined
|
4 |
+
from .basic import Basic, Atom
|
5 |
+
from .cache import cacheit
|
6 |
+
from .containers import Tuple
|
7 |
+
from .expr import Expr, AtomicExpr
|
8 |
+
from .function import AppliedUndef, FunctionClass
|
9 |
+
from .kind import NumberKind, UndefinedKind
|
10 |
+
from .logic import fuzzy_bool
|
11 |
+
from .singleton import S
|
12 |
+
from .sorting import ordered
|
13 |
+
from .sympify import sympify
|
14 |
+
from sympy.logic.boolalg import Boolean
|
15 |
+
from sympy.utilities.iterables import sift, is_sequence
|
16 |
+
from sympy.utilities.misc import filldedent
|
17 |
+
|
18 |
+
import string
|
19 |
+
import re as _re
|
20 |
+
import random
|
21 |
+
from itertools import product
|
22 |
+
from typing import Any
|
23 |
+
|
24 |
+
|
25 |
+
class Str(Atom):
|
26 |
+
"""
|
27 |
+
Represents string in SymPy.
|
28 |
+
|
29 |
+
Explanation
|
30 |
+
===========
|
31 |
+
|
32 |
+
Previously, ``Symbol`` was used where string is needed in ``args`` of SymPy
|
33 |
+
objects, e.g. denoting the name of the instance. However, since ``Symbol``
|
34 |
+
represents mathematical scalar, this class should be used instead.
|
35 |
+
|
36 |
+
"""
|
37 |
+
__slots__ = ('name',)
|
38 |
+
|
39 |
+
def __new__(cls, name, **kwargs):
|
40 |
+
if not isinstance(name, str):
|
41 |
+
raise TypeError("name should be a string, not %s" % repr(type(name)))
|
42 |
+
obj = Expr.__new__(cls, **kwargs)
|
43 |
+
obj.name = name
|
44 |
+
return obj
|
45 |
+
|
46 |
+
def __getnewargs__(self):
|
47 |
+
return (self.name,)
|
48 |
+
|
49 |
+
def _hashable_content(self):
|
50 |
+
return (self.name,)
|
51 |
+
|
52 |
+
|
53 |
+
def _filter_assumptions(kwargs):
|
54 |
+
"""Split the given dict into assumptions and non-assumptions.
|
55 |
+
Keys are taken as assumptions if they correspond to an
|
56 |
+
entry in ``_assume_defined``.
|
57 |
+
"""
|
58 |
+
assumptions, nonassumptions = map(dict, sift(kwargs.items(),
|
59 |
+
lambda i: i[0] in _assume_defined,
|
60 |
+
binary=True))
|
61 |
+
Symbol._sanitize(assumptions)
|
62 |
+
return assumptions, nonassumptions
|
63 |
+
|
64 |
+
def _symbol(s, matching_symbol=None, **assumptions):
|
65 |
+
"""Return s if s is a Symbol, else if s is a string, return either
|
66 |
+
the matching_symbol if the names are the same or else a new symbol
|
67 |
+
with the same assumptions as the matching symbol (or the
|
68 |
+
assumptions as provided).
|
69 |
+
|
70 |
+
Examples
|
71 |
+
========
|
72 |
+
|
73 |
+
>>> from sympy import Symbol
|
74 |
+
>>> from sympy.core.symbol import _symbol
|
75 |
+
>>> _symbol('y')
|
76 |
+
y
|
77 |
+
>>> _.is_real is None
|
78 |
+
True
|
79 |
+
>>> _symbol('y', real=True).is_real
|
80 |
+
True
|
81 |
+
|
82 |
+
>>> x = Symbol('x')
|
83 |
+
>>> _symbol(x, real=True)
|
84 |
+
x
|
85 |
+
>>> _.is_real is None # ignore attribute if s is a Symbol
|
86 |
+
True
|
87 |
+
|
88 |
+
Below, the variable sym has the name 'foo':
|
89 |
+
|
90 |
+
>>> sym = Symbol('foo', real=True)
|
91 |
+
|
92 |
+
Since 'x' is not the same as sym's name, a new symbol is created:
|
93 |
+
|
94 |
+
>>> _symbol('x', sym).name
|
95 |
+
'x'
|
96 |
+
|
97 |
+
It will acquire any assumptions give:
|
98 |
+
|
99 |
+
>>> _symbol('x', sym, real=False).is_real
|
100 |
+
False
|
101 |
+
|
102 |
+
Since 'foo' is the same as sym's name, sym is returned
|
103 |
+
|
104 |
+
>>> _symbol('foo', sym)
|
105 |
+
foo
|
106 |
+
|
107 |
+
Any assumptions given are ignored:
|
108 |
+
|
109 |
+
>>> _symbol('foo', sym, real=False).is_real
|
110 |
+
True
|
111 |
+
|
112 |
+
NB: the symbol here may not be the same as a symbol with the same
|
113 |
+
name defined elsewhere as a result of different assumptions.
|
114 |
+
|
115 |
+
See Also
|
116 |
+
========
|
117 |
+
|
118 |
+
sympy.core.symbol.Symbol
|
119 |
+
|
120 |
+
"""
|
121 |
+
if isinstance(s, str):
|
122 |
+
if matching_symbol and matching_symbol.name == s:
|
123 |
+
return matching_symbol
|
124 |
+
return Symbol(s, **assumptions)
|
125 |
+
elif isinstance(s, Symbol):
|
126 |
+
return s
|
127 |
+
else:
|
128 |
+
raise ValueError('symbol must be string for symbol name or Symbol')
|
129 |
+
|
130 |
+
def uniquely_named_symbol(xname, exprs=(), compare=str, modify=None, **assumptions):
|
131 |
+
"""
|
132 |
+
Return a symbol whose name is derivated from *xname* but is unique
|
133 |
+
from any other symbols in *exprs*.
|
134 |
+
|
135 |
+
*xname* and symbol names in *exprs* are passed to *compare* to be
|
136 |
+
converted to comparable forms. If ``compare(xname)`` is not unique,
|
137 |
+
it is recursively passed to *modify* until unique name is acquired.
|
138 |
+
|
139 |
+
Parameters
|
140 |
+
==========
|
141 |
+
|
142 |
+
xname : str or Symbol
|
143 |
+
Base name for the new symbol.
|
144 |
+
|
145 |
+
exprs : Expr or iterable of Expr
|
146 |
+
Expressions whose symbols are compared to *xname*.
|
147 |
+
|
148 |
+
compare : function
|
149 |
+
Unary function which transforms *xname* and symbol names from
|
150 |
+
*exprs* to comparable form.
|
151 |
+
|
152 |
+
modify : function
|
153 |
+
Unary function which modifies the string. Default is appending
|
154 |
+
the number, or increasing the number if exists.
|
155 |
+
|
156 |
+
Examples
|
157 |
+
========
|
158 |
+
|
159 |
+
By default, a number is appended to *xname* to generate unique name.
|
160 |
+
If the number already exists, it is recursively increased.
|
161 |
+
|
162 |
+
>>> from sympy.core.symbol import uniquely_named_symbol, Symbol
|
163 |
+
>>> uniquely_named_symbol('x', Symbol('x'))
|
164 |
+
x0
|
165 |
+
>>> uniquely_named_symbol('x', (Symbol('x'), Symbol('x0')))
|
166 |
+
x1
|
167 |
+
>>> uniquely_named_symbol('x0', (Symbol('x1'), Symbol('x0')))
|
168 |
+
x2
|
169 |
+
|
170 |
+
Name generation can be controlled by passing *modify* parameter.
|
171 |
+
|
172 |
+
>>> from sympy.abc import x
|
173 |
+
>>> uniquely_named_symbol('x', x, modify=lambda s: 2*s)
|
174 |
+
xx
|
175 |
+
|
176 |
+
"""
|
177 |
+
def numbered_string_incr(s, start=0):
|
178 |
+
if not s:
|
179 |
+
return str(start)
|
180 |
+
i = len(s) - 1
|
181 |
+
while i != -1:
|
182 |
+
if not s[i].isdigit():
|
183 |
+
break
|
184 |
+
i -= 1
|
185 |
+
n = str(int(s[i + 1:] or start - 1) + 1)
|
186 |
+
return s[:i + 1] + n
|
187 |
+
|
188 |
+
default = None
|
189 |
+
if is_sequence(xname):
|
190 |
+
xname, default = xname
|
191 |
+
x = compare(xname)
|
192 |
+
if not exprs:
|
193 |
+
return _symbol(x, default, **assumptions)
|
194 |
+
if not is_sequence(exprs):
|
195 |
+
exprs = [exprs]
|
196 |
+
names = set().union(
|
197 |
+
[i.name for e in exprs for i in e.atoms(Symbol)] +
|
198 |
+
[i.func.name for e in exprs for i in e.atoms(AppliedUndef)])
|
199 |
+
if modify is None:
|
200 |
+
modify = numbered_string_incr
|
201 |
+
while any(x == compare(s) for s in names):
|
202 |
+
x = modify(x)
|
203 |
+
return _symbol(x, default, **assumptions)
|
204 |
+
_uniquely_named_symbol = uniquely_named_symbol
|
205 |
+
|
206 |
+
class Symbol(AtomicExpr, Boolean):
|
207 |
+
"""
|
208 |
+
Assumptions:
|
209 |
+
commutative = True
|
210 |
+
|
211 |
+
You can override the default assumptions in the constructor.
|
212 |
+
|
213 |
+
Examples
|
214 |
+
========
|
215 |
+
|
216 |
+
>>> from sympy import symbols
|
217 |
+
>>> A,B = symbols('A,B', commutative = False)
|
218 |
+
>>> bool(A*B != B*A)
|
219 |
+
True
|
220 |
+
>>> bool(A*B*2 == 2*A*B) == True # multiplication by scalars is commutative
|
221 |
+
True
|
222 |
+
|
223 |
+
"""
|
224 |
+
|
225 |
+
is_comparable = False
|
226 |
+
|
227 |
+
__slots__ = ('name', '_assumptions_orig', '_assumptions0')
|
228 |
+
|
229 |
+
name: str
|
230 |
+
|
231 |
+
is_Symbol = True
|
232 |
+
is_symbol = True
|
233 |
+
|
234 |
+
@property
|
235 |
+
def kind(self):
|
236 |
+
if self.is_commutative:
|
237 |
+
return NumberKind
|
238 |
+
return UndefinedKind
|
239 |
+
|
240 |
+
@property
|
241 |
+
def _diff_wrt(self):
|
242 |
+
"""Allow derivatives wrt Symbols.
|
243 |
+
|
244 |
+
Examples
|
245 |
+
========
|
246 |
+
|
247 |
+
>>> from sympy import Symbol
|
248 |
+
>>> x = Symbol('x')
|
249 |
+
>>> x._diff_wrt
|
250 |
+
True
|
251 |
+
"""
|
252 |
+
return True
|
253 |
+
|
254 |
+
@staticmethod
|
255 |
+
def _sanitize(assumptions, obj=None):
|
256 |
+
"""Remove None, convert values to bool, check commutativity *in place*.
|
257 |
+
"""
|
258 |
+
|
259 |
+
# be strict about commutativity: cannot be None
|
260 |
+
is_commutative = fuzzy_bool(assumptions.get('commutative', True))
|
261 |
+
if is_commutative is None:
|
262 |
+
whose = '%s ' % obj.__name__ if obj else ''
|
263 |
+
raise ValueError(
|
264 |
+
'%scommutativity must be True or False.' % whose)
|
265 |
+
|
266 |
+
# sanitize other assumptions so 1 -> True and 0 -> False
|
267 |
+
for key in list(assumptions.keys()):
|
268 |
+
v = assumptions[key]
|
269 |
+
if v is None:
|
270 |
+
assumptions.pop(key)
|
271 |
+
continue
|
272 |
+
assumptions[key] = bool(v)
|
273 |
+
|
274 |
+
def _merge(self, assumptions):
|
275 |
+
base = self.assumptions0
|
276 |
+
for k in set(assumptions) & set(base):
|
277 |
+
if assumptions[k] != base[k]:
|
278 |
+
raise ValueError(filldedent('''
|
279 |
+
non-matching assumptions for %s: existing value
|
280 |
+
is %s and new value is %s''' % (
|
281 |
+
k, base[k], assumptions[k])))
|
282 |
+
base.update(assumptions)
|
283 |
+
return base
|
284 |
+
|
285 |
+
def __new__(cls, name, **assumptions):
|
286 |
+
"""Symbols are identified by name and assumptions::
|
287 |
+
|
288 |
+
>>> from sympy import Symbol
|
289 |
+
>>> Symbol("x") == Symbol("x")
|
290 |
+
True
|
291 |
+
>>> Symbol("x", real=True) == Symbol("x", real=False)
|
292 |
+
False
|
293 |
+
|
294 |
+
"""
|
295 |
+
cls._sanitize(assumptions, cls)
|
296 |
+
return Symbol.__xnew_cached_(cls, name, **assumptions)
|
297 |
+
|
298 |
+
@staticmethod
|
299 |
+
def __xnew__(cls, name, **assumptions): # never cached (e.g. dummy)
|
300 |
+
if not isinstance(name, str):
|
301 |
+
raise TypeError("name should be a string, not %s" % repr(type(name)))
|
302 |
+
|
303 |
+
# This is retained purely so that srepr can include commutative=True if
|
304 |
+
# that was explicitly specified but not if it was not. Ideally srepr
|
305 |
+
# should not distinguish these cases because the symbols otherwise
|
306 |
+
# compare equal and are considered equivalent.
|
307 |
+
#
|
308 |
+
# See https://github.com/sympy/sympy/issues/8873
|
309 |
+
#
|
310 |
+
assumptions_orig = assumptions.copy()
|
311 |
+
|
312 |
+
# The only assumption that is assumed by default is comutative=True:
|
313 |
+
assumptions.setdefault('commutative', True)
|
314 |
+
|
315 |
+
assumptions_kb = StdFactKB(assumptions)
|
316 |
+
assumptions0 = dict(assumptions_kb)
|
317 |
+
|
318 |
+
obj = Expr.__new__(cls)
|
319 |
+
obj.name = name
|
320 |
+
|
321 |
+
obj._assumptions = assumptions_kb
|
322 |
+
obj._assumptions_orig = assumptions_orig
|
323 |
+
obj._assumptions0 = assumptions0
|
324 |
+
|
325 |
+
# The three assumptions dicts are all a little different:
|
326 |
+
#
|
327 |
+
# >>> from sympy import Symbol
|
328 |
+
# >>> x = Symbol('x', finite=True)
|
329 |
+
# >>> x.is_positive # query an assumption
|
330 |
+
# >>> x._assumptions
|
331 |
+
# {'finite': True, 'infinite': False, 'commutative': True, 'positive': None}
|
332 |
+
# >>> x._assumptions0
|
333 |
+
# {'finite': True, 'infinite': False, 'commutative': True}
|
334 |
+
# >>> x._assumptions_orig
|
335 |
+
# {'finite': True}
|
336 |
+
#
|
337 |
+
# Two symbols with the same name are equal if their _assumptions0 are
|
338 |
+
# the same. Arguably it should be _assumptions_orig that is being
|
339 |
+
# compared because that is more transparent to the user (it is
|
340 |
+
# what was passed to the constructor modulo changes made by _sanitize).
|
341 |
+
|
342 |
+
return obj
|
343 |
+
|
344 |
+
@staticmethod
|
345 |
+
@cacheit
|
346 |
+
def __xnew_cached_(cls, name, **assumptions): # symbols are always cached
|
347 |
+
return Symbol.__xnew__(cls, name, **assumptions)
|
348 |
+
|
349 |
+
def __getnewargs_ex__(self):
|
350 |
+
return ((self.name,), self._assumptions_orig)
|
351 |
+
|
352 |
+
# NOTE: __setstate__ is not needed for pickles created by __getnewargs_ex__
|
353 |
+
# but was used before Symbol was changed to use __getnewargs_ex__ in v1.9.
|
354 |
+
# Pickles created in previous SymPy versions will still need __setstate__
|
355 |
+
# so that they can be unpickled in SymPy > v1.9.
|
356 |
+
|
357 |
+
def __setstate__(self, state):
|
358 |
+
for name, value in state.items():
|
359 |
+
setattr(self, name, value)
|
360 |
+
|
361 |
+
def _hashable_content(self):
|
362 |
+
# Note: user-specified assumptions not hashed, just derived ones
|
363 |
+
return (self.name,) + tuple(sorted(self.assumptions0.items()))
|
364 |
+
|
365 |
+
def _eval_subs(self, old, new):
|
366 |
+
if old.is_Pow:
|
367 |
+
from sympy.core.power import Pow
|
368 |
+
return Pow(self, S.One, evaluate=False)._eval_subs(old, new)
|
369 |
+
|
370 |
+
def _eval_refine(self, assumptions):
|
371 |
+
return self
|
372 |
+
|
373 |
+
@property
|
374 |
+
def assumptions0(self):
|
375 |
+
return self._assumptions0.copy()
|
376 |
+
|
377 |
+
@cacheit
|
378 |
+
def sort_key(self, order=None):
|
379 |
+
return self.class_key(), (1, (self.name,)), S.One.sort_key(), S.One
|
380 |
+
|
381 |
+
def as_dummy(self):
|
382 |
+
# only put commutativity in explicitly if it is False
|
383 |
+
return Dummy(self.name) if self.is_commutative is not False \
|
384 |
+
else Dummy(self.name, commutative=self.is_commutative)
|
385 |
+
|
386 |
+
def as_real_imag(self, deep=True, **hints):
|
387 |
+
if hints.get('ignore') == self:
|
388 |
+
return None
|
389 |
+
else:
|
390 |
+
from sympy.functions.elementary.complexes import im, re
|
391 |
+
return (re(self), im(self))
|
392 |
+
|
393 |
+
def is_constant(self, *wrt, **flags):
|
394 |
+
if not wrt:
|
395 |
+
return False
|
396 |
+
return self not in wrt
|
397 |
+
|
398 |
+
@property
|
399 |
+
def free_symbols(self):
|
400 |
+
return {self}
|
401 |
+
|
402 |
+
binary_symbols = free_symbols # in this case, not always
|
403 |
+
|
404 |
+
def as_set(self):
|
405 |
+
return S.UniversalSet
|
406 |
+
|
407 |
+
|
408 |
+
class Dummy(Symbol):
|
409 |
+
"""Dummy symbols are each unique, even if they have the same name:
|
410 |
+
|
411 |
+
Examples
|
412 |
+
========
|
413 |
+
|
414 |
+
>>> from sympy import Dummy
|
415 |
+
>>> Dummy("x") == Dummy("x")
|
416 |
+
False
|
417 |
+
|
418 |
+
If a name is not supplied then a string value of an internal count will be
|
419 |
+
used. This is useful when a temporary variable is needed and the name
|
420 |
+
of the variable used in the expression is not important.
|
421 |
+
|
422 |
+
>>> Dummy() #doctest: +SKIP
|
423 |
+
_Dummy_10
|
424 |
+
|
425 |
+
"""
|
426 |
+
|
427 |
+
# In the rare event that a Dummy object needs to be recreated, both the
|
428 |
+
# `name` and `dummy_index` should be passed. This is used by `srepr` for
|
429 |
+
# example:
|
430 |
+
# >>> d1 = Dummy()
|
431 |
+
# >>> d2 = eval(srepr(d1))
|
432 |
+
# >>> d2 == d1
|
433 |
+
# True
|
434 |
+
#
|
435 |
+
# If a new session is started between `srepr` and `eval`, there is a very
|
436 |
+
# small chance that `d2` will be equal to a previously-created Dummy.
|
437 |
+
|
438 |
+
_count = 0
|
439 |
+
_prng = random.Random()
|
440 |
+
_base_dummy_index = _prng.randint(10**6, 9*10**6)
|
441 |
+
|
442 |
+
__slots__ = ('dummy_index',)
|
443 |
+
|
444 |
+
is_Dummy = True
|
445 |
+
|
446 |
+
def __new__(cls, name=None, dummy_index=None, **assumptions):
|
447 |
+
if dummy_index is not None:
|
448 |
+
assert name is not None, "If you specify a dummy_index, you must also provide a name"
|
449 |
+
|
450 |
+
if name is None:
|
451 |
+
name = "Dummy_" + str(Dummy._count)
|
452 |
+
|
453 |
+
if dummy_index is None:
|
454 |
+
dummy_index = Dummy._base_dummy_index + Dummy._count
|
455 |
+
Dummy._count += 1
|
456 |
+
|
457 |
+
cls._sanitize(assumptions, cls)
|
458 |
+
obj = Symbol.__xnew__(cls, name, **assumptions)
|
459 |
+
|
460 |
+
obj.dummy_index = dummy_index
|
461 |
+
|
462 |
+
return obj
|
463 |
+
|
464 |
+
def __getnewargs_ex__(self):
|
465 |
+
return ((self.name, self.dummy_index), self._assumptions_orig)
|
466 |
+
|
467 |
+
@cacheit
|
468 |
+
def sort_key(self, order=None):
|
469 |
+
return self.class_key(), (
|
470 |
+
2, (self.name, self.dummy_index)), S.One.sort_key(), S.One
|
471 |
+
|
472 |
+
def _hashable_content(self):
|
473 |
+
return Symbol._hashable_content(self) + (self.dummy_index,)
|
474 |
+
|
475 |
+
|
476 |
+
class Wild(Symbol):
|
477 |
+
"""
|
478 |
+
A Wild symbol matches anything, or anything
|
479 |
+
without whatever is explicitly excluded.
|
480 |
+
|
481 |
+
Parameters
|
482 |
+
==========
|
483 |
+
|
484 |
+
name : str
|
485 |
+
Name of the Wild instance.
|
486 |
+
|
487 |
+
exclude : iterable, optional
|
488 |
+
Instances in ``exclude`` will not be matched.
|
489 |
+
|
490 |
+
properties : iterable of functions, optional
|
491 |
+
Functions, each taking an expressions as input
|
492 |
+
and returns a ``bool``. All functions in ``properties``
|
493 |
+
need to return ``True`` in order for the Wild instance
|
494 |
+
to match the expression.
|
495 |
+
|
496 |
+
Examples
|
497 |
+
========
|
498 |
+
|
499 |
+
>>> from sympy import Wild, WildFunction, cos, pi
|
500 |
+
>>> from sympy.abc import x, y, z
|
501 |
+
>>> a = Wild('a')
|
502 |
+
>>> x.match(a)
|
503 |
+
{a_: x}
|
504 |
+
>>> pi.match(a)
|
505 |
+
{a_: pi}
|
506 |
+
>>> (3*x**2).match(a*x)
|
507 |
+
{a_: 3*x}
|
508 |
+
>>> cos(x).match(a)
|
509 |
+
{a_: cos(x)}
|
510 |
+
>>> b = Wild('b', exclude=[x])
|
511 |
+
>>> (3*x**2).match(b*x)
|
512 |
+
>>> b.match(a)
|
513 |
+
{a_: b_}
|
514 |
+
>>> A = WildFunction('A')
|
515 |
+
>>> A.match(a)
|
516 |
+
{a_: A_}
|
517 |
+
|
518 |
+
Tips
|
519 |
+
====
|
520 |
+
|
521 |
+
When using Wild, be sure to use the exclude
|
522 |
+
keyword to make the pattern more precise.
|
523 |
+
Without the exclude pattern, you may get matches
|
524 |
+
that are technically correct, but not what you
|
525 |
+
wanted. For example, using the above without
|
526 |
+
exclude:
|
527 |
+
|
528 |
+
>>> from sympy import symbols
|
529 |
+
>>> a, b = symbols('a b', cls=Wild)
|
530 |
+
>>> (2 + 3*y).match(a*x + b*y)
|
531 |
+
{a_: 2/x, b_: 3}
|
532 |
+
|
533 |
+
This is technically correct, because
|
534 |
+
(2/x)*x + 3*y == 2 + 3*y, but you probably
|
535 |
+
wanted it to not match at all. The issue is that
|
536 |
+
you really did not want a and b to include x and y,
|
537 |
+
and the exclude parameter lets you specify exactly
|
538 |
+
this. With the exclude parameter, the pattern will
|
539 |
+
not match.
|
540 |
+
|
541 |
+
>>> a = Wild('a', exclude=[x, y])
|
542 |
+
>>> b = Wild('b', exclude=[x, y])
|
543 |
+
>>> (2 + 3*y).match(a*x + b*y)
|
544 |
+
|
545 |
+
Exclude also helps remove ambiguity from matches.
|
546 |
+
|
547 |
+
>>> E = 2*x**3*y*z
|
548 |
+
>>> a, b = symbols('a b', cls=Wild)
|
549 |
+
>>> E.match(a*b)
|
550 |
+
{a_: 2*y*z, b_: x**3}
|
551 |
+
>>> a = Wild('a', exclude=[x, y])
|
552 |
+
>>> E.match(a*b)
|
553 |
+
{a_: z, b_: 2*x**3*y}
|
554 |
+
>>> a = Wild('a', exclude=[x, y, z])
|
555 |
+
>>> E.match(a*b)
|
556 |
+
{a_: 2, b_: x**3*y*z}
|
557 |
+
|
558 |
+
Wild also accepts a ``properties`` parameter:
|
559 |
+
|
560 |
+
>>> a = Wild('a', properties=[lambda k: k.is_Integer])
|
561 |
+
>>> E.match(a*b)
|
562 |
+
{a_: 2, b_: x**3*y*z}
|
563 |
+
|
564 |
+
"""
|
565 |
+
is_Wild = True
|
566 |
+
|
567 |
+
__slots__ = ('exclude', 'properties')
|
568 |
+
|
569 |
+
def __new__(cls, name, exclude=(), properties=(), **assumptions):
|
570 |
+
exclude = tuple([sympify(x) for x in exclude])
|
571 |
+
properties = tuple(properties)
|
572 |
+
cls._sanitize(assumptions, cls)
|
573 |
+
return Wild.__xnew__(cls, name, exclude, properties, **assumptions)
|
574 |
+
|
575 |
+
def __getnewargs__(self):
|
576 |
+
return (self.name, self.exclude, self.properties)
|
577 |
+
|
578 |
+
@staticmethod
|
579 |
+
@cacheit
|
580 |
+
def __xnew__(cls, name, exclude, properties, **assumptions):
|
581 |
+
obj = Symbol.__xnew__(cls, name, **assumptions)
|
582 |
+
obj.exclude = exclude
|
583 |
+
obj.properties = properties
|
584 |
+
return obj
|
585 |
+
|
586 |
+
def _hashable_content(self):
|
587 |
+
return super()._hashable_content() + (self.exclude, self.properties)
|
588 |
+
|
589 |
+
# TODO add check against another Wild
|
590 |
+
def matches(self, expr, repl_dict=None, old=False):
|
591 |
+
if any(expr.has(x) for x in self.exclude):
|
592 |
+
return None
|
593 |
+
if not all(f(expr) for f in self.properties):
|
594 |
+
return None
|
595 |
+
if repl_dict is None:
|
596 |
+
repl_dict = {}
|
597 |
+
else:
|
598 |
+
repl_dict = repl_dict.copy()
|
599 |
+
repl_dict[self] = expr
|
600 |
+
return repl_dict
|
601 |
+
|
602 |
+
|
603 |
+
_range = _re.compile('([0-9]*:[0-9]+|[a-zA-Z]?:[a-zA-Z])')
|
604 |
+
|
605 |
+
|
606 |
+
def symbols(names, *, cls=Symbol, **args) -> Any:
|
607 |
+
r"""
|
608 |
+
Transform strings into instances of :class:`Symbol` class.
|
609 |
+
|
610 |
+
:func:`symbols` function returns a sequence of symbols with names taken
|
611 |
+
from ``names`` argument, which can be a comma or whitespace delimited
|
612 |
+
string, or a sequence of strings::
|
613 |
+
|
614 |
+
>>> from sympy import symbols, Function
|
615 |
+
|
616 |
+
>>> x, y, z = symbols('x,y,z')
|
617 |
+
>>> a, b, c = symbols('a b c')
|
618 |
+
|
619 |
+
The type of output is dependent on the properties of input arguments::
|
620 |
+
|
621 |
+
>>> symbols('x')
|
622 |
+
x
|
623 |
+
>>> symbols('x,')
|
624 |
+
(x,)
|
625 |
+
>>> symbols('x,y')
|
626 |
+
(x, y)
|
627 |
+
>>> symbols(('a', 'b', 'c'))
|
628 |
+
(a, b, c)
|
629 |
+
>>> symbols(['a', 'b', 'c'])
|
630 |
+
[a, b, c]
|
631 |
+
>>> symbols({'a', 'b', 'c'})
|
632 |
+
{a, b, c}
|
633 |
+
|
634 |
+
If an iterable container is needed for a single symbol, set the ``seq``
|
635 |
+
argument to ``True`` or terminate the symbol name with a comma::
|
636 |
+
|
637 |
+
>>> symbols('x', seq=True)
|
638 |
+
(x,)
|
639 |
+
|
640 |
+
To reduce typing, range syntax is supported to create indexed symbols.
|
641 |
+
Ranges are indicated by a colon and the type of range is determined by
|
642 |
+
the character to the right of the colon. If the character is a digit
|
643 |
+
then all contiguous digits to the left are taken as the nonnegative
|
644 |
+
starting value (or 0 if there is no digit left of the colon) and all
|
645 |
+
contiguous digits to the right are taken as 1 greater than the ending
|
646 |
+
value::
|
647 |
+
|
648 |
+
>>> symbols('x:10')
|
649 |
+
(x0, x1, x2, x3, x4, x5, x6, x7, x8, x9)
|
650 |
+
|
651 |
+
>>> symbols('x5:10')
|
652 |
+
(x5, x6, x7, x8, x9)
|
653 |
+
>>> symbols('x5(:2)')
|
654 |
+
(x50, x51)
|
655 |
+
|
656 |
+
>>> symbols('x5:10,y:5')
|
657 |
+
(x5, x6, x7, x8, x9, y0, y1, y2, y3, y4)
|
658 |
+
|
659 |
+
>>> symbols(('x5:10', 'y:5'))
|
660 |
+
((x5, x6, x7, x8, x9), (y0, y1, y2, y3, y4))
|
661 |
+
|
662 |
+
If the character to the right of the colon is a letter, then the single
|
663 |
+
letter to the left (or 'a' if there is none) is taken as the start
|
664 |
+
and all characters in the lexicographic range *through* the letter to
|
665 |
+
the right are used as the range::
|
666 |
+
|
667 |
+
>>> symbols('x:z')
|
668 |
+
(x, y, z)
|
669 |
+
>>> symbols('x:c') # null range
|
670 |
+
()
|
671 |
+
>>> symbols('x(:c)')
|
672 |
+
(xa, xb, xc)
|
673 |
+
|
674 |
+
>>> symbols(':c')
|
675 |
+
(a, b, c)
|
676 |
+
|
677 |
+
>>> symbols('a:d, x:z')
|
678 |
+
(a, b, c, d, x, y, z)
|
679 |
+
|
680 |
+
>>> symbols(('a:d', 'x:z'))
|
681 |
+
((a, b, c, d), (x, y, z))
|
682 |
+
|
683 |
+
Multiple ranges are supported; contiguous numerical ranges should be
|
684 |
+
separated by parentheses to disambiguate the ending number of one
|
685 |
+
range from the starting number of the next::
|
686 |
+
|
687 |
+
>>> symbols('x:2(1:3)')
|
688 |
+
(x01, x02, x11, x12)
|
689 |
+
>>> symbols(':3:2') # parsing is from left to right
|
690 |
+
(00, 01, 10, 11, 20, 21)
|
691 |
+
|
692 |
+
Only one pair of parentheses surrounding ranges are removed, so to
|
693 |
+
include parentheses around ranges, double them. And to include spaces,
|
694 |
+
commas, or colons, escape them with a backslash::
|
695 |
+
|
696 |
+
>>> symbols('x((a:b))')
|
697 |
+
(x(a), x(b))
|
698 |
+
>>> symbols(r'x(:1\,:2)') # or r'x((:1)\,(:2))'
|
699 |
+
(x(0,0), x(0,1))
|
700 |
+
|
701 |
+
All newly created symbols have assumptions set according to ``args``::
|
702 |
+
|
703 |
+
>>> a = symbols('a', integer=True)
|
704 |
+
>>> a.is_integer
|
705 |
+
True
|
706 |
+
|
707 |
+
>>> x, y, z = symbols('x,y,z', real=True)
|
708 |
+
>>> x.is_real and y.is_real and z.is_real
|
709 |
+
True
|
710 |
+
|
711 |
+
Despite its name, :func:`symbols` can create symbol-like objects like
|
712 |
+
instances of Function or Wild classes. To achieve this, set ``cls``
|
713 |
+
keyword argument to the desired type::
|
714 |
+
|
715 |
+
>>> symbols('f,g,h', cls=Function)
|
716 |
+
(f, g, h)
|
717 |
+
|
718 |
+
>>> type(_[0])
|
719 |
+
<class 'sympy.core.function.UndefinedFunction'>
|
720 |
+
|
721 |
+
"""
|
722 |
+
result = []
|
723 |
+
|
724 |
+
if isinstance(names, str):
|
725 |
+
marker = 0
|
726 |
+
splitters = r'\,', r'\:', r'\ '
|
727 |
+
literals: list[tuple[str, str]] = []
|
728 |
+
for splitter in splitters:
|
729 |
+
if splitter in names:
|
730 |
+
while chr(marker) in names:
|
731 |
+
marker += 1
|
732 |
+
lit_char = chr(marker)
|
733 |
+
marker += 1
|
734 |
+
names = names.replace(splitter, lit_char)
|
735 |
+
literals.append((lit_char, splitter[1:]))
|
736 |
+
def literal(s):
|
737 |
+
if literals:
|
738 |
+
for c, l in literals:
|
739 |
+
s = s.replace(c, l)
|
740 |
+
return s
|
741 |
+
|
742 |
+
names = names.strip()
|
743 |
+
as_seq = names.endswith(',')
|
744 |
+
if as_seq:
|
745 |
+
names = names[:-1].rstrip()
|
746 |
+
if not names:
|
747 |
+
raise ValueError('no symbols given')
|
748 |
+
|
749 |
+
# split on commas
|
750 |
+
names = [n.strip() for n in names.split(',')]
|
751 |
+
if not all(n for n in names):
|
752 |
+
raise ValueError('missing symbol between commas')
|
753 |
+
# split on spaces
|
754 |
+
for i in range(len(names) - 1, -1, -1):
|
755 |
+
names[i: i + 1] = names[i].split()
|
756 |
+
|
757 |
+
seq = args.pop('seq', as_seq)
|
758 |
+
|
759 |
+
for name in names:
|
760 |
+
if not name:
|
761 |
+
raise ValueError('missing symbol')
|
762 |
+
|
763 |
+
if ':' not in name:
|
764 |
+
symbol = cls(literal(name), **args)
|
765 |
+
result.append(symbol)
|
766 |
+
continue
|
767 |
+
|
768 |
+
split: list[str] = _range.split(name)
|
769 |
+
split_list: list[list[str]] = []
|
770 |
+
# remove 1 layer of bounding parentheses around ranges
|
771 |
+
for i in range(len(split) - 1):
|
772 |
+
if i and ':' in split[i] and split[i] != ':' and \
|
773 |
+
split[i - 1].endswith('(') and \
|
774 |
+
split[i + 1].startswith(')'):
|
775 |
+
split[i - 1] = split[i - 1][:-1]
|
776 |
+
split[i + 1] = split[i + 1][1:]
|
777 |
+
for s in split:
|
778 |
+
if ':' in s:
|
779 |
+
if s.endswith(':'):
|
780 |
+
raise ValueError('missing end range')
|
781 |
+
a, b = s.split(':')
|
782 |
+
if b[-1] in string.digits:
|
783 |
+
a_i = 0 if not a else int(a)
|
784 |
+
b_i = int(b)
|
785 |
+
split_list.append([str(c) for c in range(a_i, b_i)])
|
786 |
+
else:
|
787 |
+
a = a or 'a'
|
788 |
+
split_list.append([string.ascii_letters[c] for c in range(
|
789 |
+
string.ascii_letters.index(a),
|
790 |
+
string.ascii_letters.index(b) + 1)]) # inclusive
|
791 |
+
if not split_list[-1]:
|
792 |
+
break
|
793 |
+
else:
|
794 |
+
split_list.append([s])
|
795 |
+
else:
|
796 |
+
seq = True
|
797 |
+
if len(split_list) == 1:
|
798 |
+
names = split_list[0]
|
799 |
+
else:
|
800 |
+
names = [''.join(s) for s in product(*split_list)]
|
801 |
+
if literals:
|
802 |
+
result.extend([cls(literal(s), **args) for s in names])
|
803 |
+
else:
|
804 |
+
result.extend([cls(s, **args) for s in names])
|
805 |
+
|
806 |
+
if not seq and len(result) <= 1:
|
807 |
+
if not result:
|
808 |
+
return ()
|
809 |
+
return result[0]
|
810 |
+
|
811 |
+
return tuple(result)
|
812 |
+
else:
|
813 |
+
for name in names:
|
814 |
+
result.append(symbols(name, cls=cls, **args))
|
815 |
+
|
816 |
+
return type(names)(result)
|
817 |
+
|
818 |
+
|
819 |
+
def var(names, **args):
|
820 |
+
"""
|
821 |
+
Create symbols and inject them into the global namespace.
|
822 |
+
|
823 |
+
Explanation
|
824 |
+
===========
|
825 |
+
|
826 |
+
This calls :func:`symbols` with the same arguments and puts the results
|
827 |
+
into the *global* namespace. It's recommended not to use :func:`var` in
|
828 |
+
library code, where :func:`symbols` has to be used::
|
829 |
+
|
830 |
+
Examples
|
831 |
+
========
|
832 |
+
|
833 |
+
>>> from sympy import var
|
834 |
+
|
835 |
+
>>> var('x')
|
836 |
+
x
|
837 |
+
>>> x # noqa: F821
|
838 |
+
x
|
839 |
+
|
840 |
+
>>> var('a,ab,abc')
|
841 |
+
(a, ab, abc)
|
842 |
+
>>> abc # noqa: F821
|
843 |
+
abc
|
844 |
+
|
845 |
+
>>> var('x,y', real=True)
|
846 |
+
(x, y)
|
847 |
+
>>> x.is_real and y.is_real # noqa: F821
|
848 |
+
True
|
849 |
+
|
850 |
+
See :func:`symbols` documentation for more details on what kinds of
|
851 |
+
arguments can be passed to :func:`var`.
|
852 |
+
|
853 |
+
"""
|
854 |
+
def traverse(symbols, frame):
|
855 |
+
"""Recursively inject symbols to the global namespace. """
|
856 |
+
for symbol in symbols:
|
857 |
+
if isinstance(symbol, Basic):
|
858 |
+
frame.f_globals[symbol.name] = symbol
|
859 |
+
elif isinstance(symbol, FunctionClass):
|
860 |
+
frame.f_globals[symbol.__name__] = symbol
|
861 |
+
else:
|
862 |
+
traverse(symbol, frame)
|
863 |
+
|
864 |
+
from inspect import currentframe
|
865 |
+
frame = currentframe().f_back
|
866 |
+
|
867 |
+
try:
|
868 |
+
syms = symbols(names, **args)
|
869 |
+
|
870 |
+
if syms is not None:
|
871 |
+
if isinstance(syms, Basic):
|
872 |
+
frame.f_globals[syms.name] = syms
|
873 |
+
elif isinstance(syms, FunctionClass):
|
874 |
+
frame.f_globals[syms.__name__] = syms
|
875 |
+
else:
|
876 |
+
traverse(syms, frame)
|
877 |
+
finally:
|
878 |
+
del frame # break cyclic dependencies as stated in inspect docs
|
879 |
+
|
880 |
+
return syms
|
881 |
+
|
882 |
+
def disambiguate(*iter):
|
883 |
+
"""
|
884 |
+
Return a Tuple containing the passed expressions with symbols
|
885 |
+
that appear the same when printed replaced with numerically
|
886 |
+
subscripted symbols, and all Dummy symbols replaced with Symbols.
|
887 |
+
|
888 |
+
Parameters
|
889 |
+
==========
|
890 |
+
|
891 |
+
iter: list of symbols or expressions.
|
892 |
+
|
893 |
+
Examples
|
894 |
+
========
|
895 |
+
|
896 |
+
>>> from sympy.core.symbol import disambiguate
|
897 |
+
>>> from sympy import Dummy, Symbol, Tuple
|
898 |
+
>>> from sympy.abc import y
|
899 |
+
|
900 |
+
>>> tup = Symbol('_x'), Dummy('x'), Dummy('x')
|
901 |
+
>>> disambiguate(*tup)
|
902 |
+
(x_2, x, x_1)
|
903 |
+
|
904 |
+
>>> eqs = Tuple(Symbol('x')/y, Dummy('x')/y)
|
905 |
+
>>> disambiguate(*eqs)
|
906 |
+
(x_1/y, x/y)
|
907 |
+
|
908 |
+
>>> ix = Symbol('x', integer=True)
|
909 |
+
>>> vx = Symbol('x')
|
910 |
+
>>> disambiguate(vx + ix)
|
911 |
+
(x + x_1,)
|
912 |
+
|
913 |
+
To make your own mapping of symbols to use, pass only the free symbols
|
914 |
+
of the expressions and create a dictionary:
|
915 |
+
|
916 |
+
>>> free = eqs.free_symbols
|
917 |
+
>>> mapping = dict(zip(free, disambiguate(*free)))
|
918 |
+
>>> eqs.xreplace(mapping)
|
919 |
+
(x_1/y, x/y)
|
920 |
+
|
921 |
+
"""
|
922 |
+
new_iter = Tuple(*iter)
|
923 |
+
key = lambda x:tuple(sorted(x.assumptions0.items()))
|
924 |
+
syms = ordered(new_iter.free_symbols, keys=key)
|
925 |
+
mapping = {}
|
926 |
+
for s in syms:
|
927 |
+
mapping.setdefault(str(s).lstrip('_'), []).append(s)
|
928 |
+
reps = {}
|
929 |
+
for k in mapping:
|
930 |
+
# the first or only symbol doesn't get subscripted but make
|
931 |
+
# sure that it's a Symbol, not a Dummy
|
932 |
+
mapk0 = Symbol("%s" % (k), **mapping[k][0].assumptions0)
|
933 |
+
if mapping[k][0] != mapk0:
|
934 |
+
reps[mapping[k][0]] = mapk0
|
935 |
+
# the others get subscripts (and are made into Symbols)
|
936 |
+
skip = 0
|
937 |
+
for i in range(1, len(mapping[k])):
|
938 |
+
while True:
|
939 |
+
name = "%s_%i" % (k, i + skip)
|
940 |
+
if name not in mapping:
|
941 |
+
break
|
942 |
+
skip += 1
|
943 |
+
ki = mapping[k][i]
|
944 |
+
reps[ki] = Symbol(name, **ki.assumptions0)
|
945 |
+
return new_iter.xreplace(reps)
|
env-llmeval/lib/python3.10/site-packages/sympy/diffgeom/__init__.py
ADDED
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from .diffgeom import (
|
2 |
+
BaseCovarDerivativeOp, BaseScalarField, BaseVectorField, Commutator,
|
3 |
+
contravariant_order, CoordSystem, CoordinateSymbol,
|
4 |
+
CovarDerivativeOp, covariant_order, Differential, intcurve_diffequ,
|
5 |
+
intcurve_series, LieDerivative, Manifold, metric_to_Christoffel_1st,
|
6 |
+
metric_to_Christoffel_2nd, metric_to_Ricci_components,
|
7 |
+
metric_to_Riemann_components, Patch, Point, TensorProduct, twoform_to_matrix,
|
8 |
+
vectors_in_basis, WedgeProduct,
|
9 |
+
)
|
10 |
+
|
11 |
+
__all__ = [
|
12 |
+
'BaseCovarDerivativeOp', 'BaseScalarField', 'BaseVectorField', 'Commutator',
|
13 |
+
'contravariant_order', 'CoordSystem', 'CoordinateSymbol',
|
14 |
+
'CovarDerivativeOp', 'covariant_order', 'Differential', 'intcurve_diffequ',
|
15 |
+
'intcurve_series', 'LieDerivative', 'Manifold', 'metric_to_Christoffel_1st',
|
16 |
+
'metric_to_Christoffel_2nd', 'metric_to_Ricci_components',
|
17 |
+
'metric_to_Riemann_components', 'Patch', 'Point', 'TensorProduct',
|
18 |
+
'twoform_to_matrix', 'vectors_in_basis', 'WedgeProduct',
|
19 |
+
]
|
env-llmeval/lib/python3.10/site-packages/sympy/diffgeom/diffgeom.py
ADDED
@@ -0,0 +1,2273 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from __future__ import annotations
|
2 |
+
from typing import Any
|
3 |
+
|
4 |
+
from functools import reduce
|
5 |
+
from itertools import permutations
|
6 |
+
|
7 |
+
from sympy.combinatorics import Permutation
|
8 |
+
from sympy.core import (
|
9 |
+
Basic, Expr, Function, diff,
|
10 |
+
Pow, Mul, Add, Lambda, S, Tuple, Dict
|
11 |
+
)
|
12 |
+
from sympy.core.cache import cacheit
|
13 |
+
|
14 |
+
from sympy.core.symbol import Symbol, Dummy
|
15 |
+
from sympy.core.symbol import Str
|
16 |
+
from sympy.core.sympify import _sympify
|
17 |
+
from sympy.functions import factorial
|
18 |
+
from sympy.matrices import ImmutableDenseMatrix as Matrix
|
19 |
+
from sympy.solvers import solve
|
20 |
+
|
21 |
+
from sympy.utilities.exceptions import (sympy_deprecation_warning,
|
22 |
+
SymPyDeprecationWarning,
|
23 |
+
ignore_warnings)
|
24 |
+
|
25 |
+
|
26 |
+
# TODO you are a bit excessive in the use of Dummies
|
27 |
+
# TODO dummy point, literal field
|
28 |
+
# TODO too often one needs to call doit or simplify on the output, check the
|
29 |
+
# tests and find out why
|
30 |
+
from sympy.tensor.array import ImmutableDenseNDimArray
|
31 |
+
|
32 |
+
|
33 |
+
class Manifold(Basic):
|
34 |
+
"""
|
35 |
+
A mathematical manifold.
|
36 |
+
|
37 |
+
Explanation
|
38 |
+
===========
|
39 |
+
|
40 |
+
A manifold is a topological space that locally resembles
|
41 |
+
Euclidean space near each point [1].
|
42 |
+
This class does not provide any means to study the topological
|
43 |
+
characteristics of the manifold that it represents, though.
|
44 |
+
|
45 |
+
Parameters
|
46 |
+
==========
|
47 |
+
|
48 |
+
name : str
|
49 |
+
The name of the manifold.
|
50 |
+
|
51 |
+
dim : int
|
52 |
+
The dimension of the manifold.
|
53 |
+
|
54 |
+
Examples
|
55 |
+
========
|
56 |
+
|
57 |
+
>>> from sympy.diffgeom import Manifold
|
58 |
+
>>> m = Manifold('M', 2)
|
59 |
+
>>> m
|
60 |
+
M
|
61 |
+
>>> m.dim
|
62 |
+
2
|
63 |
+
|
64 |
+
References
|
65 |
+
==========
|
66 |
+
|
67 |
+
.. [1] https://en.wikipedia.org/wiki/Manifold
|
68 |
+
"""
|
69 |
+
|
70 |
+
def __new__(cls, name, dim, **kwargs):
|
71 |
+
if not isinstance(name, Str):
|
72 |
+
name = Str(name)
|
73 |
+
dim = _sympify(dim)
|
74 |
+
obj = super().__new__(cls, name, dim)
|
75 |
+
|
76 |
+
obj.patches = _deprecated_list(
|
77 |
+
"""
|
78 |
+
Manifold.patches is deprecated. The Manifold object is now
|
79 |
+
immutable. Instead use a separate list to keep track of the
|
80 |
+
patches.
|
81 |
+
""", [])
|
82 |
+
return obj
|
83 |
+
|
84 |
+
@property
|
85 |
+
def name(self):
|
86 |
+
return self.args[0]
|
87 |
+
|
88 |
+
@property
|
89 |
+
def dim(self):
|
90 |
+
return self.args[1]
|
91 |
+
|
92 |
+
|
93 |
+
class Patch(Basic):
|
94 |
+
"""
|
95 |
+
A patch on a manifold.
|
96 |
+
|
97 |
+
Explanation
|
98 |
+
===========
|
99 |
+
|
100 |
+
Coordinate patch, or patch in short, is a simply-connected open set around
|
101 |
+
a point in the manifold [1]. On a manifold one can have many patches that
|
102 |
+
do not always include the whole manifold. On these patches coordinate
|
103 |
+
charts can be defined that permit the parameterization of any point on the
|
104 |
+
patch in terms of a tuple of real numbers (the coordinates).
|
105 |
+
|
106 |
+
This class does not provide any means to study the topological
|
107 |
+
characteristics of the patch that it represents.
|
108 |
+
|
109 |
+
Parameters
|
110 |
+
==========
|
111 |
+
|
112 |
+
name : str
|
113 |
+
The name of the patch.
|
114 |
+
|
115 |
+
manifold : Manifold
|
116 |
+
The manifold on which the patch is defined.
|
117 |
+
|
118 |
+
Examples
|
119 |
+
========
|
120 |
+
|
121 |
+
>>> from sympy.diffgeom import Manifold, Patch
|
122 |
+
>>> m = Manifold('M', 2)
|
123 |
+
>>> p = Patch('P', m)
|
124 |
+
>>> p
|
125 |
+
P
|
126 |
+
>>> p.dim
|
127 |
+
2
|
128 |
+
|
129 |
+
References
|
130 |
+
==========
|
131 |
+
|
132 |
+
.. [1] G. Sussman, J. Wisdom, W. Farr, Functional Differential Geometry
|
133 |
+
(2013)
|
134 |
+
|
135 |
+
"""
|
136 |
+
def __new__(cls, name, manifold, **kwargs):
|
137 |
+
if not isinstance(name, Str):
|
138 |
+
name = Str(name)
|
139 |
+
obj = super().__new__(cls, name, manifold)
|
140 |
+
|
141 |
+
obj.manifold.patches.append(obj) # deprecated
|
142 |
+
obj.coord_systems = _deprecated_list(
|
143 |
+
"""
|
144 |
+
Patch.coord_systms is deprecated. The Patch class is now
|
145 |
+
immutable. Instead use a separate list to keep track of coordinate
|
146 |
+
systems.
|
147 |
+
""", [])
|
148 |
+
return obj
|
149 |
+
|
150 |
+
@property
|
151 |
+
def name(self):
|
152 |
+
return self.args[0]
|
153 |
+
|
154 |
+
@property
|
155 |
+
def manifold(self):
|
156 |
+
return self.args[1]
|
157 |
+
|
158 |
+
@property
|
159 |
+
def dim(self):
|
160 |
+
return self.manifold.dim
|
161 |
+
|
162 |
+
|
163 |
+
class CoordSystem(Basic):
|
164 |
+
"""
|
165 |
+
A coordinate system defined on the patch.
|
166 |
+
|
167 |
+
Explanation
|
168 |
+
===========
|
169 |
+
|
170 |
+
Coordinate system is a system that uses one or more coordinates to uniquely
|
171 |
+
determine the position of the points or other geometric elements on a
|
172 |
+
manifold [1].
|
173 |
+
|
174 |
+
By passing ``Symbols`` to *symbols* parameter, user can define the name and
|
175 |
+
assumptions of coordinate symbols of the coordinate system. If not passed,
|
176 |
+
these symbols are generated automatically and are assumed to be real valued.
|
177 |
+
|
178 |
+
By passing *relations* parameter, user can define the transform relations of
|
179 |
+
coordinate systems. Inverse transformation and indirect transformation can
|
180 |
+
be found automatically. If this parameter is not passed, coordinate
|
181 |
+
transformation cannot be done.
|
182 |
+
|
183 |
+
Parameters
|
184 |
+
==========
|
185 |
+
|
186 |
+
name : str
|
187 |
+
The name of the coordinate system.
|
188 |
+
|
189 |
+
patch : Patch
|
190 |
+
The patch where the coordinate system is defined.
|
191 |
+
|
192 |
+
symbols : list of Symbols, optional
|
193 |
+
Defines the names and assumptions of coordinate symbols.
|
194 |
+
|
195 |
+
relations : dict, optional
|
196 |
+
Key is a tuple of two strings, who are the names of the systems where
|
197 |
+
the coordinates transform from and transform to.
|
198 |
+
Value is a tuple of the symbols before transformation and a tuple of
|
199 |
+
the expressions after transformation.
|
200 |
+
|
201 |
+
Examples
|
202 |
+
========
|
203 |
+
|
204 |
+
We define two-dimensional Cartesian coordinate system and polar coordinate
|
205 |
+
system.
|
206 |
+
|
207 |
+
>>> from sympy import symbols, pi, sqrt, atan2, cos, sin
|
208 |
+
>>> from sympy.diffgeom import Manifold, Patch, CoordSystem
|
209 |
+
>>> m = Manifold('M', 2)
|
210 |
+
>>> p = Patch('P', m)
|
211 |
+
>>> x, y = symbols('x y', real=True)
|
212 |
+
>>> r, theta = symbols('r theta', nonnegative=True)
|
213 |
+
>>> relation_dict = {
|
214 |
+
... ('Car2D', 'Pol'): [(x, y), (sqrt(x**2 + y**2), atan2(y, x))],
|
215 |
+
... ('Pol', 'Car2D'): [(r, theta), (r*cos(theta), r*sin(theta))]
|
216 |
+
... }
|
217 |
+
>>> Car2D = CoordSystem('Car2D', p, (x, y), relation_dict)
|
218 |
+
>>> Pol = CoordSystem('Pol', p, (r, theta), relation_dict)
|
219 |
+
|
220 |
+
``symbols`` property returns ``CoordinateSymbol`` instances. These symbols
|
221 |
+
are not same with the symbols used to construct the coordinate system.
|
222 |
+
|
223 |
+
>>> Car2D
|
224 |
+
Car2D
|
225 |
+
>>> Car2D.dim
|
226 |
+
2
|
227 |
+
>>> Car2D.symbols
|
228 |
+
(x, y)
|
229 |
+
>>> _[0].func
|
230 |
+
<class 'sympy.diffgeom.diffgeom.CoordinateSymbol'>
|
231 |
+
|
232 |
+
``transformation()`` method returns the transformation function from
|
233 |
+
one coordinate system to another. ``transform()`` method returns the
|
234 |
+
transformed coordinates.
|
235 |
+
|
236 |
+
>>> Car2D.transformation(Pol)
|
237 |
+
Lambda((x, y), Matrix([
|
238 |
+
[sqrt(x**2 + y**2)],
|
239 |
+
[ atan2(y, x)]]))
|
240 |
+
>>> Car2D.transform(Pol)
|
241 |
+
Matrix([
|
242 |
+
[sqrt(x**2 + y**2)],
|
243 |
+
[ atan2(y, x)]])
|
244 |
+
>>> Car2D.transform(Pol, [1, 2])
|
245 |
+
Matrix([
|
246 |
+
[sqrt(5)],
|
247 |
+
[atan(2)]])
|
248 |
+
|
249 |
+
``jacobian()`` method returns the Jacobian matrix of coordinate
|
250 |
+
transformation between two systems. ``jacobian_determinant()`` method
|
251 |
+
returns the Jacobian determinant of coordinate transformation between two
|
252 |
+
systems.
|
253 |
+
|
254 |
+
>>> Pol.jacobian(Car2D)
|
255 |
+
Matrix([
|
256 |
+
[cos(theta), -r*sin(theta)],
|
257 |
+
[sin(theta), r*cos(theta)]])
|
258 |
+
>>> Pol.jacobian(Car2D, [1, pi/2])
|
259 |
+
Matrix([
|
260 |
+
[0, -1],
|
261 |
+
[1, 0]])
|
262 |
+
>>> Car2D.jacobian_determinant(Pol)
|
263 |
+
1/sqrt(x**2 + y**2)
|
264 |
+
>>> Car2D.jacobian_determinant(Pol, [1,0])
|
265 |
+
1
|
266 |
+
|
267 |
+
References
|
268 |
+
==========
|
269 |
+
|
270 |
+
.. [1] https://en.wikipedia.org/wiki/Coordinate_system
|
271 |
+
|
272 |
+
"""
|
273 |
+
def __new__(cls, name, patch, symbols=None, relations={}, **kwargs):
|
274 |
+
if not isinstance(name, Str):
|
275 |
+
name = Str(name)
|
276 |
+
|
277 |
+
# canonicallize the symbols
|
278 |
+
if symbols is None:
|
279 |
+
names = kwargs.get('names', None)
|
280 |
+
if names is None:
|
281 |
+
symbols = Tuple(
|
282 |
+
*[Symbol('%s_%s' % (name.name, i), real=True)
|
283 |
+
for i in range(patch.dim)]
|
284 |
+
)
|
285 |
+
else:
|
286 |
+
sympy_deprecation_warning(
|
287 |
+
f"""
|
288 |
+
The 'names' argument to CoordSystem is deprecated. Use 'symbols' instead. That
|
289 |
+
is, replace
|
290 |
+
|
291 |
+
CoordSystem(..., names={names})
|
292 |
+
|
293 |
+
with
|
294 |
+
|
295 |
+
CoordSystem(..., symbols=[{', '.join(["Symbol(" + repr(n) + ", real=True)" for n in names])}])
|
296 |
+
""",
|
297 |
+
deprecated_since_version="1.7",
|
298 |
+
active_deprecations_target="deprecated-diffgeom-mutable",
|
299 |
+
)
|
300 |
+
symbols = Tuple(
|
301 |
+
*[Symbol(n, real=True) for n in names]
|
302 |
+
)
|
303 |
+
else:
|
304 |
+
syms = []
|
305 |
+
for s in symbols:
|
306 |
+
if isinstance(s, Symbol):
|
307 |
+
syms.append(Symbol(s.name, **s._assumptions.generator))
|
308 |
+
elif isinstance(s, str):
|
309 |
+
sympy_deprecation_warning(
|
310 |
+
f"""
|
311 |
+
|
312 |
+
Passing a string as the coordinate symbol name to CoordSystem is deprecated.
|
313 |
+
Pass a Symbol with the appropriate name and assumptions instead.
|
314 |
+
|
315 |
+
That is, replace {s} with Symbol({s!r}, real=True).
|
316 |
+
""",
|
317 |
+
|
318 |
+
deprecated_since_version="1.7",
|
319 |
+
active_deprecations_target="deprecated-diffgeom-mutable",
|
320 |
+
)
|
321 |
+
syms.append(Symbol(s, real=True))
|
322 |
+
symbols = Tuple(*syms)
|
323 |
+
|
324 |
+
# canonicallize the relations
|
325 |
+
rel_temp = {}
|
326 |
+
for k,v in relations.items():
|
327 |
+
s1, s2 = k
|
328 |
+
if not isinstance(s1, Str):
|
329 |
+
s1 = Str(s1)
|
330 |
+
if not isinstance(s2, Str):
|
331 |
+
s2 = Str(s2)
|
332 |
+
key = Tuple(s1, s2)
|
333 |
+
|
334 |
+
# Old version used Lambda as a value.
|
335 |
+
if isinstance(v, Lambda):
|
336 |
+
v = (tuple(v.signature), tuple(v.expr))
|
337 |
+
else:
|
338 |
+
v = (tuple(v[0]), tuple(v[1]))
|
339 |
+
rel_temp[key] = v
|
340 |
+
relations = Dict(rel_temp)
|
341 |
+
|
342 |
+
# construct the object
|
343 |
+
obj = super().__new__(cls, name, patch, symbols, relations)
|
344 |
+
|
345 |
+
# Add deprecated attributes
|
346 |
+
obj.transforms = _deprecated_dict(
|
347 |
+
"""
|
348 |
+
CoordSystem.transforms is deprecated. The CoordSystem class is now
|
349 |
+
immutable. Use the 'relations' keyword argument to the
|
350 |
+
CoordSystems() constructor to specify relations.
|
351 |
+
""", {})
|
352 |
+
obj._names = [str(n) for n in symbols]
|
353 |
+
obj.patch.coord_systems.append(obj) # deprecated
|
354 |
+
obj._dummies = [Dummy(str(n)) for n in symbols] # deprecated
|
355 |
+
obj._dummy = Dummy()
|
356 |
+
|
357 |
+
return obj
|
358 |
+
|
359 |
+
@property
|
360 |
+
def name(self):
|
361 |
+
return self.args[0]
|
362 |
+
|
363 |
+
@property
|
364 |
+
def patch(self):
|
365 |
+
return self.args[1]
|
366 |
+
|
367 |
+
@property
|
368 |
+
def manifold(self):
|
369 |
+
return self.patch.manifold
|
370 |
+
|
371 |
+
@property
|
372 |
+
def symbols(self):
|
373 |
+
return tuple(CoordinateSymbol(self, i, **s._assumptions.generator)
|
374 |
+
for i,s in enumerate(self.args[2]))
|
375 |
+
|
376 |
+
@property
|
377 |
+
def relations(self):
|
378 |
+
return self.args[3]
|
379 |
+
|
380 |
+
@property
|
381 |
+
def dim(self):
|
382 |
+
return self.patch.dim
|
383 |
+
|
384 |
+
##########################################################################
|
385 |
+
# Finding transformation relation
|
386 |
+
##########################################################################
|
387 |
+
|
388 |
+
def transformation(self, sys):
|
389 |
+
"""
|
390 |
+
Return coordinate transformation function from *self* to *sys*.
|
391 |
+
|
392 |
+
Parameters
|
393 |
+
==========
|
394 |
+
|
395 |
+
sys : CoordSystem
|
396 |
+
|
397 |
+
Returns
|
398 |
+
=======
|
399 |
+
|
400 |
+
sympy.Lambda
|
401 |
+
|
402 |
+
Examples
|
403 |
+
========
|
404 |
+
|
405 |
+
>>> from sympy.diffgeom.rn import R2_r, R2_p
|
406 |
+
>>> R2_r.transformation(R2_p)
|
407 |
+
Lambda((x, y), Matrix([
|
408 |
+
[sqrt(x**2 + y**2)],
|
409 |
+
[ atan2(y, x)]]))
|
410 |
+
|
411 |
+
"""
|
412 |
+
signature = self.args[2]
|
413 |
+
|
414 |
+
key = Tuple(self.name, sys.name)
|
415 |
+
if self == sys:
|
416 |
+
expr = Matrix(self.symbols)
|
417 |
+
elif key in self.relations:
|
418 |
+
expr = Matrix(self.relations[key][1])
|
419 |
+
elif key[::-1] in self.relations:
|
420 |
+
expr = Matrix(self._inverse_transformation(sys, self))
|
421 |
+
else:
|
422 |
+
expr = Matrix(self._indirect_transformation(self, sys))
|
423 |
+
return Lambda(signature, expr)
|
424 |
+
|
425 |
+
@staticmethod
|
426 |
+
def _solve_inverse(sym1, sym2, exprs, sys1_name, sys2_name):
|
427 |
+
ret = solve(
|
428 |
+
[t[0] - t[1] for t in zip(sym2, exprs)],
|
429 |
+
list(sym1), dict=True)
|
430 |
+
|
431 |
+
if len(ret) == 0:
|
432 |
+
temp = "Cannot solve inverse relation from {} to {}."
|
433 |
+
raise NotImplementedError(temp.format(sys1_name, sys2_name))
|
434 |
+
elif len(ret) > 1:
|
435 |
+
temp = "Obtained multiple inverse relation from {} to {}."
|
436 |
+
raise ValueError(temp.format(sys1_name, sys2_name))
|
437 |
+
|
438 |
+
return ret[0]
|
439 |
+
|
440 |
+
@classmethod
|
441 |
+
def _inverse_transformation(cls, sys1, sys2):
|
442 |
+
# Find the transformation relation from sys2 to sys1
|
443 |
+
forward = sys1.transform(sys2)
|
444 |
+
inv_results = cls._solve_inverse(sys1.symbols, sys2.symbols, forward,
|
445 |
+
sys1.name, sys2.name)
|
446 |
+
signature = tuple(sys1.symbols)
|
447 |
+
return [inv_results[s] for s in signature]
|
448 |
+
|
449 |
+
@classmethod
|
450 |
+
@cacheit
|
451 |
+
def _indirect_transformation(cls, sys1, sys2):
|
452 |
+
# Find the transformation relation between two indirectly connected
|
453 |
+
# coordinate systems
|
454 |
+
rel = sys1.relations
|
455 |
+
path = cls._dijkstra(sys1, sys2)
|
456 |
+
|
457 |
+
transforms = []
|
458 |
+
for s1, s2 in zip(path, path[1:]):
|
459 |
+
if (s1, s2) in rel:
|
460 |
+
transforms.append(rel[(s1, s2)])
|
461 |
+
else:
|
462 |
+
sym2, inv_exprs = rel[(s2, s1)]
|
463 |
+
sym1 = tuple(Dummy() for i in sym2)
|
464 |
+
ret = cls._solve_inverse(sym2, sym1, inv_exprs, s2, s1)
|
465 |
+
ret = tuple(ret[s] for s in sym2)
|
466 |
+
transforms.append((sym1, ret))
|
467 |
+
syms = sys1.args[2]
|
468 |
+
exprs = syms
|
469 |
+
for newsyms, newexprs in transforms:
|
470 |
+
exprs = tuple(e.subs(zip(newsyms, exprs)) for e in newexprs)
|
471 |
+
return exprs
|
472 |
+
|
473 |
+
@staticmethod
|
474 |
+
def _dijkstra(sys1, sys2):
|
475 |
+
# Use Dijkstra algorithm to find the shortest path between two indirectly-connected
|
476 |
+
# coordinate systems
|
477 |
+
# return value is the list of the names of the systems.
|
478 |
+
relations = sys1.relations
|
479 |
+
graph = {}
|
480 |
+
for s1, s2 in relations.keys():
|
481 |
+
if s1 not in graph:
|
482 |
+
graph[s1] = {s2}
|
483 |
+
else:
|
484 |
+
graph[s1].add(s2)
|
485 |
+
if s2 not in graph:
|
486 |
+
graph[s2] = {s1}
|
487 |
+
else:
|
488 |
+
graph[s2].add(s1)
|
489 |
+
|
490 |
+
path_dict = {sys:[0, [], 0] for sys in graph} # minimum distance, path, times of visited
|
491 |
+
|
492 |
+
def visit(sys):
|
493 |
+
path_dict[sys][2] = 1
|
494 |
+
for newsys in graph[sys]:
|
495 |
+
distance = path_dict[sys][0] + 1
|
496 |
+
if path_dict[newsys][0] >= distance or not path_dict[newsys][1]:
|
497 |
+
path_dict[newsys][0] = distance
|
498 |
+
path_dict[newsys][1] = list(path_dict[sys][1])
|
499 |
+
path_dict[newsys][1].append(sys)
|
500 |
+
|
501 |
+
visit(sys1.name)
|
502 |
+
|
503 |
+
while True:
|
504 |
+
min_distance = max(path_dict.values(), key=lambda x:x[0])[0]
|
505 |
+
newsys = None
|
506 |
+
for sys, lst in path_dict.items():
|
507 |
+
if 0 < lst[0] <= min_distance and not lst[2]:
|
508 |
+
min_distance = lst[0]
|
509 |
+
newsys = sys
|
510 |
+
if newsys is None:
|
511 |
+
break
|
512 |
+
visit(newsys)
|
513 |
+
|
514 |
+
result = path_dict[sys2.name][1]
|
515 |
+
result.append(sys2.name)
|
516 |
+
|
517 |
+
if result == [sys2.name]:
|
518 |
+
raise KeyError("Two coordinate systems are not connected.")
|
519 |
+
return result
|
520 |
+
|
521 |
+
def connect_to(self, to_sys, from_coords, to_exprs, inverse=True, fill_in_gaps=False):
|
522 |
+
sympy_deprecation_warning(
|
523 |
+
"""
|
524 |
+
The CoordSystem.connect_to() method is deprecated. Instead,
|
525 |
+
generate a new instance of CoordSystem with the 'relations'
|
526 |
+
keyword argument (CoordSystem classes are now immutable).
|
527 |
+
""",
|
528 |
+
deprecated_since_version="1.7",
|
529 |
+
active_deprecations_target="deprecated-diffgeom-mutable",
|
530 |
+
)
|
531 |
+
|
532 |
+
from_coords, to_exprs = dummyfy(from_coords, to_exprs)
|
533 |
+
self.transforms[to_sys] = Matrix(from_coords), Matrix(to_exprs)
|
534 |
+
|
535 |
+
if inverse:
|
536 |
+
to_sys.transforms[self] = self._inv_transf(from_coords, to_exprs)
|
537 |
+
|
538 |
+
if fill_in_gaps:
|
539 |
+
self._fill_gaps_in_transformations()
|
540 |
+
|
541 |
+
@staticmethod
|
542 |
+
def _inv_transf(from_coords, to_exprs):
|
543 |
+
# Will be removed when connect_to is removed
|
544 |
+
inv_from = [i.as_dummy() for i in from_coords]
|
545 |
+
inv_to = solve(
|
546 |
+
[t[0] - t[1] for t in zip(inv_from, to_exprs)],
|
547 |
+
list(from_coords), dict=True)[0]
|
548 |
+
inv_to = [inv_to[fc] for fc in from_coords]
|
549 |
+
return Matrix(inv_from), Matrix(inv_to)
|
550 |
+
|
551 |
+
@staticmethod
|
552 |
+
def _fill_gaps_in_transformations():
|
553 |
+
# Will be removed when connect_to is removed
|
554 |
+
raise NotImplementedError
|
555 |
+
|
556 |
+
##########################################################################
|
557 |
+
# Coordinate transformations
|
558 |
+
##########################################################################
|
559 |
+
|
560 |
+
def transform(self, sys, coordinates=None):
|
561 |
+
"""
|
562 |
+
Return the result of coordinate transformation from *self* to *sys*.
|
563 |
+
If coordinates are not given, coordinate symbols of *self* are used.
|
564 |
+
|
565 |
+
Parameters
|
566 |
+
==========
|
567 |
+
|
568 |
+
sys : CoordSystem
|
569 |
+
|
570 |
+
coordinates : Any iterable, optional.
|
571 |
+
|
572 |
+
Returns
|
573 |
+
=======
|
574 |
+
|
575 |
+
sympy.ImmutableDenseMatrix containing CoordinateSymbol
|
576 |
+
|
577 |
+
Examples
|
578 |
+
========
|
579 |
+
|
580 |
+
>>> from sympy.diffgeom.rn import R2_r, R2_p
|
581 |
+
>>> R2_r.transform(R2_p)
|
582 |
+
Matrix([
|
583 |
+
[sqrt(x**2 + y**2)],
|
584 |
+
[ atan2(y, x)]])
|
585 |
+
>>> R2_r.transform(R2_p, [0, 1])
|
586 |
+
Matrix([
|
587 |
+
[ 1],
|
588 |
+
[pi/2]])
|
589 |
+
|
590 |
+
"""
|
591 |
+
if coordinates is None:
|
592 |
+
coordinates = self.symbols
|
593 |
+
if self != sys:
|
594 |
+
transf = self.transformation(sys)
|
595 |
+
coordinates = transf(*coordinates)
|
596 |
+
else:
|
597 |
+
coordinates = Matrix(coordinates)
|
598 |
+
return coordinates
|
599 |
+
|
600 |
+
def coord_tuple_transform_to(self, to_sys, coords):
|
601 |
+
"""Transform ``coords`` to coord system ``to_sys``."""
|
602 |
+
sympy_deprecation_warning(
|
603 |
+
"""
|
604 |
+
The CoordSystem.coord_tuple_transform_to() method is deprecated.
|
605 |
+
Use the CoordSystem.transform() method instead.
|
606 |
+
""",
|
607 |
+
deprecated_since_version="1.7",
|
608 |
+
active_deprecations_target="deprecated-diffgeom-mutable",
|
609 |
+
)
|
610 |
+
|
611 |
+
coords = Matrix(coords)
|
612 |
+
if self != to_sys:
|
613 |
+
with ignore_warnings(SymPyDeprecationWarning):
|
614 |
+
transf = self.transforms[to_sys]
|
615 |
+
coords = transf[1].subs(list(zip(transf[0], coords)))
|
616 |
+
return coords
|
617 |
+
|
618 |
+
def jacobian(self, sys, coordinates=None):
|
619 |
+
"""
|
620 |
+
Return the jacobian matrix of a transformation on given coordinates.
|
621 |
+
If coordinates are not given, coordinate symbols of *self* are used.
|
622 |
+
|
623 |
+
Parameters
|
624 |
+
==========
|
625 |
+
|
626 |
+
sys : CoordSystem
|
627 |
+
|
628 |
+
coordinates : Any iterable, optional.
|
629 |
+
|
630 |
+
Returns
|
631 |
+
=======
|
632 |
+
|
633 |
+
sympy.ImmutableDenseMatrix
|
634 |
+
|
635 |
+
Examples
|
636 |
+
========
|
637 |
+
|
638 |
+
>>> from sympy.diffgeom.rn import R2_r, R2_p
|
639 |
+
>>> R2_p.jacobian(R2_r)
|
640 |
+
Matrix([
|
641 |
+
[cos(theta), -rho*sin(theta)],
|
642 |
+
[sin(theta), rho*cos(theta)]])
|
643 |
+
>>> R2_p.jacobian(R2_r, [1, 0])
|
644 |
+
Matrix([
|
645 |
+
[1, 0],
|
646 |
+
[0, 1]])
|
647 |
+
|
648 |
+
"""
|
649 |
+
result = self.transform(sys).jacobian(self.symbols)
|
650 |
+
if coordinates is not None:
|
651 |
+
result = result.subs(list(zip(self.symbols, coordinates)))
|
652 |
+
return result
|
653 |
+
jacobian_matrix = jacobian
|
654 |
+
|
655 |
+
def jacobian_determinant(self, sys, coordinates=None):
|
656 |
+
"""
|
657 |
+
Return the jacobian determinant of a transformation on given
|
658 |
+
coordinates. If coordinates are not given, coordinate symbols of *self*
|
659 |
+
are used.
|
660 |
+
|
661 |
+
Parameters
|
662 |
+
==========
|
663 |
+
|
664 |
+
sys : CoordSystem
|
665 |
+
|
666 |
+
coordinates : Any iterable, optional.
|
667 |
+
|
668 |
+
Returns
|
669 |
+
=======
|
670 |
+
|
671 |
+
sympy.Expr
|
672 |
+
|
673 |
+
Examples
|
674 |
+
========
|
675 |
+
|
676 |
+
>>> from sympy.diffgeom.rn import R2_r, R2_p
|
677 |
+
>>> R2_r.jacobian_determinant(R2_p)
|
678 |
+
1/sqrt(x**2 + y**2)
|
679 |
+
>>> R2_r.jacobian_determinant(R2_p, [1, 0])
|
680 |
+
1
|
681 |
+
|
682 |
+
"""
|
683 |
+
return self.jacobian(sys, coordinates).det()
|
684 |
+
|
685 |
+
|
686 |
+
##########################################################################
|
687 |
+
# Points
|
688 |
+
##########################################################################
|
689 |
+
|
690 |
+
def point(self, coords):
|
691 |
+
"""Create a ``Point`` with coordinates given in this coord system."""
|
692 |
+
return Point(self, coords)
|
693 |
+
|
694 |
+
def point_to_coords(self, point):
|
695 |
+
"""Calculate the coordinates of a point in this coord system."""
|
696 |
+
return point.coords(self)
|
697 |
+
|
698 |
+
##########################################################################
|
699 |
+
# Base fields.
|
700 |
+
##########################################################################
|
701 |
+
|
702 |
+
def base_scalar(self, coord_index):
|
703 |
+
"""Return ``BaseScalarField`` that takes a point and returns one of the coordinates."""
|
704 |
+
return BaseScalarField(self, coord_index)
|
705 |
+
coord_function = base_scalar
|
706 |
+
|
707 |
+
def base_scalars(self):
|
708 |
+
"""Returns a list of all coordinate functions.
|
709 |
+
For more details see the ``base_scalar`` method of this class."""
|
710 |
+
return [self.base_scalar(i) for i in range(self.dim)]
|
711 |
+
coord_functions = base_scalars
|
712 |
+
|
713 |
+
def base_vector(self, coord_index):
|
714 |
+
"""Return a basis vector field.
|
715 |
+
The basis vector field for this coordinate system. It is also an
|
716 |
+
operator on scalar fields."""
|
717 |
+
return BaseVectorField(self, coord_index)
|
718 |
+
|
719 |
+
def base_vectors(self):
|
720 |
+
"""Returns a list of all base vectors.
|
721 |
+
For more details see the ``base_vector`` method of this class."""
|
722 |
+
return [self.base_vector(i) for i in range(self.dim)]
|
723 |
+
|
724 |
+
def base_oneform(self, coord_index):
|
725 |
+
"""Return a basis 1-form field.
|
726 |
+
The basis one-form field for this coordinate system. It is also an
|
727 |
+
operator on vector fields."""
|
728 |
+
return Differential(self.coord_function(coord_index))
|
729 |
+
|
730 |
+
def base_oneforms(self):
|
731 |
+
"""Returns a list of all base oneforms.
|
732 |
+
For more details see the ``base_oneform`` method of this class."""
|
733 |
+
return [self.base_oneform(i) for i in range(self.dim)]
|
734 |
+
|
735 |
+
|
736 |
+
class CoordinateSymbol(Symbol):
|
737 |
+
"""A symbol which denotes an abstract value of i-th coordinate of
|
738 |
+
the coordinate system with given context.
|
739 |
+
|
740 |
+
Explanation
|
741 |
+
===========
|
742 |
+
|
743 |
+
Each coordinates in coordinate system are represented by unique symbol,
|
744 |
+
such as x, y, z in Cartesian coordinate system.
|
745 |
+
|
746 |
+
You may not construct this class directly. Instead, use `symbols` method
|
747 |
+
of CoordSystem.
|
748 |
+
|
749 |
+
Parameters
|
750 |
+
==========
|
751 |
+
|
752 |
+
coord_sys : CoordSystem
|
753 |
+
|
754 |
+
index : integer
|
755 |
+
|
756 |
+
Examples
|
757 |
+
========
|
758 |
+
|
759 |
+
>>> from sympy import symbols, Lambda, Matrix, sqrt, atan2, cos, sin
|
760 |
+
>>> from sympy.diffgeom import Manifold, Patch, CoordSystem
|
761 |
+
>>> m = Manifold('M', 2)
|
762 |
+
>>> p = Patch('P', m)
|
763 |
+
>>> x, y = symbols('x y', real=True)
|
764 |
+
>>> r, theta = symbols('r theta', nonnegative=True)
|
765 |
+
>>> relation_dict = {
|
766 |
+
... ('Car2D', 'Pol'): Lambda((x, y), Matrix([sqrt(x**2 + y**2), atan2(y, x)])),
|
767 |
+
... ('Pol', 'Car2D'): Lambda((r, theta), Matrix([r*cos(theta), r*sin(theta)]))
|
768 |
+
... }
|
769 |
+
>>> Car2D = CoordSystem('Car2D', p, [x, y], relation_dict)
|
770 |
+
>>> Pol = CoordSystem('Pol', p, [r, theta], relation_dict)
|
771 |
+
>>> x, y = Car2D.symbols
|
772 |
+
|
773 |
+
``CoordinateSymbol`` contains its coordinate symbol and index.
|
774 |
+
|
775 |
+
>>> x.name
|
776 |
+
'x'
|
777 |
+
>>> x.coord_sys == Car2D
|
778 |
+
True
|
779 |
+
>>> x.index
|
780 |
+
0
|
781 |
+
>>> x.is_real
|
782 |
+
True
|
783 |
+
|
784 |
+
You can transform ``CoordinateSymbol`` into other coordinate system using
|
785 |
+
``rewrite()`` method.
|
786 |
+
|
787 |
+
>>> x.rewrite(Pol)
|
788 |
+
r*cos(theta)
|
789 |
+
>>> sqrt(x**2 + y**2).rewrite(Pol).simplify()
|
790 |
+
r
|
791 |
+
|
792 |
+
"""
|
793 |
+
def __new__(cls, coord_sys, index, **assumptions):
|
794 |
+
name = coord_sys.args[2][index].name
|
795 |
+
obj = super().__new__(cls, name, **assumptions)
|
796 |
+
obj.coord_sys = coord_sys
|
797 |
+
obj.index = index
|
798 |
+
return obj
|
799 |
+
|
800 |
+
def __getnewargs__(self):
|
801 |
+
return (self.coord_sys, self.index)
|
802 |
+
|
803 |
+
def _hashable_content(self):
|
804 |
+
return (
|
805 |
+
self.coord_sys, self.index
|
806 |
+
) + tuple(sorted(self.assumptions0.items()))
|
807 |
+
|
808 |
+
def _eval_rewrite(self, rule, args, **hints):
|
809 |
+
if isinstance(rule, CoordSystem):
|
810 |
+
return rule.transform(self.coord_sys)[self.index]
|
811 |
+
return super()._eval_rewrite(rule, args, **hints)
|
812 |
+
|
813 |
+
|
814 |
+
class Point(Basic):
|
815 |
+
"""Point defined in a coordinate system.
|
816 |
+
|
817 |
+
Explanation
|
818 |
+
===========
|
819 |
+
|
820 |
+
Mathematically, point is defined in the manifold and does not have any coordinates
|
821 |
+
by itself. Coordinate system is what imbues the coordinates to the point by coordinate
|
822 |
+
chart. However, due to the difficulty of realizing such logic, you must supply
|
823 |
+
a coordinate system and coordinates to define a Point here.
|
824 |
+
|
825 |
+
The usage of this object after its definition is independent of the
|
826 |
+
coordinate system that was used in order to define it, however due to
|
827 |
+
limitations in the simplification routines you can arrive at complicated
|
828 |
+
expressions if you use inappropriate coordinate systems.
|
829 |
+
|
830 |
+
Parameters
|
831 |
+
==========
|
832 |
+
|
833 |
+
coord_sys : CoordSystem
|
834 |
+
|
835 |
+
coords : list
|
836 |
+
The coordinates of the point.
|
837 |
+
|
838 |
+
Examples
|
839 |
+
========
|
840 |
+
|
841 |
+
>>> from sympy import pi
|
842 |
+
>>> from sympy.diffgeom import Point
|
843 |
+
>>> from sympy.diffgeom.rn import R2, R2_r, R2_p
|
844 |
+
>>> rho, theta = R2_p.symbols
|
845 |
+
|
846 |
+
>>> p = Point(R2_p, [rho, 3*pi/4])
|
847 |
+
|
848 |
+
>>> p.manifold == R2
|
849 |
+
True
|
850 |
+
|
851 |
+
>>> p.coords()
|
852 |
+
Matrix([
|
853 |
+
[ rho],
|
854 |
+
[3*pi/4]])
|
855 |
+
>>> p.coords(R2_r)
|
856 |
+
Matrix([
|
857 |
+
[-sqrt(2)*rho/2],
|
858 |
+
[ sqrt(2)*rho/2]])
|
859 |
+
|
860 |
+
"""
|
861 |
+
|
862 |
+
def __new__(cls, coord_sys, coords, **kwargs):
|
863 |
+
coords = Matrix(coords)
|
864 |
+
obj = super().__new__(cls, coord_sys, coords)
|
865 |
+
obj._coord_sys = coord_sys
|
866 |
+
obj._coords = coords
|
867 |
+
return obj
|
868 |
+
|
869 |
+
@property
|
870 |
+
def patch(self):
|
871 |
+
return self._coord_sys.patch
|
872 |
+
|
873 |
+
@property
|
874 |
+
def manifold(self):
|
875 |
+
return self._coord_sys.manifold
|
876 |
+
|
877 |
+
@property
|
878 |
+
def dim(self):
|
879 |
+
return self.manifold.dim
|
880 |
+
|
881 |
+
def coords(self, sys=None):
|
882 |
+
"""
|
883 |
+
Coordinates of the point in given coordinate system. If coordinate system
|
884 |
+
is not passed, it returns the coordinates in the coordinate system in which
|
885 |
+
the poin was defined.
|
886 |
+
"""
|
887 |
+
if sys is None:
|
888 |
+
return self._coords
|
889 |
+
else:
|
890 |
+
return self._coord_sys.transform(sys, self._coords)
|
891 |
+
|
892 |
+
@property
|
893 |
+
def free_symbols(self):
|
894 |
+
return self._coords.free_symbols
|
895 |
+
|
896 |
+
|
897 |
+
class BaseScalarField(Expr):
|
898 |
+
"""Base scalar field over a manifold for a given coordinate system.
|
899 |
+
|
900 |
+
Explanation
|
901 |
+
===========
|
902 |
+
|
903 |
+
A scalar field takes a point as an argument and returns a scalar.
|
904 |
+
A base scalar field of a coordinate system takes a point and returns one of
|
905 |
+
the coordinates of that point in the coordinate system in question.
|
906 |
+
|
907 |
+
To define a scalar field you need to choose the coordinate system and the
|
908 |
+
index of the coordinate.
|
909 |
+
|
910 |
+
The use of the scalar field after its definition is independent of the
|
911 |
+
coordinate system in which it was defined, however due to limitations in
|
912 |
+
the simplification routines you may arrive at more complicated
|
913 |
+
expression if you use unappropriate coordinate systems.
|
914 |
+
You can build complicated scalar fields by just building up SymPy
|
915 |
+
expressions containing ``BaseScalarField`` instances.
|
916 |
+
|
917 |
+
Parameters
|
918 |
+
==========
|
919 |
+
|
920 |
+
coord_sys : CoordSystem
|
921 |
+
|
922 |
+
index : integer
|
923 |
+
|
924 |
+
Examples
|
925 |
+
========
|
926 |
+
|
927 |
+
>>> from sympy import Function, pi
|
928 |
+
>>> from sympy.diffgeom import BaseScalarField
|
929 |
+
>>> from sympy.diffgeom.rn import R2_r, R2_p
|
930 |
+
>>> rho, _ = R2_p.symbols
|
931 |
+
>>> point = R2_p.point([rho, 0])
|
932 |
+
>>> fx, fy = R2_r.base_scalars()
|
933 |
+
>>> ftheta = BaseScalarField(R2_r, 1)
|
934 |
+
|
935 |
+
>>> fx(point)
|
936 |
+
rho
|
937 |
+
>>> fy(point)
|
938 |
+
0
|
939 |
+
|
940 |
+
>>> (fx**2+fy**2).rcall(point)
|
941 |
+
rho**2
|
942 |
+
|
943 |
+
>>> g = Function('g')
|
944 |
+
>>> fg = g(ftheta-pi)
|
945 |
+
>>> fg.rcall(point)
|
946 |
+
g(-pi)
|
947 |
+
|
948 |
+
"""
|
949 |
+
|
950 |
+
is_commutative = True
|
951 |
+
|
952 |
+
def __new__(cls, coord_sys, index, **kwargs):
|
953 |
+
index = _sympify(index)
|
954 |
+
obj = super().__new__(cls, coord_sys, index)
|
955 |
+
obj._coord_sys = coord_sys
|
956 |
+
obj._index = index
|
957 |
+
return obj
|
958 |
+
|
959 |
+
@property
|
960 |
+
def coord_sys(self):
|
961 |
+
return self.args[0]
|
962 |
+
|
963 |
+
@property
|
964 |
+
def index(self):
|
965 |
+
return self.args[1]
|
966 |
+
|
967 |
+
@property
|
968 |
+
def patch(self):
|
969 |
+
return self.coord_sys.patch
|
970 |
+
|
971 |
+
@property
|
972 |
+
def manifold(self):
|
973 |
+
return self.coord_sys.manifold
|
974 |
+
|
975 |
+
@property
|
976 |
+
def dim(self):
|
977 |
+
return self.manifold.dim
|
978 |
+
|
979 |
+
def __call__(self, *args):
|
980 |
+
"""Evaluating the field at a point or doing nothing.
|
981 |
+
If the argument is a ``Point`` instance, the field is evaluated at that
|
982 |
+
point. The field is returned itself if the argument is any other
|
983 |
+
object. It is so in order to have working recursive calling mechanics
|
984 |
+
for all fields (check the ``__call__`` method of ``Expr``).
|
985 |
+
"""
|
986 |
+
point = args[0]
|
987 |
+
if len(args) != 1 or not isinstance(point, Point):
|
988 |
+
return self
|
989 |
+
coords = point.coords(self._coord_sys)
|
990 |
+
# XXX Calling doit is necessary with all the Subs expressions
|
991 |
+
# XXX Calling simplify is necessary with all the trig expressions
|
992 |
+
return simplify(coords[self._index]).doit()
|
993 |
+
|
994 |
+
# XXX Workaround for limitations on the content of args
|
995 |
+
free_symbols: set[Any] = set()
|
996 |
+
|
997 |
+
|
998 |
+
class BaseVectorField(Expr):
|
999 |
+
r"""Base vector field over a manifold for a given coordinate system.
|
1000 |
+
|
1001 |
+
Explanation
|
1002 |
+
===========
|
1003 |
+
|
1004 |
+
A vector field is an operator taking a scalar field and returning a
|
1005 |
+
directional derivative (which is also a scalar field).
|
1006 |
+
A base vector field is the same type of operator, however the derivation is
|
1007 |
+
specifically done with respect to a chosen coordinate.
|
1008 |
+
|
1009 |
+
To define a base vector field you need to choose the coordinate system and
|
1010 |
+
the index of the coordinate.
|
1011 |
+
|
1012 |
+
The use of the vector field after its definition is independent of the
|
1013 |
+
coordinate system in which it was defined, however due to limitations in the
|
1014 |
+
simplification routines you may arrive at more complicated expression if you
|
1015 |
+
use unappropriate coordinate systems.
|
1016 |
+
|
1017 |
+
Parameters
|
1018 |
+
==========
|
1019 |
+
coord_sys : CoordSystem
|
1020 |
+
|
1021 |
+
index : integer
|
1022 |
+
|
1023 |
+
Examples
|
1024 |
+
========
|
1025 |
+
|
1026 |
+
>>> from sympy import Function
|
1027 |
+
>>> from sympy.diffgeom.rn import R2_p, R2_r
|
1028 |
+
>>> from sympy.diffgeom import BaseVectorField
|
1029 |
+
>>> from sympy import pprint
|
1030 |
+
|
1031 |
+
>>> x, y = R2_r.symbols
|
1032 |
+
>>> rho, theta = R2_p.symbols
|
1033 |
+
>>> fx, fy = R2_r.base_scalars()
|
1034 |
+
>>> point_p = R2_p.point([rho, theta])
|
1035 |
+
>>> point_r = R2_r.point([x, y])
|
1036 |
+
|
1037 |
+
>>> g = Function('g')
|
1038 |
+
>>> s_field = g(fx, fy)
|
1039 |
+
|
1040 |
+
>>> v = BaseVectorField(R2_r, 1)
|
1041 |
+
>>> pprint(v(s_field))
|
1042 |
+
/ d \|
|
1043 |
+
|---(g(x, xi))||
|
1044 |
+
\dxi /|xi=y
|
1045 |
+
>>> pprint(v(s_field).rcall(point_r).doit())
|
1046 |
+
d
|
1047 |
+
--(g(x, y))
|
1048 |
+
dy
|
1049 |
+
>>> pprint(v(s_field).rcall(point_p))
|
1050 |
+
/ d \|
|
1051 |
+
|---(g(rho*cos(theta), xi))||
|
1052 |
+
\dxi /|xi=rho*sin(theta)
|
1053 |
+
|
1054 |
+
"""
|
1055 |
+
|
1056 |
+
is_commutative = False
|
1057 |
+
|
1058 |
+
def __new__(cls, coord_sys, index, **kwargs):
|
1059 |
+
index = _sympify(index)
|
1060 |
+
obj = super().__new__(cls, coord_sys, index)
|
1061 |
+
obj._coord_sys = coord_sys
|
1062 |
+
obj._index = index
|
1063 |
+
return obj
|
1064 |
+
|
1065 |
+
@property
|
1066 |
+
def coord_sys(self):
|
1067 |
+
return self.args[0]
|
1068 |
+
|
1069 |
+
@property
|
1070 |
+
def index(self):
|
1071 |
+
return self.args[1]
|
1072 |
+
|
1073 |
+
@property
|
1074 |
+
def patch(self):
|
1075 |
+
return self.coord_sys.patch
|
1076 |
+
|
1077 |
+
@property
|
1078 |
+
def manifold(self):
|
1079 |
+
return self.coord_sys.manifold
|
1080 |
+
|
1081 |
+
@property
|
1082 |
+
def dim(self):
|
1083 |
+
return self.manifold.dim
|
1084 |
+
|
1085 |
+
def __call__(self, scalar_field):
|
1086 |
+
"""Apply on a scalar field.
|
1087 |
+
The action of a vector field on a scalar field is a directional
|
1088 |
+
differentiation.
|
1089 |
+
If the argument is not a scalar field an error is raised.
|
1090 |
+
"""
|
1091 |
+
if covariant_order(scalar_field) or contravariant_order(scalar_field):
|
1092 |
+
raise ValueError('Only scalar fields can be supplied as arguments to vector fields.')
|
1093 |
+
|
1094 |
+
if scalar_field is None:
|
1095 |
+
return self
|
1096 |
+
|
1097 |
+
base_scalars = list(scalar_field.atoms(BaseScalarField))
|
1098 |
+
|
1099 |
+
# First step: e_x(x+r**2) -> e_x(x) + 2*r*e_x(r)
|
1100 |
+
d_var = self._coord_sys._dummy
|
1101 |
+
# TODO: you need a real dummy function for the next line
|
1102 |
+
d_funcs = [Function('_#_%s' % i)(d_var) for i,
|
1103 |
+
b in enumerate(base_scalars)]
|
1104 |
+
d_result = scalar_field.subs(list(zip(base_scalars, d_funcs)))
|
1105 |
+
d_result = d_result.diff(d_var)
|
1106 |
+
|
1107 |
+
# Second step: e_x(x) -> 1 and e_x(r) -> cos(atan2(x, y))
|
1108 |
+
coords = self._coord_sys.symbols
|
1109 |
+
d_funcs_deriv = [f.diff(d_var) for f in d_funcs]
|
1110 |
+
d_funcs_deriv_sub = []
|
1111 |
+
for b in base_scalars:
|
1112 |
+
jac = self._coord_sys.jacobian(b._coord_sys, coords)
|
1113 |
+
d_funcs_deriv_sub.append(jac[b._index, self._index])
|
1114 |
+
d_result = d_result.subs(list(zip(d_funcs_deriv, d_funcs_deriv_sub)))
|
1115 |
+
|
1116 |
+
# Remove the dummies
|
1117 |
+
result = d_result.subs(list(zip(d_funcs, base_scalars)))
|
1118 |
+
result = result.subs(list(zip(coords, self._coord_sys.coord_functions())))
|
1119 |
+
return result.doit()
|
1120 |
+
|
1121 |
+
|
1122 |
+
def _find_coords(expr):
|
1123 |
+
# Finds CoordinateSystems existing in expr
|
1124 |
+
fields = expr.atoms(BaseScalarField, BaseVectorField)
|
1125 |
+
result = set()
|
1126 |
+
for f in fields:
|
1127 |
+
result.add(f._coord_sys)
|
1128 |
+
return result
|
1129 |
+
|
1130 |
+
|
1131 |
+
class Commutator(Expr):
|
1132 |
+
r"""Commutator of two vector fields.
|
1133 |
+
|
1134 |
+
Explanation
|
1135 |
+
===========
|
1136 |
+
|
1137 |
+
The commutator of two vector fields `v_1` and `v_2` is defined as the
|
1138 |
+
vector field `[v_1, v_2]` that evaluated on each scalar field `f` is equal
|
1139 |
+
to `v_1(v_2(f)) - v_2(v_1(f))`.
|
1140 |
+
|
1141 |
+
Examples
|
1142 |
+
========
|
1143 |
+
|
1144 |
+
|
1145 |
+
>>> from sympy.diffgeom.rn import R2_p, R2_r
|
1146 |
+
>>> from sympy.diffgeom import Commutator
|
1147 |
+
>>> from sympy import simplify
|
1148 |
+
|
1149 |
+
>>> fx, fy = R2_r.base_scalars()
|
1150 |
+
>>> e_x, e_y = R2_r.base_vectors()
|
1151 |
+
>>> e_r = R2_p.base_vector(0)
|
1152 |
+
|
1153 |
+
>>> c_xy = Commutator(e_x, e_y)
|
1154 |
+
>>> c_xr = Commutator(e_x, e_r)
|
1155 |
+
>>> c_xy
|
1156 |
+
0
|
1157 |
+
|
1158 |
+
Unfortunately, the current code is not able to compute everything:
|
1159 |
+
|
1160 |
+
>>> c_xr
|
1161 |
+
Commutator(e_x, e_rho)
|
1162 |
+
>>> simplify(c_xr(fy**2))
|
1163 |
+
-2*cos(theta)*y**2/(x**2 + y**2)
|
1164 |
+
|
1165 |
+
"""
|
1166 |
+
def __new__(cls, v1, v2):
|
1167 |
+
if (covariant_order(v1) or contravariant_order(v1) != 1
|
1168 |
+
or covariant_order(v2) or contravariant_order(v2) != 1):
|
1169 |
+
raise ValueError(
|
1170 |
+
'Only commutators of vector fields are supported.')
|
1171 |
+
if v1 == v2:
|
1172 |
+
return S.Zero
|
1173 |
+
coord_sys = set().union(*[_find_coords(v) for v in (v1, v2)])
|
1174 |
+
if len(coord_sys) == 1:
|
1175 |
+
# Only one coordinate systems is used, hence it is easy enough to
|
1176 |
+
# actually evaluate the commutator.
|
1177 |
+
if all(isinstance(v, BaseVectorField) for v in (v1, v2)):
|
1178 |
+
return S.Zero
|
1179 |
+
bases_1, bases_2 = [list(v.atoms(BaseVectorField))
|
1180 |
+
for v in (v1, v2)]
|
1181 |
+
coeffs_1 = [v1.expand().coeff(b) for b in bases_1]
|
1182 |
+
coeffs_2 = [v2.expand().coeff(b) for b in bases_2]
|
1183 |
+
res = 0
|
1184 |
+
for c1, b1 in zip(coeffs_1, bases_1):
|
1185 |
+
for c2, b2 in zip(coeffs_2, bases_2):
|
1186 |
+
res += c1*b1(c2)*b2 - c2*b2(c1)*b1
|
1187 |
+
return res
|
1188 |
+
else:
|
1189 |
+
obj = super().__new__(cls, v1, v2)
|
1190 |
+
obj._v1 = v1 # deprecated assignment
|
1191 |
+
obj._v2 = v2 # deprecated assignment
|
1192 |
+
return obj
|
1193 |
+
|
1194 |
+
@property
|
1195 |
+
def v1(self):
|
1196 |
+
return self.args[0]
|
1197 |
+
|
1198 |
+
@property
|
1199 |
+
def v2(self):
|
1200 |
+
return self.args[1]
|
1201 |
+
|
1202 |
+
def __call__(self, scalar_field):
|
1203 |
+
"""Apply on a scalar field.
|
1204 |
+
If the argument is not a scalar field an error is raised.
|
1205 |
+
"""
|
1206 |
+
return self.v1(self.v2(scalar_field)) - self.v2(self.v1(scalar_field))
|
1207 |
+
|
1208 |
+
|
1209 |
+
class Differential(Expr):
|
1210 |
+
r"""Return the differential (exterior derivative) of a form field.
|
1211 |
+
|
1212 |
+
Explanation
|
1213 |
+
===========
|
1214 |
+
|
1215 |
+
The differential of a form (i.e. the exterior derivative) has a complicated
|
1216 |
+
definition in the general case.
|
1217 |
+
The differential `df` of the 0-form `f` is defined for any vector field `v`
|
1218 |
+
as `df(v) = v(f)`.
|
1219 |
+
|
1220 |
+
Examples
|
1221 |
+
========
|
1222 |
+
|
1223 |
+
>>> from sympy import Function
|
1224 |
+
>>> from sympy.diffgeom.rn import R2_r
|
1225 |
+
>>> from sympy.diffgeom import Differential
|
1226 |
+
>>> from sympy import pprint
|
1227 |
+
|
1228 |
+
>>> fx, fy = R2_r.base_scalars()
|
1229 |
+
>>> e_x, e_y = R2_r.base_vectors()
|
1230 |
+
>>> g = Function('g')
|
1231 |
+
>>> s_field = g(fx, fy)
|
1232 |
+
>>> dg = Differential(s_field)
|
1233 |
+
|
1234 |
+
>>> dg
|
1235 |
+
d(g(x, y))
|
1236 |
+
>>> pprint(dg(e_x))
|
1237 |
+
/ d \|
|
1238 |
+
|---(g(xi, y))||
|
1239 |
+
\dxi /|xi=x
|
1240 |
+
>>> pprint(dg(e_y))
|
1241 |
+
/ d \|
|
1242 |
+
|---(g(x, xi))||
|
1243 |
+
\dxi /|xi=y
|
1244 |
+
|
1245 |
+
Applying the exterior derivative operator twice always results in:
|
1246 |
+
|
1247 |
+
>>> Differential(dg)
|
1248 |
+
0
|
1249 |
+
"""
|
1250 |
+
|
1251 |
+
is_commutative = False
|
1252 |
+
|
1253 |
+
def __new__(cls, form_field):
|
1254 |
+
if contravariant_order(form_field):
|
1255 |
+
raise ValueError(
|
1256 |
+
'A vector field was supplied as an argument to Differential.')
|
1257 |
+
if isinstance(form_field, Differential):
|
1258 |
+
return S.Zero
|
1259 |
+
else:
|
1260 |
+
obj = super().__new__(cls, form_field)
|
1261 |
+
obj._form_field = form_field # deprecated assignment
|
1262 |
+
return obj
|
1263 |
+
|
1264 |
+
@property
|
1265 |
+
def form_field(self):
|
1266 |
+
return self.args[0]
|
1267 |
+
|
1268 |
+
def __call__(self, *vector_fields):
|
1269 |
+
"""Apply on a list of vector_fields.
|
1270 |
+
|
1271 |
+
Explanation
|
1272 |
+
===========
|
1273 |
+
|
1274 |
+
If the number of vector fields supplied is not equal to 1 + the order of
|
1275 |
+
the form field inside the differential the result is undefined.
|
1276 |
+
|
1277 |
+
For 1-forms (i.e. differentials of scalar fields) the evaluation is
|
1278 |
+
done as `df(v)=v(f)`. However if `v` is ``None`` instead of a vector
|
1279 |
+
field, the differential is returned unchanged. This is done in order to
|
1280 |
+
permit partial contractions for higher forms.
|
1281 |
+
|
1282 |
+
In the general case the evaluation is done by applying the form field
|
1283 |
+
inside the differential on a list with one less elements than the number
|
1284 |
+
of elements in the original list. Lowering the number of vector fields
|
1285 |
+
is achieved through replacing each pair of fields by their
|
1286 |
+
commutator.
|
1287 |
+
|
1288 |
+
If the arguments are not vectors or ``None``s an error is raised.
|
1289 |
+
"""
|
1290 |
+
if any((contravariant_order(a) != 1 or covariant_order(a)) and a is not None
|
1291 |
+
for a in vector_fields):
|
1292 |
+
raise ValueError('The arguments supplied to Differential should be vector fields or Nones.')
|
1293 |
+
k = len(vector_fields)
|
1294 |
+
if k == 1:
|
1295 |
+
if vector_fields[0]:
|
1296 |
+
return vector_fields[0].rcall(self._form_field)
|
1297 |
+
return self
|
1298 |
+
else:
|
1299 |
+
# For higher form it is more complicated:
|
1300 |
+
# Invariant formula:
|
1301 |
+
# https://en.wikipedia.org/wiki/Exterior_derivative#Invariant_formula
|
1302 |
+
# df(v1, ... vn) = +/- vi(f(v1..no i..vn))
|
1303 |
+
# +/- f([vi,vj],v1..no i, no j..vn)
|
1304 |
+
f = self._form_field
|
1305 |
+
v = vector_fields
|
1306 |
+
ret = 0
|
1307 |
+
for i in range(k):
|
1308 |
+
t = v[i].rcall(f.rcall(*v[:i] + v[i + 1:]))
|
1309 |
+
ret += (-1)**i*t
|
1310 |
+
for j in range(i + 1, k):
|
1311 |
+
c = Commutator(v[i], v[j])
|
1312 |
+
if c: # TODO this is ugly - the Commutator can be Zero and
|
1313 |
+
# this causes the next line to fail
|
1314 |
+
t = f.rcall(*(c,) + v[:i] + v[i + 1:j] + v[j + 1:])
|
1315 |
+
ret += (-1)**(i + j)*t
|
1316 |
+
return ret
|
1317 |
+
|
1318 |
+
|
1319 |
+
class TensorProduct(Expr):
|
1320 |
+
"""Tensor product of forms.
|
1321 |
+
|
1322 |
+
Explanation
|
1323 |
+
===========
|
1324 |
+
|
1325 |
+
The tensor product permits the creation of multilinear functionals (i.e.
|
1326 |
+
higher order tensors) out of lower order fields (e.g. 1-forms and vector
|
1327 |
+
fields). However, the higher tensors thus created lack the interesting
|
1328 |
+
features provided by the other type of product, the wedge product, namely
|
1329 |
+
they are not antisymmetric and hence are not form fields.
|
1330 |
+
|
1331 |
+
Examples
|
1332 |
+
========
|
1333 |
+
|
1334 |
+
>>> from sympy.diffgeom.rn import R2_r
|
1335 |
+
>>> from sympy.diffgeom import TensorProduct
|
1336 |
+
|
1337 |
+
>>> fx, fy = R2_r.base_scalars()
|
1338 |
+
>>> e_x, e_y = R2_r.base_vectors()
|
1339 |
+
>>> dx, dy = R2_r.base_oneforms()
|
1340 |
+
|
1341 |
+
>>> TensorProduct(dx, dy)(e_x, e_y)
|
1342 |
+
1
|
1343 |
+
>>> TensorProduct(dx, dy)(e_y, e_x)
|
1344 |
+
0
|
1345 |
+
>>> TensorProduct(dx, fx*dy)(fx*e_x, e_y)
|
1346 |
+
x**2
|
1347 |
+
>>> TensorProduct(e_x, e_y)(fx**2, fy**2)
|
1348 |
+
4*x*y
|
1349 |
+
>>> TensorProduct(e_y, dx)(fy)
|
1350 |
+
dx
|
1351 |
+
|
1352 |
+
You can nest tensor products.
|
1353 |
+
|
1354 |
+
>>> tp1 = TensorProduct(dx, dy)
|
1355 |
+
>>> TensorProduct(tp1, dx)(e_x, e_y, e_x)
|
1356 |
+
1
|
1357 |
+
|
1358 |
+
You can make partial contraction for instance when 'raising an index'.
|
1359 |
+
Putting ``None`` in the second argument of ``rcall`` means that the
|
1360 |
+
respective position in the tensor product is left as it is.
|
1361 |
+
|
1362 |
+
>>> TP = TensorProduct
|
1363 |
+
>>> metric = TP(dx, dx) + 3*TP(dy, dy)
|
1364 |
+
>>> metric.rcall(e_y, None)
|
1365 |
+
3*dy
|
1366 |
+
|
1367 |
+
Or automatically pad the args with ``None`` without specifying them.
|
1368 |
+
|
1369 |
+
>>> metric.rcall(e_y)
|
1370 |
+
3*dy
|
1371 |
+
|
1372 |
+
"""
|
1373 |
+
def __new__(cls, *args):
|
1374 |
+
scalar = Mul(*[m for m in args if covariant_order(m) + contravariant_order(m) == 0])
|
1375 |
+
multifields = [m for m in args if covariant_order(m) + contravariant_order(m)]
|
1376 |
+
if multifields:
|
1377 |
+
if len(multifields) == 1:
|
1378 |
+
return scalar*multifields[0]
|
1379 |
+
return scalar*super().__new__(cls, *multifields)
|
1380 |
+
else:
|
1381 |
+
return scalar
|
1382 |
+
|
1383 |
+
def __call__(self, *fields):
|
1384 |
+
"""Apply on a list of fields.
|
1385 |
+
|
1386 |
+
If the number of input fields supplied is not equal to the order of
|
1387 |
+
the tensor product field, the list of arguments is padded with ``None``'s.
|
1388 |
+
|
1389 |
+
The list of arguments is divided in sublists depending on the order of
|
1390 |
+
the forms inside the tensor product. The sublists are provided as
|
1391 |
+
arguments to these forms and the resulting expressions are given to the
|
1392 |
+
constructor of ``TensorProduct``.
|
1393 |
+
|
1394 |
+
"""
|
1395 |
+
tot_order = covariant_order(self) + contravariant_order(self)
|
1396 |
+
tot_args = len(fields)
|
1397 |
+
if tot_args != tot_order:
|
1398 |
+
fields = list(fields) + [None]*(tot_order - tot_args)
|
1399 |
+
orders = [covariant_order(f) + contravariant_order(f) for f in self._args]
|
1400 |
+
indices = [sum(orders[:i + 1]) for i in range(len(orders) - 1)]
|
1401 |
+
fields = [fields[i:j] for i, j in zip([0] + indices, indices + [None])]
|
1402 |
+
multipliers = [t[0].rcall(*t[1]) for t in zip(self._args, fields)]
|
1403 |
+
return TensorProduct(*multipliers)
|
1404 |
+
|
1405 |
+
|
1406 |
+
class WedgeProduct(TensorProduct):
|
1407 |
+
"""Wedge product of forms.
|
1408 |
+
|
1409 |
+
Explanation
|
1410 |
+
===========
|
1411 |
+
|
1412 |
+
In the context of integration only completely antisymmetric forms make
|
1413 |
+
sense. The wedge product permits the creation of such forms.
|
1414 |
+
|
1415 |
+
Examples
|
1416 |
+
========
|
1417 |
+
|
1418 |
+
>>> from sympy.diffgeom.rn import R2_r
|
1419 |
+
>>> from sympy.diffgeom import WedgeProduct
|
1420 |
+
|
1421 |
+
>>> fx, fy = R2_r.base_scalars()
|
1422 |
+
>>> e_x, e_y = R2_r.base_vectors()
|
1423 |
+
>>> dx, dy = R2_r.base_oneforms()
|
1424 |
+
|
1425 |
+
>>> WedgeProduct(dx, dy)(e_x, e_y)
|
1426 |
+
1
|
1427 |
+
>>> WedgeProduct(dx, dy)(e_y, e_x)
|
1428 |
+
-1
|
1429 |
+
>>> WedgeProduct(dx, fx*dy)(fx*e_x, e_y)
|
1430 |
+
x**2
|
1431 |
+
>>> WedgeProduct(e_x, e_y)(fy, None)
|
1432 |
+
-e_x
|
1433 |
+
|
1434 |
+
You can nest wedge products.
|
1435 |
+
|
1436 |
+
>>> wp1 = WedgeProduct(dx, dy)
|
1437 |
+
>>> WedgeProduct(wp1, dx)(e_x, e_y, e_x)
|
1438 |
+
0
|
1439 |
+
|
1440 |
+
"""
|
1441 |
+
# TODO the calculation of signatures is slow
|
1442 |
+
# TODO you do not need all these permutations (neither the prefactor)
|
1443 |
+
def __call__(self, *fields):
|
1444 |
+
"""Apply on a list of vector_fields.
|
1445 |
+
The expression is rewritten internally in terms of tensor products and evaluated."""
|
1446 |
+
orders = (covariant_order(e) + contravariant_order(e) for e in self.args)
|
1447 |
+
mul = 1/Mul(*(factorial(o) for o in orders))
|
1448 |
+
perms = permutations(fields)
|
1449 |
+
perms_par = (Permutation(
|
1450 |
+
p).signature() for p in permutations(range(len(fields))))
|
1451 |
+
tensor_prod = TensorProduct(*self.args)
|
1452 |
+
return mul*Add(*[tensor_prod(*p[0])*p[1] for p in zip(perms, perms_par)])
|
1453 |
+
|
1454 |
+
|
1455 |
+
class LieDerivative(Expr):
|
1456 |
+
"""Lie derivative with respect to a vector field.
|
1457 |
+
|
1458 |
+
Explanation
|
1459 |
+
===========
|
1460 |
+
|
1461 |
+
The transport operator that defines the Lie derivative is the pushforward of
|
1462 |
+
the field to be derived along the integral curve of the field with respect
|
1463 |
+
to which one derives.
|
1464 |
+
|
1465 |
+
Examples
|
1466 |
+
========
|
1467 |
+
|
1468 |
+
>>> from sympy.diffgeom.rn import R2_r, R2_p
|
1469 |
+
>>> from sympy.diffgeom import (LieDerivative, TensorProduct)
|
1470 |
+
|
1471 |
+
>>> fx, fy = R2_r.base_scalars()
|
1472 |
+
>>> e_x, e_y = R2_r.base_vectors()
|
1473 |
+
>>> e_rho, e_theta = R2_p.base_vectors()
|
1474 |
+
>>> dx, dy = R2_r.base_oneforms()
|
1475 |
+
|
1476 |
+
>>> LieDerivative(e_x, fy)
|
1477 |
+
0
|
1478 |
+
>>> LieDerivative(e_x, fx)
|
1479 |
+
1
|
1480 |
+
>>> LieDerivative(e_x, e_x)
|
1481 |
+
0
|
1482 |
+
|
1483 |
+
The Lie derivative of a tensor field by another tensor field is equal to
|
1484 |
+
their commutator:
|
1485 |
+
|
1486 |
+
>>> LieDerivative(e_x, e_rho)
|
1487 |
+
Commutator(e_x, e_rho)
|
1488 |
+
>>> LieDerivative(e_x + e_y, fx)
|
1489 |
+
1
|
1490 |
+
|
1491 |
+
>>> tp = TensorProduct(dx, dy)
|
1492 |
+
>>> LieDerivative(e_x, tp)
|
1493 |
+
LieDerivative(e_x, TensorProduct(dx, dy))
|
1494 |
+
>>> LieDerivative(e_x, tp)
|
1495 |
+
LieDerivative(e_x, TensorProduct(dx, dy))
|
1496 |
+
|
1497 |
+
"""
|
1498 |
+
def __new__(cls, v_field, expr):
|
1499 |
+
expr_form_ord = covariant_order(expr)
|
1500 |
+
if contravariant_order(v_field) != 1 or covariant_order(v_field):
|
1501 |
+
raise ValueError('Lie derivatives are defined only with respect to'
|
1502 |
+
' vector fields. The supplied argument was not a '
|
1503 |
+
'vector field.')
|
1504 |
+
if expr_form_ord > 0:
|
1505 |
+
obj = super().__new__(cls, v_field, expr)
|
1506 |
+
# deprecated assignments
|
1507 |
+
obj._v_field = v_field
|
1508 |
+
obj._expr = expr
|
1509 |
+
return obj
|
1510 |
+
if expr.atoms(BaseVectorField):
|
1511 |
+
return Commutator(v_field, expr)
|
1512 |
+
else:
|
1513 |
+
return v_field.rcall(expr)
|
1514 |
+
|
1515 |
+
@property
|
1516 |
+
def v_field(self):
|
1517 |
+
return self.args[0]
|
1518 |
+
|
1519 |
+
@property
|
1520 |
+
def expr(self):
|
1521 |
+
return self.args[1]
|
1522 |
+
|
1523 |
+
def __call__(self, *args):
|
1524 |
+
v = self.v_field
|
1525 |
+
expr = self.expr
|
1526 |
+
lead_term = v(expr(*args))
|
1527 |
+
rest = Add(*[Mul(*args[:i] + (Commutator(v, args[i]),) + args[i + 1:])
|
1528 |
+
for i in range(len(args))])
|
1529 |
+
return lead_term - rest
|
1530 |
+
|
1531 |
+
|
1532 |
+
class BaseCovarDerivativeOp(Expr):
|
1533 |
+
"""Covariant derivative operator with respect to a base vector.
|
1534 |
+
|
1535 |
+
Examples
|
1536 |
+
========
|
1537 |
+
|
1538 |
+
>>> from sympy.diffgeom.rn import R2_r
|
1539 |
+
>>> from sympy.diffgeom import BaseCovarDerivativeOp
|
1540 |
+
>>> from sympy.diffgeom import metric_to_Christoffel_2nd, TensorProduct
|
1541 |
+
|
1542 |
+
>>> TP = TensorProduct
|
1543 |
+
>>> fx, fy = R2_r.base_scalars()
|
1544 |
+
>>> e_x, e_y = R2_r.base_vectors()
|
1545 |
+
>>> dx, dy = R2_r.base_oneforms()
|
1546 |
+
|
1547 |
+
>>> ch = metric_to_Christoffel_2nd(TP(dx, dx) + TP(dy, dy))
|
1548 |
+
>>> ch
|
1549 |
+
[[[0, 0], [0, 0]], [[0, 0], [0, 0]]]
|
1550 |
+
>>> cvd = BaseCovarDerivativeOp(R2_r, 0, ch)
|
1551 |
+
>>> cvd(fx)
|
1552 |
+
1
|
1553 |
+
>>> cvd(fx*e_x)
|
1554 |
+
e_x
|
1555 |
+
"""
|
1556 |
+
|
1557 |
+
def __new__(cls, coord_sys, index, christoffel):
|
1558 |
+
index = _sympify(index)
|
1559 |
+
christoffel = ImmutableDenseNDimArray(christoffel)
|
1560 |
+
obj = super().__new__(cls, coord_sys, index, christoffel)
|
1561 |
+
# deprecated assignments
|
1562 |
+
obj._coord_sys = coord_sys
|
1563 |
+
obj._index = index
|
1564 |
+
obj._christoffel = christoffel
|
1565 |
+
return obj
|
1566 |
+
|
1567 |
+
@property
|
1568 |
+
def coord_sys(self):
|
1569 |
+
return self.args[0]
|
1570 |
+
|
1571 |
+
@property
|
1572 |
+
def index(self):
|
1573 |
+
return self.args[1]
|
1574 |
+
|
1575 |
+
@property
|
1576 |
+
def christoffel(self):
|
1577 |
+
return self.args[2]
|
1578 |
+
|
1579 |
+
def __call__(self, field):
|
1580 |
+
"""Apply on a scalar field.
|
1581 |
+
|
1582 |
+
The action of a vector field on a scalar field is a directional
|
1583 |
+
differentiation.
|
1584 |
+
If the argument is not a scalar field the behaviour is undefined.
|
1585 |
+
"""
|
1586 |
+
if covariant_order(field) != 0:
|
1587 |
+
raise NotImplementedError()
|
1588 |
+
|
1589 |
+
field = vectors_in_basis(field, self._coord_sys)
|
1590 |
+
|
1591 |
+
wrt_vector = self._coord_sys.base_vector(self._index)
|
1592 |
+
wrt_scalar = self._coord_sys.coord_function(self._index)
|
1593 |
+
vectors = list(field.atoms(BaseVectorField))
|
1594 |
+
|
1595 |
+
# First step: replace all vectors with something susceptible to
|
1596 |
+
# derivation and do the derivation
|
1597 |
+
# TODO: you need a real dummy function for the next line
|
1598 |
+
d_funcs = [Function('_#_%s' % i)(wrt_scalar) for i,
|
1599 |
+
b in enumerate(vectors)]
|
1600 |
+
d_result = field.subs(list(zip(vectors, d_funcs)))
|
1601 |
+
d_result = wrt_vector(d_result)
|
1602 |
+
|
1603 |
+
# Second step: backsubstitute the vectors in
|
1604 |
+
d_result = d_result.subs(list(zip(d_funcs, vectors)))
|
1605 |
+
|
1606 |
+
# Third step: evaluate the derivatives of the vectors
|
1607 |
+
derivs = []
|
1608 |
+
for v in vectors:
|
1609 |
+
d = Add(*[(self._christoffel[k, wrt_vector._index, v._index]
|
1610 |
+
*v._coord_sys.base_vector(k))
|
1611 |
+
for k in range(v._coord_sys.dim)])
|
1612 |
+
derivs.append(d)
|
1613 |
+
to_subs = [wrt_vector(d) for d in d_funcs]
|
1614 |
+
# XXX: This substitution can fail when there are Dummy symbols and the
|
1615 |
+
# cache is disabled: https://github.com/sympy/sympy/issues/17794
|
1616 |
+
result = d_result.subs(list(zip(to_subs, derivs)))
|
1617 |
+
|
1618 |
+
# Remove the dummies
|
1619 |
+
result = result.subs(list(zip(d_funcs, vectors)))
|
1620 |
+
return result.doit()
|
1621 |
+
|
1622 |
+
|
1623 |
+
class CovarDerivativeOp(Expr):
|
1624 |
+
"""Covariant derivative operator.
|
1625 |
+
|
1626 |
+
Examples
|
1627 |
+
========
|
1628 |
+
|
1629 |
+
>>> from sympy.diffgeom.rn import R2_r
|
1630 |
+
>>> from sympy.diffgeom import CovarDerivativeOp
|
1631 |
+
>>> from sympy.diffgeom import metric_to_Christoffel_2nd, TensorProduct
|
1632 |
+
>>> TP = TensorProduct
|
1633 |
+
>>> fx, fy = R2_r.base_scalars()
|
1634 |
+
>>> e_x, e_y = R2_r.base_vectors()
|
1635 |
+
>>> dx, dy = R2_r.base_oneforms()
|
1636 |
+
>>> ch = metric_to_Christoffel_2nd(TP(dx, dx) + TP(dy, dy))
|
1637 |
+
|
1638 |
+
>>> ch
|
1639 |
+
[[[0, 0], [0, 0]], [[0, 0], [0, 0]]]
|
1640 |
+
>>> cvd = CovarDerivativeOp(fx*e_x, ch)
|
1641 |
+
>>> cvd(fx)
|
1642 |
+
x
|
1643 |
+
>>> cvd(fx*e_x)
|
1644 |
+
x*e_x
|
1645 |
+
|
1646 |
+
"""
|
1647 |
+
|
1648 |
+
def __new__(cls, wrt, christoffel):
|
1649 |
+
if len({v._coord_sys for v in wrt.atoms(BaseVectorField)}) > 1:
|
1650 |
+
raise NotImplementedError()
|
1651 |
+
if contravariant_order(wrt) != 1 or covariant_order(wrt):
|
1652 |
+
raise ValueError('Covariant derivatives are defined only with '
|
1653 |
+
'respect to vector fields. The supplied argument '
|
1654 |
+
'was not a vector field.')
|
1655 |
+
christoffel = ImmutableDenseNDimArray(christoffel)
|
1656 |
+
obj = super().__new__(cls, wrt, christoffel)
|
1657 |
+
# deprecated assignments
|
1658 |
+
obj._wrt = wrt
|
1659 |
+
obj._christoffel = christoffel
|
1660 |
+
return obj
|
1661 |
+
|
1662 |
+
@property
|
1663 |
+
def wrt(self):
|
1664 |
+
return self.args[0]
|
1665 |
+
|
1666 |
+
@property
|
1667 |
+
def christoffel(self):
|
1668 |
+
return self.args[1]
|
1669 |
+
|
1670 |
+
def __call__(self, field):
|
1671 |
+
vectors = list(self._wrt.atoms(BaseVectorField))
|
1672 |
+
base_ops = [BaseCovarDerivativeOp(v._coord_sys, v._index, self._christoffel)
|
1673 |
+
for v in vectors]
|
1674 |
+
return self._wrt.subs(list(zip(vectors, base_ops))).rcall(field)
|
1675 |
+
|
1676 |
+
|
1677 |
+
###############################################################################
|
1678 |
+
# Integral curves on vector fields
|
1679 |
+
###############################################################################
|
1680 |
+
def intcurve_series(vector_field, param, start_point, n=6, coord_sys=None, coeffs=False):
|
1681 |
+
r"""Return the series expansion for an integral curve of the field.
|
1682 |
+
|
1683 |
+
Explanation
|
1684 |
+
===========
|
1685 |
+
|
1686 |
+
Integral curve is a function `\gamma` taking a parameter in `R` to a point
|
1687 |
+
in the manifold. It verifies the equation:
|
1688 |
+
|
1689 |
+
`V(f)\big(\gamma(t)\big) = \frac{d}{dt}f\big(\gamma(t)\big)`
|
1690 |
+
|
1691 |
+
where the given ``vector_field`` is denoted as `V`. This holds for any
|
1692 |
+
value `t` for the parameter and any scalar field `f`.
|
1693 |
+
|
1694 |
+
This equation can also be decomposed of a basis of coordinate functions
|
1695 |
+
`V(f_i)\big(\gamma(t)\big) = \frac{d}{dt}f_i\big(\gamma(t)\big) \quad \forall i`
|
1696 |
+
|
1697 |
+
This function returns a series expansion of `\gamma(t)` in terms of the
|
1698 |
+
coordinate system ``coord_sys``. The equations and expansions are necessarily
|
1699 |
+
done in coordinate-system-dependent way as there is no other way to
|
1700 |
+
represent movement between points on the manifold (i.e. there is no such
|
1701 |
+
thing as a difference of points for a general manifold).
|
1702 |
+
|
1703 |
+
Parameters
|
1704 |
+
==========
|
1705 |
+
vector_field
|
1706 |
+
the vector field for which an integral curve will be given
|
1707 |
+
|
1708 |
+
param
|
1709 |
+
the argument of the function `\gamma` from R to the curve
|
1710 |
+
|
1711 |
+
start_point
|
1712 |
+
the point which corresponds to `\gamma(0)`
|
1713 |
+
|
1714 |
+
n
|
1715 |
+
the order to which to expand
|
1716 |
+
|
1717 |
+
coord_sys
|
1718 |
+
the coordinate system in which to expand
|
1719 |
+
coeffs (default False) - if True return a list of elements of the expansion
|
1720 |
+
|
1721 |
+
Examples
|
1722 |
+
========
|
1723 |
+
|
1724 |
+
Use the predefined R2 manifold:
|
1725 |
+
|
1726 |
+
>>> from sympy.abc import t, x, y
|
1727 |
+
>>> from sympy.diffgeom.rn import R2_p, R2_r
|
1728 |
+
>>> from sympy.diffgeom import intcurve_series
|
1729 |
+
|
1730 |
+
Specify a starting point and a vector field:
|
1731 |
+
|
1732 |
+
>>> start_point = R2_r.point([x, y])
|
1733 |
+
>>> vector_field = R2_r.e_x
|
1734 |
+
|
1735 |
+
Calculate the series:
|
1736 |
+
|
1737 |
+
>>> intcurve_series(vector_field, t, start_point, n=3)
|
1738 |
+
Matrix([
|
1739 |
+
[t + x],
|
1740 |
+
[ y]])
|
1741 |
+
|
1742 |
+
Or get the elements of the expansion in a list:
|
1743 |
+
|
1744 |
+
>>> series = intcurve_series(vector_field, t, start_point, n=3, coeffs=True)
|
1745 |
+
>>> series[0]
|
1746 |
+
Matrix([
|
1747 |
+
[x],
|
1748 |
+
[y]])
|
1749 |
+
>>> series[1]
|
1750 |
+
Matrix([
|
1751 |
+
[t],
|
1752 |
+
[0]])
|
1753 |
+
>>> series[2]
|
1754 |
+
Matrix([
|
1755 |
+
[0],
|
1756 |
+
[0]])
|
1757 |
+
|
1758 |
+
The series in the polar coordinate system:
|
1759 |
+
|
1760 |
+
>>> series = intcurve_series(vector_field, t, start_point,
|
1761 |
+
... n=3, coord_sys=R2_p, coeffs=True)
|
1762 |
+
>>> series[0]
|
1763 |
+
Matrix([
|
1764 |
+
[sqrt(x**2 + y**2)],
|
1765 |
+
[ atan2(y, x)]])
|
1766 |
+
>>> series[1]
|
1767 |
+
Matrix([
|
1768 |
+
[t*x/sqrt(x**2 + y**2)],
|
1769 |
+
[ -t*y/(x**2 + y**2)]])
|
1770 |
+
>>> series[2]
|
1771 |
+
Matrix([
|
1772 |
+
[t**2*(-x**2/(x**2 + y**2)**(3/2) + 1/sqrt(x**2 + y**2))/2],
|
1773 |
+
[ t**2*x*y/(x**2 + y**2)**2]])
|
1774 |
+
|
1775 |
+
See Also
|
1776 |
+
========
|
1777 |
+
|
1778 |
+
intcurve_diffequ
|
1779 |
+
|
1780 |
+
"""
|
1781 |
+
if contravariant_order(vector_field) != 1 or covariant_order(vector_field):
|
1782 |
+
raise ValueError('The supplied field was not a vector field.')
|
1783 |
+
|
1784 |
+
def iter_vfield(scalar_field, i):
|
1785 |
+
"""Return ``vector_field`` called `i` times on ``scalar_field``."""
|
1786 |
+
return reduce(lambda s, v: v.rcall(s), [vector_field, ]*i, scalar_field)
|
1787 |
+
|
1788 |
+
def taylor_terms_per_coord(coord_function):
|
1789 |
+
"""Return the series for one of the coordinates."""
|
1790 |
+
return [param**i*iter_vfield(coord_function, i).rcall(start_point)/factorial(i)
|
1791 |
+
for i in range(n)]
|
1792 |
+
coord_sys = coord_sys if coord_sys else start_point._coord_sys
|
1793 |
+
coord_functions = coord_sys.coord_functions()
|
1794 |
+
taylor_terms = [taylor_terms_per_coord(f) for f in coord_functions]
|
1795 |
+
if coeffs:
|
1796 |
+
return [Matrix(t) for t in zip(*taylor_terms)]
|
1797 |
+
else:
|
1798 |
+
return Matrix([sum(c) for c in taylor_terms])
|
1799 |
+
|
1800 |
+
|
1801 |
+
def intcurve_diffequ(vector_field, param, start_point, coord_sys=None):
|
1802 |
+
r"""Return the differential equation for an integral curve of the field.
|
1803 |
+
|
1804 |
+
Explanation
|
1805 |
+
===========
|
1806 |
+
|
1807 |
+
Integral curve is a function `\gamma` taking a parameter in `R` to a point
|
1808 |
+
in the manifold. It verifies the equation:
|
1809 |
+
|
1810 |
+
`V(f)\big(\gamma(t)\big) = \frac{d}{dt}f\big(\gamma(t)\big)`
|
1811 |
+
|
1812 |
+
where the given ``vector_field`` is denoted as `V`. This holds for any
|
1813 |
+
value `t` for the parameter and any scalar field `f`.
|
1814 |
+
|
1815 |
+
This function returns the differential equation of `\gamma(t)` in terms of the
|
1816 |
+
coordinate system ``coord_sys``. The equations and expansions are necessarily
|
1817 |
+
done in coordinate-system-dependent way as there is no other way to
|
1818 |
+
represent movement between points on the manifold (i.e. there is no such
|
1819 |
+
thing as a difference of points for a general manifold).
|
1820 |
+
|
1821 |
+
Parameters
|
1822 |
+
==========
|
1823 |
+
|
1824 |
+
vector_field
|
1825 |
+
the vector field for which an integral curve will be given
|
1826 |
+
|
1827 |
+
param
|
1828 |
+
the argument of the function `\gamma` from R to the curve
|
1829 |
+
|
1830 |
+
start_point
|
1831 |
+
the point which corresponds to `\gamma(0)`
|
1832 |
+
|
1833 |
+
coord_sys
|
1834 |
+
the coordinate system in which to give the equations
|
1835 |
+
|
1836 |
+
Returns
|
1837 |
+
=======
|
1838 |
+
|
1839 |
+
a tuple of (equations, initial conditions)
|
1840 |
+
|
1841 |
+
Examples
|
1842 |
+
========
|
1843 |
+
|
1844 |
+
Use the predefined R2 manifold:
|
1845 |
+
|
1846 |
+
>>> from sympy.abc import t
|
1847 |
+
>>> from sympy.diffgeom.rn import R2, R2_p, R2_r
|
1848 |
+
>>> from sympy.diffgeom import intcurve_diffequ
|
1849 |
+
|
1850 |
+
Specify a starting point and a vector field:
|
1851 |
+
|
1852 |
+
>>> start_point = R2_r.point([0, 1])
|
1853 |
+
>>> vector_field = -R2.y*R2.e_x + R2.x*R2.e_y
|
1854 |
+
|
1855 |
+
Get the equation:
|
1856 |
+
|
1857 |
+
>>> equations, init_cond = intcurve_diffequ(vector_field, t, start_point)
|
1858 |
+
>>> equations
|
1859 |
+
[f_1(t) + Derivative(f_0(t), t), -f_0(t) + Derivative(f_1(t), t)]
|
1860 |
+
>>> init_cond
|
1861 |
+
[f_0(0), f_1(0) - 1]
|
1862 |
+
|
1863 |
+
The series in the polar coordinate system:
|
1864 |
+
|
1865 |
+
>>> equations, init_cond = intcurve_diffequ(vector_field, t, start_point, R2_p)
|
1866 |
+
>>> equations
|
1867 |
+
[Derivative(f_0(t), t), Derivative(f_1(t), t) - 1]
|
1868 |
+
>>> init_cond
|
1869 |
+
[f_0(0) - 1, f_1(0) - pi/2]
|
1870 |
+
|
1871 |
+
See Also
|
1872 |
+
========
|
1873 |
+
|
1874 |
+
intcurve_series
|
1875 |
+
|
1876 |
+
"""
|
1877 |
+
if contravariant_order(vector_field) != 1 or covariant_order(vector_field):
|
1878 |
+
raise ValueError('The supplied field was not a vector field.')
|
1879 |
+
coord_sys = coord_sys if coord_sys else start_point._coord_sys
|
1880 |
+
gammas = [Function('f_%d' % i)(param) for i in range(
|
1881 |
+
start_point._coord_sys.dim)]
|
1882 |
+
arbitrary_p = Point(coord_sys, gammas)
|
1883 |
+
coord_functions = coord_sys.coord_functions()
|
1884 |
+
equations = [simplify(diff(cf.rcall(arbitrary_p), param) - vector_field.rcall(cf).rcall(arbitrary_p))
|
1885 |
+
for cf in coord_functions]
|
1886 |
+
init_cond = [simplify(cf.rcall(arbitrary_p).subs(param, 0) - cf.rcall(start_point))
|
1887 |
+
for cf in coord_functions]
|
1888 |
+
return equations, init_cond
|
1889 |
+
|
1890 |
+
|
1891 |
+
###############################################################################
|
1892 |
+
# Helpers
|
1893 |
+
###############################################################################
|
1894 |
+
def dummyfy(args, exprs):
|
1895 |
+
# TODO Is this a good idea?
|
1896 |
+
d_args = Matrix([s.as_dummy() for s in args])
|
1897 |
+
reps = dict(zip(args, d_args))
|
1898 |
+
d_exprs = Matrix([_sympify(expr).subs(reps) for expr in exprs])
|
1899 |
+
return d_args, d_exprs
|
1900 |
+
|
1901 |
+
###############################################################################
|
1902 |
+
# Helpers
|
1903 |
+
###############################################################################
|
1904 |
+
def contravariant_order(expr, _strict=False):
|
1905 |
+
"""Return the contravariant order of an expression.
|
1906 |
+
|
1907 |
+
Examples
|
1908 |
+
========
|
1909 |
+
|
1910 |
+
>>> from sympy.diffgeom import contravariant_order
|
1911 |
+
>>> from sympy.diffgeom.rn import R2
|
1912 |
+
>>> from sympy.abc import a
|
1913 |
+
|
1914 |
+
>>> contravariant_order(a)
|
1915 |
+
0
|
1916 |
+
>>> contravariant_order(a*R2.x + 2)
|
1917 |
+
0
|
1918 |
+
>>> contravariant_order(a*R2.x*R2.e_y + R2.e_x)
|
1919 |
+
1
|
1920 |
+
|
1921 |
+
"""
|
1922 |
+
# TODO move some of this to class methods.
|
1923 |
+
# TODO rewrite using the .as_blah_blah methods
|
1924 |
+
if isinstance(expr, Add):
|
1925 |
+
orders = [contravariant_order(e) for e in expr.args]
|
1926 |
+
if len(set(orders)) != 1:
|
1927 |
+
raise ValueError('Misformed expression containing contravariant fields of varying order.')
|
1928 |
+
return orders[0]
|
1929 |
+
elif isinstance(expr, Mul):
|
1930 |
+
orders = [contravariant_order(e) for e in expr.args]
|
1931 |
+
not_zero = [o for o in orders if o != 0]
|
1932 |
+
if len(not_zero) > 1:
|
1933 |
+
raise ValueError('Misformed expression containing multiplication between vectors.')
|
1934 |
+
return 0 if not not_zero else not_zero[0]
|
1935 |
+
elif isinstance(expr, Pow):
|
1936 |
+
if covariant_order(expr.base) or covariant_order(expr.exp):
|
1937 |
+
raise ValueError(
|
1938 |
+
'Misformed expression containing a power of a vector.')
|
1939 |
+
return 0
|
1940 |
+
elif isinstance(expr, BaseVectorField):
|
1941 |
+
return 1
|
1942 |
+
elif isinstance(expr, TensorProduct):
|
1943 |
+
return sum(contravariant_order(a) for a in expr.args)
|
1944 |
+
elif not _strict or expr.atoms(BaseScalarField):
|
1945 |
+
return 0
|
1946 |
+
else: # If it does not contain anything related to the diffgeom module and it is _strict
|
1947 |
+
return -1
|
1948 |
+
|
1949 |
+
|
1950 |
+
def covariant_order(expr, _strict=False):
|
1951 |
+
"""Return the covariant order of an expression.
|
1952 |
+
|
1953 |
+
Examples
|
1954 |
+
========
|
1955 |
+
|
1956 |
+
>>> from sympy.diffgeom import covariant_order
|
1957 |
+
>>> from sympy.diffgeom.rn import R2
|
1958 |
+
>>> from sympy.abc import a
|
1959 |
+
|
1960 |
+
>>> covariant_order(a)
|
1961 |
+
0
|
1962 |
+
>>> covariant_order(a*R2.x + 2)
|
1963 |
+
0
|
1964 |
+
>>> covariant_order(a*R2.x*R2.dy + R2.dx)
|
1965 |
+
1
|
1966 |
+
|
1967 |
+
"""
|
1968 |
+
# TODO move some of this to class methods.
|
1969 |
+
# TODO rewrite using the .as_blah_blah methods
|
1970 |
+
if isinstance(expr, Add):
|
1971 |
+
orders = [covariant_order(e) for e in expr.args]
|
1972 |
+
if len(set(orders)) != 1:
|
1973 |
+
raise ValueError('Misformed expression containing form fields of varying order.')
|
1974 |
+
return orders[0]
|
1975 |
+
elif isinstance(expr, Mul):
|
1976 |
+
orders = [covariant_order(e) for e in expr.args]
|
1977 |
+
not_zero = [o for o in orders if o != 0]
|
1978 |
+
if len(not_zero) > 1:
|
1979 |
+
raise ValueError('Misformed expression containing multiplication between forms.')
|
1980 |
+
return 0 if not not_zero else not_zero[0]
|
1981 |
+
elif isinstance(expr, Pow):
|
1982 |
+
if covariant_order(expr.base) or covariant_order(expr.exp):
|
1983 |
+
raise ValueError(
|
1984 |
+
'Misformed expression containing a power of a form.')
|
1985 |
+
return 0
|
1986 |
+
elif isinstance(expr, Differential):
|
1987 |
+
return covariant_order(*expr.args) + 1
|
1988 |
+
elif isinstance(expr, TensorProduct):
|
1989 |
+
return sum(covariant_order(a) for a in expr.args)
|
1990 |
+
elif not _strict or expr.atoms(BaseScalarField):
|
1991 |
+
return 0
|
1992 |
+
else: # If it does not contain anything related to the diffgeom module and it is _strict
|
1993 |
+
return -1
|
1994 |
+
|
1995 |
+
|
1996 |
+
###############################################################################
|
1997 |
+
# Coordinate transformation functions
|
1998 |
+
###############################################################################
|
1999 |
+
def vectors_in_basis(expr, to_sys):
|
2000 |
+
"""Transform all base vectors in base vectors of a specified coord basis.
|
2001 |
+
While the new base vectors are in the new coordinate system basis, any
|
2002 |
+
coefficients are kept in the old system.
|
2003 |
+
|
2004 |
+
Examples
|
2005 |
+
========
|
2006 |
+
|
2007 |
+
>>> from sympy.diffgeom import vectors_in_basis
|
2008 |
+
>>> from sympy.diffgeom.rn import R2_r, R2_p
|
2009 |
+
|
2010 |
+
>>> vectors_in_basis(R2_r.e_x, R2_p)
|
2011 |
+
-y*e_theta/(x**2 + y**2) + x*e_rho/sqrt(x**2 + y**2)
|
2012 |
+
>>> vectors_in_basis(R2_p.e_r, R2_r)
|
2013 |
+
sin(theta)*e_y + cos(theta)*e_x
|
2014 |
+
|
2015 |
+
"""
|
2016 |
+
vectors = list(expr.atoms(BaseVectorField))
|
2017 |
+
new_vectors = []
|
2018 |
+
for v in vectors:
|
2019 |
+
cs = v._coord_sys
|
2020 |
+
jac = cs.jacobian(to_sys, cs.coord_functions())
|
2021 |
+
new = (jac.T*Matrix(to_sys.base_vectors()))[v._index]
|
2022 |
+
new_vectors.append(new)
|
2023 |
+
return expr.subs(list(zip(vectors, new_vectors)))
|
2024 |
+
|
2025 |
+
|
2026 |
+
###############################################################################
|
2027 |
+
# Coordinate-dependent functions
|
2028 |
+
###############################################################################
|
2029 |
+
def twoform_to_matrix(expr):
|
2030 |
+
"""Return the matrix representing the twoform.
|
2031 |
+
|
2032 |
+
For the twoform `w` return the matrix `M` such that `M[i,j]=w(e_i, e_j)`,
|
2033 |
+
where `e_i` is the i-th base vector field for the coordinate system in
|
2034 |
+
which the expression of `w` is given.
|
2035 |
+
|
2036 |
+
Examples
|
2037 |
+
========
|
2038 |
+
|
2039 |
+
>>> from sympy.diffgeom.rn import R2
|
2040 |
+
>>> from sympy.diffgeom import twoform_to_matrix, TensorProduct
|
2041 |
+
>>> TP = TensorProduct
|
2042 |
+
|
2043 |
+
>>> twoform_to_matrix(TP(R2.dx, R2.dx) + TP(R2.dy, R2.dy))
|
2044 |
+
Matrix([
|
2045 |
+
[1, 0],
|
2046 |
+
[0, 1]])
|
2047 |
+
>>> twoform_to_matrix(R2.x*TP(R2.dx, R2.dx) + TP(R2.dy, R2.dy))
|
2048 |
+
Matrix([
|
2049 |
+
[x, 0],
|
2050 |
+
[0, 1]])
|
2051 |
+
>>> twoform_to_matrix(TP(R2.dx, R2.dx) + TP(R2.dy, R2.dy) - TP(R2.dx, R2.dy)/2)
|
2052 |
+
Matrix([
|
2053 |
+
[ 1, 0],
|
2054 |
+
[-1/2, 1]])
|
2055 |
+
|
2056 |
+
"""
|
2057 |
+
if covariant_order(expr) != 2 or contravariant_order(expr):
|
2058 |
+
raise ValueError('The input expression is not a two-form.')
|
2059 |
+
coord_sys = _find_coords(expr)
|
2060 |
+
if len(coord_sys) != 1:
|
2061 |
+
raise ValueError('The input expression concerns more than one '
|
2062 |
+
'coordinate systems, hence there is no unambiguous '
|
2063 |
+
'way to choose a coordinate system for the matrix.')
|
2064 |
+
coord_sys = coord_sys.pop()
|
2065 |
+
vectors = coord_sys.base_vectors()
|
2066 |
+
expr = expr.expand()
|
2067 |
+
matrix_content = [[expr.rcall(v1, v2) for v1 in vectors]
|
2068 |
+
for v2 in vectors]
|
2069 |
+
return Matrix(matrix_content)
|
2070 |
+
|
2071 |
+
|
2072 |
+
def metric_to_Christoffel_1st(expr):
|
2073 |
+
"""Return the nested list of Christoffel symbols for the given metric.
|
2074 |
+
This returns the Christoffel symbol of first kind that represents the
|
2075 |
+
Levi-Civita connection for the given metric.
|
2076 |
+
|
2077 |
+
Examples
|
2078 |
+
========
|
2079 |
+
|
2080 |
+
>>> from sympy.diffgeom.rn import R2
|
2081 |
+
>>> from sympy.diffgeom import metric_to_Christoffel_1st, TensorProduct
|
2082 |
+
>>> TP = TensorProduct
|
2083 |
+
|
2084 |
+
>>> metric_to_Christoffel_1st(TP(R2.dx, R2.dx) + TP(R2.dy, R2.dy))
|
2085 |
+
[[[0, 0], [0, 0]], [[0, 0], [0, 0]]]
|
2086 |
+
>>> metric_to_Christoffel_1st(R2.x*TP(R2.dx, R2.dx) + TP(R2.dy, R2.dy))
|
2087 |
+
[[[1/2, 0], [0, 0]], [[0, 0], [0, 0]]]
|
2088 |
+
|
2089 |
+
"""
|
2090 |
+
matrix = twoform_to_matrix(expr)
|
2091 |
+
if not matrix.is_symmetric():
|
2092 |
+
raise ValueError(
|
2093 |
+
'The two-form representing the metric is not symmetric.')
|
2094 |
+
coord_sys = _find_coords(expr).pop()
|
2095 |
+
deriv_matrices = [matrix.applyfunc(d) for d in coord_sys.base_vectors()]
|
2096 |
+
indices = list(range(coord_sys.dim))
|
2097 |
+
christoffel = [[[(deriv_matrices[k][i, j] + deriv_matrices[j][i, k] - deriv_matrices[i][j, k])/2
|
2098 |
+
for k in indices]
|
2099 |
+
for j in indices]
|
2100 |
+
for i in indices]
|
2101 |
+
return ImmutableDenseNDimArray(christoffel)
|
2102 |
+
|
2103 |
+
|
2104 |
+
def metric_to_Christoffel_2nd(expr):
|
2105 |
+
"""Return the nested list of Christoffel symbols for the given metric.
|
2106 |
+
This returns the Christoffel symbol of second kind that represents the
|
2107 |
+
Levi-Civita connection for the given metric.
|
2108 |
+
|
2109 |
+
Examples
|
2110 |
+
========
|
2111 |
+
|
2112 |
+
>>> from sympy.diffgeom.rn import R2
|
2113 |
+
>>> from sympy.diffgeom import metric_to_Christoffel_2nd, TensorProduct
|
2114 |
+
>>> TP = TensorProduct
|
2115 |
+
|
2116 |
+
>>> metric_to_Christoffel_2nd(TP(R2.dx, R2.dx) + TP(R2.dy, R2.dy))
|
2117 |
+
[[[0, 0], [0, 0]], [[0, 0], [0, 0]]]
|
2118 |
+
>>> metric_to_Christoffel_2nd(R2.x*TP(R2.dx, R2.dx) + TP(R2.dy, R2.dy))
|
2119 |
+
[[[1/(2*x), 0], [0, 0]], [[0, 0], [0, 0]]]
|
2120 |
+
|
2121 |
+
"""
|
2122 |
+
ch_1st = metric_to_Christoffel_1st(expr)
|
2123 |
+
coord_sys = _find_coords(expr).pop()
|
2124 |
+
indices = list(range(coord_sys.dim))
|
2125 |
+
# XXX workaround, inverting a matrix does not work if it contains non
|
2126 |
+
# symbols
|
2127 |
+
#matrix = twoform_to_matrix(expr).inv()
|
2128 |
+
matrix = twoform_to_matrix(expr)
|
2129 |
+
s_fields = set()
|
2130 |
+
for e in matrix:
|
2131 |
+
s_fields.update(e.atoms(BaseScalarField))
|
2132 |
+
s_fields = list(s_fields)
|
2133 |
+
dums = coord_sys.symbols
|
2134 |
+
matrix = matrix.subs(list(zip(s_fields, dums))).inv().subs(list(zip(dums, s_fields)))
|
2135 |
+
# XXX end of workaround
|
2136 |
+
christoffel = [[[Add(*[matrix[i, l]*ch_1st[l, j, k] for l in indices])
|
2137 |
+
for k in indices]
|
2138 |
+
for j in indices]
|
2139 |
+
for i in indices]
|
2140 |
+
return ImmutableDenseNDimArray(christoffel)
|
2141 |
+
|
2142 |
+
|
2143 |
+
def metric_to_Riemann_components(expr):
|
2144 |
+
"""Return the components of the Riemann tensor expressed in a given basis.
|
2145 |
+
|
2146 |
+
Given a metric it calculates the components of the Riemann tensor in the
|
2147 |
+
canonical basis of the coordinate system in which the metric expression is
|
2148 |
+
given.
|
2149 |
+
|
2150 |
+
Examples
|
2151 |
+
========
|
2152 |
+
|
2153 |
+
>>> from sympy import exp
|
2154 |
+
>>> from sympy.diffgeom.rn import R2
|
2155 |
+
>>> from sympy.diffgeom import metric_to_Riemann_components, TensorProduct
|
2156 |
+
>>> TP = TensorProduct
|
2157 |
+
|
2158 |
+
>>> metric_to_Riemann_components(TP(R2.dx, R2.dx) + TP(R2.dy, R2.dy))
|
2159 |
+
[[[[0, 0], [0, 0]], [[0, 0], [0, 0]]], [[[0, 0], [0, 0]], [[0, 0], [0, 0]]]]
|
2160 |
+
>>> non_trivial_metric = exp(2*R2.r)*TP(R2.dr, R2.dr) + \
|
2161 |
+
R2.r**2*TP(R2.dtheta, R2.dtheta)
|
2162 |
+
>>> non_trivial_metric
|
2163 |
+
exp(2*rho)*TensorProduct(drho, drho) + rho**2*TensorProduct(dtheta, dtheta)
|
2164 |
+
>>> riemann = metric_to_Riemann_components(non_trivial_metric)
|
2165 |
+
>>> riemann[0, :, :, :]
|
2166 |
+
[[[0, 0], [0, 0]], [[0, exp(-2*rho)*rho], [-exp(-2*rho)*rho, 0]]]
|
2167 |
+
>>> riemann[1, :, :, :]
|
2168 |
+
[[[0, -1/rho], [1/rho, 0]], [[0, 0], [0, 0]]]
|
2169 |
+
|
2170 |
+
"""
|
2171 |
+
ch_2nd = metric_to_Christoffel_2nd(expr)
|
2172 |
+
coord_sys = _find_coords(expr).pop()
|
2173 |
+
indices = list(range(coord_sys.dim))
|
2174 |
+
deriv_ch = [[[[d(ch_2nd[i, j, k])
|
2175 |
+
for d in coord_sys.base_vectors()]
|
2176 |
+
for k in indices]
|
2177 |
+
for j in indices]
|
2178 |
+
for i in indices]
|
2179 |
+
riemann_a = [[[[deriv_ch[rho][sig][nu][mu] - deriv_ch[rho][sig][mu][nu]
|
2180 |
+
for nu in indices]
|
2181 |
+
for mu in indices]
|
2182 |
+
for sig in indices]
|
2183 |
+
for rho in indices]
|
2184 |
+
riemann_b = [[[[Add(*[ch_2nd[rho, l, mu]*ch_2nd[l, sig, nu] - ch_2nd[rho, l, nu]*ch_2nd[l, sig, mu] for l in indices])
|
2185 |
+
for nu in indices]
|
2186 |
+
for mu in indices]
|
2187 |
+
for sig in indices]
|
2188 |
+
for rho in indices]
|
2189 |
+
riemann = [[[[riemann_a[rho][sig][mu][nu] + riemann_b[rho][sig][mu][nu]
|
2190 |
+
for nu in indices]
|
2191 |
+
for mu in indices]
|
2192 |
+
for sig in indices]
|
2193 |
+
for rho in indices]
|
2194 |
+
return ImmutableDenseNDimArray(riemann)
|
2195 |
+
|
2196 |
+
|
2197 |
+
def metric_to_Ricci_components(expr):
|
2198 |
+
|
2199 |
+
"""Return the components of the Ricci tensor expressed in a given basis.
|
2200 |
+
|
2201 |
+
Given a metric it calculates the components of the Ricci tensor in the
|
2202 |
+
canonical basis of the coordinate system in which the metric expression is
|
2203 |
+
given.
|
2204 |
+
|
2205 |
+
Examples
|
2206 |
+
========
|
2207 |
+
|
2208 |
+
>>> from sympy import exp
|
2209 |
+
>>> from sympy.diffgeom.rn import R2
|
2210 |
+
>>> from sympy.diffgeom import metric_to_Ricci_components, TensorProduct
|
2211 |
+
>>> TP = TensorProduct
|
2212 |
+
|
2213 |
+
>>> metric_to_Ricci_components(TP(R2.dx, R2.dx) + TP(R2.dy, R2.dy))
|
2214 |
+
[[0, 0], [0, 0]]
|
2215 |
+
>>> non_trivial_metric = exp(2*R2.r)*TP(R2.dr, R2.dr) + \
|
2216 |
+
R2.r**2*TP(R2.dtheta, R2.dtheta)
|
2217 |
+
>>> non_trivial_metric
|
2218 |
+
exp(2*rho)*TensorProduct(drho, drho) + rho**2*TensorProduct(dtheta, dtheta)
|
2219 |
+
>>> metric_to_Ricci_components(non_trivial_metric)
|
2220 |
+
[[1/rho, 0], [0, exp(-2*rho)*rho]]
|
2221 |
+
|
2222 |
+
"""
|
2223 |
+
riemann = metric_to_Riemann_components(expr)
|
2224 |
+
coord_sys = _find_coords(expr).pop()
|
2225 |
+
indices = list(range(coord_sys.dim))
|
2226 |
+
ricci = [[Add(*[riemann[k, i, k, j] for k in indices])
|
2227 |
+
for j in indices]
|
2228 |
+
for i in indices]
|
2229 |
+
return ImmutableDenseNDimArray(ricci)
|
2230 |
+
|
2231 |
+
###############################################################################
|
2232 |
+
# Classes for deprecation
|
2233 |
+
###############################################################################
|
2234 |
+
|
2235 |
+
class _deprecated_container:
|
2236 |
+
# This class gives deprecation warning.
|
2237 |
+
# When deprecated features are completely deleted, this should be removed as well.
|
2238 |
+
# See https://github.com/sympy/sympy/pull/19368
|
2239 |
+
def __init__(self, message, data):
|
2240 |
+
super().__init__(data)
|
2241 |
+
self.message = message
|
2242 |
+
|
2243 |
+
def warn(self):
|
2244 |
+
sympy_deprecation_warning(
|
2245 |
+
self.message,
|
2246 |
+
deprecated_since_version="1.7",
|
2247 |
+
active_deprecations_target="deprecated-diffgeom-mutable",
|
2248 |
+
stacklevel=4
|
2249 |
+
)
|
2250 |
+
|
2251 |
+
def __iter__(self):
|
2252 |
+
self.warn()
|
2253 |
+
return super().__iter__()
|
2254 |
+
|
2255 |
+
def __getitem__(self, key):
|
2256 |
+
self.warn()
|
2257 |
+
return super().__getitem__(key)
|
2258 |
+
|
2259 |
+
def __contains__(self, key):
|
2260 |
+
self.warn()
|
2261 |
+
return super().__contains__(key)
|
2262 |
+
|
2263 |
+
|
2264 |
+
class _deprecated_list(_deprecated_container, list):
|
2265 |
+
pass
|
2266 |
+
|
2267 |
+
|
2268 |
+
class _deprecated_dict(_deprecated_container, dict):
|
2269 |
+
pass
|
2270 |
+
|
2271 |
+
|
2272 |
+
# Import at end to avoid cyclic imports
|
2273 |
+
from sympy.simplify.simplify import simplify
|
env-llmeval/lib/python3.10/site-packages/sympy/diffgeom/tests/test_function_diffgeom_book.py
ADDED
@@ -0,0 +1,145 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.diffgeom.rn import R2, R2_p, R2_r, R3_r
|
2 |
+
from sympy.diffgeom import intcurve_series, Differential, WedgeProduct
|
3 |
+
from sympy.core import symbols, Function, Derivative
|
4 |
+
from sympy.simplify import trigsimp, simplify
|
5 |
+
from sympy.functions import sqrt, atan2, sin, cos
|
6 |
+
from sympy.matrices import Matrix
|
7 |
+
|
8 |
+
# Most of the functionality is covered in the
|
9 |
+
# test_functional_diffgeom_ch* tests which are based on the
|
10 |
+
# example from the paper of Sussman and Wisdom.
|
11 |
+
# If they do not cover something, additional tests are added in other test
|
12 |
+
# functions.
|
13 |
+
|
14 |
+
# From "Functional Differential Geometry" as of 2011
|
15 |
+
# by Sussman and Wisdom.
|
16 |
+
|
17 |
+
|
18 |
+
def test_functional_diffgeom_ch2():
|
19 |
+
x0, y0, r0, theta0 = symbols('x0, y0, r0, theta0', real=True)
|
20 |
+
x, y = symbols('x, y', real=True)
|
21 |
+
f = Function('f')
|
22 |
+
|
23 |
+
assert (R2_p.point_to_coords(R2_r.point([x0, y0])) ==
|
24 |
+
Matrix([sqrt(x0**2 + y0**2), atan2(y0, x0)]))
|
25 |
+
assert (R2_r.point_to_coords(R2_p.point([r0, theta0])) ==
|
26 |
+
Matrix([r0*cos(theta0), r0*sin(theta0)]))
|
27 |
+
|
28 |
+
assert R2_p.jacobian(R2_r, [r0, theta0]) == Matrix(
|
29 |
+
[[cos(theta0), -r0*sin(theta0)], [sin(theta0), r0*cos(theta0)]])
|
30 |
+
|
31 |
+
field = f(R2.x, R2.y)
|
32 |
+
p1_in_rect = R2_r.point([x0, y0])
|
33 |
+
p1_in_polar = R2_p.point([sqrt(x0**2 + y0**2), atan2(y0, x0)])
|
34 |
+
assert field.rcall(p1_in_rect) == f(x0, y0)
|
35 |
+
assert field.rcall(p1_in_polar) == f(x0, y0)
|
36 |
+
|
37 |
+
p_r = R2_r.point([x0, y0])
|
38 |
+
p_p = R2_p.point([r0, theta0])
|
39 |
+
assert R2.x(p_r) == x0
|
40 |
+
assert R2.x(p_p) == r0*cos(theta0)
|
41 |
+
assert R2.r(p_p) == r0
|
42 |
+
assert R2.r(p_r) == sqrt(x0**2 + y0**2)
|
43 |
+
assert R2.theta(p_r) == atan2(y0, x0)
|
44 |
+
|
45 |
+
h = R2.x*R2.r**2 + R2.y**3
|
46 |
+
assert h.rcall(p_r) == x0*(x0**2 + y0**2) + y0**3
|
47 |
+
assert h.rcall(p_p) == r0**3*sin(theta0)**3 + r0**3*cos(theta0)
|
48 |
+
|
49 |
+
|
50 |
+
def test_functional_diffgeom_ch3():
|
51 |
+
x0, y0 = symbols('x0, y0', real=True)
|
52 |
+
x, y, t = symbols('x, y, t', real=True)
|
53 |
+
f = Function('f')
|
54 |
+
b1 = Function('b1')
|
55 |
+
b2 = Function('b2')
|
56 |
+
p_r = R2_r.point([x0, y0])
|
57 |
+
|
58 |
+
s_field = f(R2.x, R2.y)
|
59 |
+
v_field = b1(R2.x)*R2.e_x + b2(R2.y)*R2.e_y
|
60 |
+
assert v_field.rcall(s_field).rcall(p_r).doit() == b1(
|
61 |
+
x0)*Derivative(f(x0, y0), x0) + b2(y0)*Derivative(f(x0, y0), y0)
|
62 |
+
|
63 |
+
assert R2.e_x(R2.r**2).rcall(p_r) == 2*x0
|
64 |
+
v = R2.e_x + 2*R2.e_y
|
65 |
+
s = R2.r**2 + 3*R2.x
|
66 |
+
assert v.rcall(s).rcall(p_r).doit() == 2*x0 + 4*y0 + 3
|
67 |
+
|
68 |
+
circ = -R2.y*R2.e_x + R2.x*R2.e_y
|
69 |
+
series = intcurve_series(circ, t, R2_r.point([1, 0]), coeffs=True)
|
70 |
+
series_x, series_y = zip(*series)
|
71 |
+
assert all(
|
72 |
+
[term == cos(t).taylor_term(i, t) for i, term in enumerate(series_x)])
|
73 |
+
assert all(
|
74 |
+
[term == sin(t).taylor_term(i, t) for i, term in enumerate(series_y)])
|
75 |
+
|
76 |
+
|
77 |
+
def test_functional_diffgeom_ch4():
|
78 |
+
x0, y0, theta0 = symbols('x0, y0, theta0', real=True)
|
79 |
+
x, y, r, theta = symbols('x, y, r, theta', real=True)
|
80 |
+
r0 = symbols('r0', positive=True)
|
81 |
+
f = Function('f')
|
82 |
+
b1 = Function('b1')
|
83 |
+
b2 = Function('b2')
|
84 |
+
p_r = R2_r.point([x0, y0])
|
85 |
+
p_p = R2_p.point([r0, theta0])
|
86 |
+
|
87 |
+
f_field = b1(R2.x, R2.y)*R2.dx + b2(R2.x, R2.y)*R2.dy
|
88 |
+
assert f_field.rcall(R2.e_x).rcall(p_r) == b1(x0, y0)
|
89 |
+
assert f_field.rcall(R2.e_y).rcall(p_r) == b2(x0, y0)
|
90 |
+
|
91 |
+
s_field_r = f(R2.x, R2.y)
|
92 |
+
df = Differential(s_field_r)
|
93 |
+
assert df(R2.e_x).rcall(p_r).doit() == Derivative(f(x0, y0), x0)
|
94 |
+
assert df(R2.e_y).rcall(p_r).doit() == Derivative(f(x0, y0), y0)
|
95 |
+
|
96 |
+
s_field_p = f(R2.r, R2.theta)
|
97 |
+
df = Differential(s_field_p)
|
98 |
+
assert trigsimp(df(R2.e_x).rcall(p_p).doit()) == (
|
99 |
+
cos(theta0)*Derivative(f(r0, theta0), r0) -
|
100 |
+
sin(theta0)*Derivative(f(r0, theta0), theta0)/r0)
|
101 |
+
assert trigsimp(df(R2.e_y).rcall(p_p).doit()) == (
|
102 |
+
sin(theta0)*Derivative(f(r0, theta0), r0) +
|
103 |
+
cos(theta0)*Derivative(f(r0, theta0), theta0)/r0)
|
104 |
+
|
105 |
+
assert R2.dx(R2.e_x).rcall(p_r) == 1
|
106 |
+
assert R2.dx(R2.e_x) == 1
|
107 |
+
assert R2.dx(R2.e_y).rcall(p_r) == 0
|
108 |
+
assert R2.dx(R2.e_y) == 0
|
109 |
+
|
110 |
+
circ = -R2.y*R2.e_x + R2.x*R2.e_y
|
111 |
+
assert R2.dx(circ).rcall(p_r).doit() == -y0
|
112 |
+
assert R2.dy(circ).rcall(p_r) == x0
|
113 |
+
assert R2.dr(circ).rcall(p_r) == 0
|
114 |
+
assert simplify(R2.dtheta(circ).rcall(p_r)) == 1
|
115 |
+
|
116 |
+
assert (circ - R2.e_theta).rcall(s_field_r).rcall(p_r) == 0
|
117 |
+
|
118 |
+
|
119 |
+
def test_functional_diffgeom_ch6():
|
120 |
+
u0, u1, u2, v0, v1, v2, w0, w1, w2 = symbols('u0:3, v0:3, w0:3', real=True)
|
121 |
+
|
122 |
+
u = u0*R2.e_x + u1*R2.e_y
|
123 |
+
v = v0*R2.e_x + v1*R2.e_y
|
124 |
+
wp = WedgeProduct(R2.dx, R2.dy)
|
125 |
+
assert wp(u, v) == u0*v1 - u1*v0
|
126 |
+
|
127 |
+
u = u0*R3_r.e_x + u1*R3_r.e_y + u2*R3_r.e_z
|
128 |
+
v = v0*R3_r.e_x + v1*R3_r.e_y + v2*R3_r.e_z
|
129 |
+
w = w0*R3_r.e_x + w1*R3_r.e_y + w2*R3_r.e_z
|
130 |
+
wp = WedgeProduct(R3_r.dx, R3_r.dy, R3_r.dz)
|
131 |
+
assert wp(
|
132 |
+
u, v, w) == Matrix(3, 3, [u0, u1, u2, v0, v1, v2, w0, w1, w2]).det()
|
133 |
+
|
134 |
+
a, b, c = symbols('a, b, c', cls=Function)
|
135 |
+
a_f = a(R3_r.x, R3_r.y, R3_r.z)
|
136 |
+
b_f = b(R3_r.x, R3_r.y, R3_r.z)
|
137 |
+
c_f = c(R3_r.x, R3_r.y, R3_r.z)
|
138 |
+
theta = a_f*R3_r.dx + b_f*R3_r.dy + c_f*R3_r.dz
|
139 |
+
dtheta = Differential(theta)
|
140 |
+
da = Differential(a_f)
|
141 |
+
db = Differential(b_f)
|
142 |
+
dc = Differential(c_f)
|
143 |
+
expr = dtheta - WedgeProduct(
|
144 |
+
da, R3_r.dx) - WedgeProduct(db, R3_r.dy) - WedgeProduct(dc, R3_r.dz)
|
145 |
+
assert expr.rcall(R3_r.e_x, R3_r.e_y) == 0
|
env-llmeval/lib/python3.10/site-packages/sympy/diffgeom/tests/test_hyperbolic_space.py
ADDED
@@ -0,0 +1,91 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
r'''
|
2 |
+
unit test describing the hyperbolic half-plane with the Poincare metric. This
|
3 |
+
is a basic model of hyperbolic geometry on the (positive) half-space
|
4 |
+
|
5 |
+
{(x,y) \in R^2 | y > 0}
|
6 |
+
|
7 |
+
with the Riemannian metric
|
8 |
+
|
9 |
+
ds^2 = (dx^2 + dy^2)/y^2
|
10 |
+
|
11 |
+
It has constant negative scalar curvature = -2
|
12 |
+
|
13 |
+
https://en.wikipedia.org/wiki/Poincare_half-plane_model
|
14 |
+
'''
|
15 |
+
from sympy.matrices.dense import diag
|
16 |
+
from sympy.diffgeom import (twoform_to_matrix,
|
17 |
+
metric_to_Christoffel_1st, metric_to_Christoffel_2nd,
|
18 |
+
metric_to_Riemann_components, metric_to_Ricci_components)
|
19 |
+
import sympy.diffgeom.rn
|
20 |
+
from sympy.tensor.array import ImmutableDenseNDimArray
|
21 |
+
|
22 |
+
|
23 |
+
def test_H2():
|
24 |
+
TP = sympy.diffgeom.TensorProduct
|
25 |
+
R2 = sympy.diffgeom.rn.R2
|
26 |
+
y = R2.y
|
27 |
+
dy = R2.dy
|
28 |
+
dx = R2.dx
|
29 |
+
g = (TP(dx, dx) + TP(dy, dy))*y**(-2)
|
30 |
+
automat = twoform_to_matrix(g)
|
31 |
+
mat = diag(y**(-2), y**(-2))
|
32 |
+
assert mat == automat
|
33 |
+
|
34 |
+
gamma1 = metric_to_Christoffel_1st(g)
|
35 |
+
assert gamma1[0, 0, 0] == 0
|
36 |
+
assert gamma1[0, 0, 1] == -y**(-3)
|
37 |
+
assert gamma1[0, 1, 0] == -y**(-3)
|
38 |
+
assert gamma1[0, 1, 1] == 0
|
39 |
+
|
40 |
+
assert gamma1[1, 1, 1] == -y**(-3)
|
41 |
+
assert gamma1[1, 1, 0] == 0
|
42 |
+
assert gamma1[1, 0, 1] == 0
|
43 |
+
assert gamma1[1, 0, 0] == y**(-3)
|
44 |
+
|
45 |
+
gamma2 = metric_to_Christoffel_2nd(g)
|
46 |
+
assert gamma2[0, 0, 0] == 0
|
47 |
+
assert gamma2[0, 0, 1] == -y**(-1)
|
48 |
+
assert gamma2[0, 1, 0] == -y**(-1)
|
49 |
+
assert gamma2[0, 1, 1] == 0
|
50 |
+
|
51 |
+
assert gamma2[1, 1, 1] == -y**(-1)
|
52 |
+
assert gamma2[1, 1, 0] == 0
|
53 |
+
assert gamma2[1, 0, 1] == 0
|
54 |
+
assert gamma2[1, 0, 0] == y**(-1)
|
55 |
+
|
56 |
+
Rm = metric_to_Riemann_components(g)
|
57 |
+
assert Rm[0, 0, 0, 0] == 0
|
58 |
+
assert Rm[0, 0, 0, 1] == 0
|
59 |
+
assert Rm[0, 0, 1, 0] == 0
|
60 |
+
assert Rm[0, 0, 1, 1] == 0
|
61 |
+
|
62 |
+
assert Rm[0, 1, 0, 0] == 0
|
63 |
+
assert Rm[0, 1, 0, 1] == -y**(-2)
|
64 |
+
assert Rm[0, 1, 1, 0] == y**(-2)
|
65 |
+
assert Rm[0, 1, 1, 1] == 0
|
66 |
+
|
67 |
+
assert Rm[1, 0, 0, 0] == 0
|
68 |
+
assert Rm[1, 0, 0, 1] == y**(-2)
|
69 |
+
assert Rm[1, 0, 1, 0] == -y**(-2)
|
70 |
+
assert Rm[1, 0, 1, 1] == 0
|
71 |
+
|
72 |
+
assert Rm[1, 1, 0, 0] == 0
|
73 |
+
assert Rm[1, 1, 0, 1] == 0
|
74 |
+
assert Rm[1, 1, 1, 0] == 0
|
75 |
+
assert Rm[1, 1, 1, 1] == 0
|
76 |
+
|
77 |
+
Ric = metric_to_Ricci_components(g)
|
78 |
+
assert Ric[0, 0] == -y**(-2)
|
79 |
+
assert Ric[0, 1] == 0
|
80 |
+
assert Ric[1, 0] == 0
|
81 |
+
assert Ric[0, 0] == -y**(-2)
|
82 |
+
|
83 |
+
assert Ric == ImmutableDenseNDimArray([-y**(-2), 0, 0, -y**(-2)], (2, 2))
|
84 |
+
|
85 |
+
## scalar curvature is -2
|
86 |
+
#TODO - it would be nice to have index contraction built-in
|
87 |
+
R = (Ric[0, 0] + Ric[1, 1])*y**2
|
88 |
+
assert R == -2
|
89 |
+
|
90 |
+
## Gauss curvature is -1
|
91 |
+
assert R/2 == -1
|
env-llmeval/lib/python3.10/site-packages/sympy/tensor/array/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (8.3 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/tensor/array/__pycache__/array_comprehension.cpython-310.pyc
ADDED
Binary file (14.1 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/tensor/array/__pycache__/array_derivatives.cpython-310.pyc
ADDED
Binary file (4.75 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/tensor/array/__pycache__/arrayop.cpython-310.pyc
ADDED
Binary file (16.4 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/tensor/array/__pycache__/dense_ndim_array.cpython-310.pyc
ADDED
Binary file (8.46 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/tensor/array/__pycache__/mutable_ndim_array.cpython-310.pyc
ADDED
Binary file (854 Bytes). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/tensor/array/__pycache__/ndim_array.cpython-310.pyc
ADDED
Binary file (21.8 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/tensor/array/__pycache__/sparse_ndim_array.cpython-310.pyc
ADDED
Binary file (7.51 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/tensor/array/expressions/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (7.13 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/tensor/array/expressions/__pycache__/array_expressions.cpython-310.pyc
ADDED
Binary file (80.7 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/tensor/array/expressions/__pycache__/arrayexpr_derivatives.cpython-310.pyc
ADDED
Binary file (7.16 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/tensor/array/expressions/__pycache__/conv_array_to_indexed.cpython-310.pyc
ADDED
Binary file (605 Bytes). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/tensor/array/expressions/__pycache__/conv_array_to_matrix.cpython-310.pyc
ADDED
Binary file (480 Bytes). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/tensor/array/expressions/__pycache__/conv_indexed_to_array.cpython-310.pyc
ADDED
Binary file (422 Bytes). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/tensor/array/expressions/__pycache__/conv_matrix_to_array.cpython-310.pyc
ADDED
Binary file (419 Bytes). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/tensor/array/expressions/__pycache__/from_array_to_indexed.cpython-310.pyc
ADDED
Binary file (3.96 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/tensor/array/expressions/__pycache__/from_array_to_matrix.cpython-310.pyc
ADDED
Binary file (32.1 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/tensor/array/expressions/__pycache__/from_indexed_to_array.cpython-310.pyc
ADDED
Binary file (9.82 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/tensor/array/expressions/__pycache__/from_matrix_to_array.cpython-310.pyc
ADDED
Binary file (4.05 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/tensor/array/expressions/__pycache__/utils.cpython-310.pyc
ADDED
Binary file (5.43 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/tensor/array/expressions/array_expressions.py
ADDED
@@ -0,0 +1,1967 @@
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import collections.abc
|
2 |
+
import operator
|
3 |
+
from collections import defaultdict, Counter
|
4 |
+
from functools import reduce
|
5 |
+
import itertools
|
6 |
+
from itertools import accumulate
|
7 |
+
from typing import Optional, List, Tuple as tTuple
|
8 |
+
|
9 |
+
import typing
|
10 |
+
|
11 |
+
from sympy.core.numbers import Integer
|
12 |
+
from sympy.core.relational import Equality
|
13 |
+
from sympy.functions.special.tensor_functions import KroneckerDelta
|
14 |
+
from sympy.core.basic import Basic
|
15 |
+
from sympy.core.containers import Tuple
|
16 |
+
from sympy.core.expr import Expr
|
17 |
+
from sympy.core.function import (Function, Lambda)
|
18 |
+
from sympy.core.mul import Mul
|
19 |
+
from sympy.core.singleton import S
|
20 |
+
from sympy.core.sorting import default_sort_key
|
21 |
+
from sympy.core.symbol import (Dummy, Symbol)
|
22 |
+
from sympy.matrices.common import MatrixCommon
|
23 |
+
from sympy.matrices.expressions.diagonal import diagonalize_vector
|
24 |
+
from sympy.matrices.expressions.matexpr import MatrixExpr
|
25 |
+
from sympy.matrices.expressions.special import ZeroMatrix
|
26 |
+
from sympy.tensor.array.arrayop import (permutedims, tensorcontraction, tensordiagonal, tensorproduct)
|
27 |
+
from sympy.tensor.array.dense_ndim_array import ImmutableDenseNDimArray
|
28 |
+
from sympy.tensor.array.ndim_array import NDimArray
|
29 |
+
from sympy.tensor.indexed import (Indexed, IndexedBase)
|
30 |
+
from sympy.matrices.expressions.matexpr import MatrixElement
|
31 |
+
from sympy.tensor.array.expressions.utils import _apply_recursively_over_nested_lists, _sort_contraction_indices, \
|
32 |
+
_get_mapping_from_subranks, _build_push_indices_up_func_transformation, _get_contraction_links, \
|
33 |
+
_build_push_indices_down_func_transformation
|
34 |
+
from sympy.combinatorics import Permutation
|
35 |
+
from sympy.combinatorics.permutations import _af_invert
|
36 |
+
from sympy.core.sympify import _sympify
|
37 |
+
|
38 |
+
|
39 |
+
class _ArrayExpr(Expr):
|
40 |
+
shape: tTuple[Expr, ...]
|
41 |
+
|
42 |
+
def __getitem__(self, item):
|
43 |
+
if not isinstance(item, collections.abc.Iterable):
|
44 |
+
item = (item,)
|
45 |
+
ArrayElement._check_shape(self, item)
|
46 |
+
return self._get(item)
|
47 |
+
|
48 |
+
def _get(self, item):
|
49 |
+
return _get_array_element_or_slice(self, item)
|
50 |
+
|
51 |
+
|
52 |
+
class ArraySymbol(_ArrayExpr):
|
53 |
+
"""
|
54 |
+
Symbol representing an array expression
|
55 |
+
"""
|
56 |
+
|
57 |
+
def __new__(cls, symbol, shape: typing.Iterable) -> "ArraySymbol":
|
58 |
+
if isinstance(symbol, str):
|
59 |
+
symbol = Symbol(symbol)
|
60 |
+
# symbol = _sympify(symbol)
|
61 |
+
shape = Tuple(*map(_sympify, shape))
|
62 |
+
obj = Expr.__new__(cls, symbol, shape)
|
63 |
+
return obj
|
64 |
+
|
65 |
+
@property
|
66 |
+
def name(self):
|
67 |
+
return self._args[0]
|
68 |
+
|
69 |
+
@property
|
70 |
+
def shape(self):
|
71 |
+
return self._args[1]
|
72 |
+
|
73 |
+
def as_explicit(self):
|
74 |
+
if not all(i.is_Integer for i in self.shape):
|
75 |
+
raise ValueError("cannot express explicit array with symbolic shape")
|
76 |
+
data = [self[i] for i in itertools.product(*[range(j) for j in self.shape])]
|
77 |
+
return ImmutableDenseNDimArray(data).reshape(*self.shape)
|
78 |
+
|
79 |
+
|
80 |
+
class ArrayElement(Expr):
|
81 |
+
"""
|
82 |
+
An element of an array.
|
83 |
+
"""
|
84 |
+
|
85 |
+
_diff_wrt = True
|
86 |
+
is_symbol = True
|
87 |
+
is_commutative = True
|
88 |
+
|
89 |
+
def __new__(cls, name, indices):
|
90 |
+
if isinstance(name, str):
|
91 |
+
name = Symbol(name)
|
92 |
+
name = _sympify(name)
|
93 |
+
if not isinstance(indices, collections.abc.Iterable):
|
94 |
+
indices = (indices,)
|
95 |
+
indices = _sympify(tuple(indices))
|
96 |
+
cls._check_shape(name, indices)
|
97 |
+
obj = Expr.__new__(cls, name, indices)
|
98 |
+
return obj
|
99 |
+
|
100 |
+
@classmethod
|
101 |
+
def _check_shape(cls, name, indices):
|
102 |
+
indices = tuple(indices)
|
103 |
+
if hasattr(name, "shape"):
|
104 |
+
index_error = IndexError("number of indices does not match shape of the array")
|
105 |
+
if len(indices) != len(name.shape):
|
106 |
+
raise index_error
|
107 |
+
if any((i >= s) == True for i, s in zip(indices, name.shape)):
|
108 |
+
raise ValueError("shape is out of bounds")
|
109 |
+
if any((i < 0) == True for i in indices):
|
110 |
+
raise ValueError("shape contains negative values")
|
111 |
+
|
112 |
+
@property
|
113 |
+
def name(self):
|
114 |
+
return self._args[0]
|
115 |
+
|
116 |
+
@property
|
117 |
+
def indices(self):
|
118 |
+
return self._args[1]
|
119 |
+
|
120 |
+
def _eval_derivative(self, s):
|
121 |
+
if not isinstance(s, ArrayElement):
|
122 |
+
return S.Zero
|
123 |
+
|
124 |
+
if s == self:
|
125 |
+
return S.One
|
126 |
+
|
127 |
+
if s.name != self.name:
|
128 |
+
return S.Zero
|
129 |
+
|
130 |
+
return Mul.fromiter(KroneckerDelta(i, j) for i, j in zip(self.indices, s.indices))
|
131 |
+
|
132 |
+
|
133 |
+
class ZeroArray(_ArrayExpr):
|
134 |
+
"""
|
135 |
+
Symbolic array of zeros. Equivalent to ``ZeroMatrix`` for matrices.
|
136 |
+
"""
|
137 |
+
|
138 |
+
def __new__(cls, *shape):
|
139 |
+
if len(shape) == 0:
|
140 |
+
return S.Zero
|
141 |
+
shape = map(_sympify, shape)
|
142 |
+
obj = Expr.__new__(cls, *shape)
|
143 |
+
return obj
|
144 |
+
|
145 |
+
@property
|
146 |
+
def shape(self):
|
147 |
+
return self._args
|
148 |
+
|
149 |
+
def as_explicit(self):
|
150 |
+
if not all(i.is_Integer for i in self.shape):
|
151 |
+
raise ValueError("Cannot return explicit form for symbolic shape.")
|
152 |
+
return ImmutableDenseNDimArray.zeros(*self.shape)
|
153 |
+
|
154 |
+
def _get(self, item):
|
155 |
+
return S.Zero
|
156 |
+
|
157 |
+
|
158 |
+
class OneArray(_ArrayExpr):
|
159 |
+
"""
|
160 |
+
Symbolic array of ones.
|
161 |
+
"""
|
162 |
+
|
163 |
+
def __new__(cls, *shape):
|
164 |
+
if len(shape) == 0:
|
165 |
+
return S.One
|
166 |
+
shape = map(_sympify, shape)
|
167 |
+
obj = Expr.__new__(cls, *shape)
|
168 |
+
return obj
|
169 |
+
|
170 |
+
@property
|
171 |
+
def shape(self):
|
172 |
+
return self._args
|
173 |
+
|
174 |
+
def as_explicit(self):
|
175 |
+
if not all(i.is_Integer for i in self.shape):
|
176 |
+
raise ValueError("Cannot return explicit form for symbolic shape.")
|
177 |
+
return ImmutableDenseNDimArray([S.One for i in range(reduce(operator.mul, self.shape))]).reshape(*self.shape)
|
178 |
+
|
179 |
+
def _get(self, item):
|
180 |
+
return S.One
|
181 |
+
|
182 |
+
|
183 |
+
class _CodegenArrayAbstract(Basic):
|
184 |
+
|
185 |
+
@property
|
186 |
+
def subranks(self):
|
187 |
+
"""
|
188 |
+
Returns the ranks of the objects in the uppermost tensor product inside
|
189 |
+
the current object. In case no tensor products are contained, return
|
190 |
+
the atomic ranks.
|
191 |
+
|
192 |
+
Examples
|
193 |
+
========
|
194 |
+
|
195 |
+
>>> from sympy.tensor.array import tensorproduct, tensorcontraction
|
196 |
+
>>> from sympy import MatrixSymbol
|
197 |
+
>>> M = MatrixSymbol("M", 3, 3)
|
198 |
+
>>> N = MatrixSymbol("N", 3, 3)
|
199 |
+
>>> P = MatrixSymbol("P", 3, 3)
|
200 |
+
|
201 |
+
Important: do not confuse the rank of the matrix with the rank of an array.
|
202 |
+
|
203 |
+
>>> tp = tensorproduct(M, N, P)
|
204 |
+
>>> tp.subranks
|
205 |
+
[2, 2, 2]
|
206 |
+
|
207 |
+
>>> co = tensorcontraction(tp, (1, 2), (3, 4))
|
208 |
+
>>> co.subranks
|
209 |
+
[2, 2, 2]
|
210 |
+
"""
|
211 |
+
return self._subranks[:]
|
212 |
+
|
213 |
+
def subrank(self):
|
214 |
+
"""
|
215 |
+
The sum of ``subranks``.
|
216 |
+
"""
|
217 |
+
return sum(self.subranks)
|
218 |
+
|
219 |
+
@property
|
220 |
+
def shape(self):
|
221 |
+
return self._shape
|
222 |
+
|
223 |
+
def doit(self, **hints):
|
224 |
+
deep = hints.get("deep", True)
|
225 |
+
if deep:
|
226 |
+
return self.func(*[arg.doit(**hints) for arg in self.args])._canonicalize()
|
227 |
+
else:
|
228 |
+
return self._canonicalize()
|
229 |
+
|
230 |
+
class ArrayTensorProduct(_CodegenArrayAbstract):
|
231 |
+
r"""
|
232 |
+
Class to represent the tensor product of array-like objects.
|
233 |
+
"""
|
234 |
+
|
235 |
+
def __new__(cls, *args, **kwargs):
|
236 |
+
args = [_sympify(arg) for arg in args]
|
237 |
+
|
238 |
+
canonicalize = kwargs.pop("canonicalize", False)
|
239 |
+
|
240 |
+
ranks = [get_rank(arg) for arg in args]
|
241 |
+
|
242 |
+
obj = Basic.__new__(cls, *args)
|
243 |
+
obj._subranks = ranks
|
244 |
+
shapes = [get_shape(i) for i in args]
|
245 |
+
|
246 |
+
if any(i is None for i in shapes):
|
247 |
+
obj._shape = None
|
248 |
+
else:
|
249 |
+
obj._shape = tuple(j for i in shapes for j in i)
|
250 |
+
if canonicalize:
|
251 |
+
return obj._canonicalize()
|
252 |
+
return obj
|
253 |
+
|
254 |
+
def _canonicalize(self):
|
255 |
+
args = self.args
|
256 |
+
args = self._flatten(args)
|
257 |
+
|
258 |
+
ranks = [get_rank(arg) for arg in args]
|
259 |
+
|
260 |
+
# Check if there are nested permutation and lift them up:
|
261 |
+
permutation_cycles = []
|
262 |
+
for i, arg in enumerate(args):
|
263 |
+
if not isinstance(arg, PermuteDims):
|
264 |
+
continue
|
265 |
+
permutation_cycles.extend([[k + sum(ranks[:i]) for k in j] for j in arg.permutation.cyclic_form])
|
266 |
+
args[i] = arg.expr
|
267 |
+
if permutation_cycles:
|
268 |
+
return _permute_dims(_array_tensor_product(*args), Permutation(sum(ranks)-1)*Permutation(permutation_cycles))
|
269 |
+
|
270 |
+
if len(args) == 1:
|
271 |
+
return args[0]
|
272 |
+
|
273 |
+
# If any object is a ZeroArray, return a ZeroArray:
|
274 |
+
if any(isinstance(arg, (ZeroArray, ZeroMatrix)) for arg in args):
|
275 |
+
shapes = reduce(operator.add, [get_shape(i) for i in args], ())
|
276 |
+
return ZeroArray(*shapes)
|
277 |
+
|
278 |
+
# If there are contraction objects inside, transform the whole
|
279 |
+
# expression into `ArrayContraction`:
|
280 |
+
contractions = {i: arg for i, arg in enumerate(args) if isinstance(arg, ArrayContraction)}
|
281 |
+
if contractions:
|
282 |
+
ranks = [_get_subrank(arg) if isinstance(arg, ArrayContraction) else get_rank(arg) for arg in args]
|
283 |
+
cumulative_ranks = list(accumulate([0] + ranks))[:-1]
|
284 |
+
tp = _array_tensor_product(*[arg.expr if isinstance(arg, ArrayContraction) else arg for arg in args])
|
285 |
+
contraction_indices = [tuple(cumulative_ranks[i] + k for k in j) for i, arg in contractions.items() for j in arg.contraction_indices]
|
286 |
+
return _array_contraction(tp, *contraction_indices)
|
287 |
+
|
288 |
+
diagonals = {i: arg for i, arg in enumerate(args) if isinstance(arg, ArrayDiagonal)}
|
289 |
+
if diagonals:
|
290 |
+
inverse_permutation = []
|
291 |
+
last_perm = []
|
292 |
+
ranks = [get_rank(arg) for arg in args]
|
293 |
+
cumulative_ranks = list(accumulate([0] + ranks))[:-1]
|
294 |
+
for i, arg in enumerate(args):
|
295 |
+
if isinstance(arg, ArrayDiagonal):
|
296 |
+
i1 = get_rank(arg) - len(arg.diagonal_indices)
|
297 |
+
i2 = len(arg.diagonal_indices)
|
298 |
+
inverse_permutation.extend([cumulative_ranks[i] + j for j in range(i1)])
|
299 |
+
last_perm.extend([cumulative_ranks[i] + j for j in range(i1, i1 + i2)])
|
300 |
+
else:
|
301 |
+
inverse_permutation.extend([cumulative_ranks[i] + j for j in range(get_rank(arg))])
|
302 |
+
inverse_permutation.extend(last_perm)
|
303 |
+
tp = _array_tensor_product(*[arg.expr if isinstance(arg, ArrayDiagonal) else arg for arg in args])
|
304 |
+
ranks2 = [_get_subrank(arg) if isinstance(arg, ArrayDiagonal) else get_rank(arg) for arg in args]
|
305 |
+
cumulative_ranks2 = list(accumulate([0] + ranks2))[:-1]
|
306 |
+
diagonal_indices = [tuple(cumulative_ranks2[i] + k for k in j) for i, arg in diagonals.items() for j in arg.diagonal_indices]
|
307 |
+
return _permute_dims(_array_diagonal(tp, *diagonal_indices), _af_invert(inverse_permutation))
|
308 |
+
|
309 |
+
return self.func(*args, canonicalize=False)
|
310 |
+
|
311 |
+
@classmethod
|
312 |
+
def _flatten(cls, args):
|
313 |
+
args = [i for arg in args for i in (arg.args if isinstance(arg, cls) else [arg])]
|
314 |
+
return args
|
315 |
+
|
316 |
+
def as_explicit(self):
|
317 |
+
return tensorproduct(*[arg.as_explicit() if hasattr(arg, "as_explicit") else arg for arg in self.args])
|
318 |
+
|
319 |
+
|
320 |
+
class ArrayAdd(_CodegenArrayAbstract):
|
321 |
+
r"""
|
322 |
+
Class for elementwise array additions.
|
323 |
+
"""
|
324 |
+
|
325 |
+
def __new__(cls, *args, **kwargs):
|
326 |
+
args = [_sympify(arg) for arg in args]
|
327 |
+
ranks = [get_rank(arg) for arg in args]
|
328 |
+
ranks = list(set(ranks))
|
329 |
+
if len(ranks) != 1:
|
330 |
+
raise ValueError("summing arrays of different ranks")
|
331 |
+
shapes = [arg.shape for arg in args]
|
332 |
+
if len({i for i in shapes if i is not None}) > 1:
|
333 |
+
raise ValueError("mismatching shapes in addition")
|
334 |
+
|
335 |
+
canonicalize = kwargs.pop("canonicalize", False)
|
336 |
+
|
337 |
+
obj = Basic.__new__(cls, *args)
|
338 |
+
obj._subranks = ranks
|
339 |
+
if any(i is None for i in shapes):
|
340 |
+
obj._shape = None
|
341 |
+
else:
|
342 |
+
obj._shape = shapes[0]
|
343 |
+
if canonicalize:
|
344 |
+
return obj._canonicalize()
|
345 |
+
return obj
|
346 |
+
|
347 |
+
def _canonicalize(self):
|
348 |
+
args = self.args
|
349 |
+
|
350 |
+
# Flatten:
|
351 |
+
args = self._flatten_args(args)
|
352 |
+
|
353 |
+
shapes = [get_shape(arg) for arg in args]
|
354 |
+
args = [arg for arg in args if not isinstance(arg, (ZeroArray, ZeroMatrix))]
|
355 |
+
if len(args) == 0:
|
356 |
+
if any(i for i in shapes if i is None):
|
357 |
+
raise NotImplementedError("cannot handle addition of ZeroMatrix/ZeroArray and undefined shape object")
|
358 |
+
return ZeroArray(*shapes[0])
|
359 |
+
elif len(args) == 1:
|
360 |
+
return args[0]
|
361 |
+
return self.func(*args, canonicalize=False)
|
362 |
+
|
363 |
+
@classmethod
|
364 |
+
def _flatten_args(cls, args):
|
365 |
+
new_args = []
|
366 |
+
for arg in args:
|
367 |
+
if isinstance(arg, ArrayAdd):
|
368 |
+
new_args.extend(arg.args)
|
369 |
+
else:
|
370 |
+
new_args.append(arg)
|
371 |
+
return new_args
|
372 |
+
|
373 |
+
def as_explicit(self):
|
374 |
+
return reduce(
|
375 |
+
operator.add,
|
376 |
+
[arg.as_explicit() if hasattr(arg, "as_explicit") else arg for arg in self.args])
|
377 |
+
|
378 |
+
|
379 |
+
class PermuteDims(_CodegenArrayAbstract):
|
380 |
+
r"""
|
381 |
+
Class to represent permutation of axes of arrays.
|
382 |
+
|
383 |
+
Examples
|
384 |
+
========
|
385 |
+
|
386 |
+
>>> from sympy.tensor.array import permutedims
|
387 |
+
>>> from sympy import MatrixSymbol
|
388 |
+
>>> M = MatrixSymbol("M", 3, 3)
|
389 |
+
>>> cg = permutedims(M, [1, 0])
|
390 |
+
|
391 |
+
The object ``cg`` represents the transposition of ``M``, as the permutation
|
392 |
+
``[1, 0]`` will act on its indices by switching them:
|
393 |
+
|
394 |
+
`M_{ij} \Rightarrow M_{ji}`
|
395 |
+
|
396 |
+
This is evident when transforming back to matrix form:
|
397 |
+
|
398 |
+
>>> from sympy.tensor.array.expressions.from_array_to_matrix import convert_array_to_matrix
|
399 |
+
>>> convert_array_to_matrix(cg)
|
400 |
+
M.T
|
401 |
+
|
402 |
+
>>> N = MatrixSymbol("N", 3, 2)
|
403 |
+
>>> cg = permutedims(N, [1, 0])
|
404 |
+
>>> cg.shape
|
405 |
+
(2, 3)
|
406 |
+
|
407 |
+
There are optional parameters that can be used as alternative to the permutation:
|
408 |
+
|
409 |
+
>>> from sympy.tensor.array.expressions import ArraySymbol, PermuteDims
|
410 |
+
>>> M = ArraySymbol("M", (1, 2, 3, 4, 5))
|
411 |
+
>>> expr = PermuteDims(M, index_order_old="ijklm", index_order_new="kijml")
|
412 |
+
>>> expr
|
413 |
+
PermuteDims(M, (0 2 1)(3 4))
|
414 |
+
>>> expr.shape
|
415 |
+
(3, 1, 2, 5, 4)
|
416 |
+
|
417 |
+
Permutations of tensor products are simplified in order to achieve a
|
418 |
+
standard form:
|
419 |
+
|
420 |
+
>>> from sympy.tensor.array import tensorproduct
|
421 |
+
>>> M = MatrixSymbol("M", 4, 5)
|
422 |
+
>>> tp = tensorproduct(M, N)
|
423 |
+
>>> tp.shape
|
424 |
+
(4, 5, 3, 2)
|
425 |
+
>>> perm1 = permutedims(tp, [2, 3, 1, 0])
|
426 |
+
|
427 |
+
The args ``(M, N)`` have been sorted and the permutation has been
|
428 |
+
simplified, the expression is equivalent:
|
429 |
+
|
430 |
+
>>> perm1.expr.args
|
431 |
+
(N, M)
|
432 |
+
>>> perm1.shape
|
433 |
+
(3, 2, 5, 4)
|
434 |
+
>>> perm1.permutation
|
435 |
+
(2 3)
|
436 |
+
|
437 |
+
The permutation in its array form has been simplified from
|
438 |
+
``[2, 3, 1, 0]`` to ``[0, 1, 3, 2]``, as the arguments of the tensor
|
439 |
+
product `M` and `N` have been switched:
|
440 |
+
|
441 |
+
>>> perm1.permutation.array_form
|
442 |
+
[0, 1, 3, 2]
|
443 |
+
|
444 |
+
We can nest a second permutation:
|
445 |
+
|
446 |
+
>>> perm2 = permutedims(perm1, [1, 0, 2, 3])
|
447 |
+
>>> perm2.shape
|
448 |
+
(2, 3, 5, 4)
|
449 |
+
>>> perm2.permutation.array_form
|
450 |
+
[1, 0, 3, 2]
|
451 |
+
"""
|
452 |
+
|
453 |
+
def __new__(cls, expr, permutation=None, index_order_old=None, index_order_new=None, **kwargs):
|
454 |
+
from sympy.combinatorics import Permutation
|
455 |
+
expr = _sympify(expr)
|
456 |
+
expr_rank = get_rank(expr)
|
457 |
+
permutation = cls._get_permutation_from_arguments(permutation, index_order_old, index_order_new, expr_rank)
|
458 |
+
permutation = Permutation(permutation)
|
459 |
+
permutation_size = permutation.size
|
460 |
+
if permutation_size != expr_rank:
|
461 |
+
raise ValueError("Permutation size must be the length of the shape of expr")
|
462 |
+
|
463 |
+
canonicalize = kwargs.pop("canonicalize", False)
|
464 |
+
|
465 |
+
obj = Basic.__new__(cls, expr, permutation)
|
466 |
+
obj._subranks = [get_rank(expr)]
|
467 |
+
shape = get_shape(expr)
|
468 |
+
if shape is None:
|
469 |
+
obj._shape = None
|
470 |
+
else:
|
471 |
+
obj._shape = tuple(shape[permutation(i)] for i in range(len(shape)))
|
472 |
+
if canonicalize:
|
473 |
+
return obj._canonicalize()
|
474 |
+
return obj
|
475 |
+
|
476 |
+
def _canonicalize(self):
|
477 |
+
expr = self.expr
|
478 |
+
permutation = self.permutation
|
479 |
+
if isinstance(expr, PermuteDims):
|
480 |
+
subexpr = expr.expr
|
481 |
+
subperm = expr.permutation
|
482 |
+
permutation = permutation * subperm
|
483 |
+
expr = subexpr
|
484 |
+
if isinstance(expr, ArrayContraction):
|
485 |
+
expr, permutation = self._PermuteDims_denestarg_ArrayContraction(expr, permutation)
|
486 |
+
if isinstance(expr, ArrayTensorProduct):
|
487 |
+
expr, permutation = self._PermuteDims_denestarg_ArrayTensorProduct(expr, permutation)
|
488 |
+
if isinstance(expr, (ZeroArray, ZeroMatrix)):
|
489 |
+
return ZeroArray(*[expr.shape[i] for i in permutation.array_form])
|
490 |
+
plist = permutation.array_form
|
491 |
+
if plist == sorted(plist):
|
492 |
+
return expr
|
493 |
+
return self.func(expr, permutation, canonicalize=False)
|
494 |
+
|
495 |
+
@property
|
496 |
+
def expr(self):
|
497 |
+
return self.args[0]
|
498 |
+
|
499 |
+
@property
|
500 |
+
def permutation(self):
|
501 |
+
return self.args[1]
|
502 |
+
|
503 |
+
@classmethod
|
504 |
+
def _PermuteDims_denestarg_ArrayTensorProduct(cls, expr, permutation):
|
505 |
+
# Get the permutation in its image-form:
|
506 |
+
perm_image_form = _af_invert(permutation.array_form)
|
507 |
+
args = list(expr.args)
|
508 |
+
# Starting index global position for every arg:
|
509 |
+
cumul = list(accumulate([0] + expr.subranks))
|
510 |
+
# Split `perm_image_form` into a list of list corresponding to the indices
|
511 |
+
# of every argument:
|
512 |
+
perm_image_form_in_components = [perm_image_form[cumul[i]:cumul[i+1]] for i in range(len(args))]
|
513 |
+
# Create an index, target-position-key array:
|
514 |
+
ps = [(i, sorted(comp)) for i, comp in enumerate(perm_image_form_in_components)]
|
515 |
+
# Sort the array according to the target-position-key:
|
516 |
+
# In this way, we define a canonical way to sort the arguments according
|
517 |
+
# to the permutation.
|
518 |
+
ps.sort(key=lambda x: x[1])
|
519 |
+
# Read the inverse-permutation (i.e. image-form) of the args:
|
520 |
+
perm_args_image_form = [i[0] for i in ps]
|
521 |
+
# Apply the args-permutation to the `args`:
|
522 |
+
args_sorted = [args[i] for i in perm_args_image_form]
|
523 |
+
# Apply the args-permutation to the array-form of the permutation of the axes (of `expr`):
|
524 |
+
perm_image_form_sorted_args = [perm_image_form_in_components[i] for i in perm_args_image_form]
|
525 |
+
new_permutation = Permutation(_af_invert([j for i in perm_image_form_sorted_args for j in i]))
|
526 |
+
return _array_tensor_product(*args_sorted), new_permutation
|
527 |
+
|
528 |
+
@classmethod
|
529 |
+
def _PermuteDims_denestarg_ArrayContraction(cls, expr, permutation):
|
530 |
+
if not isinstance(expr, ArrayContraction):
|
531 |
+
return expr, permutation
|
532 |
+
if not isinstance(expr.expr, ArrayTensorProduct):
|
533 |
+
return expr, permutation
|
534 |
+
args = expr.expr.args
|
535 |
+
subranks = [get_rank(arg) for arg in expr.expr.args]
|
536 |
+
|
537 |
+
contraction_indices = expr.contraction_indices
|
538 |
+
contraction_indices_flat = [j for i in contraction_indices for j in i]
|
539 |
+
cumul = list(accumulate([0] + subranks))
|
540 |
+
|
541 |
+
# Spread the permutation in its array form across the args in the corresponding
|
542 |
+
# tensor-product arguments with free indices:
|
543 |
+
permutation_array_blocks_up = []
|
544 |
+
image_form = _af_invert(permutation.array_form)
|
545 |
+
counter = 0
|
546 |
+
for i, e in enumerate(subranks):
|
547 |
+
current = []
|
548 |
+
for j in range(cumul[i], cumul[i+1]):
|
549 |
+
if j in contraction_indices_flat:
|
550 |
+
continue
|
551 |
+
current.append(image_form[counter])
|
552 |
+
counter += 1
|
553 |
+
permutation_array_blocks_up.append(current)
|
554 |
+
|
555 |
+
# Get the map of axis repositioning for every argument of tensor-product:
|
556 |
+
index_blocks = [list(range(cumul[i], cumul[i+1])) for i, e in enumerate(expr.subranks)]
|
557 |
+
index_blocks_up = expr._push_indices_up(expr.contraction_indices, index_blocks)
|
558 |
+
inverse_permutation = permutation**(-1)
|
559 |
+
index_blocks_up_permuted = [[inverse_permutation(j) for j in i if j is not None] for i in index_blocks_up]
|
560 |
+
|
561 |
+
# Sorting key is a list of tuple, first element is the index of `args`, second element of
|
562 |
+
# the tuple is the sorting key to sort `args` of the tensor product:
|
563 |
+
sorting_keys = list(enumerate(index_blocks_up_permuted))
|
564 |
+
sorting_keys.sort(key=lambda x: x[1])
|
565 |
+
|
566 |
+
# Now we can get the permutation acting on the args in its image-form:
|
567 |
+
new_perm_image_form = [i[0] for i in sorting_keys]
|
568 |
+
# Apply the args-level permutation to various elements:
|
569 |
+
new_index_blocks = [index_blocks[i] for i in new_perm_image_form]
|
570 |
+
new_index_perm_array_form = _af_invert([j for i in new_index_blocks for j in i])
|
571 |
+
new_args = [args[i] for i in new_perm_image_form]
|
572 |
+
new_contraction_indices = [tuple(new_index_perm_array_form[j] for j in i) for i in contraction_indices]
|
573 |
+
new_expr = _array_contraction(_array_tensor_product(*new_args), *new_contraction_indices)
|
574 |
+
new_permutation = Permutation(_af_invert([j for i in [permutation_array_blocks_up[k] for k in new_perm_image_form] for j in i]))
|
575 |
+
return new_expr, new_permutation
|
576 |
+
|
577 |
+
@classmethod
|
578 |
+
def _check_permutation_mapping(cls, expr, permutation):
|
579 |
+
subranks = expr.subranks
|
580 |
+
index2arg = [i for i, arg in enumerate(expr.args) for j in range(expr.subranks[i])]
|
581 |
+
permuted_indices = [permutation(i) for i in range(expr.subrank())]
|
582 |
+
new_args = list(expr.args)
|
583 |
+
arg_candidate_index = index2arg[permuted_indices[0]]
|
584 |
+
current_indices = []
|
585 |
+
new_permutation = []
|
586 |
+
inserted_arg_cand_indices = set()
|
587 |
+
for i, idx in enumerate(permuted_indices):
|
588 |
+
if index2arg[idx] != arg_candidate_index:
|
589 |
+
new_permutation.extend(current_indices)
|
590 |
+
current_indices = []
|
591 |
+
arg_candidate_index = index2arg[idx]
|
592 |
+
current_indices.append(idx)
|
593 |
+
arg_candidate_rank = subranks[arg_candidate_index]
|
594 |
+
if len(current_indices) == arg_candidate_rank:
|
595 |
+
new_permutation.extend(sorted(current_indices))
|
596 |
+
local_current_indices = [j - min(current_indices) for j in current_indices]
|
597 |
+
i1 = index2arg[i]
|
598 |
+
new_args[i1] = _permute_dims(new_args[i1], Permutation(local_current_indices))
|
599 |
+
inserted_arg_cand_indices.add(arg_candidate_index)
|
600 |
+
current_indices = []
|
601 |
+
new_permutation.extend(current_indices)
|
602 |
+
|
603 |
+
# TODO: swap args positions in order to simplify the expression:
|
604 |
+
# TODO: this should be in a function
|
605 |
+
args_positions = list(range(len(new_args)))
|
606 |
+
# Get possible shifts:
|
607 |
+
maps = {}
|
608 |
+
cumulative_subranks = [0] + list(accumulate(subranks))
|
609 |
+
for i in range(len(subranks)):
|
610 |
+
s = {index2arg[new_permutation[j]] for j in range(cumulative_subranks[i], cumulative_subranks[i+1])}
|
611 |
+
if len(s) != 1:
|
612 |
+
continue
|
613 |
+
elem = next(iter(s))
|
614 |
+
if i != elem:
|
615 |
+
maps[i] = elem
|
616 |
+
|
617 |
+
# Find cycles in the map:
|
618 |
+
lines = []
|
619 |
+
current_line = []
|
620 |
+
while maps:
|
621 |
+
if len(current_line) == 0:
|
622 |
+
k, v = maps.popitem()
|
623 |
+
current_line.append(k)
|
624 |
+
else:
|
625 |
+
k = current_line[-1]
|
626 |
+
if k not in maps:
|
627 |
+
current_line = []
|
628 |
+
continue
|
629 |
+
v = maps.pop(k)
|
630 |
+
if v in current_line:
|
631 |
+
lines.append(current_line)
|
632 |
+
current_line = []
|
633 |
+
continue
|
634 |
+
current_line.append(v)
|
635 |
+
for line in lines:
|
636 |
+
for i, e in enumerate(line):
|
637 |
+
args_positions[line[(i + 1) % len(line)]] = e
|
638 |
+
|
639 |
+
# TODO: function in order to permute the args:
|
640 |
+
permutation_blocks = [[new_permutation[cumulative_subranks[i] + j] for j in range(e)] for i, e in enumerate(subranks)]
|
641 |
+
new_args = [new_args[i] for i in args_positions]
|
642 |
+
new_permutation_blocks = [permutation_blocks[i] for i in args_positions]
|
643 |
+
new_permutation2 = [j for i in new_permutation_blocks for j in i]
|
644 |
+
return _array_tensor_product(*new_args), Permutation(new_permutation2) # **(-1)
|
645 |
+
|
646 |
+
@classmethod
|
647 |
+
def _check_if_there_are_closed_cycles(cls, expr, permutation):
|
648 |
+
args = list(expr.args)
|
649 |
+
subranks = expr.subranks
|
650 |
+
cyclic_form = permutation.cyclic_form
|
651 |
+
cumulative_subranks = [0] + list(accumulate(subranks))
|
652 |
+
cyclic_min = [min(i) for i in cyclic_form]
|
653 |
+
cyclic_max = [max(i) for i in cyclic_form]
|
654 |
+
cyclic_keep = []
|
655 |
+
for i, cycle in enumerate(cyclic_form):
|
656 |
+
flag = True
|
657 |
+
for j in range(len(cumulative_subranks) - 1):
|
658 |
+
if cyclic_min[i] >= cumulative_subranks[j] and cyclic_max[i] < cumulative_subranks[j+1]:
|
659 |
+
# Found a sinkable cycle.
|
660 |
+
args[j] = _permute_dims(args[j], Permutation([[k - cumulative_subranks[j] for k in cyclic_form[i]]]))
|
661 |
+
flag = False
|
662 |
+
break
|
663 |
+
if flag:
|
664 |
+
cyclic_keep.append(cyclic_form[i])
|
665 |
+
return _array_tensor_product(*args), Permutation(cyclic_keep, size=permutation.size)
|
666 |
+
|
667 |
+
def nest_permutation(self):
|
668 |
+
r"""
|
669 |
+
DEPRECATED.
|
670 |
+
"""
|
671 |
+
ret = self._nest_permutation(self.expr, self.permutation)
|
672 |
+
if ret is None:
|
673 |
+
return self
|
674 |
+
return ret
|
675 |
+
|
676 |
+
@classmethod
|
677 |
+
def _nest_permutation(cls, expr, permutation):
|
678 |
+
if isinstance(expr, ArrayTensorProduct):
|
679 |
+
return _permute_dims(*cls._check_if_there_are_closed_cycles(expr, permutation))
|
680 |
+
elif isinstance(expr, ArrayContraction):
|
681 |
+
# Invert tree hierarchy: put the contraction above.
|
682 |
+
cycles = permutation.cyclic_form
|
683 |
+
newcycles = ArrayContraction._convert_outer_indices_to_inner_indices(expr, *cycles)
|
684 |
+
newpermutation = Permutation(newcycles)
|
685 |
+
new_contr_indices = [tuple(newpermutation(j) for j in i) for i in expr.contraction_indices]
|
686 |
+
return _array_contraction(PermuteDims(expr.expr, newpermutation), *new_contr_indices)
|
687 |
+
elif isinstance(expr, ArrayAdd):
|
688 |
+
return _array_add(*[PermuteDims(arg, permutation) for arg in expr.args])
|
689 |
+
return None
|
690 |
+
|
691 |
+
def as_explicit(self):
|
692 |
+
expr = self.expr
|
693 |
+
if hasattr(expr, "as_explicit"):
|
694 |
+
expr = expr.as_explicit()
|
695 |
+
return permutedims(expr, self.permutation)
|
696 |
+
|
697 |
+
@classmethod
|
698 |
+
def _get_permutation_from_arguments(cls, permutation, index_order_old, index_order_new, dim):
|
699 |
+
if permutation is None:
|
700 |
+
if index_order_new is None or index_order_old is None:
|
701 |
+
raise ValueError("Permutation not defined")
|
702 |
+
return PermuteDims._get_permutation_from_index_orders(index_order_old, index_order_new, dim)
|
703 |
+
else:
|
704 |
+
if index_order_new is not None:
|
705 |
+
raise ValueError("index_order_new cannot be defined with permutation")
|
706 |
+
if index_order_old is not None:
|
707 |
+
raise ValueError("index_order_old cannot be defined with permutation")
|
708 |
+
return permutation
|
709 |
+
|
710 |
+
@classmethod
|
711 |
+
def _get_permutation_from_index_orders(cls, index_order_old, index_order_new, dim):
|
712 |
+
if len(set(index_order_new)) != dim:
|
713 |
+
raise ValueError("wrong number of indices in index_order_new")
|
714 |
+
if len(set(index_order_old)) != dim:
|
715 |
+
raise ValueError("wrong number of indices in index_order_old")
|
716 |
+
if len(set.symmetric_difference(set(index_order_new), set(index_order_old))) > 0:
|
717 |
+
raise ValueError("index_order_new and index_order_old must have the same indices")
|
718 |
+
permutation = [index_order_old.index(i) for i in index_order_new]
|
719 |
+
return permutation
|
720 |
+
|
721 |
+
|
722 |
+
class ArrayDiagonal(_CodegenArrayAbstract):
|
723 |
+
r"""
|
724 |
+
Class to represent the diagonal operator.
|
725 |
+
|
726 |
+
Explanation
|
727 |
+
===========
|
728 |
+
|
729 |
+
In a 2-dimensional array it returns the diagonal, this looks like the
|
730 |
+
operation:
|
731 |
+
|
732 |
+
`A_{ij} \rightarrow A_{ii}`
|
733 |
+
|
734 |
+
The diagonal over axes 1 and 2 (the second and third) of the tensor product
|
735 |
+
of two 2-dimensional arrays `A \otimes B` is
|
736 |
+
|
737 |
+
`\Big[ A_{ab} B_{cd} \Big]_{abcd} \rightarrow \Big[ A_{ai} B_{id} \Big]_{adi}`
|
738 |
+
|
739 |
+
In this last example the array expression has been reduced from
|
740 |
+
4-dimensional to 3-dimensional. Notice that no contraction has occurred,
|
741 |
+
rather there is a new index `i` for the diagonal, contraction would have
|
742 |
+
reduced the array to 2 dimensions.
|
743 |
+
|
744 |
+
Notice that the diagonalized out dimensions are added as new dimensions at
|
745 |
+
the end of the indices.
|
746 |
+
"""
|
747 |
+
|
748 |
+
def __new__(cls, expr, *diagonal_indices, **kwargs):
|
749 |
+
expr = _sympify(expr)
|
750 |
+
diagonal_indices = [Tuple(*sorted(i)) for i in diagonal_indices]
|
751 |
+
canonicalize = kwargs.get("canonicalize", False)
|
752 |
+
|
753 |
+
shape = get_shape(expr)
|
754 |
+
if shape is not None:
|
755 |
+
cls._validate(expr, *diagonal_indices, **kwargs)
|
756 |
+
# Get new shape:
|
757 |
+
positions, shape = cls._get_positions_shape(shape, diagonal_indices)
|
758 |
+
else:
|
759 |
+
positions = None
|
760 |
+
if len(diagonal_indices) == 0:
|
761 |
+
return expr
|
762 |
+
obj = Basic.__new__(cls, expr, *diagonal_indices)
|
763 |
+
obj._positions = positions
|
764 |
+
obj._subranks = _get_subranks(expr)
|
765 |
+
obj._shape = shape
|
766 |
+
if canonicalize:
|
767 |
+
return obj._canonicalize()
|
768 |
+
return obj
|
769 |
+
|
770 |
+
def _canonicalize(self):
|
771 |
+
expr = self.expr
|
772 |
+
diagonal_indices = self.diagonal_indices
|
773 |
+
trivial_diags = [i for i in diagonal_indices if len(i) == 1]
|
774 |
+
if len(trivial_diags) > 0:
|
775 |
+
trivial_pos = {e[0]: i for i, e in enumerate(diagonal_indices) if len(e) == 1}
|
776 |
+
diag_pos = {e: i for i, e in enumerate(diagonal_indices) if len(e) > 1}
|
777 |
+
diagonal_indices_short = [i for i in diagonal_indices if len(i) > 1]
|
778 |
+
rank1 = get_rank(self)
|
779 |
+
rank2 = len(diagonal_indices)
|
780 |
+
rank3 = rank1 - rank2
|
781 |
+
inv_permutation = []
|
782 |
+
counter1 = 0
|
783 |
+
indices_down = ArrayDiagonal._push_indices_down(diagonal_indices_short, list(range(rank1)), get_rank(expr))
|
784 |
+
for i in indices_down:
|
785 |
+
if i in trivial_pos:
|
786 |
+
inv_permutation.append(rank3 + trivial_pos[i])
|
787 |
+
elif isinstance(i, (Integer, int)):
|
788 |
+
inv_permutation.append(counter1)
|
789 |
+
counter1 += 1
|
790 |
+
else:
|
791 |
+
inv_permutation.append(rank3 + diag_pos[i])
|
792 |
+
permutation = _af_invert(inv_permutation)
|
793 |
+
if len(diagonal_indices_short) > 0:
|
794 |
+
return _permute_dims(_array_diagonal(expr, *diagonal_indices_short), permutation)
|
795 |
+
else:
|
796 |
+
return _permute_dims(expr, permutation)
|
797 |
+
if isinstance(expr, ArrayAdd):
|
798 |
+
return self._ArrayDiagonal_denest_ArrayAdd(expr, *diagonal_indices)
|
799 |
+
if isinstance(expr, ArrayDiagonal):
|
800 |
+
return self._ArrayDiagonal_denest_ArrayDiagonal(expr, *diagonal_indices)
|
801 |
+
if isinstance(expr, PermuteDims):
|
802 |
+
return self._ArrayDiagonal_denest_PermuteDims(expr, *diagonal_indices)
|
803 |
+
if isinstance(expr, (ZeroArray, ZeroMatrix)):
|
804 |
+
positions, shape = self._get_positions_shape(expr.shape, diagonal_indices)
|
805 |
+
return ZeroArray(*shape)
|
806 |
+
return self.func(expr, *diagonal_indices, canonicalize=False)
|
807 |
+
|
808 |
+
@staticmethod
|
809 |
+
def _validate(expr, *diagonal_indices, **kwargs):
|
810 |
+
# Check that no diagonalization happens on indices with mismatched
|
811 |
+
# dimensions:
|
812 |
+
shape = get_shape(expr)
|
813 |
+
for i in diagonal_indices:
|
814 |
+
if any(j >= len(shape) for j in i):
|
815 |
+
raise ValueError("index is larger than expression shape")
|
816 |
+
if len({shape[j] for j in i}) != 1:
|
817 |
+
raise ValueError("diagonalizing indices of different dimensions")
|
818 |
+
if not kwargs.get("allow_trivial_diags", False) and len(i) <= 1:
|
819 |
+
raise ValueError("need at least two axes to diagonalize")
|
820 |
+
if len(set(i)) != len(i):
|
821 |
+
raise ValueError("axis index cannot be repeated")
|
822 |
+
|
823 |
+
@staticmethod
|
824 |
+
def _remove_trivial_dimensions(shape, *diagonal_indices):
|
825 |
+
return [tuple(j for j in i) for i in diagonal_indices if shape[i[0]] != 1]
|
826 |
+
|
827 |
+
@property
|
828 |
+
def expr(self):
|
829 |
+
return self.args[0]
|
830 |
+
|
831 |
+
@property
|
832 |
+
def diagonal_indices(self):
|
833 |
+
return self.args[1:]
|
834 |
+
|
835 |
+
@staticmethod
|
836 |
+
def _flatten(expr, *outer_diagonal_indices):
|
837 |
+
inner_diagonal_indices = expr.diagonal_indices
|
838 |
+
all_inner = [j for i in inner_diagonal_indices for j in i]
|
839 |
+
all_inner.sort()
|
840 |
+
# TODO: add API for total rank and cumulative rank:
|
841 |
+
total_rank = _get_subrank(expr)
|
842 |
+
inner_rank = len(all_inner)
|
843 |
+
outer_rank = total_rank - inner_rank
|
844 |
+
shifts = [0 for i in range(outer_rank)]
|
845 |
+
counter = 0
|
846 |
+
pointer = 0
|
847 |
+
for i in range(outer_rank):
|
848 |
+
while pointer < inner_rank and counter >= all_inner[pointer]:
|
849 |
+
counter += 1
|
850 |
+
pointer += 1
|
851 |
+
shifts[i] += pointer
|
852 |
+
counter += 1
|
853 |
+
outer_diagonal_indices = tuple(tuple(shifts[j] + j for j in i) for i in outer_diagonal_indices)
|
854 |
+
diagonal_indices = inner_diagonal_indices + outer_diagonal_indices
|
855 |
+
return _array_diagonal(expr.expr, *diagonal_indices)
|
856 |
+
|
857 |
+
@classmethod
|
858 |
+
def _ArrayDiagonal_denest_ArrayAdd(cls, expr, *diagonal_indices):
|
859 |
+
return _array_add(*[_array_diagonal(arg, *diagonal_indices) for arg in expr.args])
|
860 |
+
|
861 |
+
@classmethod
|
862 |
+
def _ArrayDiagonal_denest_ArrayDiagonal(cls, expr, *diagonal_indices):
|
863 |
+
return cls._flatten(expr, *diagonal_indices)
|
864 |
+
|
865 |
+
@classmethod
|
866 |
+
def _ArrayDiagonal_denest_PermuteDims(cls, expr: PermuteDims, *diagonal_indices):
|
867 |
+
back_diagonal_indices = [[expr.permutation(j) for j in i] for i in diagonal_indices]
|
868 |
+
nondiag = [i for i in range(get_rank(expr)) if not any(i in j for j in diagonal_indices)]
|
869 |
+
back_nondiag = [expr.permutation(i) for i in nondiag]
|
870 |
+
remap = {e: i for i, e in enumerate(sorted(back_nondiag))}
|
871 |
+
new_permutation1 = [remap[i] for i in back_nondiag]
|
872 |
+
shift = len(new_permutation1)
|
873 |
+
diag_block_perm = [i + shift for i in range(len(back_diagonal_indices))]
|
874 |
+
new_permutation = new_permutation1 + diag_block_perm
|
875 |
+
return _permute_dims(
|
876 |
+
_array_diagonal(
|
877 |
+
expr.expr,
|
878 |
+
*back_diagonal_indices
|
879 |
+
),
|
880 |
+
new_permutation
|
881 |
+
)
|
882 |
+
|
883 |
+
def _push_indices_down_nonstatic(self, indices):
|
884 |
+
transform = lambda x: self._positions[x] if x < len(self._positions) else None
|
885 |
+
return _apply_recursively_over_nested_lists(transform, indices)
|
886 |
+
|
887 |
+
def _push_indices_up_nonstatic(self, indices):
|
888 |
+
|
889 |
+
def transform(x):
|
890 |
+
for i, e in enumerate(self._positions):
|
891 |
+
if (isinstance(e, int) and x == e) or (isinstance(e, tuple) and x in e):
|
892 |
+
return i
|
893 |
+
|
894 |
+
return _apply_recursively_over_nested_lists(transform, indices)
|
895 |
+
|
896 |
+
@classmethod
|
897 |
+
def _push_indices_down(cls, diagonal_indices, indices, rank):
|
898 |
+
positions, shape = cls._get_positions_shape(range(rank), diagonal_indices)
|
899 |
+
transform = lambda x: positions[x] if x < len(positions) else None
|
900 |
+
return _apply_recursively_over_nested_lists(transform, indices)
|
901 |
+
|
902 |
+
@classmethod
|
903 |
+
def _push_indices_up(cls, diagonal_indices, indices, rank):
|
904 |
+
positions, shape = cls._get_positions_shape(range(rank), diagonal_indices)
|
905 |
+
|
906 |
+
def transform(x):
|
907 |
+
for i, e in enumerate(positions):
|
908 |
+
if (isinstance(e, int) and x == e) or (isinstance(e, (tuple, Tuple)) and (x in e)):
|
909 |
+
return i
|
910 |
+
|
911 |
+
return _apply_recursively_over_nested_lists(transform, indices)
|
912 |
+
|
913 |
+
@classmethod
|
914 |
+
def _get_positions_shape(cls, shape, diagonal_indices):
|
915 |
+
data1 = tuple((i, shp) for i, shp in enumerate(shape) if not any(i in j for j in diagonal_indices))
|
916 |
+
pos1, shp1 = zip(*data1) if data1 else ((), ())
|
917 |
+
data2 = tuple((i, shape[i[0]]) for i in diagonal_indices)
|
918 |
+
pos2, shp2 = zip(*data2) if data2 else ((), ())
|
919 |
+
positions = pos1 + pos2
|
920 |
+
shape = shp1 + shp2
|
921 |
+
return positions, shape
|
922 |
+
|
923 |
+
def as_explicit(self):
|
924 |
+
expr = self.expr
|
925 |
+
if hasattr(expr, "as_explicit"):
|
926 |
+
expr = expr.as_explicit()
|
927 |
+
return tensordiagonal(expr, *self.diagonal_indices)
|
928 |
+
|
929 |
+
|
930 |
+
class ArrayElementwiseApplyFunc(_CodegenArrayAbstract):
|
931 |
+
|
932 |
+
def __new__(cls, function, element):
|
933 |
+
|
934 |
+
if not isinstance(function, Lambda):
|
935 |
+
d = Dummy('d')
|
936 |
+
function = Lambda(d, function(d))
|
937 |
+
|
938 |
+
obj = _CodegenArrayAbstract.__new__(cls, function, element)
|
939 |
+
obj._subranks = _get_subranks(element)
|
940 |
+
return obj
|
941 |
+
|
942 |
+
@property
|
943 |
+
def function(self):
|
944 |
+
return self.args[0]
|
945 |
+
|
946 |
+
@property
|
947 |
+
def expr(self):
|
948 |
+
return self.args[1]
|
949 |
+
|
950 |
+
@property
|
951 |
+
def shape(self):
|
952 |
+
return self.expr.shape
|
953 |
+
|
954 |
+
def _get_function_fdiff(self):
|
955 |
+
d = Dummy("d")
|
956 |
+
function = self.function(d)
|
957 |
+
fdiff = function.diff(d)
|
958 |
+
if isinstance(fdiff, Function):
|
959 |
+
fdiff = type(fdiff)
|
960 |
+
else:
|
961 |
+
fdiff = Lambda(d, fdiff)
|
962 |
+
return fdiff
|
963 |
+
|
964 |
+
def as_explicit(self):
|
965 |
+
expr = self.expr
|
966 |
+
if hasattr(expr, "as_explicit"):
|
967 |
+
expr = expr.as_explicit()
|
968 |
+
return expr.applyfunc(self.function)
|
969 |
+
|
970 |
+
|
971 |
+
class ArrayContraction(_CodegenArrayAbstract):
|
972 |
+
r"""
|
973 |
+
This class is meant to represent contractions of arrays in a form easily
|
974 |
+
processable by the code printers.
|
975 |
+
"""
|
976 |
+
|
977 |
+
def __new__(cls, expr, *contraction_indices, **kwargs):
|
978 |
+
contraction_indices = _sort_contraction_indices(contraction_indices)
|
979 |
+
expr = _sympify(expr)
|
980 |
+
|
981 |
+
canonicalize = kwargs.get("canonicalize", False)
|
982 |
+
|
983 |
+
obj = Basic.__new__(cls, expr, *contraction_indices)
|
984 |
+
obj._subranks = _get_subranks(expr)
|
985 |
+
obj._mapping = _get_mapping_from_subranks(obj._subranks)
|
986 |
+
|
987 |
+
free_indices_to_position = {i: i for i in range(sum(obj._subranks)) if all(i not in cind for cind in contraction_indices)}
|
988 |
+
obj._free_indices_to_position = free_indices_to_position
|
989 |
+
|
990 |
+
shape = get_shape(expr)
|
991 |
+
cls._validate(expr, *contraction_indices)
|
992 |
+
if shape:
|
993 |
+
shape = tuple(shp for i, shp in enumerate(shape) if not any(i in j for j in contraction_indices))
|
994 |
+
obj._shape = shape
|
995 |
+
if canonicalize:
|
996 |
+
return obj._canonicalize()
|
997 |
+
return obj
|
998 |
+
|
999 |
+
def _canonicalize(self):
|
1000 |
+
expr = self.expr
|
1001 |
+
contraction_indices = self.contraction_indices
|
1002 |
+
|
1003 |
+
if len(contraction_indices) == 0:
|
1004 |
+
return expr
|
1005 |
+
|
1006 |
+
if isinstance(expr, ArrayContraction):
|
1007 |
+
return self._ArrayContraction_denest_ArrayContraction(expr, *contraction_indices)
|
1008 |
+
|
1009 |
+
if isinstance(expr, (ZeroArray, ZeroMatrix)):
|
1010 |
+
return self._ArrayContraction_denest_ZeroArray(expr, *contraction_indices)
|
1011 |
+
|
1012 |
+
if isinstance(expr, PermuteDims):
|
1013 |
+
return self._ArrayContraction_denest_PermuteDims(expr, *contraction_indices)
|
1014 |
+
|
1015 |
+
if isinstance(expr, ArrayTensorProduct):
|
1016 |
+
expr, contraction_indices = self._sort_fully_contracted_args(expr, contraction_indices)
|
1017 |
+
expr, contraction_indices = self._lower_contraction_to_addends(expr, contraction_indices)
|
1018 |
+
if len(contraction_indices) == 0:
|
1019 |
+
return expr
|
1020 |
+
|
1021 |
+
if isinstance(expr, ArrayDiagonal):
|
1022 |
+
return self._ArrayContraction_denest_ArrayDiagonal(expr, *contraction_indices)
|
1023 |
+
|
1024 |
+
if isinstance(expr, ArrayAdd):
|
1025 |
+
return self._ArrayContraction_denest_ArrayAdd(expr, *contraction_indices)
|
1026 |
+
|
1027 |
+
# Check single index contractions on 1-dimensional axes:
|
1028 |
+
contraction_indices = [i for i in contraction_indices if len(i) > 1 or get_shape(expr)[i[0]] != 1]
|
1029 |
+
if len(contraction_indices) == 0:
|
1030 |
+
return expr
|
1031 |
+
|
1032 |
+
return self.func(expr, *contraction_indices, canonicalize=False)
|
1033 |
+
|
1034 |
+
def __mul__(self, other):
|
1035 |
+
if other == 1:
|
1036 |
+
return self
|
1037 |
+
else:
|
1038 |
+
raise NotImplementedError("Product of N-dim arrays is not uniquely defined. Use another method.")
|
1039 |
+
|
1040 |
+
def __rmul__(self, other):
|
1041 |
+
if other == 1:
|
1042 |
+
return self
|
1043 |
+
else:
|
1044 |
+
raise NotImplementedError("Product of N-dim arrays is not uniquely defined. Use another method.")
|
1045 |
+
|
1046 |
+
@staticmethod
|
1047 |
+
def _validate(expr, *contraction_indices):
|
1048 |
+
shape = get_shape(expr)
|
1049 |
+
if shape is None:
|
1050 |
+
return
|
1051 |
+
|
1052 |
+
# Check that no contraction happens when the shape is mismatched:
|
1053 |
+
for i in contraction_indices:
|
1054 |
+
if len({shape[j] for j in i if shape[j] != -1}) != 1:
|
1055 |
+
raise ValueError("contracting indices of different dimensions")
|
1056 |
+
|
1057 |
+
@classmethod
|
1058 |
+
def _push_indices_down(cls, contraction_indices, indices):
|
1059 |
+
flattened_contraction_indices = [j for i in contraction_indices for j in i]
|
1060 |
+
flattened_contraction_indices.sort()
|
1061 |
+
transform = _build_push_indices_down_func_transformation(flattened_contraction_indices)
|
1062 |
+
return _apply_recursively_over_nested_lists(transform, indices)
|
1063 |
+
|
1064 |
+
@classmethod
|
1065 |
+
def _push_indices_up(cls, contraction_indices, indices):
|
1066 |
+
flattened_contraction_indices = [j for i in contraction_indices for j in i]
|
1067 |
+
flattened_contraction_indices.sort()
|
1068 |
+
transform = _build_push_indices_up_func_transformation(flattened_contraction_indices)
|
1069 |
+
return _apply_recursively_over_nested_lists(transform, indices)
|
1070 |
+
|
1071 |
+
@classmethod
|
1072 |
+
def _lower_contraction_to_addends(cls, expr, contraction_indices):
|
1073 |
+
if isinstance(expr, ArrayAdd):
|
1074 |
+
raise NotImplementedError()
|
1075 |
+
if not isinstance(expr, ArrayTensorProduct):
|
1076 |
+
return expr, contraction_indices
|
1077 |
+
subranks = expr.subranks
|
1078 |
+
cumranks = list(accumulate([0] + subranks))
|
1079 |
+
contraction_indices_remaining = []
|
1080 |
+
contraction_indices_args = [[] for i in expr.args]
|
1081 |
+
backshift = set()
|
1082 |
+
for i, contraction_group in enumerate(contraction_indices):
|
1083 |
+
for j in range(len(expr.args)):
|
1084 |
+
if not isinstance(expr.args[j], ArrayAdd):
|
1085 |
+
continue
|
1086 |
+
if all(cumranks[j] <= k < cumranks[j+1] for k in contraction_group):
|
1087 |
+
contraction_indices_args[j].append([k - cumranks[j] for k in contraction_group])
|
1088 |
+
backshift.update(contraction_group)
|
1089 |
+
break
|
1090 |
+
else:
|
1091 |
+
contraction_indices_remaining.append(contraction_group)
|
1092 |
+
if len(contraction_indices_remaining) == len(contraction_indices):
|
1093 |
+
return expr, contraction_indices
|
1094 |
+
total_rank = get_rank(expr)
|
1095 |
+
shifts = list(accumulate([1 if i in backshift else 0 for i in range(total_rank)]))
|
1096 |
+
contraction_indices_remaining = [Tuple.fromiter(j - shifts[j] for j in i) for i in contraction_indices_remaining]
|
1097 |
+
ret = _array_tensor_product(*[
|
1098 |
+
_array_contraction(arg, *contr) for arg, contr in zip(expr.args, contraction_indices_args)
|
1099 |
+
])
|
1100 |
+
return ret, contraction_indices_remaining
|
1101 |
+
|
1102 |
+
def split_multiple_contractions(self):
|
1103 |
+
"""
|
1104 |
+
Recognize multiple contractions and attempt at rewriting them as paired-contractions.
|
1105 |
+
|
1106 |
+
This allows some contractions involving more than two indices to be
|
1107 |
+
rewritten as multiple contractions involving two indices, thus allowing
|
1108 |
+
the expression to be rewritten as a matrix multiplication line.
|
1109 |
+
|
1110 |
+
Examples:
|
1111 |
+
|
1112 |
+
* `A_ij b_j0 C_jk` ===> `A*DiagMatrix(b)*C`
|
1113 |
+
|
1114 |
+
Care for:
|
1115 |
+
- matrix being diagonalized (i.e. `A_ii`)
|
1116 |
+
- vectors being diagonalized (i.e. `a_i0`)
|
1117 |
+
|
1118 |
+
Multiple contractions can be split into matrix multiplications if
|
1119 |
+
not more than two arguments are non-diagonals or non-vectors.
|
1120 |
+
Vectors get diagonalized while diagonal matrices remain diagonal.
|
1121 |
+
The non-diagonal matrices can be at the beginning or at the end
|
1122 |
+
of the final matrix multiplication line.
|
1123 |
+
"""
|
1124 |
+
|
1125 |
+
editor = _EditArrayContraction(self)
|
1126 |
+
|
1127 |
+
contraction_indices = self.contraction_indices
|
1128 |
+
|
1129 |
+
onearray_insert = []
|
1130 |
+
|
1131 |
+
for indl, links in enumerate(contraction_indices):
|
1132 |
+
if len(links) <= 2:
|
1133 |
+
continue
|
1134 |
+
|
1135 |
+
# Check multiple contractions:
|
1136 |
+
#
|
1137 |
+
# Examples:
|
1138 |
+
#
|
1139 |
+
# * `A_ij b_j0 C_jk` ===> `A*DiagMatrix(b)*C \otimes OneArray(1)` with permutation (1 2)
|
1140 |
+
#
|
1141 |
+
# Care for:
|
1142 |
+
# - matrix being diagonalized (i.e. `A_ii`)
|
1143 |
+
# - vectors being diagonalized (i.e. `a_i0`)
|
1144 |
+
|
1145 |
+
# Multiple contractions can be split into matrix multiplications if
|
1146 |
+
# not more than three arguments are non-diagonals or non-vectors.
|
1147 |
+
#
|
1148 |
+
# Vectors get diagonalized while diagonal matrices remain diagonal.
|
1149 |
+
# The non-diagonal matrices can be at the beginning or at the end
|
1150 |
+
# of the final matrix multiplication line.
|
1151 |
+
|
1152 |
+
positions = editor.get_mapping_for_index(indl)
|
1153 |
+
|
1154 |
+
# Also consider the case of diagonal matrices being contracted:
|
1155 |
+
current_dimension = self.expr.shape[links[0]]
|
1156 |
+
|
1157 |
+
not_vectors = []
|
1158 |
+
vectors = []
|
1159 |
+
for arg_ind, rel_ind in positions:
|
1160 |
+
arg = editor.args_with_ind[arg_ind]
|
1161 |
+
mat = arg.element
|
1162 |
+
abs_arg_start, abs_arg_end = editor.get_absolute_range(arg)
|
1163 |
+
other_arg_pos = 1-rel_ind
|
1164 |
+
other_arg_abs = abs_arg_start + other_arg_pos
|
1165 |
+
if ((1 not in mat.shape) or
|
1166 |
+
((current_dimension == 1) is True and mat.shape != (1, 1)) or
|
1167 |
+
any(other_arg_abs in l for li, l in enumerate(contraction_indices) if li != indl)
|
1168 |
+
):
|
1169 |
+
not_vectors.append((arg, rel_ind))
|
1170 |
+
else:
|
1171 |
+
vectors.append((arg, rel_ind))
|
1172 |
+
if len(not_vectors) > 2:
|
1173 |
+
# If more than two arguments in the multiple contraction are
|
1174 |
+
# non-vectors and non-diagonal matrices, we cannot find a way
|
1175 |
+
# to split this contraction into a matrix multiplication line:
|
1176 |
+
continue
|
1177 |
+
# Three cases to handle:
|
1178 |
+
# - zero non-vectors
|
1179 |
+
# - one non-vector
|
1180 |
+
# - two non-vectors
|
1181 |
+
for v, rel_ind in vectors:
|
1182 |
+
v.element = diagonalize_vector(v.element)
|
1183 |
+
vectors_to_loop = not_vectors[:1] + vectors + not_vectors[1:]
|
1184 |
+
first_not_vector, rel_ind = vectors_to_loop[0]
|
1185 |
+
new_index = first_not_vector.indices[rel_ind]
|
1186 |
+
|
1187 |
+
for v, rel_ind in vectors_to_loop[1:-1]:
|
1188 |
+
v.indices[rel_ind] = new_index
|
1189 |
+
new_index = editor.get_new_contraction_index()
|
1190 |
+
assert v.indices.index(None) == 1 - rel_ind
|
1191 |
+
v.indices[v.indices.index(None)] = new_index
|
1192 |
+
onearray_insert.append(v)
|
1193 |
+
|
1194 |
+
last_vec, rel_ind = vectors_to_loop[-1]
|
1195 |
+
last_vec.indices[rel_ind] = new_index
|
1196 |
+
|
1197 |
+
for v in onearray_insert:
|
1198 |
+
editor.insert_after(v, _ArgE(OneArray(1), [None]))
|
1199 |
+
|
1200 |
+
return editor.to_array_contraction()
|
1201 |
+
|
1202 |
+
def flatten_contraction_of_diagonal(self):
|
1203 |
+
if not isinstance(self.expr, ArrayDiagonal):
|
1204 |
+
return self
|
1205 |
+
contraction_down = self.expr._push_indices_down(self.expr.diagonal_indices, self.contraction_indices)
|
1206 |
+
new_contraction_indices = []
|
1207 |
+
diagonal_indices = self.expr.diagonal_indices[:]
|
1208 |
+
for i in contraction_down:
|
1209 |
+
contraction_group = list(i)
|
1210 |
+
for j in i:
|
1211 |
+
diagonal_with = [k for k in diagonal_indices if j in k]
|
1212 |
+
contraction_group.extend([l for k in diagonal_with for l in k])
|
1213 |
+
diagonal_indices = [k for k in diagonal_indices if k not in diagonal_with]
|
1214 |
+
new_contraction_indices.append(sorted(set(contraction_group)))
|
1215 |
+
|
1216 |
+
new_contraction_indices = ArrayDiagonal._push_indices_up(diagonal_indices, new_contraction_indices)
|
1217 |
+
return _array_contraction(
|
1218 |
+
_array_diagonal(
|
1219 |
+
self.expr.expr,
|
1220 |
+
*diagonal_indices
|
1221 |
+
),
|
1222 |
+
*new_contraction_indices
|
1223 |
+
)
|
1224 |
+
|
1225 |
+
@staticmethod
|
1226 |
+
def _get_free_indices_to_position_map(free_indices, contraction_indices):
|
1227 |
+
free_indices_to_position = {}
|
1228 |
+
flattened_contraction_indices = [j for i in contraction_indices for j in i]
|
1229 |
+
counter = 0
|
1230 |
+
for ind in free_indices:
|
1231 |
+
while counter in flattened_contraction_indices:
|
1232 |
+
counter += 1
|
1233 |
+
free_indices_to_position[ind] = counter
|
1234 |
+
counter += 1
|
1235 |
+
return free_indices_to_position
|
1236 |
+
|
1237 |
+
@staticmethod
|
1238 |
+
def _get_index_shifts(expr):
|
1239 |
+
"""
|
1240 |
+
Get the mapping of indices at the positions before the contraction
|
1241 |
+
occurs.
|
1242 |
+
|
1243 |
+
Examples
|
1244 |
+
========
|
1245 |
+
|
1246 |
+
>>> from sympy.tensor.array import tensorproduct, tensorcontraction
|
1247 |
+
>>> from sympy import MatrixSymbol
|
1248 |
+
>>> M = MatrixSymbol("M", 3, 3)
|
1249 |
+
>>> N = MatrixSymbol("N", 3, 3)
|
1250 |
+
>>> cg = tensorcontraction(tensorproduct(M, N), [1, 2])
|
1251 |
+
>>> cg._get_index_shifts(cg)
|
1252 |
+
[0, 2]
|
1253 |
+
|
1254 |
+
Indeed, ``cg`` after the contraction has two dimensions, 0 and 1. They
|
1255 |
+
need to be shifted by 0 and 2 to get the corresponding positions before
|
1256 |
+
the contraction (that is, 0 and 3).
|
1257 |
+
"""
|
1258 |
+
inner_contraction_indices = expr.contraction_indices
|
1259 |
+
all_inner = [j for i in inner_contraction_indices for j in i]
|
1260 |
+
all_inner.sort()
|
1261 |
+
# TODO: add API for total rank and cumulative rank:
|
1262 |
+
total_rank = _get_subrank(expr)
|
1263 |
+
inner_rank = len(all_inner)
|
1264 |
+
outer_rank = total_rank - inner_rank
|
1265 |
+
shifts = [0 for i in range(outer_rank)]
|
1266 |
+
counter = 0
|
1267 |
+
pointer = 0
|
1268 |
+
for i in range(outer_rank):
|
1269 |
+
while pointer < inner_rank and counter >= all_inner[pointer]:
|
1270 |
+
counter += 1
|
1271 |
+
pointer += 1
|
1272 |
+
shifts[i] += pointer
|
1273 |
+
counter += 1
|
1274 |
+
return shifts
|
1275 |
+
|
1276 |
+
@staticmethod
|
1277 |
+
def _convert_outer_indices_to_inner_indices(expr, *outer_contraction_indices):
|
1278 |
+
shifts = ArrayContraction._get_index_shifts(expr)
|
1279 |
+
outer_contraction_indices = tuple(tuple(shifts[j] + j for j in i) for i in outer_contraction_indices)
|
1280 |
+
return outer_contraction_indices
|
1281 |
+
|
1282 |
+
@staticmethod
|
1283 |
+
def _flatten(expr, *outer_contraction_indices):
|
1284 |
+
inner_contraction_indices = expr.contraction_indices
|
1285 |
+
outer_contraction_indices = ArrayContraction._convert_outer_indices_to_inner_indices(expr, *outer_contraction_indices)
|
1286 |
+
contraction_indices = inner_contraction_indices + outer_contraction_indices
|
1287 |
+
return _array_contraction(expr.expr, *contraction_indices)
|
1288 |
+
|
1289 |
+
@classmethod
|
1290 |
+
def _ArrayContraction_denest_ArrayContraction(cls, expr, *contraction_indices):
|
1291 |
+
return cls._flatten(expr, *contraction_indices)
|
1292 |
+
|
1293 |
+
@classmethod
|
1294 |
+
def _ArrayContraction_denest_ZeroArray(cls, expr, *contraction_indices):
|
1295 |
+
contraction_indices_flat = [j for i in contraction_indices for j in i]
|
1296 |
+
shape = [e for i, e in enumerate(expr.shape) if i not in contraction_indices_flat]
|
1297 |
+
return ZeroArray(*shape)
|
1298 |
+
|
1299 |
+
@classmethod
|
1300 |
+
def _ArrayContraction_denest_ArrayAdd(cls, expr, *contraction_indices):
|
1301 |
+
return _array_add(*[_array_contraction(i, *contraction_indices) for i in expr.args])
|
1302 |
+
|
1303 |
+
@classmethod
|
1304 |
+
def _ArrayContraction_denest_PermuteDims(cls, expr, *contraction_indices):
|
1305 |
+
permutation = expr.permutation
|
1306 |
+
plist = permutation.array_form
|
1307 |
+
new_contraction_indices = [tuple(permutation(j) for j in i) for i in contraction_indices]
|
1308 |
+
new_plist = [i for i in plist if not any(i in j for j in new_contraction_indices)]
|
1309 |
+
new_plist = cls._push_indices_up(new_contraction_indices, new_plist)
|
1310 |
+
return _permute_dims(
|
1311 |
+
_array_contraction(expr.expr, *new_contraction_indices),
|
1312 |
+
Permutation(new_plist)
|
1313 |
+
)
|
1314 |
+
|
1315 |
+
@classmethod
|
1316 |
+
def _ArrayContraction_denest_ArrayDiagonal(cls, expr: 'ArrayDiagonal', *contraction_indices):
|
1317 |
+
diagonal_indices = list(expr.diagonal_indices)
|
1318 |
+
down_contraction_indices = expr._push_indices_down(expr.diagonal_indices, contraction_indices, get_rank(expr.expr))
|
1319 |
+
# Flatten diagonally contracted indices:
|
1320 |
+
down_contraction_indices = [[k for j in i for k in (j if isinstance(j, (tuple, Tuple)) else [j])] for i in down_contraction_indices]
|
1321 |
+
new_contraction_indices = []
|
1322 |
+
for contr_indgrp in down_contraction_indices:
|
1323 |
+
ind = contr_indgrp[:]
|
1324 |
+
for j, diag_indgrp in enumerate(diagonal_indices):
|
1325 |
+
if diag_indgrp is None:
|
1326 |
+
continue
|
1327 |
+
if any(i in diag_indgrp for i in contr_indgrp):
|
1328 |
+
ind.extend(diag_indgrp)
|
1329 |
+
diagonal_indices[j] = None
|
1330 |
+
new_contraction_indices.append(sorted(set(ind)))
|
1331 |
+
|
1332 |
+
new_diagonal_indices_down = [i for i in diagonal_indices if i is not None]
|
1333 |
+
new_diagonal_indices = ArrayContraction._push_indices_up(new_contraction_indices, new_diagonal_indices_down)
|
1334 |
+
return _array_diagonal(
|
1335 |
+
_array_contraction(expr.expr, *new_contraction_indices),
|
1336 |
+
*new_diagonal_indices
|
1337 |
+
)
|
1338 |
+
|
1339 |
+
@classmethod
|
1340 |
+
def _sort_fully_contracted_args(cls, expr, contraction_indices):
|
1341 |
+
if expr.shape is None:
|
1342 |
+
return expr, contraction_indices
|
1343 |
+
cumul = list(accumulate([0] + expr.subranks))
|
1344 |
+
index_blocks = [list(range(cumul[i], cumul[i+1])) for i in range(len(expr.args))]
|
1345 |
+
contraction_indices_flat = {j for i in contraction_indices for j in i}
|
1346 |
+
fully_contracted = [all(j in contraction_indices_flat for j in range(cumul[i], cumul[i+1])) for i, arg in enumerate(expr.args)]
|
1347 |
+
new_pos = sorted(range(len(expr.args)), key=lambda x: (0, default_sort_key(expr.args[x])) if fully_contracted[x] else (1,))
|
1348 |
+
new_args = [expr.args[i] for i in new_pos]
|
1349 |
+
new_index_blocks_flat = [j for i in new_pos for j in index_blocks[i]]
|
1350 |
+
index_permutation_array_form = _af_invert(new_index_blocks_flat)
|
1351 |
+
new_contraction_indices = [tuple(index_permutation_array_form[j] for j in i) for i in contraction_indices]
|
1352 |
+
new_contraction_indices = _sort_contraction_indices(new_contraction_indices)
|
1353 |
+
return _array_tensor_product(*new_args), new_contraction_indices
|
1354 |
+
|
1355 |
+
def _get_contraction_tuples(self):
|
1356 |
+
r"""
|
1357 |
+
Return tuples containing the argument index and position within the
|
1358 |
+
argument of the index position.
|
1359 |
+
|
1360 |
+
Examples
|
1361 |
+
========
|
1362 |
+
|
1363 |
+
>>> from sympy import MatrixSymbol
|
1364 |
+
>>> from sympy.abc import N
|
1365 |
+
>>> from sympy.tensor.array import tensorproduct, tensorcontraction
|
1366 |
+
>>> A = MatrixSymbol("A", N, N)
|
1367 |
+
>>> B = MatrixSymbol("B", N, N)
|
1368 |
+
|
1369 |
+
>>> cg = tensorcontraction(tensorproduct(A, B), (1, 2))
|
1370 |
+
>>> cg._get_contraction_tuples()
|
1371 |
+
[[(0, 1), (1, 0)]]
|
1372 |
+
|
1373 |
+
Notes
|
1374 |
+
=====
|
1375 |
+
|
1376 |
+
Here the contraction pair `(1, 2)` meaning that the 2nd and 3rd indices
|
1377 |
+
of the tensor product `A\otimes B` are contracted, has been transformed
|
1378 |
+
into `(0, 1)` and `(1, 0)`, identifying the same indices in a different
|
1379 |
+
notation. `(0, 1)` is the second index (1) of the first argument (i.e.
|
1380 |
+
0 or `A`). `(1, 0)` is the first index (i.e. 0) of the second
|
1381 |
+
argument (i.e. 1 or `B`).
|
1382 |
+
"""
|
1383 |
+
mapping = self._mapping
|
1384 |
+
return [[mapping[j] for j in i] for i in self.contraction_indices]
|
1385 |
+
|
1386 |
+
@staticmethod
|
1387 |
+
def _contraction_tuples_to_contraction_indices(expr, contraction_tuples):
|
1388 |
+
# TODO: check that `expr` has `.subranks`:
|
1389 |
+
ranks = expr.subranks
|
1390 |
+
cumulative_ranks = [0] + list(accumulate(ranks))
|
1391 |
+
return [tuple(cumulative_ranks[j]+k for j, k in i) for i in contraction_tuples]
|
1392 |
+
|
1393 |
+
@property
|
1394 |
+
def free_indices(self):
|
1395 |
+
return self._free_indices[:]
|
1396 |
+
|
1397 |
+
@property
|
1398 |
+
def free_indices_to_position(self):
|
1399 |
+
return dict(self._free_indices_to_position)
|
1400 |
+
|
1401 |
+
@property
|
1402 |
+
def expr(self):
|
1403 |
+
return self.args[0]
|
1404 |
+
|
1405 |
+
@property
|
1406 |
+
def contraction_indices(self):
|
1407 |
+
return self.args[1:]
|
1408 |
+
|
1409 |
+
def _contraction_indices_to_components(self):
|
1410 |
+
expr = self.expr
|
1411 |
+
if not isinstance(expr, ArrayTensorProduct):
|
1412 |
+
raise NotImplementedError("only for contractions of tensor products")
|
1413 |
+
ranks = expr.subranks
|
1414 |
+
mapping = {}
|
1415 |
+
counter = 0
|
1416 |
+
for i, rank in enumerate(ranks):
|
1417 |
+
for j in range(rank):
|
1418 |
+
mapping[counter] = (i, j)
|
1419 |
+
counter += 1
|
1420 |
+
return mapping
|
1421 |
+
|
1422 |
+
def sort_args_by_name(self):
|
1423 |
+
"""
|
1424 |
+
Sort arguments in the tensor product so that their order is lexicographical.
|
1425 |
+
|
1426 |
+
Examples
|
1427 |
+
========
|
1428 |
+
|
1429 |
+
>>> from sympy.tensor.array.expressions.from_matrix_to_array import convert_matrix_to_array
|
1430 |
+
>>> from sympy import MatrixSymbol
|
1431 |
+
>>> from sympy.abc import N
|
1432 |
+
>>> A = MatrixSymbol("A", N, N)
|
1433 |
+
>>> B = MatrixSymbol("B", N, N)
|
1434 |
+
>>> C = MatrixSymbol("C", N, N)
|
1435 |
+
>>> D = MatrixSymbol("D", N, N)
|
1436 |
+
|
1437 |
+
>>> cg = convert_matrix_to_array(C*D*A*B)
|
1438 |
+
>>> cg
|
1439 |
+
ArrayContraction(ArrayTensorProduct(A, D, C, B), (0, 3), (1, 6), (2, 5))
|
1440 |
+
>>> cg.sort_args_by_name()
|
1441 |
+
ArrayContraction(ArrayTensorProduct(A, D, B, C), (0, 3), (1, 4), (2, 7))
|
1442 |
+
"""
|
1443 |
+
expr = self.expr
|
1444 |
+
if not isinstance(expr, ArrayTensorProduct):
|
1445 |
+
return self
|
1446 |
+
args = expr.args
|
1447 |
+
sorted_data = sorted(enumerate(args), key=lambda x: default_sort_key(x[1]))
|
1448 |
+
pos_sorted, args_sorted = zip(*sorted_data)
|
1449 |
+
reordering_map = {i: pos_sorted.index(i) for i, arg in enumerate(args)}
|
1450 |
+
contraction_tuples = self._get_contraction_tuples()
|
1451 |
+
contraction_tuples = [[(reordering_map[j], k) for j, k in i] for i in contraction_tuples]
|
1452 |
+
c_tp = _array_tensor_product(*args_sorted)
|
1453 |
+
new_contr_indices = self._contraction_tuples_to_contraction_indices(
|
1454 |
+
c_tp,
|
1455 |
+
contraction_tuples
|
1456 |
+
)
|
1457 |
+
return _array_contraction(c_tp, *new_contr_indices)
|
1458 |
+
|
1459 |
+
def _get_contraction_links(self):
|
1460 |
+
r"""
|
1461 |
+
Returns a dictionary of links between arguments in the tensor product
|
1462 |
+
being contracted.
|
1463 |
+
|
1464 |
+
See the example for an explanation of the values.
|
1465 |
+
|
1466 |
+
Examples
|
1467 |
+
========
|
1468 |
+
|
1469 |
+
>>> from sympy import MatrixSymbol
|
1470 |
+
>>> from sympy.abc import N
|
1471 |
+
>>> from sympy.tensor.array.expressions.from_matrix_to_array import convert_matrix_to_array
|
1472 |
+
>>> A = MatrixSymbol("A", N, N)
|
1473 |
+
>>> B = MatrixSymbol("B", N, N)
|
1474 |
+
>>> C = MatrixSymbol("C", N, N)
|
1475 |
+
>>> D = MatrixSymbol("D", N, N)
|
1476 |
+
|
1477 |
+
Matrix multiplications are pairwise contractions between neighboring
|
1478 |
+
matrices:
|
1479 |
+
|
1480 |
+
`A_{ij} B_{jk} C_{kl} D_{lm}`
|
1481 |
+
|
1482 |
+
>>> cg = convert_matrix_to_array(A*B*C*D)
|
1483 |
+
>>> cg
|
1484 |
+
ArrayContraction(ArrayTensorProduct(B, C, A, D), (0, 5), (1, 2), (3, 6))
|
1485 |
+
|
1486 |
+
>>> cg._get_contraction_links()
|
1487 |
+
{0: {0: (2, 1), 1: (1, 0)}, 1: {0: (0, 1), 1: (3, 0)}, 2: {1: (0, 0)}, 3: {0: (1, 1)}}
|
1488 |
+
|
1489 |
+
This dictionary is interpreted as follows: argument in position 0 (i.e.
|
1490 |
+
matrix `A`) has its second index (i.e. 1) contracted to `(1, 0)`, that
|
1491 |
+
is argument in position 1 (matrix `B`) on the first index slot of `B`,
|
1492 |
+
this is the contraction provided by the index `j` from `A`.
|
1493 |
+
|
1494 |
+
The argument in position 1 (that is, matrix `B`) has two contractions,
|
1495 |
+
the ones provided by the indices `j` and `k`, respectively the first
|
1496 |
+
and second indices (0 and 1 in the sub-dict). The link `(0, 1)` and
|
1497 |
+
`(2, 0)` respectively. `(0, 1)` is the index slot 1 (the 2nd) of
|
1498 |
+
argument in position 0 (that is, `A_{\ldot j}`), and so on.
|
1499 |
+
"""
|
1500 |
+
args, dlinks = _get_contraction_links([self], self.subranks, *self.contraction_indices)
|
1501 |
+
return dlinks
|
1502 |
+
|
1503 |
+
def as_explicit(self):
|
1504 |
+
expr = self.expr
|
1505 |
+
if hasattr(expr, "as_explicit"):
|
1506 |
+
expr = expr.as_explicit()
|
1507 |
+
return tensorcontraction(expr, *self.contraction_indices)
|
1508 |
+
|
1509 |
+
|
1510 |
+
class Reshape(_CodegenArrayAbstract):
|
1511 |
+
"""
|
1512 |
+
Reshape the dimensions of an array expression.
|
1513 |
+
|
1514 |
+
Examples
|
1515 |
+
========
|
1516 |
+
|
1517 |
+
>>> from sympy.tensor.array.expressions import ArraySymbol, Reshape
|
1518 |
+
>>> A = ArraySymbol("A", (6,))
|
1519 |
+
>>> A.shape
|
1520 |
+
(6,)
|
1521 |
+
>>> Reshape(A, (3, 2)).shape
|
1522 |
+
(3, 2)
|
1523 |
+
|
1524 |
+
Check the component-explicit forms:
|
1525 |
+
|
1526 |
+
>>> A.as_explicit()
|
1527 |
+
[A[0], A[1], A[2], A[3], A[4], A[5]]
|
1528 |
+
>>> Reshape(A, (3, 2)).as_explicit()
|
1529 |
+
[[A[0], A[1]], [A[2], A[3]], [A[4], A[5]]]
|
1530 |
+
|
1531 |
+
"""
|
1532 |
+
|
1533 |
+
def __new__(cls, expr, shape):
|
1534 |
+
expr = _sympify(expr)
|
1535 |
+
if not isinstance(shape, Tuple):
|
1536 |
+
shape = Tuple(*shape)
|
1537 |
+
if Equality(Mul.fromiter(expr.shape), Mul.fromiter(shape)) == False:
|
1538 |
+
raise ValueError("shape mismatch")
|
1539 |
+
obj = Expr.__new__(cls, expr, shape)
|
1540 |
+
obj._shape = tuple(shape)
|
1541 |
+
obj._expr = expr
|
1542 |
+
return obj
|
1543 |
+
|
1544 |
+
@property
|
1545 |
+
def shape(self):
|
1546 |
+
return self._shape
|
1547 |
+
|
1548 |
+
@property
|
1549 |
+
def expr(self):
|
1550 |
+
return self._expr
|
1551 |
+
|
1552 |
+
def doit(self, *args, **kwargs):
|
1553 |
+
if kwargs.get("deep", True):
|
1554 |
+
expr = self.expr.doit(*args, **kwargs)
|
1555 |
+
else:
|
1556 |
+
expr = self.expr
|
1557 |
+
if isinstance(expr, (MatrixCommon, NDimArray)):
|
1558 |
+
return expr.reshape(*self.shape)
|
1559 |
+
return Reshape(expr, self.shape)
|
1560 |
+
|
1561 |
+
def as_explicit(self):
|
1562 |
+
ee = self.expr
|
1563 |
+
if hasattr(ee, "as_explicit"):
|
1564 |
+
ee = ee.as_explicit()
|
1565 |
+
if isinstance(ee, MatrixCommon):
|
1566 |
+
from sympy import Array
|
1567 |
+
ee = Array(ee)
|
1568 |
+
elif isinstance(ee, MatrixExpr):
|
1569 |
+
return self
|
1570 |
+
return ee.reshape(*self.shape)
|
1571 |
+
|
1572 |
+
|
1573 |
+
class _ArgE:
|
1574 |
+
"""
|
1575 |
+
The ``_ArgE`` object contains references to the array expression
|
1576 |
+
(``.element``) and a list containing the information about index
|
1577 |
+
contractions (``.indices``).
|
1578 |
+
|
1579 |
+
Index contractions are numbered and contracted indices show the number of
|
1580 |
+
the contraction. Uncontracted indices have ``None`` value.
|
1581 |
+
|
1582 |
+
For example:
|
1583 |
+
``_ArgE(M, [None, 3])``
|
1584 |
+
This object means that expression ``M`` is part of an array contraction
|
1585 |
+
and has two indices, the first is not contracted (value ``None``),
|
1586 |
+
the second index is contracted to the 4th (i.e. number ``3``) group of the
|
1587 |
+
array contraction object.
|
1588 |
+
"""
|
1589 |
+
indices: List[Optional[int]]
|
1590 |
+
|
1591 |
+
def __init__(self, element, indices: Optional[List[Optional[int]]] = None):
|
1592 |
+
self.element = element
|
1593 |
+
if indices is None:
|
1594 |
+
self.indices = [None for i in range(get_rank(element))]
|
1595 |
+
else:
|
1596 |
+
self.indices = indices
|
1597 |
+
|
1598 |
+
def __str__(self):
|
1599 |
+
return "_ArgE(%s, %s)" % (self.element, self.indices)
|
1600 |
+
|
1601 |
+
__repr__ = __str__
|
1602 |
+
|
1603 |
+
|
1604 |
+
class _IndPos:
|
1605 |
+
"""
|
1606 |
+
Index position, requiring two integers in the constructor:
|
1607 |
+
|
1608 |
+
- arg: the position of the argument in the tensor product,
|
1609 |
+
- rel: the relative position of the index inside the argument.
|
1610 |
+
"""
|
1611 |
+
def __init__(self, arg: int, rel: int):
|
1612 |
+
self.arg = arg
|
1613 |
+
self.rel = rel
|
1614 |
+
|
1615 |
+
def __str__(self):
|
1616 |
+
return "_IndPos(%i, %i)" % (self.arg, self.rel)
|
1617 |
+
|
1618 |
+
__repr__ = __str__
|
1619 |
+
|
1620 |
+
def __iter__(self):
|
1621 |
+
yield from [self.arg, self.rel]
|
1622 |
+
|
1623 |
+
|
1624 |
+
class _EditArrayContraction:
|
1625 |
+
"""
|
1626 |
+
Utility class to help manipulate array contraction objects.
|
1627 |
+
|
1628 |
+
This class takes as input an ``ArrayContraction`` object and turns it into
|
1629 |
+
an editable object.
|
1630 |
+
|
1631 |
+
The field ``args_with_ind`` of this class is a list of ``_ArgE`` objects
|
1632 |
+
which can be used to easily edit the contraction structure of the
|
1633 |
+
expression.
|
1634 |
+
|
1635 |
+
Once editing is finished, the ``ArrayContraction`` object may be recreated
|
1636 |
+
by calling the ``.to_array_contraction()`` method.
|
1637 |
+
"""
|
1638 |
+
|
1639 |
+
def __init__(self, base_array: typing.Union[ArrayContraction, ArrayDiagonal, ArrayTensorProduct]):
|
1640 |
+
|
1641 |
+
expr: Basic
|
1642 |
+
diagonalized: tTuple[tTuple[int, ...], ...]
|
1643 |
+
contraction_indices: List[tTuple[int]]
|
1644 |
+
if isinstance(base_array, ArrayContraction):
|
1645 |
+
mapping = _get_mapping_from_subranks(base_array.subranks)
|
1646 |
+
expr = base_array.expr
|
1647 |
+
contraction_indices = base_array.contraction_indices
|
1648 |
+
diagonalized = ()
|
1649 |
+
elif isinstance(base_array, ArrayDiagonal):
|
1650 |
+
|
1651 |
+
if isinstance(base_array.expr, ArrayContraction):
|
1652 |
+
mapping = _get_mapping_from_subranks(base_array.expr.subranks)
|
1653 |
+
expr = base_array.expr.expr
|
1654 |
+
diagonalized = ArrayContraction._push_indices_down(base_array.expr.contraction_indices, base_array.diagonal_indices)
|
1655 |
+
contraction_indices = base_array.expr.contraction_indices
|
1656 |
+
elif isinstance(base_array.expr, ArrayTensorProduct):
|
1657 |
+
mapping = {}
|
1658 |
+
expr = base_array.expr
|
1659 |
+
diagonalized = base_array.diagonal_indices
|
1660 |
+
contraction_indices = []
|
1661 |
+
else:
|
1662 |
+
mapping = {}
|
1663 |
+
expr = base_array.expr
|
1664 |
+
diagonalized = base_array.diagonal_indices
|
1665 |
+
contraction_indices = []
|
1666 |
+
|
1667 |
+
elif isinstance(base_array, ArrayTensorProduct):
|
1668 |
+
expr = base_array
|
1669 |
+
contraction_indices = []
|
1670 |
+
diagonalized = ()
|
1671 |
+
else:
|
1672 |
+
raise NotImplementedError()
|
1673 |
+
|
1674 |
+
if isinstance(expr, ArrayTensorProduct):
|
1675 |
+
args = list(expr.args)
|
1676 |
+
else:
|
1677 |
+
args = [expr]
|
1678 |
+
|
1679 |
+
args_with_ind: List[_ArgE] = [_ArgE(arg) for arg in args]
|
1680 |
+
for i, contraction_tuple in enumerate(contraction_indices):
|
1681 |
+
for j in contraction_tuple:
|
1682 |
+
arg_pos, rel_pos = mapping[j]
|
1683 |
+
args_with_ind[arg_pos].indices[rel_pos] = i
|
1684 |
+
self.args_with_ind: List[_ArgE] = args_with_ind
|
1685 |
+
self.number_of_contraction_indices: int = len(contraction_indices)
|
1686 |
+
self._track_permutation: Optional[List[List[int]]] = None
|
1687 |
+
|
1688 |
+
mapping = _get_mapping_from_subranks(base_array.subranks)
|
1689 |
+
|
1690 |
+
# Trick: add diagonalized indices as negative indices into the editor object:
|
1691 |
+
for i, e in enumerate(diagonalized):
|
1692 |
+
for j in e:
|
1693 |
+
arg_pos, rel_pos = mapping[j]
|
1694 |
+
self.args_with_ind[arg_pos].indices[rel_pos] = -1 - i
|
1695 |
+
|
1696 |
+
def insert_after(self, arg: _ArgE, new_arg: _ArgE):
|
1697 |
+
pos = self.args_with_ind.index(arg)
|
1698 |
+
self.args_with_ind.insert(pos + 1, new_arg)
|
1699 |
+
|
1700 |
+
def get_new_contraction_index(self):
|
1701 |
+
self.number_of_contraction_indices += 1
|
1702 |
+
return self.number_of_contraction_indices - 1
|
1703 |
+
|
1704 |
+
def refresh_indices(self):
|
1705 |
+
updates = {}
|
1706 |
+
for arg_with_ind in self.args_with_ind:
|
1707 |
+
updates.update({i: -1 for i in arg_with_ind.indices if i is not None})
|
1708 |
+
for i, e in enumerate(sorted(updates)):
|
1709 |
+
updates[e] = i
|
1710 |
+
self.number_of_contraction_indices = len(updates)
|
1711 |
+
for arg_with_ind in self.args_with_ind:
|
1712 |
+
arg_with_ind.indices = [updates.get(i, None) for i in arg_with_ind.indices]
|
1713 |
+
|
1714 |
+
def merge_scalars(self):
|
1715 |
+
scalars = []
|
1716 |
+
for arg_with_ind in self.args_with_ind:
|
1717 |
+
if len(arg_with_ind.indices) == 0:
|
1718 |
+
scalars.append(arg_with_ind)
|
1719 |
+
for i in scalars:
|
1720 |
+
self.args_with_ind.remove(i)
|
1721 |
+
scalar = Mul.fromiter([i.element for i in scalars])
|
1722 |
+
if len(self.args_with_ind) == 0:
|
1723 |
+
self.args_with_ind.append(_ArgE(scalar))
|
1724 |
+
else:
|
1725 |
+
from sympy.tensor.array.expressions.from_array_to_matrix import _a2m_tensor_product
|
1726 |
+
self.args_with_ind[0].element = _a2m_tensor_product(scalar, self.args_with_ind[0].element)
|
1727 |
+
|
1728 |
+
def to_array_contraction(self):
|
1729 |
+
|
1730 |
+
# Count the ranks of the arguments:
|
1731 |
+
counter = 0
|
1732 |
+
# Create a collector for the new diagonal indices:
|
1733 |
+
diag_indices = defaultdict(list)
|
1734 |
+
|
1735 |
+
count_index_freq = Counter()
|
1736 |
+
for arg_with_ind in self.args_with_ind:
|
1737 |
+
count_index_freq.update(Counter(arg_with_ind.indices))
|
1738 |
+
|
1739 |
+
free_index_count = count_index_freq[None]
|
1740 |
+
|
1741 |
+
# Construct the inverse permutation:
|
1742 |
+
inv_perm1 = []
|
1743 |
+
inv_perm2 = []
|
1744 |
+
# Keep track of which diagonal indices have already been processed:
|
1745 |
+
done = set()
|
1746 |
+
|
1747 |
+
# Counter for the diagonal indices:
|
1748 |
+
counter4 = 0
|
1749 |
+
|
1750 |
+
for arg_with_ind in self.args_with_ind:
|
1751 |
+
# If some diagonalization axes have been removed, they should be
|
1752 |
+
# permuted in order to keep the permutation.
|
1753 |
+
# Add permutation here
|
1754 |
+
counter2 = 0 # counter for the indices
|
1755 |
+
for i in arg_with_ind.indices:
|
1756 |
+
if i is None:
|
1757 |
+
inv_perm1.append(counter4)
|
1758 |
+
counter2 += 1
|
1759 |
+
counter4 += 1
|
1760 |
+
continue
|
1761 |
+
if i >= 0:
|
1762 |
+
continue
|
1763 |
+
# Reconstruct the diagonal indices:
|
1764 |
+
diag_indices[-1 - i].append(counter + counter2)
|
1765 |
+
if count_index_freq[i] == 1 and i not in done:
|
1766 |
+
inv_perm1.append(free_index_count - 1 - i)
|
1767 |
+
done.add(i)
|
1768 |
+
elif i not in done:
|
1769 |
+
inv_perm2.append(free_index_count - 1 - i)
|
1770 |
+
done.add(i)
|
1771 |
+
counter2 += 1
|
1772 |
+
# Remove negative indices to restore a proper editor object:
|
1773 |
+
arg_with_ind.indices = [i if i is not None and i >= 0 else None for i in arg_with_ind.indices]
|
1774 |
+
counter += len([i for i in arg_with_ind.indices if i is None or i < 0])
|
1775 |
+
|
1776 |
+
inverse_permutation = inv_perm1 + inv_perm2
|
1777 |
+
permutation = _af_invert(inverse_permutation)
|
1778 |
+
|
1779 |
+
# Get the diagonal indices after the detection of HadamardProduct in the expression:
|
1780 |
+
diag_indices_filtered = [tuple(v) for v in diag_indices.values() if len(v) > 1]
|
1781 |
+
|
1782 |
+
self.merge_scalars()
|
1783 |
+
self.refresh_indices()
|
1784 |
+
args = [arg.element for arg in self.args_with_ind]
|
1785 |
+
contraction_indices = self.get_contraction_indices()
|
1786 |
+
expr = _array_contraction(_array_tensor_product(*args), *contraction_indices)
|
1787 |
+
expr2 = _array_diagonal(expr, *diag_indices_filtered)
|
1788 |
+
if self._track_permutation is not None:
|
1789 |
+
permutation2 = _af_invert([j for i in self._track_permutation for j in i])
|
1790 |
+
expr2 = _permute_dims(expr2, permutation2)
|
1791 |
+
|
1792 |
+
expr3 = _permute_dims(expr2, permutation)
|
1793 |
+
return expr3
|
1794 |
+
|
1795 |
+
def get_contraction_indices(self) -> List[List[int]]:
|
1796 |
+
contraction_indices: List[List[int]] = [[] for i in range(self.number_of_contraction_indices)]
|
1797 |
+
current_position: int = 0
|
1798 |
+
for i, arg_with_ind in enumerate(self.args_with_ind):
|
1799 |
+
for j in arg_with_ind.indices:
|
1800 |
+
if j is not None:
|
1801 |
+
contraction_indices[j].append(current_position)
|
1802 |
+
current_position += 1
|
1803 |
+
return contraction_indices
|
1804 |
+
|
1805 |
+
def get_mapping_for_index(self, ind) -> List[_IndPos]:
|
1806 |
+
if ind >= self.number_of_contraction_indices:
|
1807 |
+
raise ValueError("index value exceeding the index range")
|
1808 |
+
positions: List[_IndPos] = []
|
1809 |
+
for i, arg_with_ind in enumerate(self.args_with_ind):
|
1810 |
+
for j, arg_ind in enumerate(arg_with_ind.indices):
|
1811 |
+
if ind == arg_ind:
|
1812 |
+
positions.append(_IndPos(i, j))
|
1813 |
+
return positions
|
1814 |
+
|
1815 |
+
def get_contraction_indices_to_ind_rel_pos(self) -> List[List[_IndPos]]:
|
1816 |
+
contraction_indices: List[List[_IndPos]] = [[] for i in range(self.number_of_contraction_indices)]
|
1817 |
+
for i, arg_with_ind in enumerate(self.args_with_ind):
|
1818 |
+
for j, ind in enumerate(arg_with_ind.indices):
|
1819 |
+
if ind is not None:
|
1820 |
+
contraction_indices[ind].append(_IndPos(i, j))
|
1821 |
+
return contraction_indices
|
1822 |
+
|
1823 |
+
def count_args_with_index(self, index: int) -> int:
|
1824 |
+
"""
|
1825 |
+
Count the number of arguments that have the given index.
|
1826 |
+
"""
|
1827 |
+
counter: int = 0
|
1828 |
+
for arg_with_ind in self.args_with_ind:
|
1829 |
+
if index in arg_with_ind.indices:
|
1830 |
+
counter += 1
|
1831 |
+
return counter
|
1832 |
+
|
1833 |
+
def get_args_with_index(self, index: int) -> List[_ArgE]:
|
1834 |
+
"""
|
1835 |
+
Get a list of arguments having the given index.
|
1836 |
+
"""
|
1837 |
+
ret: List[_ArgE] = [i for i in self.args_with_ind if index in i.indices]
|
1838 |
+
return ret
|
1839 |
+
|
1840 |
+
@property
|
1841 |
+
def number_of_diagonal_indices(self):
|
1842 |
+
data = set()
|
1843 |
+
for arg in self.args_with_ind:
|
1844 |
+
data.update({i for i in arg.indices if i is not None and i < 0})
|
1845 |
+
return len(data)
|
1846 |
+
|
1847 |
+
def track_permutation_start(self):
|
1848 |
+
permutation = []
|
1849 |
+
perm_diag = []
|
1850 |
+
counter = 0
|
1851 |
+
counter2 = -1
|
1852 |
+
for arg_with_ind in self.args_with_ind:
|
1853 |
+
perm = []
|
1854 |
+
for i in arg_with_ind.indices:
|
1855 |
+
if i is not None:
|
1856 |
+
if i < 0:
|
1857 |
+
perm_diag.append(counter2)
|
1858 |
+
counter2 -= 1
|
1859 |
+
continue
|
1860 |
+
perm.append(counter)
|
1861 |
+
counter += 1
|
1862 |
+
permutation.append(perm)
|
1863 |
+
max_ind = max([max(i) if i else -1 for i in permutation]) if permutation else -1
|
1864 |
+
perm_diag = [max_ind - i for i in perm_diag]
|
1865 |
+
self._track_permutation = permutation + [perm_diag]
|
1866 |
+
|
1867 |
+
def track_permutation_merge(self, destination: _ArgE, from_element: _ArgE):
|
1868 |
+
index_destination = self.args_with_ind.index(destination)
|
1869 |
+
index_element = self.args_with_ind.index(from_element)
|
1870 |
+
self._track_permutation[index_destination].extend(self._track_permutation[index_element]) # type: ignore
|
1871 |
+
self._track_permutation.pop(index_element) # type: ignore
|
1872 |
+
|
1873 |
+
def get_absolute_free_range(self, arg: _ArgE) -> typing.Tuple[int, int]:
|
1874 |
+
"""
|
1875 |
+
Return the range of the free indices of the arg as absolute positions
|
1876 |
+
among all free indices.
|
1877 |
+
"""
|
1878 |
+
counter = 0
|
1879 |
+
for arg_with_ind in self.args_with_ind:
|
1880 |
+
number_free_indices = len([i for i in arg_with_ind.indices if i is None])
|
1881 |
+
if arg_with_ind == arg:
|
1882 |
+
return counter, counter + number_free_indices
|
1883 |
+
counter += number_free_indices
|
1884 |
+
raise IndexError("argument not found")
|
1885 |
+
|
1886 |
+
def get_absolute_range(self, arg: _ArgE) -> typing.Tuple[int, int]:
|
1887 |
+
"""
|
1888 |
+
Return the absolute range of indices for arg, disregarding dummy
|
1889 |
+
indices.
|
1890 |
+
"""
|
1891 |
+
counter = 0
|
1892 |
+
for arg_with_ind in self.args_with_ind:
|
1893 |
+
number_indices = len(arg_with_ind.indices)
|
1894 |
+
if arg_with_ind == arg:
|
1895 |
+
return counter, counter + number_indices
|
1896 |
+
counter += number_indices
|
1897 |
+
raise IndexError("argument not found")
|
1898 |
+
|
1899 |
+
|
1900 |
+
def get_rank(expr):
|
1901 |
+
if isinstance(expr, (MatrixExpr, MatrixElement)):
|
1902 |
+
return 2
|
1903 |
+
if isinstance(expr, _CodegenArrayAbstract):
|
1904 |
+
return len(expr.shape)
|
1905 |
+
if isinstance(expr, NDimArray):
|
1906 |
+
return expr.rank()
|
1907 |
+
if isinstance(expr, Indexed):
|
1908 |
+
return expr.rank
|
1909 |
+
if isinstance(expr, IndexedBase):
|
1910 |
+
shape = expr.shape
|
1911 |
+
if shape is None:
|
1912 |
+
return -1
|
1913 |
+
else:
|
1914 |
+
return len(shape)
|
1915 |
+
if hasattr(expr, "shape"):
|
1916 |
+
return len(expr.shape)
|
1917 |
+
return 0
|
1918 |
+
|
1919 |
+
|
1920 |
+
def _get_subrank(expr):
|
1921 |
+
if isinstance(expr, _CodegenArrayAbstract):
|
1922 |
+
return expr.subrank()
|
1923 |
+
return get_rank(expr)
|
1924 |
+
|
1925 |
+
|
1926 |
+
def _get_subranks(expr):
|
1927 |
+
if isinstance(expr, _CodegenArrayAbstract):
|
1928 |
+
return expr.subranks
|
1929 |
+
else:
|
1930 |
+
return [get_rank(expr)]
|
1931 |
+
|
1932 |
+
|
1933 |
+
def get_shape(expr):
|
1934 |
+
if hasattr(expr, "shape"):
|
1935 |
+
return expr.shape
|
1936 |
+
return ()
|
1937 |
+
|
1938 |
+
|
1939 |
+
def nest_permutation(expr):
|
1940 |
+
if isinstance(expr, PermuteDims):
|
1941 |
+
return expr.nest_permutation()
|
1942 |
+
else:
|
1943 |
+
return expr
|
1944 |
+
|
1945 |
+
|
1946 |
+
def _array_tensor_product(*args, **kwargs):
|
1947 |
+
return ArrayTensorProduct(*args, canonicalize=True, **kwargs)
|
1948 |
+
|
1949 |
+
|
1950 |
+
def _array_contraction(expr, *contraction_indices, **kwargs):
|
1951 |
+
return ArrayContraction(expr, *contraction_indices, canonicalize=True, **kwargs)
|
1952 |
+
|
1953 |
+
|
1954 |
+
def _array_diagonal(expr, *diagonal_indices, **kwargs):
|
1955 |
+
return ArrayDiagonal(expr, *diagonal_indices, canonicalize=True, **kwargs)
|
1956 |
+
|
1957 |
+
|
1958 |
+
def _permute_dims(expr, permutation, **kwargs):
|
1959 |
+
return PermuteDims(expr, permutation, canonicalize=True, **kwargs)
|
1960 |
+
|
1961 |
+
|
1962 |
+
def _array_add(*args, **kwargs):
|
1963 |
+
return ArrayAdd(*args, canonicalize=True, **kwargs)
|
1964 |
+
|
1965 |
+
|
1966 |
+
def _get_array_element_or_slice(expr, indices):
|
1967 |
+
return ArrayElement(expr, indices)
|
env-llmeval/lib/python3.10/site-packages/sympy/tensor/array/expressions/conv_array_to_indexed.py
ADDED
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.tensor.array.expressions import from_array_to_indexed
|
2 |
+
from sympy.utilities.decorator import deprecated
|
3 |
+
|
4 |
+
|
5 |
+
_conv_to_from_decorator = deprecated(
|
6 |
+
"module has been renamed by replacing 'conv_' with 'from_' in its name",
|
7 |
+
deprecated_since_version="1.11",
|
8 |
+
active_deprecations_target="deprecated-conv-array-expr-module-names",
|
9 |
+
)
|
10 |
+
|
11 |
+
|
12 |
+
convert_array_to_indexed = _conv_to_from_decorator(from_array_to_indexed.convert_array_to_indexed)
|
env-llmeval/lib/python3.10/site-packages/sympy/tensor/array/expressions/conv_array_to_matrix.py
ADDED
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.tensor.array.expressions import from_array_to_matrix
|
2 |
+
from sympy.tensor.array.expressions.conv_array_to_indexed import _conv_to_from_decorator
|
3 |
+
|
4 |
+
convert_array_to_matrix = _conv_to_from_decorator(from_array_to_matrix.convert_array_to_matrix)
|
5 |
+
_array2matrix = _conv_to_from_decorator(from_array_to_matrix._array2matrix)
|
6 |
+
_remove_trivial_dims = _conv_to_from_decorator(from_array_to_matrix._remove_trivial_dims)
|
env-llmeval/lib/python3.10/site-packages/sympy/tensor/array/expressions/conv_indexed_to_array.py
ADDED
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.tensor.array.expressions import from_indexed_to_array
|
2 |
+
from sympy.tensor.array.expressions.conv_array_to_indexed import _conv_to_from_decorator
|
3 |
+
|
4 |
+
convert_indexed_to_array = _conv_to_from_decorator(from_indexed_to_array.convert_indexed_to_array)
|
env-llmeval/lib/python3.10/site-packages/sympy/tensor/array/expressions/conv_matrix_to_array.py
ADDED
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.tensor.array.expressions import from_matrix_to_array
|
2 |
+
from sympy.tensor.array.expressions.conv_array_to_indexed import _conv_to_from_decorator
|
3 |
+
|
4 |
+
convert_matrix_to_array = _conv_to_from_decorator(from_matrix_to_array.convert_matrix_to_array)
|
env-llmeval/lib/python3.10/site-packages/sympy/tensor/array/expressions/from_array_to_indexed.py
ADDED
@@ -0,0 +1,84 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import collections.abc
|
2 |
+
import operator
|
3 |
+
from itertools import accumulate
|
4 |
+
|
5 |
+
from sympy import Mul, Sum, Dummy, Add
|
6 |
+
from sympy.tensor.array.expressions import PermuteDims, ArrayAdd, ArrayElementwiseApplyFunc, Reshape
|
7 |
+
from sympy.tensor.array.expressions.array_expressions import ArrayTensorProduct, get_rank, ArrayContraction, \
|
8 |
+
ArrayDiagonal, get_shape, _get_array_element_or_slice, _ArrayExpr
|
9 |
+
from sympy.tensor.array.expressions.utils import _apply_permutation_to_list
|
10 |
+
|
11 |
+
|
12 |
+
def convert_array_to_indexed(expr, indices):
|
13 |
+
return _ConvertArrayToIndexed().do_convert(expr, indices)
|
14 |
+
|
15 |
+
|
16 |
+
class _ConvertArrayToIndexed:
|
17 |
+
|
18 |
+
def __init__(self):
|
19 |
+
self.count_dummies = 0
|
20 |
+
|
21 |
+
def do_convert(self, expr, indices):
|
22 |
+
if isinstance(expr, ArrayTensorProduct):
|
23 |
+
cumul = list(accumulate([0] + [get_rank(arg) for arg in expr.args]))
|
24 |
+
indices_grp = [indices[cumul[i]:cumul[i+1]] for i in range(len(expr.args))]
|
25 |
+
return Mul.fromiter(self.do_convert(arg, ind) for arg, ind in zip(expr.args, indices_grp))
|
26 |
+
if isinstance(expr, ArrayContraction):
|
27 |
+
new_indices = [None for i in range(get_rank(expr.expr))]
|
28 |
+
limits = []
|
29 |
+
bottom_shape = get_shape(expr.expr)
|
30 |
+
for contraction_index_grp in expr.contraction_indices:
|
31 |
+
d = Dummy(f"d{self.count_dummies}")
|
32 |
+
self.count_dummies += 1
|
33 |
+
dim = bottom_shape[contraction_index_grp[0]]
|
34 |
+
limits.append((d, 0, dim-1))
|
35 |
+
for i in contraction_index_grp:
|
36 |
+
new_indices[i] = d
|
37 |
+
j = 0
|
38 |
+
for i in range(len(new_indices)):
|
39 |
+
if new_indices[i] is None:
|
40 |
+
new_indices[i] = indices[j]
|
41 |
+
j += 1
|
42 |
+
newexpr = self.do_convert(expr.expr, new_indices)
|
43 |
+
return Sum(newexpr, *limits)
|
44 |
+
if isinstance(expr, ArrayDiagonal):
|
45 |
+
new_indices = [None for i in range(get_rank(expr.expr))]
|
46 |
+
ind_pos = expr._push_indices_down(expr.diagonal_indices, list(range(len(indices))), get_rank(expr))
|
47 |
+
for i, index in zip(ind_pos, indices):
|
48 |
+
if isinstance(i, collections.abc.Iterable):
|
49 |
+
for j in i:
|
50 |
+
new_indices[j] = index
|
51 |
+
else:
|
52 |
+
new_indices[i] = index
|
53 |
+
newexpr = self.do_convert(expr.expr, new_indices)
|
54 |
+
return newexpr
|
55 |
+
if isinstance(expr, PermuteDims):
|
56 |
+
permuted_indices = _apply_permutation_to_list(expr.permutation, indices)
|
57 |
+
return self.do_convert(expr.expr, permuted_indices)
|
58 |
+
if isinstance(expr, ArrayAdd):
|
59 |
+
return Add.fromiter(self.do_convert(arg, indices) for arg in expr.args)
|
60 |
+
if isinstance(expr, _ArrayExpr):
|
61 |
+
return expr.__getitem__(tuple(indices))
|
62 |
+
if isinstance(expr, ArrayElementwiseApplyFunc):
|
63 |
+
return expr.function(self.do_convert(expr.expr, indices))
|
64 |
+
if isinstance(expr, Reshape):
|
65 |
+
shape_up = expr.shape
|
66 |
+
shape_down = get_shape(expr.expr)
|
67 |
+
cumul = list(accumulate([1] + list(reversed(shape_up)), operator.mul))
|
68 |
+
one_index = Add.fromiter(i*s for i, s in zip(reversed(indices), cumul))
|
69 |
+
dest_indices = [None for _ in shape_down]
|
70 |
+
c = 1
|
71 |
+
for i, e in enumerate(reversed(shape_down)):
|
72 |
+
if c == 1:
|
73 |
+
if i == len(shape_down) - 1:
|
74 |
+
dest_indices[i] = one_index
|
75 |
+
else:
|
76 |
+
dest_indices[i] = one_index % e
|
77 |
+
elif i == len(shape_down) - 1:
|
78 |
+
dest_indices[i] = one_index // c
|
79 |
+
else:
|
80 |
+
dest_indices[i] = one_index // c % e
|
81 |
+
c *= e
|
82 |
+
dest_indices.reverse()
|
83 |
+
return self.do_convert(expr.expr, dest_indices)
|
84 |
+
return _get_array_element_or_slice(expr, indices)
|
env-llmeval/lib/python3.10/site-packages/sympy/tensor/array/expressions/from_array_to_matrix.py
ADDED
@@ -0,0 +1,1003 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import itertools
|
2 |
+
from collections import defaultdict
|
3 |
+
from typing import Tuple as tTuple, Union as tUnion, FrozenSet, Dict as tDict, List, Optional
|
4 |
+
from functools import singledispatch
|
5 |
+
from itertools import accumulate
|
6 |
+
|
7 |
+
from sympy import MatMul, Basic, Wild, KroneckerProduct
|
8 |
+
from sympy.assumptions.ask import (Q, ask)
|
9 |
+
from sympy.core.mul import Mul
|
10 |
+
from sympy.core.singleton import S
|
11 |
+
from sympy.matrices.expressions.diagonal import DiagMatrix
|
12 |
+
from sympy.matrices.expressions.hadamard import hadamard_product, HadamardPower
|
13 |
+
from sympy.matrices.expressions.matexpr import MatrixExpr
|
14 |
+
from sympy.matrices.expressions.special import (Identity, ZeroMatrix, OneMatrix)
|
15 |
+
from sympy.matrices.expressions.trace import Trace
|
16 |
+
from sympy.matrices.expressions.transpose import Transpose
|
17 |
+
from sympy.combinatorics.permutations import _af_invert, Permutation
|
18 |
+
from sympy.matrices.common import MatrixCommon
|
19 |
+
from sympy.matrices.expressions.applyfunc import ElementwiseApplyFunction
|
20 |
+
from sympy.matrices.expressions.matexpr import MatrixElement
|
21 |
+
from sympy.tensor.array.expressions.array_expressions import PermuteDims, ArrayDiagonal, \
|
22 |
+
ArrayTensorProduct, OneArray, get_rank, _get_subrank, ZeroArray, ArrayContraction, \
|
23 |
+
ArrayAdd, _CodegenArrayAbstract, get_shape, ArrayElementwiseApplyFunc, _ArrayExpr, _EditArrayContraction, _ArgE, \
|
24 |
+
ArrayElement, _array_tensor_product, _array_contraction, _array_diagonal, _array_add, _permute_dims
|
25 |
+
from sympy.tensor.array.expressions.utils import _get_mapping_from_subranks
|
26 |
+
|
27 |
+
|
28 |
+
def _get_candidate_for_matmul_from_contraction(scan_indices: List[Optional[int]], remaining_args: List[_ArgE]) -> tTuple[Optional[_ArgE], bool, int]:
|
29 |
+
|
30 |
+
scan_indices_int: List[int] = [i for i in scan_indices if i is not None]
|
31 |
+
if len(scan_indices_int) == 0:
|
32 |
+
return None, False, -1
|
33 |
+
|
34 |
+
transpose: bool = False
|
35 |
+
candidate: Optional[_ArgE] = None
|
36 |
+
candidate_index: int = -1
|
37 |
+
for arg_with_ind2 in remaining_args:
|
38 |
+
if not isinstance(arg_with_ind2.element, MatrixExpr):
|
39 |
+
continue
|
40 |
+
for index in scan_indices_int:
|
41 |
+
if candidate_index != -1 and candidate_index != index:
|
42 |
+
# A candidate index has already been selected, check
|
43 |
+
# repetitions only for that index:
|
44 |
+
continue
|
45 |
+
if index in arg_with_ind2.indices:
|
46 |
+
if set(arg_with_ind2.indices) == {index}:
|
47 |
+
# Index repeated twice in arg_with_ind2
|
48 |
+
candidate = None
|
49 |
+
break
|
50 |
+
if candidate is None:
|
51 |
+
candidate = arg_with_ind2
|
52 |
+
candidate_index = index
|
53 |
+
transpose = (index == arg_with_ind2.indices[1])
|
54 |
+
else:
|
55 |
+
# Index repeated more than twice, break
|
56 |
+
candidate = None
|
57 |
+
break
|
58 |
+
return candidate, transpose, candidate_index
|
59 |
+
|
60 |
+
|
61 |
+
def _insert_candidate_into_editor(editor: _EditArrayContraction, arg_with_ind: _ArgE, candidate: _ArgE, transpose1: bool, transpose2: bool):
|
62 |
+
other = candidate.element
|
63 |
+
other_index: Optional[int]
|
64 |
+
if transpose2:
|
65 |
+
other = Transpose(other)
|
66 |
+
other_index = candidate.indices[0]
|
67 |
+
else:
|
68 |
+
other_index = candidate.indices[1]
|
69 |
+
new_element = (Transpose(arg_with_ind.element) if transpose1 else arg_with_ind.element) * other
|
70 |
+
editor.args_with_ind.remove(candidate)
|
71 |
+
new_arge = _ArgE(new_element)
|
72 |
+
return new_arge, other_index
|
73 |
+
|
74 |
+
|
75 |
+
def _support_function_tp1_recognize(contraction_indices, args):
|
76 |
+
if len(contraction_indices) == 0:
|
77 |
+
return _a2m_tensor_product(*args)
|
78 |
+
|
79 |
+
ac = _array_contraction(_array_tensor_product(*args), *contraction_indices)
|
80 |
+
editor = _EditArrayContraction(ac)
|
81 |
+
editor.track_permutation_start()
|
82 |
+
|
83 |
+
while True:
|
84 |
+
flag_stop = True
|
85 |
+
for i, arg_with_ind in enumerate(editor.args_with_ind):
|
86 |
+
if not isinstance(arg_with_ind.element, MatrixExpr):
|
87 |
+
continue
|
88 |
+
|
89 |
+
first_index = arg_with_ind.indices[0]
|
90 |
+
second_index = arg_with_ind.indices[1]
|
91 |
+
|
92 |
+
first_frequency = editor.count_args_with_index(first_index)
|
93 |
+
second_frequency = editor.count_args_with_index(second_index)
|
94 |
+
|
95 |
+
if first_index is not None and first_frequency == 1 and first_index == second_index:
|
96 |
+
flag_stop = False
|
97 |
+
arg_with_ind.element = Trace(arg_with_ind.element)._normalize()
|
98 |
+
arg_with_ind.indices = []
|
99 |
+
break
|
100 |
+
|
101 |
+
scan_indices = []
|
102 |
+
if first_frequency == 2:
|
103 |
+
scan_indices.append(first_index)
|
104 |
+
if second_frequency == 2:
|
105 |
+
scan_indices.append(second_index)
|
106 |
+
|
107 |
+
candidate, transpose, found_index = _get_candidate_for_matmul_from_contraction(scan_indices, editor.args_with_ind[i+1:])
|
108 |
+
if candidate is not None:
|
109 |
+
flag_stop = False
|
110 |
+
editor.track_permutation_merge(arg_with_ind, candidate)
|
111 |
+
transpose1 = found_index == first_index
|
112 |
+
new_arge, other_index = _insert_candidate_into_editor(editor, arg_with_ind, candidate, transpose1, transpose)
|
113 |
+
if found_index == first_index:
|
114 |
+
new_arge.indices = [second_index, other_index]
|
115 |
+
else:
|
116 |
+
new_arge.indices = [first_index, other_index]
|
117 |
+
set_indices = set(new_arge.indices)
|
118 |
+
if len(set_indices) == 1 and set_indices != {None}:
|
119 |
+
# This is a trace:
|
120 |
+
new_arge.element = Trace(new_arge.element)._normalize()
|
121 |
+
new_arge.indices = []
|
122 |
+
editor.args_with_ind[i] = new_arge
|
123 |
+
# TODO: is this break necessary?
|
124 |
+
break
|
125 |
+
|
126 |
+
if flag_stop:
|
127 |
+
break
|
128 |
+
|
129 |
+
editor.refresh_indices()
|
130 |
+
return editor.to_array_contraction()
|
131 |
+
|
132 |
+
|
133 |
+
def _find_trivial_matrices_rewrite(expr: ArrayTensorProduct):
|
134 |
+
# If there are matrices of trivial shape in the tensor product (i.e. shape
|
135 |
+
# (1, 1)), try to check if there is a suitable non-trivial MatMul where the
|
136 |
+
# expression can be inserted.
|
137 |
+
|
138 |
+
# For example, if "a" has shape (1, 1) and "b" has shape (k, 1), the
|
139 |
+
# expressions "_array_tensor_product(a, b*b.T)" can be rewritten as
|
140 |
+
# "b*a*b.T"
|
141 |
+
|
142 |
+
trivial_matrices = []
|
143 |
+
pos: Optional[int] = None
|
144 |
+
first: Optional[MatrixExpr] = None
|
145 |
+
second: Optional[MatrixExpr] = None
|
146 |
+
removed: List[int] = []
|
147 |
+
counter: int = 0
|
148 |
+
args: List[Optional[Basic]] = list(expr.args)
|
149 |
+
for i, arg in enumerate(expr.args):
|
150 |
+
if isinstance(arg, MatrixExpr):
|
151 |
+
if arg.shape == (1, 1):
|
152 |
+
trivial_matrices.append(arg)
|
153 |
+
args[i] = None
|
154 |
+
removed.extend([counter, counter+1])
|
155 |
+
elif pos is None and isinstance(arg, MatMul):
|
156 |
+
margs = arg.args
|
157 |
+
for j, e in enumerate(margs):
|
158 |
+
if isinstance(e, MatrixExpr) and e.shape[1] == 1:
|
159 |
+
pos = i
|
160 |
+
first = MatMul.fromiter(margs[:j+1])
|
161 |
+
second = MatMul.fromiter(margs[j+1:])
|
162 |
+
break
|
163 |
+
counter += get_rank(arg)
|
164 |
+
if pos is None:
|
165 |
+
return expr, []
|
166 |
+
args[pos] = (first*MatMul.fromiter(i for i in trivial_matrices)*second).doit()
|
167 |
+
return _array_tensor_product(*[i for i in args if i is not None]), removed
|
168 |
+
|
169 |
+
|
170 |
+
def _find_trivial_kronecker_products_broadcast(expr: ArrayTensorProduct):
|
171 |
+
newargs: List[Basic] = []
|
172 |
+
removed = []
|
173 |
+
count_dims = 0
|
174 |
+
for i, arg in enumerate(expr.args):
|
175 |
+
count_dims += get_rank(arg)
|
176 |
+
shape = get_shape(arg)
|
177 |
+
current_range = [count_dims-i for i in range(len(shape), 0, -1)]
|
178 |
+
if (shape == (1, 1) and len(newargs) > 0 and 1 not in get_shape(newargs[-1]) and
|
179 |
+
isinstance(newargs[-1], MatrixExpr) and isinstance(arg, MatrixExpr)):
|
180 |
+
# KroneckerProduct object allows the trick of broadcasting:
|
181 |
+
newargs[-1] = KroneckerProduct(newargs[-1], arg)
|
182 |
+
removed.extend(current_range)
|
183 |
+
elif 1 not in shape and len(newargs) > 0 and get_shape(newargs[-1]) == (1, 1):
|
184 |
+
# Broadcast:
|
185 |
+
newargs[-1] = KroneckerProduct(newargs[-1], arg)
|
186 |
+
prev_range = [i for i in range(min(current_range)) if i not in removed]
|
187 |
+
removed.extend(prev_range[-2:])
|
188 |
+
else:
|
189 |
+
newargs.append(arg)
|
190 |
+
return _array_tensor_product(*newargs), removed
|
191 |
+
|
192 |
+
|
193 |
+
@singledispatch
|
194 |
+
def _array2matrix(expr):
|
195 |
+
return expr
|
196 |
+
|
197 |
+
|
198 |
+
@_array2matrix.register(ZeroArray)
|
199 |
+
def _(expr: ZeroArray):
|
200 |
+
if get_rank(expr) == 2:
|
201 |
+
return ZeroMatrix(*expr.shape)
|
202 |
+
else:
|
203 |
+
return expr
|
204 |
+
|
205 |
+
|
206 |
+
@_array2matrix.register(ArrayTensorProduct)
|
207 |
+
def _(expr: ArrayTensorProduct):
|
208 |
+
return _a2m_tensor_product(*[_array2matrix(arg) for arg in expr.args])
|
209 |
+
|
210 |
+
|
211 |
+
@_array2matrix.register(ArrayContraction)
|
212 |
+
def _(expr: ArrayContraction):
|
213 |
+
expr = expr.flatten_contraction_of_diagonal()
|
214 |
+
expr = identify_removable_identity_matrices(expr)
|
215 |
+
expr = expr.split_multiple_contractions()
|
216 |
+
expr = identify_hadamard_products(expr)
|
217 |
+
if not isinstance(expr, ArrayContraction):
|
218 |
+
return _array2matrix(expr)
|
219 |
+
subexpr = expr.expr
|
220 |
+
contraction_indices: tTuple[tTuple[int]] = expr.contraction_indices
|
221 |
+
if contraction_indices == ((0,), (1,)) or (
|
222 |
+
contraction_indices == ((0,),) and subexpr.shape[1] == 1
|
223 |
+
) or (
|
224 |
+
contraction_indices == ((1,),) and subexpr.shape[0] == 1
|
225 |
+
):
|
226 |
+
shape = subexpr.shape
|
227 |
+
subexpr = _array2matrix(subexpr)
|
228 |
+
if isinstance(subexpr, MatrixExpr):
|
229 |
+
return OneMatrix(1, shape[0])*subexpr*OneMatrix(shape[1], 1)
|
230 |
+
if isinstance(subexpr, ArrayTensorProduct):
|
231 |
+
newexpr = _array_contraction(_array2matrix(subexpr), *contraction_indices)
|
232 |
+
contraction_indices = newexpr.contraction_indices
|
233 |
+
if any(i > 2 for i in newexpr.subranks):
|
234 |
+
addends = _array_add(*[_a2m_tensor_product(*j) for j in itertools.product(*[i.args if isinstance(i,
|
235 |
+
ArrayAdd) else [i] for i in expr.expr.args])])
|
236 |
+
newexpr = _array_contraction(addends, *contraction_indices)
|
237 |
+
if isinstance(newexpr, ArrayAdd):
|
238 |
+
ret = _array2matrix(newexpr)
|
239 |
+
return ret
|
240 |
+
assert isinstance(newexpr, ArrayContraction)
|
241 |
+
ret = _support_function_tp1_recognize(contraction_indices, list(newexpr.expr.args))
|
242 |
+
return ret
|
243 |
+
elif not isinstance(subexpr, _CodegenArrayAbstract):
|
244 |
+
ret = _array2matrix(subexpr)
|
245 |
+
if isinstance(ret, MatrixExpr):
|
246 |
+
assert expr.contraction_indices == ((0, 1),)
|
247 |
+
return _a2m_trace(ret)
|
248 |
+
else:
|
249 |
+
return _array_contraction(ret, *expr.contraction_indices)
|
250 |
+
|
251 |
+
|
252 |
+
@_array2matrix.register(ArrayDiagonal)
|
253 |
+
def _(expr: ArrayDiagonal):
|
254 |
+
pexpr = _array_diagonal(_array2matrix(expr.expr), *expr.diagonal_indices)
|
255 |
+
pexpr = identify_hadamard_products(pexpr)
|
256 |
+
if isinstance(pexpr, ArrayDiagonal):
|
257 |
+
pexpr = _array_diag2contr_diagmatrix(pexpr)
|
258 |
+
if expr == pexpr:
|
259 |
+
return expr
|
260 |
+
return _array2matrix(pexpr)
|
261 |
+
|
262 |
+
|
263 |
+
@_array2matrix.register(PermuteDims)
|
264 |
+
def _(expr: PermuteDims):
|
265 |
+
if expr.permutation.array_form == [1, 0]:
|
266 |
+
return _a2m_transpose(_array2matrix(expr.expr))
|
267 |
+
elif isinstance(expr.expr, ArrayTensorProduct):
|
268 |
+
ranks = expr.expr.subranks
|
269 |
+
inv_permutation = expr.permutation**(-1)
|
270 |
+
newrange = [inv_permutation(i) for i in range(sum(ranks))]
|
271 |
+
newpos = []
|
272 |
+
counter = 0
|
273 |
+
for rank in ranks:
|
274 |
+
newpos.append(newrange[counter:counter+rank])
|
275 |
+
counter += rank
|
276 |
+
newargs = []
|
277 |
+
newperm = []
|
278 |
+
scalars = []
|
279 |
+
for pos, arg in zip(newpos, expr.expr.args):
|
280 |
+
if len(pos) == 0:
|
281 |
+
scalars.append(_array2matrix(arg))
|
282 |
+
elif pos == sorted(pos):
|
283 |
+
newargs.append((_array2matrix(arg), pos[0]))
|
284 |
+
newperm.extend(pos)
|
285 |
+
elif len(pos) == 2:
|
286 |
+
newargs.append((_a2m_transpose(_array2matrix(arg)), pos[0]))
|
287 |
+
newperm.extend(reversed(pos))
|
288 |
+
else:
|
289 |
+
raise NotImplementedError()
|
290 |
+
newargs = [i[0] for i in newargs]
|
291 |
+
return _permute_dims(_a2m_tensor_product(*scalars, *newargs), _af_invert(newperm))
|
292 |
+
elif isinstance(expr.expr, ArrayContraction):
|
293 |
+
mat_mul_lines = _array2matrix(expr.expr)
|
294 |
+
if not isinstance(mat_mul_lines, ArrayTensorProduct):
|
295 |
+
return _permute_dims(mat_mul_lines, expr.permutation)
|
296 |
+
# TODO: this assumes that all arguments are matrices, it may not be the case:
|
297 |
+
permutation = Permutation(2*len(mat_mul_lines.args)-1)*expr.permutation
|
298 |
+
permuted = [permutation(i) for i in range(2*len(mat_mul_lines.args))]
|
299 |
+
args_array = [None for i in mat_mul_lines.args]
|
300 |
+
for i in range(len(mat_mul_lines.args)):
|
301 |
+
p1 = permuted[2*i]
|
302 |
+
p2 = permuted[2*i+1]
|
303 |
+
if p1 // 2 != p2 // 2:
|
304 |
+
return _permute_dims(mat_mul_lines, permutation)
|
305 |
+
if p1 > p2:
|
306 |
+
args_array[i] = _a2m_transpose(mat_mul_lines.args[p1 // 2])
|
307 |
+
else:
|
308 |
+
args_array[i] = mat_mul_lines.args[p1 // 2]
|
309 |
+
return _a2m_tensor_product(*args_array)
|
310 |
+
else:
|
311 |
+
return expr
|
312 |
+
|
313 |
+
|
314 |
+
@_array2matrix.register(ArrayAdd)
|
315 |
+
def _(expr: ArrayAdd):
|
316 |
+
addends = [_array2matrix(arg) for arg in expr.args]
|
317 |
+
return _a2m_add(*addends)
|
318 |
+
|
319 |
+
|
320 |
+
@_array2matrix.register(ArrayElementwiseApplyFunc)
|
321 |
+
def _(expr: ArrayElementwiseApplyFunc):
|
322 |
+
subexpr = _array2matrix(expr.expr)
|
323 |
+
if isinstance(subexpr, MatrixExpr):
|
324 |
+
if subexpr.shape != (1, 1):
|
325 |
+
d = expr.function.bound_symbols[0]
|
326 |
+
w = Wild("w", exclude=[d])
|
327 |
+
p = Wild("p", exclude=[d])
|
328 |
+
m = expr.function.expr.match(w*d**p)
|
329 |
+
if m is not None:
|
330 |
+
return m[w]*HadamardPower(subexpr, m[p])
|
331 |
+
return ElementwiseApplyFunction(expr.function, subexpr)
|
332 |
+
else:
|
333 |
+
return ArrayElementwiseApplyFunc(expr.function, subexpr)
|
334 |
+
|
335 |
+
|
336 |
+
@_array2matrix.register(ArrayElement)
|
337 |
+
def _(expr: ArrayElement):
|
338 |
+
ret = _array2matrix(expr.name)
|
339 |
+
if isinstance(ret, MatrixExpr):
|
340 |
+
return MatrixElement(ret, *expr.indices)
|
341 |
+
return ArrayElement(ret, expr.indices)
|
342 |
+
|
343 |
+
|
344 |
+
@singledispatch
|
345 |
+
def _remove_trivial_dims(expr):
|
346 |
+
return expr, []
|
347 |
+
|
348 |
+
|
349 |
+
@_remove_trivial_dims.register(ArrayTensorProduct)
|
350 |
+
def _(expr: ArrayTensorProduct):
|
351 |
+
# Recognize expressions like [x, y] with shape (k, 1, k, 1) as `x*y.T`.
|
352 |
+
# The matrix expression has to be equivalent to the tensor product of the
|
353 |
+
# matrices, with trivial dimensions (i.e. dim=1) dropped.
|
354 |
+
# That is, add contractions over trivial dimensions:
|
355 |
+
|
356 |
+
removed = []
|
357 |
+
newargs = []
|
358 |
+
cumul = list(accumulate([0] + [get_rank(arg) for arg in expr.args]))
|
359 |
+
pending = None
|
360 |
+
prev_i = None
|
361 |
+
for i, arg in enumerate(expr.args):
|
362 |
+
current_range = list(range(cumul[i], cumul[i+1]))
|
363 |
+
if isinstance(arg, OneArray):
|
364 |
+
removed.extend(current_range)
|
365 |
+
continue
|
366 |
+
if not isinstance(arg, (MatrixExpr, MatrixCommon)):
|
367 |
+
rarg, rem = _remove_trivial_dims(arg)
|
368 |
+
removed.extend(rem)
|
369 |
+
newargs.append(rarg)
|
370 |
+
continue
|
371 |
+
elif getattr(arg, "is_Identity", False) and arg.shape == (1, 1):
|
372 |
+
if arg.shape == (1, 1):
|
373 |
+
# Ignore identity matrices of shape (1, 1) - they are equivalent to scalar 1.
|
374 |
+
removed.extend(current_range)
|
375 |
+
continue
|
376 |
+
elif arg.shape == (1, 1):
|
377 |
+
arg, _ = _remove_trivial_dims(arg)
|
378 |
+
# Matrix is equivalent to scalar:
|
379 |
+
if len(newargs) == 0:
|
380 |
+
newargs.append(arg)
|
381 |
+
elif 1 in get_shape(newargs[-1]):
|
382 |
+
if newargs[-1].shape[1] == 1:
|
383 |
+
newargs[-1] = newargs[-1]*arg
|
384 |
+
else:
|
385 |
+
newargs[-1] = arg*newargs[-1]
|
386 |
+
removed.extend(current_range)
|
387 |
+
else:
|
388 |
+
newargs.append(arg)
|
389 |
+
elif 1 in arg.shape:
|
390 |
+
k = [i for i in arg.shape if i != 1][0]
|
391 |
+
if pending is None:
|
392 |
+
pending = k
|
393 |
+
prev_i = i
|
394 |
+
newargs.append(arg)
|
395 |
+
elif pending == k:
|
396 |
+
prev = newargs[-1]
|
397 |
+
if prev.shape[0] == 1:
|
398 |
+
d1 = cumul[prev_i]
|
399 |
+
prev = _a2m_transpose(prev)
|
400 |
+
else:
|
401 |
+
d1 = cumul[prev_i] + 1
|
402 |
+
if arg.shape[1] == 1:
|
403 |
+
d2 = cumul[i] + 1
|
404 |
+
arg = _a2m_transpose(arg)
|
405 |
+
else:
|
406 |
+
d2 = cumul[i]
|
407 |
+
newargs[-1] = prev*arg
|
408 |
+
pending = None
|
409 |
+
removed.extend([d1, d2])
|
410 |
+
else:
|
411 |
+
newargs.append(arg)
|
412 |
+
pending = k
|
413 |
+
prev_i = i
|
414 |
+
else:
|
415 |
+
newargs.append(arg)
|
416 |
+
pending = None
|
417 |
+
newexpr, newremoved = _a2m_tensor_product(*newargs), sorted(removed)
|
418 |
+
if isinstance(newexpr, ArrayTensorProduct):
|
419 |
+
newexpr, newremoved2 = _find_trivial_matrices_rewrite(newexpr)
|
420 |
+
newremoved = _combine_removed(-1, newremoved, newremoved2)
|
421 |
+
if isinstance(newexpr, ArrayTensorProduct):
|
422 |
+
newexpr, newremoved2 = _find_trivial_kronecker_products_broadcast(newexpr)
|
423 |
+
newremoved = _combine_removed(-1, newremoved, newremoved2)
|
424 |
+
return newexpr, newremoved
|
425 |
+
|
426 |
+
|
427 |
+
@_remove_trivial_dims.register(ArrayAdd)
|
428 |
+
def _(expr: ArrayAdd):
|
429 |
+
rec = [_remove_trivial_dims(arg) for arg in expr.args]
|
430 |
+
newargs, removed = zip(*rec)
|
431 |
+
if len({get_shape(i) for i in newargs}) > 1:
|
432 |
+
return expr, []
|
433 |
+
if len(removed) == 0:
|
434 |
+
return expr, removed
|
435 |
+
removed1 = removed[0]
|
436 |
+
return _a2m_add(*newargs), removed1
|
437 |
+
|
438 |
+
|
439 |
+
@_remove_trivial_dims.register(PermuteDims)
|
440 |
+
def _(expr: PermuteDims):
|
441 |
+
subexpr, subremoved = _remove_trivial_dims(expr.expr)
|
442 |
+
p = expr.permutation.array_form
|
443 |
+
pinv = _af_invert(expr.permutation.array_form)
|
444 |
+
shift = list(accumulate([1 if i in subremoved else 0 for i in range(len(p))]))
|
445 |
+
premoved = [pinv[i] for i in subremoved]
|
446 |
+
p2 = [e - shift[e] for i, e in enumerate(p) if e not in subremoved]
|
447 |
+
# TODO: check if subremoved should be permuted as well...
|
448 |
+
newexpr = _permute_dims(subexpr, p2)
|
449 |
+
premoved = sorted(premoved)
|
450 |
+
if newexpr != expr:
|
451 |
+
newexpr, removed2 = _remove_trivial_dims(_array2matrix(newexpr))
|
452 |
+
premoved = _combine_removed(-1, premoved, removed2)
|
453 |
+
return newexpr, premoved
|
454 |
+
|
455 |
+
|
456 |
+
@_remove_trivial_dims.register(ArrayContraction)
|
457 |
+
def _(expr: ArrayContraction):
|
458 |
+
new_expr, removed0 = _array_contraction_to_diagonal_multiple_identity(expr)
|
459 |
+
if new_expr != expr:
|
460 |
+
new_expr2, removed1 = _remove_trivial_dims(_array2matrix(new_expr))
|
461 |
+
removed = _combine_removed(-1, removed0, removed1)
|
462 |
+
return new_expr2, removed
|
463 |
+
rank1 = get_rank(expr)
|
464 |
+
expr, removed1 = remove_identity_matrices(expr)
|
465 |
+
if not isinstance(expr, ArrayContraction):
|
466 |
+
expr2, removed2 = _remove_trivial_dims(expr)
|
467 |
+
return expr2, _combine_removed(rank1, removed1, removed2)
|
468 |
+
newexpr, removed2 = _remove_trivial_dims(expr.expr)
|
469 |
+
shifts = list(accumulate([1 if i in removed2 else 0 for i in range(get_rank(expr.expr))]))
|
470 |
+
new_contraction_indices = [tuple(j for j in i if j not in removed2) for i in expr.contraction_indices]
|
471 |
+
# Remove possible empty tuples "()":
|
472 |
+
new_contraction_indices = [i for i in new_contraction_indices if len(i) > 0]
|
473 |
+
contraction_indices_flat = [j for i in expr.contraction_indices for j in i]
|
474 |
+
removed2 = [i for i in removed2 if i not in contraction_indices_flat]
|
475 |
+
new_contraction_indices = [tuple(j - shifts[j] for j in i) for i in new_contraction_indices]
|
476 |
+
# Shift removed2:
|
477 |
+
removed2 = ArrayContraction._push_indices_up(expr.contraction_indices, removed2)
|
478 |
+
removed = _combine_removed(rank1, removed1, removed2)
|
479 |
+
return _array_contraction(newexpr, *new_contraction_indices), list(removed)
|
480 |
+
|
481 |
+
|
482 |
+
def _remove_diagonalized_identity_matrices(expr: ArrayDiagonal):
|
483 |
+
assert isinstance(expr, ArrayDiagonal)
|
484 |
+
editor = _EditArrayContraction(expr)
|
485 |
+
mapping = {i: {j for j in editor.args_with_ind if i in j.indices} for i in range(-1, -1-editor.number_of_diagonal_indices, -1)}
|
486 |
+
removed = []
|
487 |
+
counter: int = 0
|
488 |
+
for i, arg_with_ind in enumerate(editor.args_with_ind):
|
489 |
+
counter += len(arg_with_ind.indices)
|
490 |
+
if isinstance(arg_with_ind.element, Identity):
|
491 |
+
if None in arg_with_ind.indices and any(i is not None and (i < 0) == True for i in arg_with_ind.indices):
|
492 |
+
diag_ind = [j for j in arg_with_ind.indices if j is not None][0]
|
493 |
+
other = [j for j in mapping[diag_ind] if j != arg_with_ind][0]
|
494 |
+
if not isinstance(other.element, MatrixExpr):
|
495 |
+
continue
|
496 |
+
if 1 not in other.element.shape:
|
497 |
+
continue
|
498 |
+
if None not in other.indices:
|
499 |
+
continue
|
500 |
+
editor.args_with_ind[i].element = None
|
501 |
+
none_index = other.indices.index(None)
|
502 |
+
other.element = DiagMatrix(other.element)
|
503 |
+
other_range = editor.get_absolute_range(other)
|
504 |
+
removed.extend([other_range[0] + none_index])
|
505 |
+
editor.args_with_ind = [i for i in editor.args_with_ind if i.element is not None]
|
506 |
+
removed = ArrayDiagonal._push_indices_up(expr.diagonal_indices, removed, get_rank(expr.expr))
|
507 |
+
return editor.to_array_contraction(), removed
|
508 |
+
|
509 |
+
|
510 |
+
@_remove_trivial_dims.register(ArrayDiagonal)
|
511 |
+
def _(expr: ArrayDiagonal):
|
512 |
+
newexpr, removed = _remove_trivial_dims(expr.expr)
|
513 |
+
shifts = list(accumulate([0] + [1 if i in removed else 0 for i in range(get_rank(expr.expr))]))
|
514 |
+
new_diag_indices_map = {i: tuple(j for j in i if j not in removed) for i in expr.diagonal_indices}
|
515 |
+
for old_diag_tuple, new_diag_tuple in new_diag_indices_map.items():
|
516 |
+
if len(new_diag_tuple) == 1:
|
517 |
+
removed = [i for i in removed if i not in old_diag_tuple]
|
518 |
+
new_diag_indices = [tuple(j - shifts[j] for j in i) for i in new_diag_indices_map.values()]
|
519 |
+
rank = get_rank(expr.expr)
|
520 |
+
removed = ArrayDiagonal._push_indices_up(expr.diagonal_indices, removed, rank)
|
521 |
+
removed = sorted(set(removed))
|
522 |
+
# If there are single axes to diagonalize remaining, it means that their
|
523 |
+
# corresponding dimension has been removed, they no longer need diagonalization:
|
524 |
+
new_diag_indices = [i for i in new_diag_indices if len(i) > 0]
|
525 |
+
if len(new_diag_indices) > 0:
|
526 |
+
newexpr2 = _array_diagonal(newexpr, *new_diag_indices, allow_trivial_diags=True)
|
527 |
+
else:
|
528 |
+
newexpr2 = newexpr
|
529 |
+
if isinstance(newexpr2, ArrayDiagonal):
|
530 |
+
newexpr3, removed2 = _remove_diagonalized_identity_matrices(newexpr2)
|
531 |
+
removed = _combine_removed(-1, removed, removed2)
|
532 |
+
return newexpr3, removed
|
533 |
+
else:
|
534 |
+
return newexpr2, removed
|
535 |
+
|
536 |
+
|
537 |
+
@_remove_trivial_dims.register(ElementwiseApplyFunction)
|
538 |
+
def _(expr: ElementwiseApplyFunction):
|
539 |
+
subexpr, removed = _remove_trivial_dims(expr.expr)
|
540 |
+
if subexpr.shape == (1, 1):
|
541 |
+
# TODO: move this to ElementwiseApplyFunction
|
542 |
+
return expr.function(subexpr), removed + [0, 1]
|
543 |
+
return ElementwiseApplyFunction(expr.function, subexpr), []
|
544 |
+
|
545 |
+
|
546 |
+
@_remove_trivial_dims.register(ArrayElementwiseApplyFunc)
|
547 |
+
def _(expr: ArrayElementwiseApplyFunc):
|
548 |
+
subexpr, removed = _remove_trivial_dims(expr.expr)
|
549 |
+
return ArrayElementwiseApplyFunc(expr.function, subexpr), removed
|
550 |
+
|
551 |
+
|
552 |
+
def convert_array_to_matrix(expr):
|
553 |
+
r"""
|
554 |
+
Recognize matrix expressions in codegen objects.
|
555 |
+
|
556 |
+
If more than one matrix multiplication line have been detected, return a
|
557 |
+
list with the matrix expressions.
|
558 |
+
|
559 |
+
Examples
|
560 |
+
========
|
561 |
+
|
562 |
+
>>> from sympy.tensor.array.expressions.from_indexed_to_array import convert_indexed_to_array
|
563 |
+
>>> from sympy.tensor.array import tensorcontraction, tensorproduct
|
564 |
+
>>> from sympy import MatrixSymbol, Sum
|
565 |
+
>>> from sympy.abc import i, j, k, l, N
|
566 |
+
>>> from sympy.tensor.array.expressions.from_matrix_to_array import convert_matrix_to_array
|
567 |
+
>>> from sympy.tensor.array.expressions.from_array_to_matrix import convert_array_to_matrix
|
568 |
+
>>> A = MatrixSymbol("A", N, N)
|
569 |
+
>>> B = MatrixSymbol("B", N, N)
|
570 |
+
>>> C = MatrixSymbol("C", N, N)
|
571 |
+
>>> D = MatrixSymbol("D", N, N)
|
572 |
+
|
573 |
+
>>> expr = Sum(A[i, j]*B[j, k], (j, 0, N-1))
|
574 |
+
>>> cg = convert_indexed_to_array(expr)
|
575 |
+
>>> convert_array_to_matrix(cg)
|
576 |
+
A*B
|
577 |
+
>>> cg = convert_indexed_to_array(expr, first_indices=[k])
|
578 |
+
>>> convert_array_to_matrix(cg)
|
579 |
+
B.T*A.T
|
580 |
+
|
581 |
+
Transposition is detected:
|
582 |
+
|
583 |
+
>>> expr = Sum(A[j, i]*B[j, k], (j, 0, N-1))
|
584 |
+
>>> cg = convert_indexed_to_array(expr)
|
585 |
+
>>> convert_array_to_matrix(cg)
|
586 |
+
A.T*B
|
587 |
+
>>> cg = convert_indexed_to_array(expr, first_indices=[k])
|
588 |
+
>>> convert_array_to_matrix(cg)
|
589 |
+
B.T*A
|
590 |
+
|
591 |
+
Detect the trace:
|
592 |
+
|
593 |
+
>>> expr = Sum(A[i, i], (i, 0, N-1))
|
594 |
+
>>> cg = convert_indexed_to_array(expr)
|
595 |
+
>>> convert_array_to_matrix(cg)
|
596 |
+
Trace(A)
|
597 |
+
|
598 |
+
Recognize some more complex traces:
|
599 |
+
|
600 |
+
>>> expr = Sum(A[i, j]*B[j, i], (i, 0, N-1), (j, 0, N-1))
|
601 |
+
>>> cg = convert_indexed_to_array(expr)
|
602 |
+
>>> convert_array_to_matrix(cg)
|
603 |
+
Trace(A*B)
|
604 |
+
|
605 |
+
More complicated expressions:
|
606 |
+
|
607 |
+
>>> expr = Sum(A[i, j]*B[k, j]*A[l, k], (j, 0, N-1), (k, 0, N-1))
|
608 |
+
>>> cg = convert_indexed_to_array(expr)
|
609 |
+
>>> convert_array_to_matrix(cg)
|
610 |
+
A*B.T*A.T
|
611 |
+
|
612 |
+
Expressions constructed from matrix expressions do not contain literal
|
613 |
+
indices, the positions of free indices are returned instead:
|
614 |
+
|
615 |
+
>>> expr = A*B
|
616 |
+
>>> cg = convert_matrix_to_array(expr)
|
617 |
+
>>> convert_array_to_matrix(cg)
|
618 |
+
A*B
|
619 |
+
|
620 |
+
If more than one line of matrix multiplications is detected, return
|
621 |
+
separate matrix multiplication factors embedded in a tensor product object:
|
622 |
+
|
623 |
+
>>> cg = tensorcontraction(tensorproduct(A, B, C, D), (1, 2), (5, 6))
|
624 |
+
>>> convert_array_to_matrix(cg)
|
625 |
+
ArrayTensorProduct(A*B, C*D)
|
626 |
+
|
627 |
+
The two lines have free indices at axes 0, 3 and 4, 7, respectively.
|
628 |
+
"""
|
629 |
+
rec = _array2matrix(expr)
|
630 |
+
rec, removed = _remove_trivial_dims(rec)
|
631 |
+
return rec
|
632 |
+
|
633 |
+
|
634 |
+
def _array_diag2contr_diagmatrix(expr: ArrayDiagonal):
|
635 |
+
if isinstance(expr.expr, ArrayTensorProduct):
|
636 |
+
args = list(expr.expr.args)
|
637 |
+
diag_indices = list(expr.diagonal_indices)
|
638 |
+
mapping = _get_mapping_from_subranks([_get_subrank(arg) for arg in args])
|
639 |
+
tuple_links = [[mapping[j] for j in i] for i in diag_indices]
|
640 |
+
contr_indices = []
|
641 |
+
total_rank = get_rank(expr)
|
642 |
+
replaced = [False for arg in args]
|
643 |
+
for i, (abs_pos, rel_pos) in enumerate(zip(diag_indices, tuple_links)):
|
644 |
+
if len(abs_pos) != 2:
|
645 |
+
continue
|
646 |
+
(pos1_outer, pos1_inner), (pos2_outer, pos2_inner) = rel_pos
|
647 |
+
arg1 = args[pos1_outer]
|
648 |
+
arg2 = args[pos2_outer]
|
649 |
+
if get_rank(arg1) != 2 or get_rank(arg2) != 2:
|
650 |
+
if replaced[pos1_outer]:
|
651 |
+
diag_indices[i] = None
|
652 |
+
if replaced[pos2_outer]:
|
653 |
+
diag_indices[i] = None
|
654 |
+
continue
|
655 |
+
pos1_in2 = 1 - pos1_inner
|
656 |
+
pos2_in2 = 1 - pos2_inner
|
657 |
+
if arg1.shape[pos1_in2] == 1:
|
658 |
+
if arg1.shape[pos1_inner] != 1:
|
659 |
+
darg1 = DiagMatrix(arg1)
|
660 |
+
else:
|
661 |
+
darg1 = arg1
|
662 |
+
args.append(darg1)
|
663 |
+
contr_indices.append(((pos2_outer, pos2_inner), (len(args)-1, pos1_inner)))
|
664 |
+
total_rank += 1
|
665 |
+
diag_indices[i] = None
|
666 |
+
args[pos1_outer] = OneArray(arg1.shape[pos1_in2])
|
667 |
+
replaced[pos1_outer] = True
|
668 |
+
elif arg2.shape[pos2_in2] == 1:
|
669 |
+
if arg2.shape[pos2_inner] != 1:
|
670 |
+
darg2 = DiagMatrix(arg2)
|
671 |
+
else:
|
672 |
+
darg2 = arg2
|
673 |
+
args.append(darg2)
|
674 |
+
contr_indices.append(((pos1_outer, pos1_inner), (len(args)-1, pos2_inner)))
|
675 |
+
total_rank += 1
|
676 |
+
diag_indices[i] = None
|
677 |
+
args[pos2_outer] = OneArray(arg2.shape[pos2_in2])
|
678 |
+
replaced[pos2_outer] = True
|
679 |
+
diag_indices_new = [i for i in diag_indices if i is not None]
|
680 |
+
cumul = list(accumulate([0] + [get_rank(arg) for arg in args]))
|
681 |
+
contr_indices2 = [tuple(cumul[a] + b for a, b in i) for i in contr_indices]
|
682 |
+
tc = _array_contraction(
|
683 |
+
_array_tensor_product(*args), *contr_indices2
|
684 |
+
)
|
685 |
+
td = _array_diagonal(tc, *diag_indices_new)
|
686 |
+
return td
|
687 |
+
return expr
|
688 |
+
|
689 |
+
|
690 |
+
def _a2m_mul(*args):
|
691 |
+
if not any(isinstance(i, _CodegenArrayAbstract) for i in args):
|
692 |
+
from sympy.matrices.expressions.matmul import MatMul
|
693 |
+
return MatMul(*args).doit()
|
694 |
+
else:
|
695 |
+
return _array_contraction(
|
696 |
+
_array_tensor_product(*args),
|
697 |
+
*[(2*i-1, 2*i) for i in range(1, len(args))]
|
698 |
+
)
|
699 |
+
|
700 |
+
|
701 |
+
def _a2m_tensor_product(*args):
|
702 |
+
scalars = []
|
703 |
+
arrays = []
|
704 |
+
for arg in args:
|
705 |
+
if isinstance(arg, (MatrixExpr, _ArrayExpr, _CodegenArrayAbstract)):
|
706 |
+
arrays.append(arg)
|
707 |
+
else:
|
708 |
+
scalars.append(arg)
|
709 |
+
scalar = Mul.fromiter(scalars)
|
710 |
+
if len(arrays) == 0:
|
711 |
+
return scalar
|
712 |
+
if scalar != 1:
|
713 |
+
if isinstance(arrays[0], _CodegenArrayAbstract):
|
714 |
+
arrays = [scalar] + arrays
|
715 |
+
else:
|
716 |
+
arrays[0] *= scalar
|
717 |
+
return _array_tensor_product(*arrays)
|
718 |
+
|
719 |
+
|
720 |
+
def _a2m_add(*args):
|
721 |
+
if not any(isinstance(i, _CodegenArrayAbstract) for i in args):
|
722 |
+
from sympy.matrices.expressions.matadd import MatAdd
|
723 |
+
return MatAdd(*args).doit()
|
724 |
+
else:
|
725 |
+
return _array_add(*args)
|
726 |
+
|
727 |
+
|
728 |
+
def _a2m_trace(arg):
|
729 |
+
if isinstance(arg, _CodegenArrayAbstract):
|
730 |
+
return _array_contraction(arg, (0, 1))
|
731 |
+
else:
|
732 |
+
from sympy.matrices.expressions.trace import Trace
|
733 |
+
return Trace(arg)
|
734 |
+
|
735 |
+
|
736 |
+
def _a2m_transpose(arg):
|
737 |
+
if isinstance(arg, _CodegenArrayAbstract):
|
738 |
+
return _permute_dims(arg, [1, 0])
|
739 |
+
else:
|
740 |
+
from sympy.matrices.expressions.transpose import Transpose
|
741 |
+
return Transpose(arg).doit()
|
742 |
+
|
743 |
+
|
744 |
+
def identify_hadamard_products(expr: tUnion[ArrayContraction, ArrayDiagonal]):
|
745 |
+
|
746 |
+
editor: _EditArrayContraction = _EditArrayContraction(expr)
|
747 |
+
|
748 |
+
map_contr_to_args: tDict[FrozenSet, List[_ArgE]] = defaultdict(list)
|
749 |
+
map_ind_to_inds: tDict[Optional[int], int] = defaultdict(int)
|
750 |
+
for arg_with_ind in editor.args_with_ind:
|
751 |
+
for ind in arg_with_ind.indices:
|
752 |
+
map_ind_to_inds[ind] += 1
|
753 |
+
if None in arg_with_ind.indices:
|
754 |
+
continue
|
755 |
+
map_contr_to_args[frozenset(arg_with_ind.indices)].append(arg_with_ind)
|
756 |
+
|
757 |
+
k: FrozenSet[int]
|
758 |
+
v: List[_ArgE]
|
759 |
+
for k, v in map_contr_to_args.items():
|
760 |
+
make_trace: bool = False
|
761 |
+
if len(k) == 1 and next(iter(k)) >= 0 and sum([next(iter(k)) in i for i in map_contr_to_args]) == 1:
|
762 |
+
# This is a trace: the arguments are fully contracted with only one
|
763 |
+
# index, and the index isn't used anywhere else:
|
764 |
+
make_trace = True
|
765 |
+
first_element = S.One
|
766 |
+
elif len(k) != 2:
|
767 |
+
# Hadamard product only defined for matrices:
|
768 |
+
continue
|
769 |
+
if len(v) == 1:
|
770 |
+
# Hadamard product with a single argument makes no sense:
|
771 |
+
continue
|
772 |
+
for ind in k:
|
773 |
+
if map_ind_to_inds[ind] <= 2:
|
774 |
+
# There is no other contraction, skip:
|
775 |
+
continue
|
776 |
+
|
777 |
+
def check_transpose(x):
|
778 |
+
x = [i if i >= 0 else -1-i for i in x]
|
779 |
+
return x == sorted(x)
|
780 |
+
|
781 |
+
# Check if expression is a trace:
|
782 |
+
if all([map_ind_to_inds[j] == len(v) and j >= 0 for j in k]) and all([j >= 0 for j in k]):
|
783 |
+
# This is a trace
|
784 |
+
make_trace = True
|
785 |
+
first_element = v[0].element
|
786 |
+
if not check_transpose(v[0].indices):
|
787 |
+
first_element = first_element.T
|
788 |
+
hadamard_factors = v[1:]
|
789 |
+
else:
|
790 |
+
hadamard_factors = v
|
791 |
+
|
792 |
+
# This is a Hadamard product:
|
793 |
+
|
794 |
+
hp = hadamard_product(*[i.element if check_transpose(i.indices) else Transpose(i.element) for i in hadamard_factors])
|
795 |
+
hp_indices = v[0].indices
|
796 |
+
if not check_transpose(hadamard_factors[0].indices):
|
797 |
+
hp_indices = list(reversed(hp_indices))
|
798 |
+
if make_trace:
|
799 |
+
hp = Trace(first_element*hp.T)._normalize()
|
800 |
+
hp_indices = []
|
801 |
+
editor.insert_after(v[0], _ArgE(hp, hp_indices))
|
802 |
+
for i in v:
|
803 |
+
editor.args_with_ind.remove(i)
|
804 |
+
|
805 |
+
return editor.to_array_contraction()
|
806 |
+
|
807 |
+
|
808 |
+
def identify_removable_identity_matrices(expr):
|
809 |
+
editor = _EditArrayContraction(expr)
|
810 |
+
|
811 |
+
flag = True
|
812 |
+
while flag:
|
813 |
+
flag = False
|
814 |
+
for arg_with_ind in editor.args_with_ind:
|
815 |
+
if isinstance(arg_with_ind.element, Identity):
|
816 |
+
k = arg_with_ind.element.shape[0]
|
817 |
+
# Candidate for removal:
|
818 |
+
if arg_with_ind.indices == [None, None]:
|
819 |
+
# Free identity matrix, will be cleared by _remove_trivial_dims:
|
820 |
+
continue
|
821 |
+
elif None in arg_with_ind.indices:
|
822 |
+
ind = [j for j in arg_with_ind.indices if j is not None][0]
|
823 |
+
counted = editor.count_args_with_index(ind)
|
824 |
+
if counted == 1:
|
825 |
+
# Identity matrix contracted only on one index with itself,
|
826 |
+
# transform to a OneArray(k) element:
|
827 |
+
editor.insert_after(arg_with_ind, OneArray(k))
|
828 |
+
editor.args_with_ind.remove(arg_with_ind)
|
829 |
+
flag = True
|
830 |
+
break
|
831 |
+
elif counted > 2:
|
832 |
+
# Case counted = 2 is a matrix multiplication by identity matrix, skip it.
|
833 |
+
# Case counted > 2 is a multiple contraction,
|
834 |
+
# this is a case where the contraction becomes a diagonalization if the
|
835 |
+
# identity matrix is dropped.
|
836 |
+
continue
|
837 |
+
elif arg_with_ind.indices[0] == arg_with_ind.indices[1]:
|
838 |
+
ind = arg_with_ind.indices[0]
|
839 |
+
counted = editor.count_args_with_index(ind)
|
840 |
+
if counted > 1:
|
841 |
+
editor.args_with_ind.remove(arg_with_ind)
|
842 |
+
flag = True
|
843 |
+
break
|
844 |
+
else:
|
845 |
+
# This is a trace, skip it as it will be recognized somewhere else:
|
846 |
+
pass
|
847 |
+
elif ask(Q.diagonal(arg_with_ind.element)):
|
848 |
+
if arg_with_ind.indices == [None, None]:
|
849 |
+
continue
|
850 |
+
elif None in arg_with_ind.indices:
|
851 |
+
pass
|
852 |
+
elif arg_with_ind.indices[0] == arg_with_ind.indices[1]:
|
853 |
+
ind = arg_with_ind.indices[0]
|
854 |
+
counted = editor.count_args_with_index(ind)
|
855 |
+
if counted == 3:
|
856 |
+
# A_ai B_bi D_ii ==> A_ai D_ij B_bj
|
857 |
+
ind_new = editor.get_new_contraction_index()
|
858 |
+
other_args = [j for j in editor.args_with_ind if j != arg_with_ind]
|
859 |
+
other_args[1].indices = [ind_new if j == ind else j for j in other_args[1].indices]
|
860 |
+
arg_with_ind.indices = [ind, ind_new]
|
861 |
+
flag = True
|
862 |
+
break
|
863 |
+
|
864 |
+
return editor.to_array_contraction()
|
865 |
+
|
866 |
+
|
867 |
+
def remove_identity_matrices(expr: ArrayContraction):
|
868 |
+
editor = _EditArrayContraction(expr)
|
869 |
+
removed: List[int] = []
|
870 |
+
|
871 |
+
permutation_map = {}
|
872 |
+
|
873 |
+
free_indices = list(accumulate([0] + [sum([i is None for i in arg.indices]) for arg in editor.args_with_ind]))
|
874 |
+
free_map = {k: v for k, v in zip(editor.args_with_ind, free_indices[:-1])}
|
875 |
+
|
876 |
+
update_pairs = {}
|
877 |
+
|
878 |
+
for ind in range(editor.number_of_contraction_indices):
|
879 |
+
args = editor.get_args_with_index(ind)
|
880 |
+
identity_matrices = [i for i in args if isinstance(i.element, Identity)]
|
881 |
+
number_identity_matrices = len(identity_matrices)
|
882 |
+
# If the contraction involves a non-identity matrix and multiple identity matrices:
|
883 |
+
if number_identity_matrices != len(args) - 1 or number_identity_matrices == 0:
|
884 |
+
continue
|
885 |
+
# Get the non-identity element:
|
886 |
+
non_identity = [i for i in args if not isinstance(i.element, Identity)][0]
|
887 |
+
# Check that all identity matrices have at least one free index
|
888 |
+
# (otherwise they would be contractions to some other elements)
|
889 |
+
if any([None not in i.indices for i in identity_matrices]):
|
890 |
+
continue
|
891 |
+
# Mark the identity matrices for removal:
|
892 |
+
for i in identity_matrices:
|
893 |
+
i.element = None
|
894 |
+
removed.extend(range(free_map[i], free_map[i] + len([j for j in i.indices if j is None])))
|
895 |
+
last_removed = removed.pop(-1)
|
896 |
+
update_pairs[last_removed, ind] = non_identity.indices[:]
|
897 |
+
# Remove the indices from the non-identity matrix, as the contraction
|
898 |
+
# no longer exists:
|
899 |
+
non_identity.indices = [None if i == ind else i for i in non_identity.indices]
|
900 |
+
|
901 |
+
removed.sort()
|
902 |
+
|
903 |
+
shifts = list(accumulate([1 if i in removed else 0 for i in range(get_rank(expr))]))
|
904 |
+
for (last_removed, ind), non_identity_indices in update_pairs.items():
|
905 |
+
pos = [free_map[non_identity] + i for i, e in enumerate(non_identity_indices) if e == ind]
|
906 |
+
assert len(pos) == 1
|
907 |
+
for j in pos:
|
908 |
+
permutation_map[j] = last_removed
|
909 |
+
|
910 |
+
editor.args_with_ind = [i for i in editor.args_with_ind if i.element is not None]
|
911 |
+
ret_expr = editor.to_array_contraction()
|
912 |
+
permutation = []
|
913 |
+
counter = 0
|
914 |
+
counter2 = 0
|
915 |
+
for j in range(get_rank(expr)):
|
916 |
+
if j in removed:
|
917 |
+
continue
|
918 |
+
if counter2 in permutation_map:
|
919 |
+
target = permutation_map[counter2]
|
920 |
+
permutation.append(target - shifts[target])
|
921 |
+
counter2 += 1
|
922 |
+
else:
|
923 |
+
while counter in permutation_map.values():
|
924 |
+
counter += 1
|
925 |
+
permutation.append(counter)
|
926 |
+
counter += 1
|
927 |
+
counter2 += 1
|
928 |
+
ret_expr2 = _permute_dims(ret_expr, _af_invert(permutation))
|
929 |
+
return ret_expr2, removed
|
930 |
+
|
931 |
+
|
932 |
+
def _combine_removed(dim: int, removed1: List[int], removed2: List[int]) -> List[int]:
|
933 |
+
# Concatenate two axis removal operations as performed by
|
934 |
+
# _remove_trivial_dims,
|
935 |
+
removed1 = sorted(removed1)
|
936 |
+
removed2 = sorted(removed2)
|
937 |
+
i = 0
|
938 |
+
j = 0
|
939 |
+
removed = []
|
940 |
+
while True:
|
941 |
+
if j >= len(removed2):
|
942 |
+
while i < len(removed1):
|
943 |
+
removed.append(removed1[i])
|
944 |
+
i += 1
|
945 |
+
break
|
946 |
+
elif i < len(removed1) and removed1[i] <= i + removed2[j]:
|
947 |
+
removed.append(removed1[i])
|
948 |
+
i += 1
|
949 |
+
else:
|
950 |
+
removed.append(i + removed2[j])
|
951 |
+
j += 1
|
952 |
+
return removed
|
953 |
+
|
954 |
+
|
955 |
+
def _array_contraction_to_diagonal_multiple_identity(expr: ArrayContraction):
|
956 |
+
editor = _EditArrayContraction(expr)
|
957 |
+
editor.track_permutation_start()
|
958 |
+
removed: List[int] = []
|
959 |
+
diag_index_counter: int = 0
|
960 |
+
for i in range(editor.number_of_contraction_indices):
|
961 |
+
identities = []
|
962 |
+
args = []
|
963 |
+
for j, arg in enumerate(editor.args_with_ind):
|
964 |
+
if i not in arg.indices:
|
965 |
+
continue
|
966 |
+
if isinstance(arg.element, Identity):
|
967 |
+
identities.append(arg)
|
968 |
+
else:
|
969 |
+
args.append(arg)
|
970 |
+
if len(identities) == 0:
|
971 |
+
continue
|
972 |
+
if len(args) + len(identities) < 3:
|
973 |
+
continue
|
974 |
+
new_diag_ind = -1 - diag_index_counter
|
975 |
+
diag_index_counter += 1
|
976 |
+
# Variable "flag" to control whether to skip this contraction set:
|
977 |
+
flag: bool = True
|
978 |
+
for i1, id1 in enumerate(identities):
|
979 |
+
if None not in id1.indices:
|
980 |
+
flag = True
|
981 |
+
break
|
982 |
+
free_pos = list(range(*editor.get_absolute_free_range(id1)))[0]
|
983 |
+
editor._track_permutation[-1].append(free_pos) # type: ignore
|
984 |
+
id1.element = None
|
985 |
+
flag = False
|
986 |
+
break
|
987 |
+
if flag:
|
988 |
+
continue
|
989 |
+
for arg in identities[:i1] + identities[i1+1:]:
|
990 |
+
arg.element = None
|
991 |
+
removed.extend(range(*editor.get_absolute_free_range(arg)))
|
992 |
+
for arg in args:
|
993 |
+
arg.indices = [new_diag_ind if j == i else j for j in arg.indices]
|
994 |
+
for j, e in enumerate(editor.args_with_ind):
|
995 |
+
if e.element is None:
|
996 |
+
editor._track_permutation[j] = None # type: ignore
|
997 |
+
editor._track_permutation = [i for i in editor._track_permutation if i is not None] # type: ignore
|
998 |
+
# Renumber permutation array form in order to deal with deleted positions:
|
999 |
+
remap = {e: i for i, e in enumerate(sorted({k for j in editor._track_permutation for k in j}))}
|
1000 |
+
editor._track_permutation = [[remap[j] for j in i] for i in editor._track_permutation]
|
1001 |
+
editor.args_with_ind = [i for i in editor.args_with_ind if i.element is not None]
|
1002 |
+
new_expr = editor.to_array_contraction()
|
1003 |
+
return new_expr, removed
|
env-llmeval/lib/python3.10/site-packages/sympy/tensor/array/expressions/from_matrix_to_array.py
ADDED
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy import KroneckerProduct
|
2 |
+
from sympy.core.basic import Basic
|
3 |
+
from sympy.core.function import Lambda
|
4 |
+
from sympy.core.mul import Mul
|
5 |
+
from sympy.core.numbers import Integer
|
6 |
+
from sympy.core.power import Pow
|
7 |
+
from sympy.core.singleton import S
|
8 |
+
from sympy.core.symbol import (Dummy, symbols)
|
9 |
+
from sympy.matrices.expressions.hadamard import (HadamardPower, HadamardProduct)
|
10 |
+
from sympy.matrices.expressions.matadd import MatAdd
|
11 |
+
from sympy.matrices.expressions.matmul import MatMul
|
12 |
+
from sympy.matrices.expressions.matpow import MatPow
|
13 |
+
from sympy.matrices.expressions.trace import Trace
|
14 |
+
from sympy.matrices.expressions.transpose import Transpose
|
15 |
+
from sympy.matrices.expressions.matexpr import MatrixExpr
|
16 |
+
from sympy.tensor.array.expressions.array_expressions import \
|
17 |
+
ArrayElementwiseApplyFunc, _array_tensor_product, _array_contraction, \
|
18 |
+
_array_diagonal, _array_add, _permute_dims, Reshape
|
19 |
+
|
20 |
+
|
21 |
+
def convert_matrix_to_array(expr: Basic) -> Basic:
|
22 |
+
if isinstance(expr, MatMul):
|
23 |
+
args_nonmat = []
|
24 |
+
args = []
|
25 |
+
for arg in expr.args:
|
26 |
+
if isinstance(arg, MatrixExpr):
|
27 |
+
args.append(arg)
|
28 |
+
else:
|
29 |
+
args_nonmat.append(convert_matrix_to_array(arg))
|
30 |
+
contractions = [(2*i+1, 2*i+2) for i in range(len(args)-1)]
|
31 |
+
scalar = _array_tensor_product(*args_nonmat) if args_nonmat else S.One
|
32 |
+
if scalar == 1:
|
33 |
+
tprod = _array_tensor_product(
|
34 |
+
*[convert_matrix_to_array(arg) for arg in args])
|
35 |
+
else:
|
36 |
+
tprod = _array_tensor_product(
|
37 |
+
scalar,
|
38 |
+
*[convert_matrix_to_array(arg) for arg in args])
|
39 |
+
return _array_contraction(
|
40 |
+
tprod,
|
41 |
+
*contractions
|
42 |
+
)
|
43 |
+
elif isinstance(expr, MatAdd):
|
44 |
+
return _array_add(
|
45 |
+
*[convert_matrix_to_array(arg) for arg in expr.args]
|
46 |
+
)
|
47 |
+
elif isinstance(expr, Transpose):
|
48 |
+
return _permute_dims(
|
49 |
+
convert_matrix_to_array(expr.args[0]), [1, 0]
|
50 |
+
)
|
51 |
+
elif isinstance(expr, Trace):
|
52 |
+
inner_expr: MatrixExpr = convert_matrix_to_array(expr.arg) # type: ignore
|
53 |
+
return _array_contraction(inner_expr, (0, len(inner_expr.shape) - 1))
|
54 |
+
elif isinstance(expr, Mul):
|
55 |
+
return _array_tensor_product(*[convert_matrix_to_array(i) for i in expr.args])
|
56 |
+
elif isinstance(expr, Pow):
|
57 |
+
base = convert_matrix_to_array(expr.base)
|
58 |
+
if (expr.exp > 0) == True:
|
59 |
+
return _array_tensor_product(*[base for i in range(expr.exp)])
|
60 |
+
else:
|
61 |
+
return expr
|
62 |
+
elif isinstance(expr, MatPow):
|
63 |
+
base = convert_matrix_to_array(expr.base)
|
64 |
+
if expr.exp.is_Integer != True:
|
65 |
+
b = symbols("b", cls=Dummy)
|
66 |
+
return ArrayElementwiseApplyFunc(Lambda(b, b**expr.exp), convert_matrix_to_array(base))
|
67 |
+
elif (expr.exp > 0) == True:
|
68 |
+
return convert_matrix_to_array(MatMul.fromiter(base for i in range(expr.exp)))
|
69 |
+
else:
|
70 |
+
return expr
|
71 |
+
elif isinstance(expr, HadamardProduct):
|
72 |
+
tp = _array_tensor_product(*[convert_matrix_to_array(arg) for arg in expr.args])
|
73 |
+
diag = [[2*i for i in range(len(expr.args))], [2*i+1 for i in range(len(expr.args))]]
|
74 |
+
return _array_diagonal(tp, *diag)
|
75 |
+
elif isinstance(expr, HadamardPower):
|
76 |
+
base, exp = expr.args
|
77 |
+
if isinstance(exp, Integer) and exp > 0:
|
78 |
+
return convert_matrix_to_array(HadamardProduct.fromiter(base for i in range(exp)))
|
79 |
+
else:
|
80 |
+
d = Dummy("d")
|
81 |
+
return ArrayElementwiseApplyFunc(Lambda(d, d**exp), base)
|
82 |
+
elif isinstance(expr, KroneckerProduct):
|
83 |
+
kp_args = [convert_matrix_to_array(arg) for arg in expr.args]
|
84 |
+
permutation = [2*i for i in range(len(kp_args))] + [2*i + 1 for i in range(len(kp_args))]
|
85 |
+
return Reshape(_permute_dims(_array_tensor_product(*kp_args), permutation), expr.shape)
|
86 |
+
else:
|
87 |
+
return expr
|