Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- llmeval-env/lib/python3.10/site-packages/sympy/core/assumptions.py +692 -0
- llmeval-env/lib/python3.10/site-packages/sympy/core/assumptions_generated.py +1615 -0
- llmeval-env/lib/python3.10/site-packages/sympy/core/basic.py +2233 -0
- llmeval-env/lib/python3.10/site-packages/sympy/core/evalf.py +1801 -0
- llmeval-env/lib/python3.10/site-packages/sympy/core/exprtools.py +1569 -0
- llmeval-env/lib/python3.10/site-packages/sympy/core/facts.py +634 -0
- llmeval-env/lib/python3.10/site-packages/sympy/core/kind.py +388 -0
- llmeval-env/lib/python3.10/site-packages/sympy/core/mul.py +2195 -0
- llmeval-env/lib/python3.10/site-packages/sympy/core/parameters.py +161 -0
- llmeval-env/lib/python3.10/site-packages/sympy/discrete/__init__.py +20 -0
- llmeval-env/lib/python3.10/site-packages/sympy/discrete/__pycache__/__init__.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/discrete/__pycache__/convolutions.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/discrete/__pycache__/recurrences.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/discrete/__pycache__/transforms.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/discrete/convolutions.py +488 -0
- llmeval-env/lib/python3.10/site-packages/sympy/discrete/recurrences.py +166 -0
- llmeval-env/lib/python3.10/site-packages/sympy/discrete/tests/__init__.py +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/discrete/tests/__pycache__/__init__.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/discrete/tests/__pycache__/test_convolutions.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/discrete/tests/__pycache__/test_recurrences.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/discrete/tests/__pycache__/test_transforms.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/discrete/tests/test_convolutions.py +365 -0
- llmeval-env/lib/python3.10/site-packages/sympy/discrete/tests/test_recurrences.py +59 -0
- llmeval-env/lib/python3.10/site-packages/sympy/discrete/tests/test_transforms.py +154 -0
- llmeval-env/lib/python3.10/site-packages/sympy/discrete/transforms.py +425 -0
- llmeval-env/lib/python3.10/site-packages/sympy/solvers/__pycache__/__init__.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/solvers/__pycache__/bivariate.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/solvers/__pycache__/decompogen.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/solvers/__pycache__/deutils.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/solvers/__pycache__/inequalities.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/solvers/__pycache__/pde.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/solvers/__pycache__/polysys.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/solvers/__pycache__/recurr.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/solvers/__pycache__/solvers.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/solvers/__pycache__/solveset.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/solvers/diophantine/__init__.py +5 -0
- llmeval-env/lib/python3.10/site-packages/sympy/solvers/diophantine/__pycache__/__init__.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/solvers/diophantine/__pycache__/diophantine.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/solvers/diophantine/diophantine.py +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/solvers/diophantine/tests/__init__.py +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/solvers/diophantine/tests/__pycache__/__init__.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/solvers/diophantine/tests/__pycache__/test_diophantine.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/solvers/diophantine/tests/test_diophantine.py +1037 -0
- llmeval-env/lib/python3.10/site-packages/sympy/solvers/ode/__pycache__/__init__.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/solvers/ode/__pycache__/hypergeometric.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/solvers/ode/__pycache__/lie_group.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/solvers/ode/__pycache__/nonhomogeneous.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/solvers/ode/__pycache__/ode.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/solvers/ode/__pycache__/riccati.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/solvers/ode/__pycache__/single.cpython-310.pyc +0 -0
llmeval-env/lib/python3.10/site-packages/sympy/core/assumptions.py
ADDED
@@ -0,0 +1,692 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
This module contains the machinery handling assumptions.
|
3 |
+
Do also consider the guide :ref:`assumptions-guide`.
|
4 |
+
|
5 |
+
All symbolic objects have assumption attributes that can be accessed via
|
6 |
+
``.is_<assumption name>`` attribute.
|
7 |
+
|
8 |
+
Assumptions determine certain properties of symbolic objects and can
|
9 |
+
have 3 possible values: ``True``, ``False``, ``None``. ``True`` is returned if the
|
10 |
+
object has the property and ``False`` is returned if it does not or cannot
|
11 |
+
(i.e. does not make sense):
|
12 |
+
|
13 |
+
>>> from sympy import I
|
14 |
+
>>> I.is_algebraic
|
15 |
+
True
|
16 |
+
>>> I.is_real
|
17 |
+
False
|
18 |
+
>>> I.is_prime
|
19 |
+
False
|
20 |
+
|
21 |
+
When the property cannot be determined (or when a method is not
|
22 |
+
implemented) ``None`` will be returned. For example, a generic symbol, ``x``,
|
23 |
+
may or may not be positive so a value of ``None`` is returned for ``x.is_positive``.
|
24 |
+
|
25 |
+
By default, all symbolic values are in the largest set in the given context
|
26 |
+
without specifying the property. For example, a symbol that has a property
|
27 |
+
being integer, is also real, complex, etc.
|
28 |
+
|
29 |
+
Here follows a list of possible assumption names:
|
30 |
+
|
31 |
+
.. glossary::
|
32 |
+
|
33 |
+
commutative
|
34 |
+
object commutes with any other object with
|
35 |
+
respect to multiplication operation. See [12]_.
|
36 |
+
|
37 |
+
complex
|
38 |
+
object can have only values from the set
|
39 |
+
of complex numbers. See [13]_.
|
40 |
+
|
41 |
+
imaginary
|
42 |
+
object value is a number that can be written as a real
|
43 |
+
number multiplied by the imaginary unit ``I``. See
|
44 |
+
[3]_. Please note that ``0`` is not considered to be an
|
45 |
+
imaginary number, see
|
46 |
+
`issue #7649 <https://github.com/sympy/sympy/issues/7649>`_.
|
47 |
+
|
48 |
+
real
|
49 |
+
object can have only values from the set
|
50 |
+
of real numbers.
|
51 |
+
|
52 |
+
extended_real
|
53 |
+
object can have only values from the set
|
54 |
+
of real numbers, ``oo`` and ``-oo``.
|
55 |
+
|
56 |
+
integer
|
57 |
+
object can have only values from the set
|
58 |
+
of integers.
|
59 |
+
|
60 |
+
odd
|
61 |
+
even
|
62 |
+
object can have only values from the set of
|
63 |
+
odd (even) integers [2]_.
|
64 |
+
|
65 |
+
prime
|
66 |
+
object is a natural number greater than 1 that has
|
67 |
+
no positive divisors other than 1 and itself. See [6]_.
|
68 |
+
|
69 |
+
composite
|
70 |
+
object is a positive integer that has at least one positive
|
71 |
+
divisor other than 1 or the number itself. See [4]_.
|
72 |
+
|
73 |
+
zero
|
74 |
+
object has the value of 0.
|
75 |
+
|
76 |
+
nonzero
|
77 |
+
object is a real number that is not zero.
|
78 |
+
|
79 |
+
rational
|
80 |
+
object can have only values from the set
|
81 |
+
of rationals.
|
82 |
+
|
83 |
+
algebraic
|
84 |
+
object can have only values from the set
|
85 |
+
of algebraic numbers [11]_.
|
86 |
+
|
87 |
+
transcendental
|
88 |
+
object can have only values from the set
|
89 |
+
of transcendental numbers [10]_.
|
90 |
+
|
91 |
+
irrational
|
92 |
+
object value cannot be represented exactly by :class:`~.Rational`, see [5]_.
|
93 |
+
|
94 |
+
finite
|
95 |
+
infinite
|
96 |
+
object absolute value is bounded (arbitrarily large).
|
97 |
+
See [7]_, [8]_, [9]_.
|
98 |
+
|
99 |
+
negative
|
100 |
+
nonnegative
|
101 |
+
object can have only negative (nonnegative)
|
102 |
+
values [1]_.
|
103 |
+
|
104 |
+
positive
|
105 |
+
nonpositive
|
106 |
+
object can have only positive (nonpositive) values.
|
107 |
+
|
108 |
+
extended_negative
|
109 |
+
extended_nonnegative
|
110 |
+
extended_positive
|
111 |
+
extended_nonpositive
|
112 |
+
extended_nonzero
|
113 |
+
as without the extended part, but also including infinity with
|
114 |
+
corresponding sign, e.g., extended_positive includes ``oo``
|
115 |
+
|
116 |
+
hermitian
|
117 |
+
antihermitian
|
118 |
+
object belongs to the field of Hermitian
|
119 |
+
(antihermitian) operators.
|
120 |
+
|
121 |
+
Examples
|
122 |
+
========
|
123 |
+
|
124 |
+
>>> from sympy import Symbol
|
125 |
+
>>> x = Symbol('x', real=True); x
|
126 |
+
x
|
127 |
+
>>> x.is_real
|
128 |
+
True
|
129 |
+
>>> x.is_complex
|
130 |
+
True
|
131 |
+
|
132 |
+
See Also
|
133 |
+
========
|
134 |
+
|
135 |
+
.. seealso::
|
136 |
+
|
137 |
+
:py:class:`sympy.core.numbers.ImaginaryUnit`
|
138 |
+
:py:class:`sympy.core.numbers.Zero`
|
139 |
+
:py:class:`sympy.core.numbers.One`
|
140 |
+
:py:class:`sympy.core.numbers.Infinity`
|
141 |
+
:py:class:`sympy.core.numbers.NegativeInfinity`
|
142 |
+
:py:class:`sympy.core.numbers.ComplexInfinity`
|
143 |
+
|
144 |
+
Notes
|
145 |
+
=====
|
146 |
+
|
147 |
+
The fully-resolved assumptions for any SymPy expression
|
148 |
+
can be obtained as follows:
|
149 |
+
|
150 |
+
>>> from sympy.core.assumptions import assumptions
|
151 |
+
>>> x = Symbol('x',positive=True)
|
152 |
+
>>> assumptions(x + I)
|
153 |
+
{'commutative': True, 'complex': True, 'composite': False, 'even':
|
154 |
+
False, 'extended_negative': False, 'extended_nonnegative': False,
|
155 |
+
'extended_nonpositive': False, 'extended_nonzero': False,
|
156 |
+
'extended_positive': False, 'extended_real': False, 'finite': True,
|
157 |
+
'imaginary': False, 'infinite': False, 'integer': False, 'irrational':
|
158 |
+
False, 'negative': False, 'noninteger': False, 'nonnegative': False,
|
159 |
+
'nonpositive': False, 'nonzero': False, 'odd': False, 'positive':
|
160 |
+
False, 'prime': False, 'rational': False, 'real': False, 'zero':
|
161 |
+
False}
|
162 |
+
|
163 |
+
Developers Notes
|
164 |
+
================
|
165 |
+
|
166 |
+
The current (and possibly incomplete) values are stored
|
167 |
+
in the ``obj._assumptions dictionary``; queries to getter methods
|
168 |
+
(with property decorators) or attributes of objects/classes
|
169 |
+
will return values and update the dictionary.
|
170 |
+
|
171 |
+
>>> eq = x**2 + I
|
172 |
+
>>> eq._assumptions
|
173 |
+
{}
|
174 |
+
>>> eq.is_finite
|
175 |
+
True
|
176 |
+
>>> eq._assumptions
|
177 |
+
{'finite': True, 'infinite': False}
|
178 |
+
|
179 |
+
For a :class:`~.Symbol`, there are two locations for assumptions that may
|
180 |
+
be of interest. The ``assumptions0`` attribute gives the full set of
|
181 |
+
assumptions derived from a given set of initial assumptions. The
|
182 |
+
latter assumptions are stored as ``Symbol._assumptions_orig``
|
183 |
+
|
184 |
+
>>> Symbol('x', prime=True, even=True)._assumptions_orig
|
185 |
+
{'even': True, 'prime': True}
|
186 |
+
|
187 |
+
The ``_assumptions_orig`` are not necessarily canonical nor are they filtered
|
188 |
+
in any way: they records the assumptions used to instantiate a Symbol and (for
|
189 |
+
storage purposes) represent a more compact representation of the assumptions
|
190 |
+
needed to recreate the full set in ``Symbol.assumptions0``.
|
191 |
+
|
192 |
+
|
193 |
+
References
|
194 |
+
==========
|
195 |
+
|
196 |
+
.. [1] https://en.wikipedia.org/wiki/Negative_number
|
197 |
+
.. [2] https://en.wikipedia.org/wiki/Parity_%28mathematics%29
|
198 |
+
.. [3] https://en.wikipedia.org/wiki/Imaginary_number
|
199 |
+
.. [4] https://en.wikipedia.org/wiki/Composite_number
|
200 |
+
.. [5] https://en.wikipedia.org/wiki/Irrational_number
|
201 |
+
.. [6] https://en.wikipedia.org/wiki/Prime_number
|
202 |
+
.. [7] https://en.wikipedia.org/wiki/Finite
|
203 |
+
.. [8] https://docs.python.org/3/library/math.html#math.isfinite
|
204 |
+
.. [9] https://numpy.org/doc/stable/reference/generated/numpy.isfinite.html
|
205 |
+
.. [10] https://en.wikipedia.org/wiki/Transcendental_number
|
206 |
+
.. [11] https://en.wikipedia.org/wiki/Algebraic_number
|
207 |
+
.. [12] https://en.wikipedia.org/wiki/Commutative_property
|
208 |
+
.. [13] https://en.wikipedia.org/wiki/Complex_number
|
209 |
+
|
210 |
+
"""
|
211 |
+
|
212 |
+
from sympy.utilities.exceptions import sympy_deprecation_warning
|
213 |
+
|
214 |
+
from .facts import FactRules, FactKB
|
215 |
+
from .sympify import sympify
|
216 |
+
|
217 |
+
from sympy.core.random import _assumptions_shuffle as shuffle
|
218 |
+
from sympy.core.assumptions_generated import generated_assumptions as _assumptions
|
219 |
+
|
220 |
+
def _load_pre_generated_assumption_rules():
|
221 |
+
""" Load the assumption rules from pre-generated data
|
222 |
+
|
223 |
+
To update the pre-generated data, see :method::`_generate_assumption_rules`
|
224 |
+
"""
|
225 |
+
_assume_rules=FactRules._from_python(_assumptions)
|
226 |
+
return _assume_rules
|
227 |
+
|
228 |
+
def _generate_assumption_rules():
|
229 |
+
""" Generate the default assumption rules
|
230 |
+
|
231 |
+
This method should only be called to update the pre-generated
|
232 |
+
assumption rules.
|
233 |
+
|
234 |
+
To update the pre-generated assumptions run: bin/ask_update.py
|
235 |
+
|
236 |
+
"""
|
237 |
+
_assume_rules = FactRules([
|
238 |
+
|
239 |
+
'integer -> rational',
|
240 |
+
'rational -> real',
|
241 |
+
'rational -> algebraic',
|
242 |
+
'algebraic -> complex',
|
243 |
+
'transcendental == complex & !algebraic',
|
244 |
+
'real -> hermitian',
|
245 |
+
'imaginary -> complex',
|
246 |
+
'imaginary -> antihermitian',
|
247 |
+
'extended_real -> commutative',
|
248 |
+
'complex -> commutative',
|
249 |
+
'complex -> finite',
|
250 |
+
|
251 |
+
'odd == integer & !even',
|
252 |
+
'even == integer & !odd',
|
253 |
+
|
254 |
+
'real -> complex',
|
255 |
+
'extended_real -> real | infinite',
|
256 |
+
'real == extended_real & finite',
|
257 |
+
|
258 |
+
'extended_real == extended_negative | zero | extended_positive',
|
259 |
+
'extended_negative == extended_nonpositive & extended_nonzero',
|
260 |
+
'extended_positive == extended_nonnegative & extended_nonzero',
|
261 |
+
|
262 |
+
'extended_nonpositive == extended_real & !extended_positive',
|
263 |
+
'extended_nonnegative == extended_real & !extended_negative',
|
264 |
+
|
265 |
+
'real == negative | zero | positive',
|
266 |
+
'negative == nonpositive & nonzero',
|
267 |
+
'positive == nonnegative & nonzero',
|
268 |
+
|
269 |
+
'nonpositive == real & !positive',
|
270 |
+
'nonnegative == real & !negative',
|
271 |
+
|
272 |
+
'positive == extended_positive & finite',
|
273 |
+
'negative == extended_negative & finite',
|
274 |
+
'nonpositive == extended_nonpositive & finite',
|
275 |
+
'nonnegative == extended_nonnegative & finite',
|
276 |
+
'nonzero == extended_nonzero & finite',
|
277 |
+
|
278 |
+
'zero -> even & finite',
|
279 |
+
'zero == extended_nonnegative & extended_nonpositive',
|
280 |
+
'zero == nonnegative & nonpositive',
|
281 |
+
'nonzero -> real',
|
282 |
+
|
283 |
+
'prime -> integer & positive',
|
284 |
+
'composite -> integer & positive & !prime',
|
285 |
+
'!composite -> !positive | !even | prime',
|
286 |
+
|
287 |
+
'irrational == real & !rational',
|
288 |
+
|
289 |
+
'imaginary -> !extended_real',
|
290 |
+
|
291 |
+
'infinite == !finite',
|
292 |
+
'noninteger == extended_real & !integer',
|
293 |
+
'extended_nonzero == extended_real & !zero',
|
294 |
+
])
|
295 |
+
return _assume_rules
|
296 |
+
|
297 |
+
|
298 |
+
_assume_rules = _load_pre_generated_assumption_rules()
|
299 |
+
_assume_defined = _assume_rules.defined_facts.copy()
|
300 |
+
_assume_defined.add('polar')
|
301 |
+
_assume_defined = frozenset(_assume_defined)
|
302 |
+
|
303 |
+
|
304 |
+
def assumptions(expr, _check=None):
|
305 |
+
"""return the T/F assumptions of ``expr``"""
|
306 |
+
n = sympify(expr)
|
307 |
+
if n.is_Symbol:
|
308 |
+
rv = n.assumptions0 # are any important ones missing?
|
309 |
+
if _check is not None:
|
310 |
+
rv = {k: rv[k] for k in set(rv) & set(_check)}
|
311 |
+
return rv
|
312 |
+
rv = {}
|
313 |
+
for k in _assume_defined if _check is None else _check:
|
314 |
+
v = getattr(n, 'is_{}'.format(k))
|
315 |
+
if v is not None:
|
316 |
+
rv[k] = v
|
317 |
+
return rv
|
318 |
+
|
319 |
+
|
320 |
+
def common_assumptions(exprs, check=None):
|
321 |
+
"""return those assumptions which have the same True or False
|
322 |
+
value for all the given expressions.
|
323 |
+
|
324 |
+
Examples
|
325 |
+
========
|
326 |
+
|
327 |
+
>>> from sympy.core import common_assumptions
|
328 |
+
>>> from sympy import oo, pi, sqrt
|
329 |
+
>>> common_assumptions([-4, 0, sqrt(2), 2, pi, oo])
|
330 |
+
{'commutative': True, 'composite': False,
|
331 |
+
'extended_real': True, 'imaginary': False, 'odd': False}
|
332 |
+
|
333 |
+
By default, all assumptions are tested; pass an iterable of the
|
334 |
+
assumptions to limit those that are reported:
|
335 |
+
|
336 |
+
>>> common_assumptions([0, 1, 2], ['positive', 'integer'])
|
337 |
+
{'integer': True}
|
338 |
+
"""
|
339 |
+
check = _assume_defined if check is None else set(check)
|
340 |
+
if not check or not exprs:
|
341 |
+
return {}
|
342 |
+
|
343 |
+
# get all assumptions for each
|
344 |
+
assume = [assumptions(i, _check=check) for i in sympify(exprs)]
|
345 |
+
# focus on those of interest that are True
|
346 |
+
for i, e in enumerate(assume):
|
347 |
+
assume[i] = {k: e[k] for k in set(e) & check}
|
348 |
+
# what assumptions are in common?
|
349 |
+
common = set.intersection(*[set(i) for i in assume])
|
350 |
+
# which ones hold the same value
|
351 |
+
a = assume[0]
|
352 |
+
return {k: a[k] for k in common if all(a[k] == b[k]
|
353 |
+
for b in assume)}
|
354 |
+
|
355 |
+
|
356 |
+
def failing_assumptions(expr, **assumptions):
|
357 |
+
"""
|
358 |
+
Return a dictionary containing assumptions with values not
|
359 |
+
matching those of the passed assumptions.
|
360 |
+
|
361 |
+
Examples
|
362 |
+
========
|
363 |
+
|
364 |
+
>>> from sympy import failing_assumptions, Symbol
|
365 |
+
|
366 |
+
>>> x = Symbol('x', positive=True)
|
367 |
+
>>> y = Symbol('y')
|
368 |
+
>>> failing_assumptions(6*x + y, positive=True)
|
369 |
+
{'positive': None}
|
370 |
+
|
371 |
+
>>> failing_assumptions(x**2 - 1, positive=True)
|
372 |
+
{'positive': None}
|
373 |
+
|
374 |
+
If *expr* satisfies all of the assumptions, an empty dictionary is returned.
|
375 |
+
|
376 |
+
>>> failing_assumptions(x**2, positive=True)
|
377 |
+
{}
|
378 |
+
|
379 |
+
"""
|
380 |
+
expr = sympify(expr)
|
381 |
+
failed = {}
|
382 |
+
for k in assumptions:
|
383 |
+
test = getattr(expr, 'is_%s' % k, None)
|
384 |
+
if test is not assumptions[k]:
|
385 |
+
failed[k] = test
|
386 |
+
return failed # {} or {assumption: value != desired}
|
387 |
+
|
388 |
+
|
389 |
+
def check_assumptions(expr, against=None, **assume):
|
390 |
+
"""
|
391 |
+
Checks whether assumptions of ``expr`` match the T/F assumptions
|
392 |
+
given (or possessed by ``against``). True is returned if all
|
393 |
+
assumptions match; False is returned if there is a mismatch and
|
394 |
+
the assumption in ``expr`` is not None; else None is returned.
|
395 |
+
|
396 |
+
Explanation
|
397 |
+
===========
|
398 |
+
|
399 |
+
*assume* is a dict of assumptions with True or False values
|
400 |
+
|
401 |
+
Examples
|
402 |
+
========
|
403 |
+
|
404 |
+
>>> from sympy import Symbol, pi, I, exp, check_assumptions
|
405 |
+
>>> check_assumptions(-5, integer=True)
|
406 |
+
True
|
407 |
+
>>> check_assumptions(pi, real=True, integer=False)
|
408 |
+
True
|
409 |
+
>>> check_assumptions(pi, negative=True)
|
410 |
+
False
|
411 |
+
>>> check_assumptions(exp(I*pi/7), real=False)
|
412 |
+
True
|
413 |
+
>>> x = Symbol('x', positive=True)
|
414 |
+
>>> check_assumptions(2*x + 1, positive=True)
|
415 |
+
True
|
416 |
+
>>> check_assumptions(-2*x - 5, positive=True)
|
417 |
+
False
|
418 |
+
|
419 |
+
To check assumptions of *expr* against another variable or expression,
|
420 |
+
pass the expression or variable as ``against``.
|
421 |
+
|
422 |
+
>>> check_assumptions(2*x + 1, x)
|
423 |
+
True
|
424 |
+
|
425 |
+
To see if a number matches the assumptions of an expression, pass
|
426 |
+
the number as the first argument, else its specific assumptions
|
427 |
+
may not have a non-None value in the expression:
|
428 |
+
|
429 |
+
>>> check_assumptions(x, 3)
|
430 |
+
>>> check_assumptions(3, x)
|
431 |
+
True
|
432 |
+
|
433 |
+
``None`` is returned if ``check_assumptions()`` could not conclude.
|
434 |
+
|
435 |
+
>>> check_assumptions(2*x - 1, x)
|
436 |
+
|
437 |
+
>>> z = Symbol('z')
|
438 |
+
>>> check_assumptions(z, real=True)
|
439 |
+
|
440 |
+
See Also
|
441 |
+
========
|
442 |
+
|
443 |
+
failing_assumptions
|
444 |
+
|
445 |
+
"""
|
446 |
+
expr = sympify(expr)
|
447 |
+
if against is not None:
|
448 |
+
if assume:
|
449 |
+
raise ValueError(
|
450 |
+
'Expecting `against` or `assume`, not both.')
|
451 |
+
assume = assumptions(against)
|
452 |
+
known = True
|
453 |
+
for k, v in assume.items():
|
454 |
+
if v is None:
|
455 |
+
continue
|
456 |
+
e = getattr(expr, 'is_' + k, None)
|
457 |
+
if e is None:
|
458 |
+
known = None
|
459 |
+
elif v != e:
|
460 |
+
return False
|
461 |
+
return known
|
462 |
+
|
463 |
+
|
464 |
+
class StdFactKB(FactKB):
|
465 |
+
"""A FactKB specialized for the built-in rules
|
466 |
+
|
467 |
+
This is the only kind of FactKB that Basic objects should use.
|
468 |
+
"""
|
469 |
+
def __init__(self, facts=None):
|
470 |
+
super().__init__(_assume_rules)
|
471 |
+
# save a copy of the facts dict
|
472 |
+
if not facts:
|
473 |
+
self._generator = {}
|
474 |
+
elif not isinstance(facts, FactKB):
|
475 |
+
self._generator = facts.copy()
|
476 |
+
else:
|
477 |
+
self._generator = facts.generator
|
478 |
+
if facts:
|
479 |
+
self.deduce_all_facts(facts)
|
480 |
+
|
481 |
+
def copy(self):
|
482 |
+
return self.__class__(self)
|
483 |
+
|
484 |
+
@property
|
485 |
+
def generator(self):
|
486 |
+
return self._generator.copy()
|
487 |
+
|
488 |
+
|
489 |
+
def as_property(fact):
|
490 |
+
"""Convert a fact name to the name of the corresponding property"""
|
491 |
+
return 'is_%s' % fact
|
492 |
+
|
493 |
+
|
494 |
+
def make_property(fact):
|
495 |
+
"""Create the automagic property corresponding to a fact."""
|
496 |
+
|
497 |
+
def getit(self):
|
498 |
+
try:
|
499 |
+
return self._assumptions[fact]
|
500 |
+
except KeyError:
|
501 |
+
if self._assumptions is self.default_assumptions:
|
502 |
+
self._assumptions = self.default_assumptions.copy()
|
503 |
+
return _ask(fact, self)
|
504 |
+
|
505 |
+
getit.func_name = as_property(fact)
|
506 |
+
return property(getit)
|
507 |
+
|
508 |
+
|
509 |
+
def _ask(fact, obj):
|
510 |
+
"""
|
511 |
+
Find the truth value for a property of an object.
|
512 |
+
|
513 |
+
This function is called when a request is made to see what a fact
|
514 |
+
value is.
|
515 |
+
|
516 |
+
For this we use several techniques:
|
517 |
+
|
518 |
+
First, the fact-evaluation function is tried, if it exists (for
|
519 |
+
example _eval_is_integer). Then we try related facts. For example
|
520 |
+
|
521 |
+
rational --> integer
|
522 |
+
|
523 |
+
another example is joined rule:
|
524 |
+
|
525 |
+
integer & !odd --> even
|
526 |
+
|
527 |
+
so in the latter case if we are looking at what 'even' value is,
|
528 |
+
'integer' and 'odd' facts will be asked.
|
529 |
+
|
530 |
+
In all cases, when we settle on some fact value, its implications are
|
531 |
+
deduced, and the result is cached in ._assumptions.
|
532 |
+
"""
|
533 |
+
# FactKB which is dict-like and maps facts to their known values:
|
534 |
+
assumptions = obj._assumptions
|
535 |
+
|
536 |
+
# A dict that maps facts to their handlers:
|
537 |
+
handler_map = obj._prop_handler
|
538 |
+
|
539 |
+
# This is our queue of facts to check:
|
540 |
+
facts_to_check = [fact]
|
541 |
+
facts_queued = {fact}
|
542 |
+
|
543 |
+
# Loop over the queue as it extends
|
544 |
+
for fact_i in facts_to_check:
|
545 |
+
|
546 |
+
# If fact_i has already been determined then we don't need to rerun the
|
547 |
+
# handler. There is a potential race condition for multithreaded code
|
548 |
+
# though because it's possible that fact_i was checked in another
|
549 |
+
# thread. The main logic of the loop below would potentially skip
|
550 |
+
# checking assumptions[fact] in this case so we check it once after the
|
551 |
+
# loop to be sure.
|
552 |
+
if fact_i in assumptions:
|
553 |
+
continue
|
554 |
+
|
555 |
+
# Now we call the associated handler for fact_i if it exists.
|
556 |
+
fact_i_value = None
|
557 |
+
handler_i = handler_map.get(fact_i)
|
558 |
+
if handler_i is not None:
|
559 |
+
fact_i_value = handler_i(obj)
|
560 |
+
|
561 |
+
# If we get a new value for fact_i then we should update our knowledge
|
562 |
+
# of fact_i as well as any related facts that can be inferred using the
|
563 |
+
# inference rules connecting the fact_i and any other fact values that
|
564 |
+
# are already known.
|
565 |
+
if fact_i_value is not None:
|
566 |
+
assumptions.deduce_all_facts(((fact_i, fact_i_value),))
|
567 |
+
|
568 |
+
# Usually if assumptions[fact] is now not None then that is because of
|
569 |
+
# the call to deduce_all_facts above. The handler for fact_i returned
|
570 |
+
# True or False and knowing fact_i (which is equal to fact in the first
|
571 |
+
# iteration) implies knowing a value for fact. It is also possible
|
572 |
+
# though that independent code e.g. called indirectly by the handler or
|
573 |
+
# called in another thread in a multithreaded context might have
|
574 |
+
# resulted in assumptions[fact] being set. Either way we return it.
|
575 |
+
fact_value = assumptions.get(fact)
|
576 |
+
if fact_value is not None:
|
577 |
+
return fact_value
|
578 |
+
|
579 |
+
# Extend the queue with other facts that might determine fact_i. Here
|
580 |
+
# we randomise the order of the facts that are checked. This should not
|
581 |
+
# lead to any non-determinism if all handlers are logically consistent
|
582 |
+
# with the inference rules for the facts. Non-deterministic assumptions
|
583 |
+
# queries can result from bugs in the handlers that are exposed by this
|
584 |
+
# call to shuffle. These are pushed to the back of the queue meaning
|
585 |
+
# that the inference graph is traversed in breadth-first order.
|
586 |
+
new_facts_to_check = list(_assume_rules.prereq[fact_i] - facts_queued)
|
587 |
+
shuffle(new_facts_to_check)
|
588 |
+
facts_to_check.extend(new_facts_to_check)
|
589 |
+
facts_queued.update(new_facts_to_check)
|
590 |
+
|
591 |
+
# The above loop should be able to handle everything fine in a
|
592 |
+
# single-threaded context but in multithreaded code it is possible that
|
593 |
+
# this thread skipped computing a particular fact that was computed in
|
594 |
+
# another thread (due to the continue). In that case it is possible that
|
595 |
+
# fact was inferred and is now stored in the assumptions dict but it wasn't
|
596 |
+
# checked for in the body of the loop. This is an obscure case but to make
|
597 |
+
# sure we catch it we check once here at the end of the loop.
|
598 |
+
if fact in assumptions:
|
599 |
+
return assumptions[fact]
|
600 |
+
|
601 |
+
# This query can not be answered. It's possible that e.g. another thread
|
602 |
+
# has already stored None for fact but assumptions._tell does not mind if
|
603 |
+
# we call _tell twice setting the same value. If this raises
|
604 |
+
# InconsistentAssumptions then it probably means that another thread
|
605 |
+
# attempted to compute this and got a value of True or False rather than
|
606 |
+
# None. In that case there must be a bug in at least one of the handlers.
|
607 |
+
# If the handlers are all deterministic and are consistent with the
|
608 |
+
# inference rules then the same value should be computed for fact in all
|
609 |
+
# threads.
|
610 |
+
assumptions._tell(fact, None)
|
611 |
+
return None
|
612 |
+
|
613 |
+
|
614 |
+
def _prepare_class_assumptions(cls):
|
615 |
+
"""Precompute class level assumptions and generate handlers.
|
616 |
+
|
617 |
+
This is called by Basic.__init_subclass__ each time a Basic subclass is
|
618 |
+
defined.
|
619 |
+
"""
|
620 |
+
|
621 |
+
local_defs = {}
|
622 |
+
for k in _assume_defined:
|
623 |
+
attrname = as_property(k)
|
624 |
+
v = cls.__dict__.get(attrname, '')
|
625 |
+
if isinstance(v, (bool, int, type(None))):
|
626 |
+
if v is not None:
|
627 |
+
v = bool(v)
|
628 |
+
local_defs[k] = v
|
629 |
+
|
630 |
+
defs = {}
|
631 |
+
for base in reversed(cls.__bases__):
|
632 |
+
assumptions = getattr(base, '_explicit_class_assumptions', None)
|
633 |
+
if assumptions is not None:
|
634 |
+
defs.update(assumptions)
|
635 |
+
defs.update(local_defs)
|
636 |
+
|
637 |
+
cls._explicit_class_assumptions = defs
|
638 |
+
cls.default_assumptions = StdFactKB(defs)
|
639 |
+
|
640 |
+
cls._prop_handler = {}
|
641 |
+
for k in _assume_defined:
|
642 |
+
eval_is_meth = getattr(cls, '_eval_is_%s' % k, None)
|
643 |
+
if eval_is_meth is not None:
|
644 |
+
cls._prop_handler[k] = eval_is_meth
|
645 |
+
|
646 |
+
# Put definite results directly into the class dict, for speed
|
647 |
+
for k, v in cls.default_assumptions.items():
|
648 |
+
setattr(cls, as_property(k), v)
|
649 |
+
|
650 |
+
# protection e.g. for Integer.is_even=F <- (Rational.is_integer=F)
|
651 |
+
derived_from_bases = set()
|
652 |
+
for base in cls.__bases__:
|
653 |
+
default_assumptions = getattr(base, 'default_assumptions', None)
|
654 |
+
# is an assumption-aware class
|
655 |
+
if default_assumptions is not None:
|
656 |
+
derived_from_bases.update(default_assumptions)
|
657 |
+
|
658 |
+
for fact in derived_from_bases - set(cls.default_assumptions):
|
659 |
+
pname = as_property(fact)
|
660 |
+
if pname not in cls.__dict__:
|
661 |
+
setattr(cls, pname, make_property(fact))
|
662 |
+
|
663 |
+
# Finally, add any missing automagic property (e.g. for Basic)
|
664 |
+
for fact in _assume_defined:
|
665 |
+
pname = as_property(fact)
|
666 |
+
if not hasattr(cls, pname):
|
667 |
+
setattr(cls, pname, make_property(fact))
|
668 |
+
|
669 |
+
|
670 |
+
# XXX: ManagedProperties used to be the metaclass for Basic but now Basic does
|
671 |
+
# not use a metaclass. We leave this here for backwards compatibility for now
|
672 |
+
# in case someone has been using the ManagedProperties class in downstream
|
673 |
+
# code. The reason that it might have been used is that when subclassing a
|
674 |
+
# class and wanting to use a metaclass the metaclass must be a subclass of the
|
675 |
+
# metaclass for the class that is being subclassed. Anyone wanting to subclass
|
676 |
+
# Basic and use a metaclass in their subclass would have needed to subclass
|
677 |
+
# ManagedProperties. Here ManagedProperties is not the metaclass for Basic any
|
678 |
+
# more but it should still be usable as a metaclass for Basic subclasses since
|
679 |
+
# it is a subclass of type which is now the metaclass for Basic.
|
680 |
+
class ManagedProperties(type):
|
681 |
+
def __init__(cls, *args, **kwargs):
|
682 |
+
msg = ("The ManagedProperties metaclass. "
|
683 |
+
"Basic does not use metaclasses any more")
|
684 |
+
sympy_deprecation_warning(msg,
|
685 |
+
deprecated_since_version="1.12",
|
686 |
+
active_deprecations_target='managedproperties')
|
687 |
+
|
688 |
+
# Here we still call this function in case someone is using
|
689 |
+
# ManagedProperties for something that is not a Basic subclass. For
|
690 |
+
# Basic subclasses this function is now called by __init_subclass__ and
|
691 |
+
# so this metaclass is not needed any more.
|
692 |
+
_prepare_class_assumptions(cls)
|
llmeval-env/lib/python3.10/site-packages/sympy/core/assumptions_generated.py
ADDED
@@ -0,0 +1,1615 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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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}
|
llmeval-env/lib/python3.10/site-packages/sympy/core/basic.py
ADDED
@@ -0,0 +1,2233 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Base class for all the objects in SymPy"""
|
2 |
+
from __future__ import annotations
|
3 |
+
|
4 |
+
from collections import defaultdict
|
5 |
+
from collections.abc import Mapping
|
6 |
+
from itertools import chain, zip_longest
|
7 |
+
|
8 |
+
from .assumptions import _prepare_class_assumptions
|
9 |
+
from .cache import cacheit
|
10 |
+
from .core import ordering_of_classes
|
11 |
+
from .sympify import _sympify, sympify, SympifyError, _external_converter
|
12 |
+
from .sorting import ordered
|
13 |
+
from .kind import Kind, UndefinedKind
|
14 |
+
from ._print_helpers import Printable
|
15 |
+
|
16 |
+
from sympy.utilities.decorator import deprecated
|
17 |
+
from sympy.utilities.exceptions import sympy_deprecation_warning
|
18 |
+
from sympy.utilities.iterables import iterable, numbered_symbols
|
19 |
+
from sympy.utilities.misc import filldedent, func_name
|
20 |
+
|
21 |
+
from inspect import getmro
|
22 |
+
|
23 |
+
|
24 |
+
def as_Basic(expr):
|
25 |
+
"""Return expr as a Basic instance using strict sympify
|
26 |
+
or raise a TypeError; this is just a wrapper to _sympify,
|
27 |
+
raising a TypeError instead of a SympifyError."""
|
28 |
+
try:
|
29 |
+
return _sympify(expr)
|
30 |
+
except SympifyError:
|
31 |
+
raise TypeError(
|
32 |
+
'Argument must be a Basic object, not `%s`' % func_name(
|
33 |
+
expr))
|
34 |
+
|
35 |
+
|
36 |
+
def _old_compare(x: type, y: type) -> int:
|
37 |
+
# If the other object is not a Basic subclass, then we are not equal to it.
|
38 |
+
if not issubclass(y, Basic):
|
39 |
+
return -1
|
40 |
+
|
41 |
+
n1 = x.__name__
|
42 |
+
n2 = y.__name__
|
43 |
+
if n1 == n2:
|
44 |
+
return 0
|
45 |
+
|
46 |
+
UNKNOWN = len(ordering_of_classes) + 1
|
47 |
+
try:
|
48 |
+
i1 = ordering_of_classes.index(n1)
|
49 |
+
except ValueError:
|
50 |
+
i1 = UNKNOWN
|
51 |
+
try:
|
52 |
+
i2 = ordering_of_classes.index(n2)
|
53 |
+
except ValueError:
|
54 |
+
i2 = UNKNOWN
|
55 |
+
if i1 == UNKNOWN and i2 == UNKNOWN:
|
56 |
+
return (n1 > n2) - (n1 < n2)
|
57 |
+
return (i1 > i2) - (i1 < i2)
|
58 |
+
|
59 |
+
|
60 |
+
class Basic(Printable):
|
61 |
+
"""
|
62 |
+
Base class for all SymPy objects.
|
63 |
+
|
64 |
+
Notes and conventions
|
65 |
+
=====================
|
66 |
+
|
67 |
+
1) Always use ``.args``, when accessing parameters of some instance:
|
68 |
+
|
69 |
+
>>> from sympy import cot
|
70 |
+
>>> from sympy.abc import x, y
|
71 |
+
|
72 |
+
>>> cot(x).args
|
73 |
+
(x,)
|
74 |
+
|
75 |
+
>>> cot(x).args[0]
|
76 |
+
x
|
77 |
+
|
78 |
+
>>> (x*y).args
|
79 |
+
(x, y)
|
80 |
+
|
81 |
+
>>> (x*y).args[1]
|
82 |
+
y
|
83 |
+
|
84 |
+
|
85 |
+
2) Never use internal methods or variables (the ones prefixed with ``_``):
|
86 |
+
|
87 |
+
>>> cot(x)._args # do not use this, use cot(x).args instead
|
88 |
+
(x,)
|
89 |
+
|
90 |
+
|
91 |
+
3) By "SymPy object" we mean something that can be returned by
|
92 |
+
``sympify``. But not all objects one encounters using SymPy are
|
93 |
+
subclasses of Basic. For example, mutable objects are not:
|
94 |
+
|
95 |
+
>>> from sympy import Basic, Matrix, sympify
|
96 |
+
>>> A = Matrix([[1, 2], [3, 4]]).as_mutable()
|
97 |
+
>>> isinstance(A, Basic)
|
98 |
+
False
|
99 |
+
|
100 |
+
>>> B = sympify(A)
|
101 |
+
>>> isinstance(B, Basic)
|
102 |
+
True
|
103 |
+
"""
|
104 |
+
__slots__ = ('_mhash', # hash value
|
105 |
+
'_args', # arguments
|
106 |
+
'_assumptions'
|
107 |
+
)
|
108 |
+
|
109 |
+
_args: tuple[Basic, ...]
|
110 |
+
_mhash: int | None
|
111 |
+
|
112 |
+
@property
|
113 |
+
def __sympy__(self):
|
114 |
+
return True
|
115 |
+
|
116 |
+
def __init_subclass__(cls):
|
117 |
+
# Initialize the default_assumptions FactKB and also any assumptions
|
118 |
+
# property methods. This method will only be called for subclasses of
|
119 |
+
# Basic but not for Basic itself so we call
|
120 |
+
# _prepare_class_assumptions(Basic) below the class definition.
|
121 |
+
_prepare_class_assumptions(cls)
|
122 |
+
|
123 |
+
# To be overridden with True in the appropriate subclasses
|
124 |
+
is_number = False
|
125 |
+
is_Atom = False
|
126 |
+
is_Symbol = False
|
127 |
+
is_symbol = False
|
128 |
+
is_Indexed = False
|
129 |
+
is_Dummy = False
|
130 |
+
is_Wild = False
|
131 |
+
is_Function = False
|
132 |
+
is_Add = False
|
133 |
+
is_Mul = False
|
134 |
+
is_Pow = False
|
135 |
+
is_Number = False
|
136 |
+
is_Float = False
|
137 |
+
is_Rational = False
|
138 |
+
is_Integer = False
|
139 |
+
is_NumberSymbol = False
|
140 |
+
is_Order = False
|
141 |
+
is_Derivative = False
|
142 |
+
is_Piecewise = False
|
143 |
+
is_Poly = False
|
144 |
+
is_AlgebraicNumber = False
|
145 |
+
is_Relational = False
|
146 |
+
is_Equality = False
|
147 |
+
is_Boolean = False
|
148 |
+
is_Not = False
|
149 |
+
is_Matrix = False
|
150 |
+
is_Vector = False
|
151 |
+
is_Point = False
|
152 |
+
is_MatAdd = False
|
153 |
+
is_MatMul = False
|
154 |
+
is_real: bool | None
|
155 |
+
is_extended_real: bool | None
|
156 |
+
is_zero: bool | None
|
157 |
+
is_negative: bool | None
|
158 |
+
is_commutative: bool | None
|
159 |
+
|
160 |
+
kind: Kind = UndefinedKind
|
161 |
+
|
162 |
+
def __new__(cls, *args):
|
163 |
+
obj = object.__new__(cls)
|
164 |
+
obj._assumptions = cls.default_assumptions
|
165 |
+
obj._mhash = None # will be set by __hash__ method.
|
166 |
+
|
167 |
+
obj._args = args # all items in args must be Basic objects
|
168 |
+
return obj
|
169 |
+
|
170 |
+
def copy(self):
|
171 |
+
return self.func(*self.args)
|
172 |
+
|
173 |
+
def __getnewargs__(self):
|
174 |
+
return self.args
|
175 |
+
|
176 |
+
def __getstate__(self):
|
177 |
+
return None
|
178 |
+
|
179 |
+
def __setstate__(self, state):
|
180 |
+
for name, value in state.items():
|
181 |
+
setattr(self, name, value)
|
182 |
+
|
183 |
+
def __reduce_ex__(self, protocol):
|
184 |
+
if protocol < 2:
|
185 |
+
msg = "Only pickle protocol 2 or higher is supported by SymPy"
|
186 |
+
raise NotImplementedError(msg)
|
187 |
+
return super().__reduce_ex__(protocol)
|
188 |
+
|
189 |
+
def __hash__(self) -> int:
|
190 |
+
# hash cannot be cached using cache_it because infinite recurrence
|
191 |
+
# occurs as hash is needed for setting cache dictionary keys
|
192 |
+
h = self._mhash
|
193 |
+
if h is None:
|
194 |
+
h = hash((type(self).__name__,) + self._hashable_content())
|
195 |
+
self._mhash = h
|
196 |
+
return h
|
197 |
+
|
198 |
+
def _hashable_content(self):
|
199 |
+
"""Return a tuple of information about self that can be used to
|
200 |
+
compute the hash. If a class defines additional attributes,
|
201 |
+
like ``name`` in Symbol, then this method should be updated
|
202 |
+
accordingly to return such relevant attributes.
|
203 |
+
|
204 |
+
Defining more than _hashable_content is necessary if __eq__ has
|
205 |
+
been defined by a class. See note about this in Basic.__eq__."""
|
206 |
+
return self._args
|
207 |
+
|
208 |
+
@property
|
209 |
+
def assumptions0(self):
|
210 |
+
"""
|
211 |
+
Return object `type` assumptions.
|
212 |
+
|
213 |
+
For example:
|
214 |
+
|
215 |
+
Symbol('x', real=True)
|
216 |
+
Symbol('x', integer=True)
|
217 |
+
|
218 |
+
are different objects. In other words, besides Python type (Symbol in
|
219 |
+
this case), the initial assumptions are also forming their typeinfo.
|
220 |
+
|
221 |
+
Examples
|
222 |
+
========
|
223 |
+
|
224 |
+
>>> from sympy import Symbol
|
225 |
+
>>> from sympy.abc import x
|
226 |
+
>>> x.assumptions0
|
227 |
+
{'commutative': True}
|
228 |
+
>>> x = Symbol("x", positive=True)
|
229 |
+
>>> x.assumptions0
|
230 |
+
{'commutative': True, 'complex': True, 'extended_negative': False,
|
231 |
+
'extended_nonnegative': True, 'extended_nonpositive': False,
|
232 |
+
'extended_nonzero': True, 'extended_positive': True, 'extended_real':
|
233 |
+
True, 'finite': True, 'hermitian': True, 'imaginary': False,
|
234 |
+
'infinite': False, 'negative': False, 'nonnegative': True,
|
235 |
+
'nonpositive': False, 'nonzero': True, 'positive': True, 'real':
|
236 |
+
True, 'zero': False}
|
237 |
+
"""
|
238 |
+
return {}
|
239 |
+
|
240 |
+
def compare(self, other):
|
241 |
+
"""
|
242 |
+
Return -1, 0, 1 if the object is smaller, equal, or greater than other.
|
243 |
+
|
244 |
+
Not in the mathematical sense. If the object is of a different type
|
245 |
+
from the "other" then their classes are ordered according to
|
246 |
+
the sorted_classes list.
|
247 |
+
|
248 |
+
Examples
|
249 |
+
========
|
250 |
+
|
251 |
+
>>> from sympy.abc import x, y
|
252 |
+
>>> x.compare(y)
|
253 |
+
-1
|
254 |
+
>>> x.compare(x)
|
255 |
+
0
|
256 |
+
>>> y.compare(x)
|
257 |
+
1
|
258 |
+
|
259 |
+
"""
|
260 |
+
# all redefinitions of __cmp__ method should start with the
|
261 |
+
# following lines:
|
262 |
+
if self is other:
|
263 |
+
return 0
|
264 |
+
n1 = self.__class__
|
265 |
+
n2 = other.__class__
|
266 |
+
c = _old_compare(n1, n2)
|
267 |
+
if c:
|
268 |
+
return c
|
269 |
+
#
|
270 |
+
st = self._hashable_content()
|
271 |
+
ot = other._hashable_content()
|
272 |
+
c = (len(st) > len(ot)) - (len(st) < len(ot))
|
273 |
+
if c:
|
274 |
+
return c
|
275 |
+
for l, r in zip(st, ot):
|
276 |
+
l = Basic(*l) if isinstance(l, frozenset) else l
|
277 |
+
r = Basic(*r) if isinstance(r, frozenset) else r
|
278 |
+
if isinstance(l, Basic):
|
279 |
+
c = l.compare(r)
|
280 |
+
else:
|
281 |
+
c = (l > r) - (l < r)
|
282 |
+
if c:
|
283 |
+
return c
|
284 |
+
return 0
|
285 |
+
|
286 |
+
@staticmethod
|
287 |
+
def _compare_pretty(a, b):
|
288 |
+
from sympy.series.order import Order
|
289 |
+
if isinstance(a, Order) and not isinstance(b, Order):
|
290 |
+
return 1
|
291 |
+
if not isinstance(a, Order) and isinstance(b, Order):
|
292 |
+
return -1
|
293 |
+
|
294 |
+
if a.is_Rational and b.is_Rational:
|
295 |
+
l = a.p * b.q
|
296 |
+
r = b.p * a.q
|
297 |
+
return (l > r) - (l < r)
|
298 |
+
else:
|
299 |
+
from .symbol import Wild
|
300 |
+
p1, p2, p3 = Wild("p1"), Wild("p2"), Wild("p3")
|
301 |
+
r_a = a.match(p1 * p2**p3)
|
302 |
+
if r_a and p3 in r_a:
|
303 |
+
a3 = r_a[p3]
|
304 |
+
r_b = b.match(p1 * p2**p3)
|
305 |
+
if r_b and p3 in r_b:
|
306 |
+
b3 = r_b[p3]
|
307 |
+
c = Basic.compare(a3, b3)
|
308 |
+
if c != 0:
|
309 |
+
return c
|
310 |
+
|
311 |
+
return Basic.compare(a, b)
|
312 |
+
|
313 |
+
@classmethod
|
314 |
+
def fromiter(cls, args, **assumptions):
|
315 |
+
"""
|
316 |
+
Create a new object from an iterable.
|
317 |
+
|
318 |
+
This is a convenience function that allows one to create objects from
|
319 |
+
any iterable, without having to convert to a list or tuple first.
|
320 |
+
|
321 |
+
Examples
|
322 |
+
========
|
323 |
+
|
324 |
+
>>> from sympy import Tuple
|
325 |
+
>>> Tuple.fromiter(i for i in range(5))
|
326 |
+
(0, 1, 2, 3, 4)
|
327 |
+
|
328 |
+
"""
|
329 |
+
return cls(*tuple(args), **assumptions)
|
330 |
+
|
331 |
+
@classmethod
|
332 |
+
def class_key(cls):
|
333 |
+
"""Nice order of classes."""
|
334 |
+
return 5, 0, cls.__name__
|
335 |
+
|
336 |
+
@cacheit
|
337 |
+
def sort_key(self, order=None):
|
338 |
+
"""
|
339 |
+
Return a sort key.
|
340 |
+
|
341 |
+
Examples
|
342 |
+
========
|
343 |
+
|
344 |
+
>>> from sympy import S, I
|
345 |
+
|
346 |
+
>>> sorted([S(1)/2, I, -I], key=lambda x: x.sort_key())
|
347 |
+
[1/2, -I, I]
|
348 |
+
|
349 |
+
>>> S("[x, 1/x, 1/x**2, x**2, x**(1/2), x**(1/4), x**(3/2)]")
|
350 |
+
[x, 1/x, x**(-2), x**2, sqrt(x), x**(1/4), x**(3/2)]
|
351 |
+
>>> sorted(_, key=lambda x: x.sort_key())
|
352 |
+
[x**(-2), 1/x, x**(1/4), sqrt(x), x, x**(3/2), x**2]
|
353 |
+
|
354 |
+
"""
|
355 |
+
|
356 |
+
# XXX: remove this when issue 5169 is fixed
|
357 |
+
def inner_key(arg):
|
358 |
+
if isinstance(arg, Basic):
|
359 |
+
return arg.sort_key(order)
|
360 |
+
else:
|
361 |
+
return arg
|
362 |
+
|
363 |
+
args = self._sorted_args
|
364 |
+
args = len(args), tuple([inner_key(arg) for arg in args])
|
365 |
+
return self.class_key(), args, S.One.sort_key(), S.One
|
366 |
+
|
367 |
+
def _do_eq_sympify(self, other):
|
368 |
+
"""Returns a boolean indicating whether a == b when either a
|
369 |
+
or b is not a Basic. This is only done for types that were either
|
370 |
+
added to `converter` by a 3rd party or when the object has `_sympy_`
|
371 |
+
defined. This essentially reuses the code in `_sympify` that is
|
372 |
+
specific for this use case. Non-user defined types that are meant
|
373 |
+
to work with SymPy should be handled directly in the __eq__ methods
|
374 |
+
of the `Basic` classes it could equate to and not be converted. Note
|
375 |
+
that after conversion, `==` is used again since it is not
|
376 |
+
necessarily clear whether `self` or `other`'s __eq__ method needs
|
377 |
+
to be used."""
|
378 |
+
for superclass in type(other).__mro__:
|
379 |
+
conv = _external_converter.get(superclass)
|
380 |
+
if conv is not None:
|
381 |
+
return self == conv(other)
|
382 |
+
if hasattr(other, '_sympy_'):
|
383 |
+
return self == other._sympy_()
|
384 |
+
return NotImplemented
|
385 |
+
|
386 |
+
def __eq__(self, other):
|
387 |
+
"""Return a boolean indicating whether a == b on the basis of
|
388 |
+
their symbolic trees.
|
389 |
+
|
390 |
+
This is the same as a.compare(b) == 0 but faster.
|
391 |
+
|
392 |
+
Notes
|
393 |
+
=====
|
394 |
+
|
395 |
+
If a class that overrides __eq__() needs to retain the
|
396 |
+
implementation of __hash__() from a parent class, the
|
397 |
+
interpreter must be told this explicitly by setting
|
398 |
+
__hash__ : Callable[[object], int] = <ParentClass>.__hash__.
|
399 |
+
Otherwise the inheritance of __hash__() will be blocked,
|
400 |
+
just as if __hash__ had been explicitly set to None.
|
401 |
+
|
402 |
+
References
|
403 |
+
==========
|
404 |
+
|
405 |
+
from https://docs.python.org/dev/reference/datamodel.html#object.__hash__
|
406 |
+
"""
|
407 |
+
if self is other:
|
408 |
+
return True
|
409 |
+
|
410 |
+
if not isinstance(other, Basic):
|
411 |
+
return self._do_eq_sympify(other)
|
412 |
+
|
413 |
+
# check for pure number expr
|
414 |
+
if not (self.is_Number and other.is_Number) and (
|
415 |
+
type(self) != type(other)):
|
416 |
+
return False
|
417 |
+
a, b = self._hashable_content(), other._hashable_content()
|
418 |
+
if a != b:
|
419 |
+
return False
|
420 |
+
# check number *in* an expression
|
421 |
+
for a, b in zip(a, b):
|
422 |
+
if not isinstance(a, Basic):
|
423 |
+
continue
|
424 |
+
if a.is_Number and type(a) != type(b):
|
425 |
+
return False
|
426 |
+
return True
|
427 |
+
|
428 |
+
def __ne__(self, other):
|
429 |
+
"""``a != b`` -> Compare two symbolic trees and see whether they are different
|
430 |
+
|
431 |
+
this is the same as:
|
432 |
+
|
433 |
+
``a.compare(b) != 0``
|
434 |
+
|
435 |
+
but faster
|
436 |
+
"""
|
437 |
+
return not self == other
|
438 |
+
|
439 |
+
def dummy_eq(self, other, symbol=None):
|
440 |
+
"""
|
441 |
+
Compare two expressions and handle dummy symbols.
|
442 |
+
|
443 |
+
Examples
|
444 |
+
========
|
445 |
+
|
446 |
+
>>> from sympy import Dummy
|
447 |
+
>>> from sympy.abc import x, y
|
448 |
+
|
449 |
+
>>> u = Dummy('u')
|
450 |
+
|
451 |
+
>>> (u**2 + 1).dummy_eq(x**2 + 1)
|
452 |
+
True
|
453 |
+
>>> (u**2 + 1) == (x**2 + 1)
|
454 |
+
False
|
455 |
+
|
456 |
+
>>> (u**2 + y).dummy_eq(x**2 + y, x)
|
457 |
+
True
|
458 |
+
>>> (u**2 + y).dummy_eq(x**2 + y, y)
|
459 |
+
False
|
460 |
+
|
461 |
+
"""
|
462 |
+
s = self.as_dummy()
|
463 |
+
o = _sympify(other)
|
464 |
+
o = o.as_dummy()
|
465 |
+
|
466 |
+
dummy_symbols = [i for i in s.free_symbols if i.is_Dummy]
|
467 |
+
|
468 |
+
if len(dummy_symbols) == 1:
|
469 |
+
dummy = dummy_symbols.pop()
|
470 |
+
else:
|
471 |
+
return s == o
|
472 |
+
|
473 |
+
if symbol is None:
|
474 |
+
symbols = o.free_symbols
|
475 |
+
|
476 |
+
if len(symbols) == 1:
|
477 |
+
symbol = symbols.pop()
|
478 |
+
else:
|
479 |
+
return s == o
|
480 |
+
|
481 |
+
tmp = dummy.__class__()
|
482 |
+
|
483 |
+
return s.xreplace({dummy: tmp}) == o.xreplace({symbol: tmp})
|
484 |
+
|
485 |
+
def atoms(self, *types):
|
486 |
+
"""Returns the atoms that form the current object.
|
487 |
+
|
488 |
+
By default, only objects that are truly atomic and cannot
|
489 |
+
be divided into smaller pieces are returned: symbols, numbers,
|
490 |
+
and number symbols like I and pi. It is possible to request
|
491 |
+
atoms of any type, however, as demonstrated below.
|
492 |
+
|
493 |
+
Examples
|
494 |
+
========
|
495 |
+
|
496 |
+
>>> from sympy import I, pi, sin
|
497 |
+
>>> from sympy.abc import x, y
|
498 |
+
>>> (1 + x + 2*sin(y + I*pi)).atoms()
|
499 |
+
{1, 2, I, pi, x, y}
|
500 |
+
|
501 |
+
If one or more types are given, the results will contain only
|
502 |
+
those types of atoms.
|
503 |
+
|
504 |
+
>>> from sympy import Number, NumberSymbol, Symbol
|
505 |
+
>>> (1 + x + 2*sin(y + I*pi)).atoms(Symbol)
|
506 |
+
{x, y}
|
507 |
+
|
508 |
+
>>> (1 + x + 2*sin(y + I*pi)).atoms(Number)
|
509 |
+
{1, 2}
|
510 |
+
|
511 |
+
>>> (1 + x + 2*sin(y + I*pi)).atoms(Number, NumberSymbol)
|
512 |
+
{1, 2, pi}
|
513 |
+
|
514 |
+
>>> (1 + x + 2*sin(y + I*pi)).atoms(Number, NumberSymbol, I)
|
515 |
+
{1, 2, I, pi}
|
516 |
+
|
517 |
+
Note that I (imaginary unit) and zoo (complex infinity) are special
|
518 |
+
types of number symbols and are not part of the NumberSymbol class.
|
519 |
+
|
520 |
+
The type can be given implicitly, too:
|
521 |
+
|
522 |
+
>>> (1 + x + 2*sin(y + I*pi)).atoms(x) # x is a Symbol
|
523 |
+
{x, y}
|
524 |
+
|
525 |
+
Be careful to check your assumptions when using the implicit option
|
526 |
+
since ``S(1).is_Integer = True`` but ``type(S(1))`` is ``One``, a special type
|
527 |
+
of SymPy atom, while ``type(S(2))`` is type ``Integer`` and will find all
|
528 |
+
integers in an expression:
|
529 |
+
|
530 |
+
>>> from sympy import S
|
531 |
+
>>> (1 + x + 2*sin(y + I*pi)).atoms(S(1))
|
532 |
+
{1}
|
533 |
+
|
534 |
+
>>> (1 + x + 2*sin(y + I*pi)).atoms(S(2))
|
535 |
+
{1, 2}
|
536 |
+
|
537 |
+
Finally, arguments to atoms() can select more than atomic atoms: any
|
538 |
+
SymPy type (loaded in core/__init__.py) can be listed as an argument
|
539 |
+
and those types of "atoms" as found in scanning the arguments of the
|
540 |
+
expression recursively:
|
541 |
+
|
542 |
+
>>> from sympy import Function, Mul
|
543 |
+
>>> from sympy.core.function import AppliedUndef
|
544 |
+
>>> f = Function('f')
|
545 |
+
>>> (1 + f(x) + 2*sin(y + I*pi)).atoms(Function)
|
546 |
+
{f(x), sin(y + I*pi)}
|
547 |
+
>>> (1 + f(x) + 2*sin(y + I*pi)).atoms(AppliedUndef)
|
548 |
+
{f(x)}
|
549 |
+
|
550 |
+
>>> (1 + x + 2*sin(y + I*pi)).atoms(Mul)
|
551 |
+
{I*pi, 2*sin(y + I*pi)}
|
552 |
+
|
553 |
+
"""
|
554 |
+
if types:
|
555 |
+
types = tuple(
|
556 |
+
[t if isinstance(t, type) else type(t) for t in types])
|
557 |
+
nodes = _preorder_traversal(self)
|
558 |
+
if types:
|
559 |
+
result = {node for node in nodes if isinstance(node, types)}
|
560 |
+
else:
|
561 |
+
result = {node for node in nodes if not node.args}
|
562 |
+
return result
|
563 |
+
|
564 |
+
@property
|
565 |
+
def free_symbols(self) -> set[Basic]:
|
566 |
+
"""Return from the atoms of self those which are free symbols.
|
567 |
+
|
568 |
+
Not all free symbols are ``Symbol``. Eg: IndexedBase('I')[0].free_symbols
|
569 |
+
|
570 |
+
For most expressions, all symbols are free symbols. For some classes
|
571 |
+
this is not true. e.g. Integrals use Symbols for the dummy variables
|
572 |
+
which are bound variables, so Integral has a method to return all
|
573 |
+
symbols except those. Derivative keeps track of symbols with respect
|
574 |
+
to which it will perform a derivative; those are
|
575 |
+
bound variables, too, so it has its own free_symbols method.
|
576 |
+
|
577 |
+
Any other method that uses bound variables should implement a
|
578 |
+
free_symbols method."""
|
579 |
+
empty: set[Basic] = set()
|
580 |
+
return empty.union(*(a.free_symbols for a in self.args))
|
581 |
+
|
582 |
+
@property
|
583 |
+
def expr_free_symbols(self):
|
584 |
+
sympy_deprecation_warning("""
|
585 |
+
The expr_free_symbols property is deprecated. Use free_symbols to get
|
586 |
+
the free symbols of an expression.
|
587 |
+
""",
|
588 |
+
deprecated_since_version="1.9",
|
589 |
+
active_deprecations_target="deprecated-expr-free-symbols")
|
590 |
+
return set()
|
591 |
+
|
592 |
+
def as_dummy(self):
|
593 |
+
"""Return the expression with any objects having structurally
|
594 |
+
bound symbols replaced with unique, canonical symbols within
|
595 |
+
the object in which they appear and having only the default
|
596 |
+
assumption for commutativity being True. When applied to a
|
597 |
+
symbol a new symbol having only the same commutativity will be
|
598 |
+
returned.
|
599 |
+
|
600 |
+
Examples
|
601 |
+
========
|
602 |
+
|
603 |
+
>>> from sympy import Integral, Symbol
|
604 |
+
>>> from sympy.abc import x
|
605 |
+
>>> r = Symbol('r', real=True)
|
606 |
+
>>> Integral(r, (r, x)).as_dummy()
|
607 |
+
Integral(_0, (_0, x))
|
608 |
+
>>> _.variables[0].is_real is None
|
609 |
+
True
|
610 |
+
>>> r.as_dummy()
|
611 |
+
_r
|
612 |
+
|
613 |
+
Notes
|
614 |
+
=====
|
615 |
+
|
616 |
+
Any object that has structurally bound variables should have
|
617 |
+
a property, `bound_symbols` that returns those symbols
|
618 |
+
appearing in the object.
|
619 |
+
"""
|
620 |
+
from .symbol import Dummy, Symbol
|
621 |
+
def can(x):
|
622 |
+
# mask free that shadow bound
|
623 |
+
free = x.free_symbols
|
624 |
+
bound = set(x.bound_symbols)
|
625 |
+
d = {i: Dummy() for i in bound & free}
|
626 |
+
x = x.subs(d)
|
627 |
+
# replace bound with canonical names
|
628 |
+
x = x.xreplace(x.canonical_variables)
|
629 |
+
# return after undoing masking
|
630 |
+
return x.xreplace({v: k for k, v in d.items()})
|
631 |
+
if not self.has(Symbol):
|
632 |
+
return self
|
633 |
+
return self.replace(
|
634 |
+
lambda x: hasattr(x, 'bound_symbols'),
|
635 |
+
can,
|
636 |
+
simultaneous=False)
|
637 |
+
|
638 |
+
@property
|
639 |
+
def canonical_variables(self):
|
640 |
+
"""Return a dictionary mapping any variable defined in
|
641 |
+
``self.bound_symbols`` to Symbols that do not clash
|
642 |
+
with any free symbols in the expression.
|
643 |
+
|
644 |
+
Examples
|
645 |
+
========
|
646 |
+
|
647 |
+
>>> from sympy import Lambda
|
648 |
+
>>> from sympy.abc import x
|
649 |
+
>>> Lambda(x, 2*x).canonical_variables
|
650 |
+
{x: _0}
|
651 |
+
"""
|
652 |
+
if not hasattr(self, 'bound_symbols'):
|
653 |
+
return {}
|
654 |
+
dums = numbered_symbols('_')
|
655 |
+
reps = {}
|
656 |
+
# watch out for free symbol that are not in bound symbols;
|
657 |
+
# those that are in bound symbols are about to get changed
|
658 |
+
bound = self.bound_symbols
|
659 |
+
names = {i.name for i in self.free_symbols - set(bound)}
|
660 |
+
for b in bound:
|
661 |
+
d = next(dums)
|
662 |
+
if b.is_Symbol:
|
663 |
+
while d.name in names:
|
664 |
+
d = next(dums)
|
665 |
+
reps[b] = d
|
666 |
+
return reps
|
667 |
+
|
668 |
+
def rcall(self, *args):
|
669 |
+
"""Apply on the argument recursively through the expression tree.
|
670 |
+
|
671 |
+
This method is used to simulate a common abuse of notation for
|
672 |
+
operators. For instance, in SymPy the following will not work:
|
673 |
+
|
674 |
+
``(x+Lambda(y, 2*y))(z) == x+2*z``,
|
675 |
+
|
676 |
+
however, you can use:
|
677 |
+
|
678 |
+
>>> from sympy import Lambda
|
679 |
+
>>> from sympy.abc import x, y, z
|
680 |
+
>>> (x + Lambda(y, 2*y)).rcall(z)
|
681 |
+
x + 2*z
|
682 |
+
"""
|
683 |
+
return Basic._recursive_call(self, args)
|
684 |
+
|
685 |
+
@staticmethod
|
686 |
+
def _recursive_call(expr_to_call, on_args):
|
687 |
+
"""Helper for rcall method."""
|
688 |
+
from .symbol import Symbol
|
689 |
+
def the_call_method_is_overridden(expr):
|
690 |
+
for cls in getmro(type(expr)):
|
691 |
+
if '__call__' in cls.__dict__:
|
692 |
+
return cls != Basic
|
693 |
+
|
694 |
+
if callable(expr_to_call) and the_call_method_is_overridden(expr_to_call):
|
695 |
+
if isinstance(expr_to_call, Symbol): # XXX When you call a Symbol it is
|
696 |
+
return expr_to_call # transformed into an UndefFunction
|
697 |
+
else:
|
698 |
+
return expr_to_call(*on_args)
|
699 |
+
elif expr_to_call.args:
|
700 |
+
args = [Basic._recursive_call(
|
701 |
+
sub, on_args) for sub in expr_to_call.args]
|
702 |
+
return type(expr_to_call)(*args)
|
703 |
+
else:
|
704 |
+
return expr_to_call
|
705 |
+
|
706 |
+
def is_hypergeometric(self, k):
|
707 |
+
from sympy.simplify.simplify import hypersimp
|
708 |
+
from sympy.functions.elementary.piecewise import Piecewise
|
709 |
+
if self.has(Piecewise):
|
710 |
+
return None
|
711 |
+
return hypersimp(self, k) is not None
|
712 |
+
|
713 |
+
@property
|
714 |
+
def is_comparable(self):
|
715 |
+
"""Return True if self can be computed to a real number
|
716 |
+
(or already is a real number) with precision, else False.
|
717 |
+
|
718 |
+
Examples
|
719 |
+
========
|
720 |
+
|
721 |
+
>>> from sympy import exp_polar, pi, I
|
722 |
+
>>> (I*exp_polar(I*pi/2)).is_comparable
|
723 |
+
True
|
724 |
+
>>> (I*exp_polar(I*pi*2)).is_comparable
|
725 |
+
False
|
726 |
+
|
727 |
+
A False result does not mean that `self` cannot be rewritten
|
728 |
+
into a form that would be comparable. For example, the
|
729 |
+
difference computed below is zero but without simplification
|
730 |
+
it does not evaluate to a zero with precision:
|
731 |
+
|
732 |
+
>>> e = 2**pi*(1 + 2**pi)
|
733 |
+
>>> dif = e - e.expand()
|
734 |
+
>>> dif.is_comparable
|
735 |
+
False
|
736 |
+
>>> dif.n(2)._prec
|
737 |
+
1
|
738 |
+
|
739 |
+
"""
|
740 |
+
is_extended_real = self.is_extended_real
|
741 |
+
if is_extended_real is False:
|
742 |
+
return False
|
743 |
+
if not self.is_number:
|
744 |
+
return False
|
745 |
+
# don't re-eval numbers that are already evaluated since
|
746 |
+
# this will create spurious precision
|
747 |
+
n, i = [p.evalf(2) if not p.is_Number else p
|
748 |
+
for p in self.as_real_imag()]
|
749 |
+
if not (i.is_Number and n.is_Number):
|
750 |
+
return False
|
751 |
+
if i:
|
752 |
+
# if _prec = 1 we can't decide and if not,
|
753 |
+
# the answer is False because numbers with
|
754 |
+
# imaginary parts can't be compared
|
755 |
+
# so return False
|
756 |
+
return False
|
757 |
+
else:
|
758 |
+
return n._prec != 1
|
759 |
+
|
760 |
+
@property
|
761 |
+
def func(self):
|
762 |
+
"""
|
763 |
+
The top-level function in an expression.
|
764 |
+
|
765 |
+
The following should hold for all objects::
|
766 |
+
|
767 |
+
>> x == x.func(*x.args)
|
768 |
+
|
769 |
+
Examples
|
770 |
+
========
|
771 |
+
|
772 |
+
>>> from sympy.abc import x
|
773 |
+
>>> a = 2*x
|
774 |
+
>>> a.func
|
775 |
+
<class 'sympy.core.mul.Mul'>
|
776 |
+
>>> a.args
|
777 |
+
(2, x)
|
778 |
+
>>> a.func(*a.args)
|
779 |
+
2*x
|
780 |
+
>>> a == a.func(*a.args)
|
781 |
+
True
|
782 |
+
|
783 |
+
"""
|
784 |
+
return self.__class__
|
785 |
+
|
786 |
+
@property
|
787 |
+
def args(self) -> tuple[Basic, ...]:
|
788 |
+
"""Returns a tuple of arguments of 'self'.
|
789 |
+
|
790 |
+
Examples
|
791 |
+
========
|
792 |
+
|
793 |
+
>>> from sympy import cot
|
794 |
+
>>> from sympy.abc import x, y
|
795 |
+
|
796 |
+
>>> cot(x).args
|
797 |
+
(x,)
|
798 |
+
|
799 |
+
>>> cot(x).args[0]
|
800 |
+
x
|
801 |
+
|
802 |
+
>>> (x*y).args
|
803 |
+
(x, y)
|
804 |
+
|
805 |
+
>>> (x*y).args[1]
|
806 |
+
y
|
807 |
+
|
808 |
+
Notes
|
809 |
+
=====
|
810 |
+
|
811 |
+
Never use self._args, always use self.args.
|
812 |
+
Only use _args in __new__ when creating a new function.
|
813 |
+
Do not override .args() from Basic (so that it is easy to
|
814 |
+
change the interface in the future if needed).
|
815 |
+
"""
|
816 |
+
return self._args
|
817 |
+
|
818 |
+
@property
|
819 |
+
def _sorted_args(self):
|
820 |
+
"""
|
821 |
+
The same as ``args``. Derived classes which do not fix an
|
822 |
+
order on their arguments should override this method to
|
823 |
+
produce the sorted representation.
|
824 |
+
"""
|
825 |
+
return self.args
|
826 |
+
|
827 |
+
def as_content_primitive(self, radical=False, clear=True):
|
828 |
+
"""A stub to allow Basic args (like Tuple) to be skipped when computing
|
829 |
+
the content and primitive components of an expression.
|
830 |
+
|
831 |
+
See Also
|
832 |
+
========
|
833 |
+
|
834 |
+
sympy.core.expr.Expr.as_content_primitive
|
835 |
+
"""
|
836 |
+
return S.One, self
|
837 |
+
|
838 |
+
def subs(self, *args, **kwargs):
|
839 |
+
"""
|
840 |
+
Substitutes old for new in an expression after sympifying args.
|
841 |
+
|
842 |
+
`args` is either:
|
843 |
+
- two arguments, e.g. foo.subs(old, new)
|
844 |
+
- one iterable argument, e.g. foo.subs(iterable). The iterable may be
|
845 |
+
o an iterable container with (old, new) pairs. In this case the
|
846 |
+
replacements are processed in the order given with successive
|
847 |
+
patterns possibly affecting replacements already made.
|
848 |
+
o a dict or set whose key/value items correspond to old/new pairs.
|
849 |
+
In this case the old/new pairs will be sorted by op count and in
|
850 |
+
case of a tie, by number of args and the default_sort_key. The
|
851 |
+
resulting sorted list is then processed as an iterable container
|
852 |
+
(see previous).
|
853 |
+
|
854 |
+
If the keyword ``simultaneous`` is True, the subexpressions will not be
|
855 |
+
evaluated until all the substitutions have been made.
|
856 |
+
|
857 |
+
Examples
|
858 |
+
========
|
859 |
+
|
860 |
+
>>> from sympy import pi, exp, limit, oo
|
861 |
+
>>> from sympy.abc import x, y
|
862 |
+
>>> (1 + x*y).subs(x, pi)
|
863 |
+
pi*y + 1
|
864 |
+
>>> (1 + x*y).subs({x:pi, y:2})
|
865 |
+
1 + 2*pi
|
866 |
+
>>> (1 + x*y).subs([(x, pi), (y, 2)])
|
867 |
+
1 + 2*pi
|
868 |
+
>>> reps = [(y, x**2), (x, 2)]
|
869 |
+
>>> (x + y).subs(reps)
|
870 |
+
6
|
871 |
+
>>> (x + y).subs(reversed(reps))
|
872 |
+
x**2 + 2
|
873 |
+
|
874 |
+
>>> (x**2 + x**4).subs(x**2, y)
|
875 |
+
y**2 + y
|
876 |
+
|
877 |
+
To replace only the x**2 but not the x**4, use xreplace:
|
878 |
+
|
879 |
+
>>> (x**2 + x**4).xreplace({x**2: y})
|
880 |
+
x**4 + y
|
881 |
+
|
882 |
+
To delay evaluation until all substitutions have been made,
|
883 |
+
set the keyword ``simultaneous`` to True:
|
884 |
+
|
885 |
+
>>> (x/y).subs([(x, 0), (y, 0)])
|
886 |
+
0
|
887 |
+
>>> (x/y).subs([(x, 0), (y, 0)], simultaneous=True)
|
888 |
+
nan
|
889 |
+
|
890 |
+
This has the added feature of not allowing subsequent substitutions
|
891 |
+
to affect those already made:
|
892 |
+
|
893 |
+
>>> ((x + y)/y).subs({x + y: y, y: x + y})
|
894 |
+
1
|
895 |
+
>>> ((x + y)/y).subs({x + y: y, y: x + y}, simultaneous=True)
|
896 |
+
y/(x + y)
|
897 |
+
|
898 |
+
In order to obtain a canonical result, unordered iterables are
|
899 |
+
sorted by count_op length, number of arguments and by the
|
900 |
+
default_sort_key to break any ties. All other iterables are left
|
901 |
+
unsorted.
|
902 |
+
|
903 |
+
>>> from sympy import sqrt, sin, cos
|
904 |
+
>>> from sympy.abc import a, b, c, d, e
|
905 |
+
|
906 |
+
>>> A = (sqrt(sin(2*x)), a)
|
907 |
+
>>> B = (sin(2*x), b)
|
908 |
+
>>> C = (cos(2*x), c)
|
909 |
+
>>> D = (x, d)
|
910 |
+
>>> E = (exp(x), e)
|
911 |
+
|
912 |
+
>>> expr = sqrt(sin(2*x))*sin(exp(x)*x)*cos(2*x) + sin(2*x)
|
913 |
+
|
914 |
+
>>> expr.subs(dict([A, B, C, D, E]))
|
915 |
+
a*c*sin(d*e) + b
|
916 |
+
|
917 |
+
The resulting expression represents a literal replacement of the
|
918 |
+
old arguments with the new arguments. This may not reflect the
|
919 |
+
limiting behavior of the expression:
|
920 |
+
|
921 |
+
>>> (x**3 - 3*x).subs({x: oo})
|
922 |
+
nan
|
923 |
+
|
924 |
+
>>> limit(x**3 - 3*x, x, oo)
|
925 |
+
oo
|
926 |
+
|
927 |
+
If the substitution will be followed by numerical
|
928 |
+
evaluation, it is better to pass the substitution to
|
929 |
+
evalf as
|
930 |
+
|
931 |
+
>>> (1/x).evalf(subs={x: 3.0}, n=21)
|
932 |
+
0.333333333333333333333
|
933 |
+
|
934 |
+
rather than
|
935 |
+
|
936 |
+
>>> (1/x).subs({x: 3.0}).evalf(21)
|
937 |
+
0.333333333333333314830
|
938 |
+
|
939 |
+
as the former will ensure that the desired level of precision is
|
940 |
+
obtained.
|
941 |
+
|
942 |
+
See Also
|
943 |
+
========
|
944 |
+
replace: replacement capable of doing wildcard-like matching,
|
945 |
+
parsing of match, and conditional replacements
|
946 |
+
xreplace: exact node replacement in expr tree; also capable of
|
947 |
+
using matching rules
|
948 |
+
sympy.core.evalf.EvalfMixin.evalf: calculates the given formula to a desired level of precision
|
949 |
+
|
950 |
+
"""
|
951 |
+
from .containers import Dict
|
952 |
+
from .symbol import Dummy, Symbol
|
953 |
+
from .numbers import _illegal
|
954 |
+
|
955 |
+
unordered = False
|
956 |
+
if len(args) == 1:
|
957 |
+
|
958 |
+
sequence = args[0]
|
959 |
+
if isinstance(sequence, set):
|
960 |
+
unordered = True
|
961 |
+
elif isinstance(sequence, (Dict, Mapping)):
|
962 |
+
unordered = True
|
963 |
+
sequence = sequence.items()
|
964 |
+
elif not iterable(sequence):
|
965 |
+
raise ValueError(filldedent("""
|
966 |
+
When a single argument is passed to subs
|
967 |
+
it should be a dictionary of old: new pairs or an iterable
|
968 |
+
of (old, new) tuples."""))
|
969 |
+
elif len(args) == 2:
|
970 |
+
sequence = [args]
|
971 |
+
else:
|
972 |
+
raise ValueError("subs accepts either 1 or 2 arguments")
|
973 |
+
|
974 |
+
def sympify_old(old):
|
975 |
+
if isinstance(old, str):
|
976 |
+
# Use Symbol rather than parse_expr for old
|
977 |
+
return Symbol(old)
|
978 |
+
elif isinstance(old, type):
|
979 |
+
# Allow a type e.g. Function('f') or sin
|
980 |
+
return sympify(old, strict=False)
|
981 |
+
else:
|
982 |
+
return sympify(old, strict=True)
|
983 |
+
|
984 |
+
def sympify_new(new):
|
985 |
+
if isinstance(new, (str, type)):
|
986 |
+
# Allow a type or parse a string input
|
987 |
+
return sympify(new, strict=False)
|
988 |
+
else:
|
989 |
+
return sympify(new, strict=True)
|
990 |
+
|
991 |
+
sequence = [(sympify_old(s1), sympify_new(s2)) for s1, s2 in sequence]
|
992 |
+
|
993 |
+
# skip if there is no change
|
994 |
+
sequence = [(s1, s2) for s1, s2 in sequence if not _aresame(s1, s2)]
|
995 |
+
|
996 |
+
simultaneous = kwargs.pop('simultaneous', False)
|
997 |
+
|
998 |
+
if unordered:
|
999 |
+
from .sorting import _nodes, default_sort_key
|
1000 |
+
sequence = dict(sequence)
|
1001 |
+
# order so more complex items are first and items
|
1002 |
+
# of identical complexity are ordered so
|
1003 |
+
# f(x) < f(y) < x < y
|
1004 |
+
# \___ 2 __/ \_1_/ <- number of nodes
|
1005 |
+
#
|
1006 |
+
# For more complex ordering use an unordered sequence.
|
1007 |
+
k = list(ordered(sequence, default=False, keys=(
|
1008 |
+
lambda x: -_nodes(x),
|
1009 |
+
default_sort_key,
|
1010 |
+
)))
|
1011 |
+
sequence = [(k, sequence[k]) for k in k]
|
1012 |
+
# do infinities first
|
1013 |
+
if not simultaneous:
|
1014 |
+
redo = [i for i, seq in enumerate(sequence) if seq[1] in _illegal]
|
1015 |
+
for i in reversed(redo):
|
1016 |
+
sequence.insert(0, sequence.pop(i))
|
1017 |
+
|
1018 |
+
if simultaneous: # XXX should this be the default for dict subs?
|
1019 |
+
reps = {}
|
1020 |
+
rv = self
|
1021 |
+
kwargs['hack2'] = True
|
1022 |
+
m = Dummy('subs_m')
|
1023 |
+
for old, new in sequence:
|
1024 |
+
com = new.is_commutative
|
1025 |
+
if com is None:
|
1026 |
+
com = True
|
1027 |
+
d = Dummy('subs_d', commutative=com)
|
1028 |
+
# using d*m so Subs will be used on dummy variables
|
1029 |
+
# in things like Derivative(f(x, y), x) in which x
|
1030 |
+
# is both free and bound
|
1031 |
+
rv = rv._subs(old, d*m, **kwargs)
|
1032 |
+
if not isinstance(rv, Basic):
|
1033 |
+
break
|
1034 |
+
reps[d] = new
|
1035 |
+
reps[m] = S.One # get rid of m
|
1036 |
+
return rv.xreplace(reps)
|
1037 |
+
else:
|
1038 |
+
rv = self
|
1039 |
+
for old, new in sequence:
|
1040 |
+
rv = rv._subs(old, new, **kwargs)
|
1041 |
+
if not isinstance(rv, Basic):
|
1042 |
+
break
|
1043 |
+
return rv
|
1044 |
+
|
1045 |
+
@cacheit
|
1046 |
+
def _subs(self, old, new, **hints):
|
1047 |
+
"""Substitutes an expression old -> new.
|
1048 |
+
|
1049 |
+
If self is not equal to old then _eval_subs is called.
|
1050 |
+
If _eval_subs does not want to make any special replacement
|
1051 |
+
then a None is received which indicates that the fallback
|
1052 |
+
should be applied wherein a search for replacements is made
|
1053 |
+
amongst the arguments of self.
|
1054 |
+
|
1055 |
+
>>> from sympy import Add
|
1056 |
+
>>> from sympy.abc import x, y, z
|
1057 |
+
|
1058 |
+
Examples
|
1059 |
+
========
|
1060 |
+
|
1061 |
+
Add's _eval_subs knows how to target x + y in the following
|
1062 |
+
so it makes the change:
|
1063 |
+
|
1064 |
+
>>> (x + y + z).subs(x + y, 1)
|
1065 |
+
z + 1
|
1066 |
+
|
1067 |
+
Add's _eval_subs does not need to know how to find x + y in
|
1068 |
+
the following:
|
1069 |
+
|
1070 |
+
>>> Add._eval_subs(z*(x + y) + 3, x + y, 1) is None
|
1071 |
+
True
|
1072 |
+
|
1073 |
+
The returned None will cause the fallback routine to traverse the args and
|
1074 |
+
pass the z*(x + y) arg to Mul where the change will take place and the
|
1075 |
+
substitution will succeed:
|
1076 |
+
|
1077 |
+
>>> (z*(x + y) + 3).subs(x + y, 1)
|
1078 |
+
z + 3
|
1079 |
+
|
1080 |
+
** Developers Notes **
|
1081 |
+
|
1082 |
+
An _eval_subs routine for a class should be written if:
|
1083 |
+
|
1084 |
+
1) any arguments are not instances of Basic (e.g. bool, tuple);
|
1085 |
+
|
1086 |
+
2) some arguments should not be targeted (as in integration
|
1087 |
+
variables);
|
1088 |
+
|
1089 |
+
3) if there is something other than a literal replacement
|
1090 |
+
that should be attempted (as in Piecewise where the condition
|
1091 |
+
may be updated without doing a replacement).
|
1092 |
+
|
1093 |
+
If it is overridden, here are some special cases that might arise:
|
1094 |
+
|
1095 |
+
1) If it turns out that no special change was made and all
|
1096 |
+
the original sub-arguments should be checked for
|
1097 |
+
replacements then None should be returned.
|
1098 |
+
|
1099 |
+
2) If it is necessary to do substitutions on a portion of
|
1100 |
+
the expression then _subs should be called. _subs will
|
1101 |
+
handle the case of any sub-expression being equal to old
|
1102 |
+
(which usually would not be the case) while its fallback
|
1103 |
+
will handle the recursion into the sub-arguments. For
|
1104 |
+
example, after Add's _eval_subs removes some matching terms
|
1105 |
+
it must process the remaining terms so it calls _subs
|
1106 |
+
on each of the un-matched terms and then adds them
|
1107 |
+
onto the terms previously obtained.
|
1108 |
+
|
1109 |
+
3) If the initial expression should remain unchanged then
|
1110 |
+
the original expression should be returned. (Whenever an
|
1111 |
+
expression is returned, modified or not, no further
|
1112 |
+
substitution of old -> new is attempted.) Sum's _eval_subs
|
1113 |
+
routine uses this strategy when a substitution is attempted
|
1114 |
+
on any of its summation variables.
|
1115 |
+
"""
|
1116 |
+
|
1117 |
+
def fallback(self, old, new):
|
1118 |
+
"""
|
1119 |
+
Try to replace old with new in any of self's arguments.
|
1120 |
+
"""
|
1121 |
+
hit = False
|
1122 |
+
args = list(self.args)
|
1123 |
+
for i, arg in enumerate(args):
|
1124 |
+
if not hasattr(arg, '_eval_subs'):
|
1125 |
+
continue
|
1126 |
+
arg = arg._subs(old, new, **hints)
|
1127 |
+
if not _aresame(arg, args[i]):
|
1128 |
+
hit = True
|
1129 |
+
args[i] = arg
|
1130 |
+
if hit:
|
1131 |
+
rv = self.func(*args)
|
1132 |
+
hack2 = hints.get('hack2', False)
|
1133 |
+
if hack2 and self.is_Mul and not rv.is_Mul: # 2-arg hack
|
1134 |
+
coeff = S.One
|
1135 |
+
nonnumber = []
|
1136 |
+
for i in args:
|
1137 |
+
if i.is_Number:
|
1138 |
+
coeff *= i
|
1139 |
+
else:
|
1140 |
+
nonnumber.append(i)
|
1141 |
+
nonnumber = self.func(*nonnumber)
|
1142 |
+
if coeff is S.One:
|
1143 |
+
return nonnumber
|
1144 |
+
else:
|
1145 |
+
return self.func(coeff, nonnumber, evaluate=False)
|
1146 |
+
return rv
|
1147 |
+
return self
|
1148 |
+
|
1149 |
+
if _aresame(self, old):
|
1150 |
+
return new
|
1151 |
+
|
1152 |
+
rv = self._eval_subs(old, new)
|
1153 |
+
if rv is None:
|
1154 |
+
rv = fallback(self, old, new)
|
1155 |
+
return rv
|
1156 |
+
|
1157 |
+
def _eval_subs(self, old, new):
|
1158 |
+
"""Override this stub if you want to do anything more than
|
1159 |
+
attempt a replacement of old with new in the arguments of self.
|
1160 |
+
|
1161 |
+
See also
|
1162 |
+
========
|
1163 |
+
|
1164 |
+
_subs
|
1165 |
+
"""
|
1166 |
+
return None
|
1167 |
+
|
1168 |
+
def xreplace(self, rule):
|
1169 |
+
"""
|
1170 |
+
Replace occurrences of objects within the expression.
|
1171 |
+
|
1172 |
+
Parameters
|
1173 |
+
==========
|
1174 |
+
|
1175 |
+
rule : dict-like
|
1176 |
+
Expresses a replacement rule
|
1177 |
+
|
1178 |
+
Returns
|
1179 |
+
=======
|
1180 |
+
|
1181 |
+
xreplace : the result of the replacement
|
1182 |
+
|
1183 |
+
Examples
|
1184 |
+
========
|
1185 |
+
|
1186 |
+
>>> from sympy import symbols, pi, exp
|
1187 |
+
>>> x, y, z = symbols('x y z')
|
1188 |
+
>>> (1 + x*y).xreplace({x: pi})
|
1189 |
+
pi*y + 1
|
1190 |
+
>>> (1 + x*y).xreplace({x: pi, y: 2})
|
1191 |
+
1 + 2*pi
|
1192 |
+
|
1193 |
+
Replacements occur only if an entire node in the expression tree is
|
1194 |
+
matched:
|
1195 |
+
|
1196 |
+
>>> (x*y + z).xreplace({x*y: pi})
|
1197 |
+
z + pi
|
1198 |
+
>>> (x*y*z).xreplace({x*y: pi})
|
1199 |
+
x*y*z
|
1200 |
+
>>> (2*x).xreplace({2*x: y, x: z})
|
1201 |
+
y
|
1202 |
+
>>> (2*2*x).xreplace({2*x: y, x: z})
|
1203 |
+
4*z
|
1204 |
+
>>> (x + y + 2).xreplace({x + y: 2})
|
1205 |
+
x + y + 2
|
1206 |
+
>>> (x + 2 + exp(x + 2)).xreplace({x + 2: y})
|
1207 |
+
x + exp(y) + 2
|
1208 |
+
|
1209 |
+
xreplace does not differentiate between free and bound symbols. In the
|
1210 |
+
following, subs(x, y) would not change x since it is a bound symbol,
|
1211 |
+
but xreplace does:
|
1212 |
+
|
1213 |
+
>>> from sympy import Integral
|
1214 |
+
>>> Integral(x, (x, 1, 2*x)).xreplace({x: y})
|
1215 |
+
Integral(y, (y, 1, 2*y))
|
1216 |
+
|
1217 |
+
Trying to replace x with an expression raises an error:
|
1218 |
+
|
1219 |
+
>>> Integral(x, (x, 1, 2*x)).xreplace({x: 2*y}) # doctest: +SKIP
|
1220 |
+
ValueError: Invalid limits given: ((2*y, 1, 4*y),)
|
1221 |
+
|
1222 |
+
See Also
|
1223 |
+
========
|
1224 |
+
replace: replacement capable of doing wildcard-like matching,
|
1225 |
+
parsing of match, and conditional replacements
|
1226 |
+
subs: substitution of subexpressions as defined by the objects
|
1227 |
+
themselves.
|
1228 |
+
|
1229 |
+
"""
|
1230 |
+
value, _ = self._xreplace(rule)
|
1231 |
+
return value
|
1232 |
+
|
1233 |
+
def _xreplace(self, rule):
|
1234 |
+
"""
|
1235 |
+
Helper for xreplace. Tracks whether a replacement actually occurred.
|
1236 |
+
"""
|
1237 |
+
if self in rule:
|
1238 |
+
return rule[self], True
|
1239 |
+
elif rule:
|
1240 |
+
args = []
|
1241 |
+
changed = False
|
1242 |
+
for a in self.args:
|
1243 |
+
_xreplace = getattr(a, '_xreplace', None)
|
1244 |
+
if _xreplace is not None:
|
1245 |
+
a_xr = _xreplace(rule)
|
1246 |
+
args.append(a_xr[0])
|
1247 |
+
changed |= a_xr[1]
|
1248 |
+
else:
|
1249 |
+
args.append(a)
|
1250 |
+
args = tuple(args)
|
1251 |
+
if changed:
|
1252 |
+
return self.func(*args), True
|
1253 |
+
return self, False
|
1254 |
+
|
1255 |
+
@cacheit
|
1256 |
+
def has(self, *patterns):
|
1257 |
+
"""
|
1258 |
+
Test whether any subexpression matches any of the patterns.
|
1259 |
+
|
1260 |
+
Examples
|
1261 |
+
========
|
1262 |
+
|
1263 |
+
>>> from sympy import sin
|
1264 |
+
>>> from sympy.abc import x, y, z
|
1265 |
+
>>> (x**2 + sin(x*y)).has(z)
|
1266 |
+
False
|
1267 |
+
>>> (x**2 + sin(x*y)).has(x, y, z)
|
1268 |
+
True
|
1269 |
+
>>> x.has(x)
|
1270 |
+
True
|
1271 |
+
|
1272 |
+
Note ``has`` is a structural algorithm with no knowledge of
|
1273 |
+
mathematics. Consider the following half-open interval:
|
1274 |
+
|
1275 |
+
>>> from sympy import Interval
|
1276 |
+
>>> i = Interval.Lopen(0, 5); i
|
1277 |
+
Interval.Lopen(0, 5)
|
1278 |
+
>>> i.args
|
1279 |
+
(0, 5, True, False)
|
1280 |
+
>>> i.has(4) # there is no "4" in the arguments
|
1281 |
+
False
|
1282 |
+
>>> i.has(0) # there *is* a "0" in the arguments
|
1283 |
+
True
|
1284 |
+
|
1285 |
+
Instead, use ``contains`` to determine whether a number is in the
|
1286 |
+
interval or not:
|
1287 |
+
|
1288 |
+
>>> i.contains(4)
|
1289 |
+
True
|
1290 |
+
>>> i.contains(0)
|
1291 |
+
False
|
1292 |
+
|
1293 |
+
|
1294 |
+
Note that ``expr.has(*patterns)`` is exactly equivalent to
|
1295 |
+
``any(expr.has(p) for p in patterns)``. In particular, ``False`` is
|
1296 |
+
returned when the list of patterns is empty.
|
1297 |
+
|
1298 |
+
>>> x.has()
|
1299 |
+
False
|
1300 |
+
|
1301 |
+
"""
|
1302 |
+
return self._has(iterargs, *patterns)
|
1303 |
+
|
1304 |
+
def has_xfree(self, s: set[Basic]):
|
1305 |
+
"""Return True if self has any of the patterns in s as a
|
1306 |
+
free argument, else False. This is like `Basic.has_free`
|
1307 |
+
but this will only report exact argument matches.
|
1308 |
+
|
1309 |
+
Examples
|
1310 |
+
========
|
1311 |
+
|
1312 |
+
>>> from sympy import Function
|
1313 |
+
>>> from sympy.abc import x, y
|
1314 |
+
>>> f = Function('f')
|
1315 |
+
>>> f(x).has_xfree({f})
|
1316 |
+
False
|
1317 |
+
>>> f(x).has_xfree({f(x)})
|
1318 |
+
True
|
1319 |
+
>>> f(x + 1).has_xfree({x})
|
1320 |
+
True
|
1321 |
+
>>> f(x + 1).has_xfree({x + 1})
|
1322 |
+
True
|
1323 |
+
>>> f(x + y + 1).has_xfree({x + 1})
|
1324 |
+
False
|
1325 |
+
"""
|
1326 |
+
# protect O(1) containment check by requiring:
|
1327 |
+
if type(s) is not set:
|
1328 |
+
raise TypeError('expecting set argument')
|
1329 |
+
return any(a in s for a in iterfreeargs(self))
|
1330 |
+
|
1331 |
+
@cacheit
|
1332 |
+
def has_free(self, *patterns):
|
1333 |
+
"""Return True if self has object(s) ``x`` as a free expression
|
1334 |
+
else False.
|
1335 |
+
|
1336 |
+
Examples
|
1337 |
+
========
|
1338 |
+
|
1339 |
+
>>> from sympy import Integral, Function
|
1340 |
+
>>> from sympy.abc import x, y
|
1341 |
+
>>> f = Function('f')
|
1342 |
+
>>> g = Function('g')
|
1343 |
+
>>> expr = Integral(f(x), (f(x), 1, g(y)))
|
1344 |
+
>>> expr.free_symbols
|
1345 |
+
{y}
|
1346 |
+
>>> expr.has_free(g(y))
|
1347 |
+
True
|
1348 |
+
>>> expr.has_free(*(x, f(x)))
|
1349 |
+
False
|
1350 |
+
|
1351 |
+
This works for subexpressions and types, too:
|
1352 |
+
|
1353 |
+
>>> expr.has_free(g)
|
1354 |
+
True
|
1355 |
+
>>> (x + y + 1).has_free(y + 1)
|
1356 |
+
True
|
1357 |
+
"""
|
1358 |
+
if not patterns:
|
1359 |
+
return False
|
1360 |
+
p0 = patterns[0]
|
1361 |
+
if len(patterns) == 1 and iterable(p0) and not isinstance(p0, Basic):
|
1362 |
+
# Basic can contain iterables (though not non-Basic, ideally)
|
1363 |
+
# but don't encourage mixed passing patterns
|
1364 |
+
raise TypeError(filldedent('''
|
1365 |
+
Expecting 1 or more Basic args, not a single
|
1366 |
+
non-Basic iterable. Don't forget to unpack
|
1367 |
+
iterables: `eq.has_free(*patterns)`'''))
|
1368 |
+
# try quick test first
|
1369 |
+
s = set(patterns)
|
1370 |
+
rv = self.has_xfree(s)
|
1371 |
+
if rv:
|
1372 |
+
return rv
|
1373 |
+
# now try matching through slower _has
|
1374 |
+
return self._has(iterfreeargs, *patterns)
|
1375 |
+
|
1376 |
+
def _has(self, iterargs, *patterns):
|
1377 |
+
# separate out types and unhashable objects
|
1378 |
+
type_set = set() # only types
|
1379 |
+
p_set = set() # hashable non-types
|
1380 |
+
for p in patterns:
|
1381 |
+
if isinstance(p, type) and issubclass(p, Basic):
|
1382 |
+
type_set.add(p)
|
1383 |
+
continue
|
1384 |
+
if not isinstance(p, Basic):
|
1385 |
+
try:
|
1386 |
+
p = _sympify(p)
|
1387 |
+
except SympifyError:
|
1388 |
+
continue # Basic won't have this in it
|
1389 |
+
p_set.add(p) # fails if object defines __eq__ but
|
1390 |
+
# doesn't define __hash__
|
1391 |
+
types = tuple(type_set) #
|
1392 |
+
for i in iterargs(self): #
|
1393 |
+
if i in p_set: # <--- here, too
|
1394 |
+
return True
|
1395 |
+
if isinstance(i, types):
|
1396 |
+
return True
|
1397 |
+
|
1398 |
+
# use matcher if defined, e.g. operations defines
|
1399 |
+
# matcher that checks for exact subset containment,
|
1400 |
+
# (x + y + 1).has(x + 1) -> True
|
1401 |
+
for i in p_set - type_set: # types don't have matchers
|
1402 |
+
if not hasattr(i, '_has_matcher'):
|
1403 |
+
continue
|
1404 |
+
match = i._has_matcher()
|
1405 |
+
if any(match(arg) for arg in iterargs(self)):
|
1406 |
+
return True
|
1407 |
+
|
1408 |
+
# no success
|
1409 |
+
return False
|
1410 |
+
|
1411 |
+
def replace(self, query, value, map=False, simultaneous=True, exact=None):
|
1412 |
+
"""
|
1413 |
+
Replace matching subexpressions of ``self`` with ``value``.
|
1414 |
+
|
1415 |
+
If ``map = True`` then also return the mapping {old: new} where ``old``
|
1416 |
+
was a sub-expression found with query and ``new`` is the replacement
|
1417 |
+
value for it. If the expression itself does not match the query, then
|
1418 |
+
the returned value will be ``self.xreplace(map)`` otherwise it should
|
1419 |
+
be ``self.subs(ordered(map.items()))``.
|
1420 |
+
|
1421 |
+
Traverses an expression tree and performs replacement of matching
|
1422 |
+
subexpressions from the bottom to the top of the tree. The default
|
1423 |
+
approach is to do the replacement in a simultaneous fashion so
|
1424 |
+
changes made are targeted only once. If this is not desired or causes
|
1425 |
+
problems, ``simultaneous`` can be set to False.
|
1426 |
+
|
1427 |
+
In addition, if an expression containing more than one Wild symbol
|
1428 |
+
is being used to match subexpressions and the ``exact`` flag is None
|
1429 |
+
it will be set to True so the match will only succeed if all non-zero
|
1430 |
+
values are received for each Wild that appears in the match pattern.
|
1431 |
+
Setting this to False accepts a match of 0; while setting it True
|
1432 |
+
accepts all matches that have a 0 in them. See example below for
|
1433 |
+
cautions.
|
1434 |
+
|
1435 |
+
The list of possible combinations of queries and replacement values
|
1436 |
+
is listed below:
|
1437 |
+
|
1438 |
+
Examples
|
1439 |
+
========
|
1440 |
+
|
1441 |
+
Initial setup
|
1442 |
+
|
1443 |
+
>>> from sympy import log, sin, cos, tan, Wild, Mul, Add
|
1444 |
+
>>> from sympy.abc import x, y
|
1445 |
+
>>> f = log(sin(x)) + tan(sin(x**2))
|
1446 |
+
|
1447 |
+
1.1. type -> type
|
1448 |
+
obj.replace(type, newtype)
|
1449 |
+
|
1450 |
+
When object of type ``type`` is found, replace it with the
|
1451 |
+
result of passing its argument(s) to ``newtype``.
|
1452 |
+
|
1453 |
+
>>> f.replace(sin, cos)
|
1454 |
+
log(cos(x)) + tan(cos(x**2))
|
1455 |
+
>>> sin(x).replace(sin, cos, map=True)
|
1456 |
+
(cos(x), {sin(x): cos(x)})
|
1457 |
+
>>> (x*y).replace(Mul, Add)
|
1458 |
+
x + y
|
1459 |
+
|
1460 |
+
1.2. type -> func
|
1461 |
+
obj.replace(type, func)
|
1462 |
+
|
1463 |
+
When object of type ``type`` is found, apply ``func`` to its
|
1464 |
+
argument(s). ``func`` must be written to handle the number
|
1465 |
+
of arguments of ``type``.
|
1466 |
+
|
1467 |
+
>>> f.replace(sin, lambda arg: sin(2*arg))
|
1468 |
+
log(sin(2*x)) + tan(sin(2*x**2))
|
1469 |
+
>>> (x*y).replace(Mul, lambda *args: sin(2*Mul(*args)))
|
1470 |
+
sin(2*x*y)
|
1471 |
+
|
1472 |
+
2.1. pattern -> expr
|
1473 |
+
obj.replace(pattern(wild), expr(wild))
|
1474 |
+
|
1475 |
+
Replace subexpressions matching ``pattern`` with the expression
|
1476 |
+
written in terms of the Wild symbols in ``pattern``.
|
1477 |
+
|
1478 |
+
>>> a, b = map(Wild, 'ab')
|
1479 |
+
>>> f.replace(sin(a), tan(a))
|
1480 |
+
log(tan(x)) + tan(tan(x**2))
|
1481 |
+
>>> f.replace(sin(a), tan(a/2))
|
1482 |
+
log(tan(x/2)) + tan(tan(x**2/2))
|
1483 |
+
>>> f.replace(sin(a), a)
|
1484 |
+
log(x) + tan(x**2)
|
1485 |
+
>>> (x*y).replace(a*x, a)
|
1486 |
+
y
|
1487 |
+
|
1488 |
+
Matching is exact by default when more than one Wild symbol
|
1489 |
+
is used: matching fails unless the match gives non-zero
|
1490 |
+
values for all Wild symbols:
|
1491 |
+
|
1492 |
+
>>> (2*x + y).replace(a*x + b, b - a)
|
1493 |
+
y - 2
|
1494 |
+
>>> (2*x).replace(a*x + b, b - a)
|
1495 |
+
2*x
|
1496 |
+
|
1497 |
+
When set to False, the results may be non-intuitive:
|
1498 |
+
|
1499 |
+
>>> (2*x).replace(a*x + b, b - a, exact=False)
|
1500 |
+
2/x
|
1501 |
+
|
1502 |
+
2.2. pattern -> func
|
1503 |
+
obj.replace(pattern(wild), lambda wild: expr(wild))
|
1504 |
+
|
1505 |
+
All behavior is the same as in 2.1 but now a function in terms of
|
1506 |
+
pattern variables is used rather than an expression:
|
1507 |
+
|
1508 |
+
>>> f.replace(sin(a), lambda a: sin(2*a))
|
1509 |
+
log(sin(2*x)) + tan(sin(2*x**2))
|
1510 |
+
|
1511 |
+
3.1. func -> func
|
1512 |
+
obj.replace(filter, func)
|
1513 |
+
|
1514 |
+
Replace subexpression ``e`` with ``func(e)`` if ``filter(e)``
|
1515 |
+
is True.
|
1516 |
+
|
1517 |
+
>>> g = 2*sin(x**3)
|
1518 |
+
>>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2)
|
1519 |
+
4*sin(x**9)
|
1520 |
+
|
1521 |
+
The expression itself is also targeted by the query but is done in
|
1522 |
+
such a fashion that changes are not made twice.
|
1523 |
+
|
1524 |
+
>>> e = x*(x*y + 1)
|
1525 |
+
>>> e.replace(lambda x: x.is_Mul, lambda x: 2*x)
|
1526 |
+
2*x*(2*x*y + 1)
|
1527 |
+
|
1528 |
+
When matching a single symbol, `exact` will default to True, but
|
1529 |
+
this may or may not be the behavior that is desired:
|
1530 |
+
|
1531 |
+
Here, we want `exact=False`:
|
1532 |
+
|
1533 |
+
>>> from sympy import Function
|
1534 |
+
>>> f = Function('f')
|
1535 |
+
>>> e = f(1) + f(0)
|
1536 |
+
>>> q = f(a), lambda a: f(a + 1)
|
1537 |
+
>>> e.replace(*q, exact=False)
|
1538 |
+
f(1) + f(2)
|
1539 |
+
>>> e.replace(*q, exact=True)
|
1540 |
+
f(0) + f(2)
|
1541 |
+
|
1542 |
+
But here, the nature of matching makes selecting
|
1543 |
+
the right setting tricky:
|
1544 |
+
|
1545 |
+
>>> e = x**(1 + y)
|
1546 |
+
>>> (x**(1 + y)).replace(x**(1 + a), lambda a: x**-a, exact=False)
|
1547 |
+
x
|
1548 |
+
>>> (x**(1 + y)).replace(x**(1 + a), lambda a: x**-a, exact=True)
|
1549 |
+
x**(-x - y + 1)
|
1550 |
+
>>> (x**y).replace(x**(1 + a), lambda a: x**-a, exact=False)
|
1551 |
+
x
|
1552 |
+
>>> (x**y).replace(x**(1 + a), lambda a: x**-a, exact=True)
|
1553 |
+
x**(1 - y)
|
1554 |
+
|
1555 |
+
It is probably better to use a different form of the query
|
1556 |
+
that describes the target expression more precisely:
|
1557 |
+
|
1558 |
+
>>> (1 + x**(1 + y)).replace(
|
1559 |
+
... lambda x: x.is_Pow and x.exp.is_Add and x.exp.args[0] == 1,
|
1560 |
+
... lambda x: x.base**(1 - (x.exp - 1)))
|
1561 |
+
...
|
1562 |
+
x**(1 - y) + 1
|
1563 |
+
|
1564 |
+
See Also
|
1565 |
+
========
|
1566 |
+
|
1567 |
+
subs: substitution of subexpressions as defined by the objects
|
1568 |
+
themselves.
|
1569 |
+
xreplace: exact node replacement in expr tree; also capable of
|
1570 |
+
using matching rules
|
1571 |
+
|
1572 |
+
"""
|
1573 |
+
|
1574 |
+
try:
|
1575 |
+
query = _sympify(query)
|
1576 |
+
except SympifyError:
|
1577 |
+
pass
|
1578 |
+
try:
|
1579 |
+
value = _sympify(value)
|
1580 |
+
except SympifyError:
|
1581 |
+
pass
|
1582 |
+
if isinstance(query, type):
|
1583 |
+
_query = lambda expr: isinstance(expr, query)
|
1584 |
+
|
1585 |
+
if isinstance(value, type):
|
1586 |
+
_value = lambda expr, result: value(*expr.args)
|
1587 |
+
elif callable(value):
|
1588 |
+
_value = lambda expr, result: value(*expr.args)
|
1589 |
+
else:
|
1590 |
+
raise TypeError(
|
1591 |
+
"given a type, replace() expects another "
|
1592 |
+
"type or a callable")
|
1593 |
+
elif isinstance(query, Basic):
|
1594 |
+
_query = lambda expr: expr.match(query)
|
1595 |
+
if exact is None:
|
1596 |
+
from .symbol import Wild
|
1597 |
+
exact = (len(query.atoms(Wild)) > 1)
|
1598 |
+
|
1599 |
+
if isinstance(value, Basic):
|
1600 |
+
if exact:
|
1601 |
+
_value = lambda expr, result: (value.subs(result)
|
1602 |
+
if all(result.values()) else expr)
|
1603 |
+
else:
|
1604 |
+
_value = lambda expr, result: value.subs(result)
|
1605 |
+
elif callable(value):
|
1606 |
+
# match dictionary keys get the trailing underscore stripped
|
1607 |
+
# from them and are then passed as keywords to the callable;
|
1608 |
+
# if ``exact`` is True, only accept match if there are no null
|
1609 |
+
# values amongst those matched.
|
1610 |
+
if exact:
|
1611 |
+
_value = lambda expr, result: (value(**
|
1612 |
+
{str(k)[:-1]: v for k, v in result.items()})
|
1613 |
+
if all(val for val in result.values()) else expr)
|
1614 |
+
else:
|
1615 |
+
_value = lambda expr, result: value(**
|
1616 |
+
{str(k)[:-1]: v for k, v in result.items()})
|
1617 |
+
else:
|
1618 |
+
raise TypeError(
|
1619 |
+
"given an expression, replace() expects "
|
1620 |
+
"another expression or a callable")
|
1621 |
+
elif callable(query):
|
1622 |
+
_query = query
|
1623 |
+
|
1624 |
+
if callable(value):
|
1625 |
+
_value = lambda expr, result: value(expr)
|
1626 |
+
else:
|
1627 |
+
raise TypeError(
|
1628 |
+
"given a callable, replace() expects "
|
1629 |
+
"another callable")
|
1630 |
+
else:
|
1631 |
+
raise TypeError(
|
1632 |
+
"first argument to replace() must be a "
|
1633 |
+
"type, an expression or a callable")
|
1634 |
+
|
1635 |
+
def walk(rv, F):
|
1636 |
+
"""Apply ``F`` to args and then to result.
|
1637 |
+
"""
|
1638 |
+
args = getattr(rv, 'args', None)
|
1639 |
+
if args is not None:
|
1640 |
+
if args:
|
1641 |
+
newargs = tuple([walk(a, F) for a in args])
|
1642 |
+
if args != newargs:
|
1643 |
+
rv = rv.func(*newargs)
|
1644 |
+
if simultaneous:
|
1645 |
+
# if rv is something that was already
|
1646 |
+
# matched (that was changed) then skip
|
1647 |
+
# applying F again
|
1648 |
+
for i, e in enumerate(args):
|
1649 |
+
if rv == e and e != newargs[i]:
|
1650 |
+
return rv
|
1651 |
+
rv = F(rv)
|
1652 |
+
return rv
|
1653 |
+
|
1654 |
+
mapping = {} # changes that took place
|
1655 |
+
|
1656 |
+
def rec_replace(expr):
|
1657 |
+
result = _query(expr)
|
1658 |
+
if result or result == {}:
|
1659 |
+
v = _value(expr, result)
|
1660 |
+
if v is not None and v != expr:
|
1661 |
+
if map:
|
1662 |
+
mapping[expr] = v
|
1663 |
+
expr = v
|
1664 |
+
return expr
|
1665 |
+
|
1666 |
+
rv = walk(self, rec_replace)
|
1667 |
+
return (rv, mapping) if map else rv
|
1668 |
+
|
1669 |
+
def find(self, query, group=False):
|
1670 |
+
"""Find all subexpressions matching a query."""
|
1671 |
+
query = _make_find_query(query)
|
1672 |
+
results = list(filter(query, _preorder_traversal(self)))
|
1673 |
+
|
1674 |
+
if not group:
|
1675 |
+
return set(results)
|
1676 |
+
else:
|
1677 |
+
groups = {}
|
1678 |
+
|
1679 |
+
for result in results:
|
1680 |
+
if result in groups:
|
1681 |
+
groups[result] += 1
|
1682 |
+
else:
|
1683 |
+
groups[result] = 1
|
1684 |
+
|
1685 |
+
return groups
|
1686 |
+
|
1687 |
+
def count(self, query):
|
1688 |
+
"""Count the number of matching subexpressions."""
|
1689 |
+
query = _make_find_query(query)
|
1690 |
+
return sum(bool(query(sub)) for sub in _preorder_traversal(self))
|
1691 |
+
|
1692 |
+
def matches(self, expr, repl_dict=None, old=False):
|
1693 |
+
"""
|
1694 |
+
Helper method for match() that looks for a match between Wild symbols
|
1695 |
+
in self and expressions in expr.
|
1696 |
+
|
1697 |
+
Examples
|
1698 |
+
========
|
1699 |
+
|
1700 |
+
>>> from sympy import symbols, Wild, Basic
|
1701 |
+
>>> a, b, c = symbols('a b c')
|
1702 |
+
>>> x = Wild('x')
|
1703 |
+
>>> Basic(a + x, x).matches(Basic(a + b, c)) is None
|
1704 |
+
True
|
1705 |
+
>>> Basic(a + x, x).matches(Basic(a + b + c, b + c))
|
1706 |
+
{x_: b + c}
|
1707 |
+
"""
|
1708 |
+
expr = sympify(expr)
|
1709 |
+
if not isinstance(expr, self.__class__):
|
1710 |
+
return None
|
1711 |
+
|
1712 |
+
if repl_dict is None:
|
1713 |
+
repl_dict = {}
|
1714 |
+
else:
|
1715 |
+
repl_dict = repl_dict.copy()
|
1716 |
+
|
1717 |
+
if self == expr:
|
1718 |
+
return repl_dict
|
1719 |
+
|
1720 |
+
if len(self.args) != len(expr.args):
|
1721 |
+
return None
|
1722 |
+
|
1723 |
+
d = repl_dict # already a copy
|
1724 |
+
for arg, other_arg in zip(self.args, expr.args):
|
1725 |
+
if arg == other_arg:
|
1726 |
+
continue
|
1727 |
+
if arg.is_Relational:
|
1728 |
+
try:
|
1729 |
+
d = arg.xreplace(d).matches(other_arg, d, old=old)
|
1730 |
+
except TypeError: # Should be InvalidComparisonError when introduced
|
1731 |
+
d = None
|
1732 |
+
else:
|
1733 |
+
d = arg.xreplace(d).matches(other_arg, d, old=old)
|
1734 |
+
if d is None:
|
1735 |
+
return None
|
1736 |
+
return d
|
1737 |
+
|
1738 |
+
def match(self, pattern, old=False):
|
1739 |
+
"""
|
1740 |
+
Pattern matching.
|
1741 |
+
|
1742 |
+
Wild symbols match all.
|
1743 |
+
|
1744 |
+
Return ``None`` when expression (self) does not match
|
1745 |
+
with pattern. Otherwise return a dictionary such that::
|
1746 |
+
|
1747 |
+
pattern.xreplace(self.match(pattern)) == self
|
1748 |
+
|
1749 |
+
Examples
|
1750 |
+
========
|
1751 |
+
|
1752 |
+
>>> from sympy import Wild, Sum
|
1753 |
+
>>> from sympy.abc import x, y
|
1754 |
+
>>> p = Wild("p")
|
1755 |
+
>>> q = Wild("q")
|
1756 |
+
>>> r = Wild("r")
|
1757 |
+
>>> e = (x+y)**(x+y)
|
1758 |
+
>>> e.match(p**p)
|
1759 |
+
{p_: x + y}
|
1760 |
+
>>> e.match(p**q)
|
1761 |
+
{p_: x + y, q_: x + y}
|
1762 |
+
>>> e = (2*x)**2
|
1763 |
+
>>> e.match(p*q**r)
|
1764 |
+
{p_: 4, q_: x, r_: 2}
|
1765 |
+
>>> (p*q**r).xreplace(e.match(p*q**r))
|
1766 |
+
4*x**2
|
1767 |
+
|
1768 |
+
Structurally bound symbols are ignored during matching:
|
1769 |
+
|
1770 |
+
>>> Sum(x, (x, 1, 2)).match(Sum(y, (y, 1, p)))
|
1771 |
+
{p_: 2}
|
1772 |
+
|
1773 |
+
But they can be identified if desired:
|
1774 |
+
|
1775 |
+
>>> Sum(x, (x, 1, 2)).match(Sum(q, (q, 1, p)))
|
1776 |
+
{p_: 2, q_: x}
|
1777 |
+
|
1778 |
+
The ``old`` flag will give the old-style pattern matching where
|
1779 |
+
expressions and patterns are essentially solved to give the
|
1780 |
+
match. Both of the following give None unless ``old=True``:
|
1781 |
+
|
1782 |
+
>>> (x - 2).match(p - x, old=True)
|
1783 |
+
{p_: 2*x - 2}
|
1784 |
+
>>> (2/x).match(p*x, old=True)
|
1785 |
+
{p_: 2/x**2}
|
1786 |
+
|
1787 |
+
"""
|
1788 |
+
pattern = sympify(pattern)
|
1789 |
+
# match non-bound symbols
|
1790 |
+
canonical = lambda x: x if x.is_Symbol else x.as_dummy()
|
1791 |
+
m = canonical(pattern).matches(canonical(self), old=old)
|
1792 |
+
if m is None:
|
1793 |
+
return m
|
1794 |
+
from .symbol import Wild
|
1795 |
+
from .function import WildFunction
|
1796 |
+
from ..tensor.tensor import WildTensor, WildTensorIndex, WildTensorHead
|
1797 |
+
wild = pattern.atoms(Wild, WildFunction, WildTensor, WildTensorIndex, WildTensorHead)
|
1798 |
+
# sanity check
|
1799 |
+
if set(m) - wild:
|
1800 |
+
raise ValueError(filldedent('''
|
1801 |
+
Some `matches` routine did not use a copy of repl_dict
|
1802 |
+
and injected unexpected symbols. Report this as an
|
1803 |
+
error at https://github.com/sympy/sympy/issues'''))
|
1804 |
+
# now see if bound symbols were requested
|
1805 |
+
bwild = wild - set(m)
|
1806 |
+
if not bwild:
|
1807 |
+
return m
|
1808 |
+
# replace free-Wild symbols in pattern with match result
|
1809 |
+
# so they will match but not be in the next match
|
1810 |
+
wpat = pattern.xreplace(m)
|
1811 |
+
# identify remaining bound wild
|
1812 |
+
w = wpat.matches(self, old=old)
|
1813 |
+
# add them to m
|
1814 |
+
if w:
|
1815 |
+
m.update(w)
|
1816 |
+
# done
|
1817 |
+
return m
|
1818 |
+
|
1819 |
+
def count_ops(self, visual=None):
|
1820 |
+
"""Wrapper for count_ops that returns the operation count."""
|
1821 |
+
from .function import count_ops
|
1822 |
+
return count_ops(self, visual)
|
1823 |
+
|
1824 |
+
def doit(self, **hints):
|
1825 |
+
"""Evaluate objects that are not evaluated by default like limits,
|
1826 |
+
integrals, sums and products. All objects of this kind will be
|
1827 |
+
evaluated recursively, unless some species were excluded via 'hints'
|
1828 |
+
or unless the 'deep' hint was set to 'False'.
|
1829 |
+
|
1830 |
+
>>> from sympy import Integral
|
1831 |
+
>>> from sympy.abc import x
|
1832 |
+
|
1833 |
+
>>> 2*Integral(x, x)
|
1834 |
+
2*Integral(x, x)
|
1835 |
+
|
1836 |
+
>>> (2*Integral(x, x)).doit()
|
1837 |
+
x**2
|
1838 |
+
|
1839 |
+
>>> (2*Integral(x, x)).doit(deep=False)
|
1840 |
+
2*Integral(x, x)
|
1841 |
+
|
1842 |
+
"""
|
1843 |
+
if hints.get('deep', True):
|
1844 |
+
terms = [term.doit(**hints) if isinstance(term, Basic) else term
|
1845 |
+
for term in self.args]
|
1846 |
+
return self.func(*terms)
|
1847 |
+
else:
|
1848 |
+
return self
|
1849 |
+
|
1850 |
+
def simplify(self, **kwargs):
|
1851 |
+
"""See the simplify function in sympy.simplify"""
|
1852 |
+
from sympy.simplify.simplify import simplify
|
1853 |
+
return simplify(self, **kwargs)
|
1854 |
+
|
1855 |
+
def refine(self, assumption=True):
|
1856 |
+
"""See the refine function in sympy.assumptions"""
|
1857 |
+
from sympy.assumptions.refine import refine
|
1858 |
+
return refine(self, assumption)
|
1859 |
+
|
1860 |
+
def _eval_derivative_n_times(self, s, n):
|
1861 |
+
# This is the default evaluator for derivatives (as called by `diff`
|
1862 |
+
# and `Derivative`), it will attempt a loop to derive the expression
|
1863 |
+
# `n` times by calling the corresponding `_eval_derivative` method,
|
1864 |
+
# while leaving the derivative unevaluated if `n` is symbolic. This
|
1865 |
+
# method should be overridden if the object has a closed form for its
|
1866 |
+
# symbolic n-th derivative.
|
1867 |
+
from .numbers import Integer
|
1868 |
+
if isinstance(n, (int, Integer)):
|
1869 |
+
obj = self
|
1870 |
+
for i in range(n):
|
1871 |
+
obj2 = obj._eval_derivative(s)
|
1872 |
+
if obj == obj2 or obj2 is None:
|
1873 |
+
break
|
1874 |
+
obj = obj2
|
1875 |
+
return obj2
|
1876 |
+
else:
|
1877 |
+
return None
|
1878 |
+
|
1879 |
+
def rewrite(self, *args, deep=True, **hints):
|
1880 |
+
"""
|
1881 |
+
Rewrite *self* using a defined rule.
|
1882 |
+
|
1883 |
+
Rewriting transforms an expression to another, which is mathematically
|
1884 |
+
equivalent but structurally different. For example you can rewrite
|
1885 |
+
trigonometric functions as complex exponentials or combinatorial
|
1886 |
+
functions as gamma function.
|
1887 |
+
|
1888 |
+
This method takes a *pattern* and a *rule* as positional arguments.
|
1889 |
+
*pattern* is optional parameter which defines the types of expressions
|
1890 |
+
that will be transformed. If it is not passed, all possible expressions
|
1891 |
+
will be rewritten. *rule* defines how the expression will be rewritten.
|
1892 |
+
|
1893 |
+
Parameters
|
1894 |
+
==========
|
1895 |
+
|
1896 |
+
args : Expr
|
1897 |
+
A *rule*, or *pattern* and *rule*.
|
1898 |
+
- *pattern* is a type or an iterable of types.
|
1899 |
+
- *rule* can be any object.
|
1900 |
+
|
1901 |
+
deep : bool, optional
|
1902 |
+
If ``True``, subexpressions are recursively transformed. Default is
|
1903 |
+
``True``.
|
1904 |
+
|
1905 |
+
Examples
|
1906 |
+
========
|
1907 |
+
|
1908 |
+
If *pattern* is unspecified, all possible expressions are transformed.
|
1909 |
+
|
1910 |
+
>>> from sympy import cos, sin, exp, I
|
1911 |
+
>>> from sympy.abc import x
|
1912 |
+
>>> expr = cos(x) + I*sin(x)
|
1913 |
+
>>> expr.rewrite(exp)
|
1914 |
+
exp(I*x)
|
1915 |
+
|
1916 |
+
Pattern can be a type or an iterable of types.
|
1917 |
+
|
1918 |
+
>>> expr.rewrite(sin, exp)
|
1919 |
+
exp(I*x)/2 + cos(x) - exp(-I*x)/2
|
1920 |
+
>>> expr.rewrite([cos,], exp)
|
1921 |
+
exp(I*x)/2 + I*sin(x) + exp(-I*x)/2
|
1922 |
+
>>> expr.rewrite([cos, sin], exp)
|
1923 |
+
exp(I*x)
|
1924 |
+
|
1925 |
+
Rewriting behavior can be implemented by defining ``_eval_rewrite()``
|
1926 |
+
method.
|
1927 |
+
|
1928 |
+
>>> from sympy import Expr, sqrt, pi
|
1929 |
+
>>> class MySin(Expr):
|
1930 |
+
... def _eval_rewrite(self, rule, args, **hints):
|
1931 |
+
... x, = args
|
1932 |
+
... if rule == cos:
|
1933 |
+
... return cos(pi/2 - x, evaluate=False)
|
1934 |
+
... if rule == sqrt:
|
1935 |
+
... return sqrt(1 - cos(x)**2)
|
1936 |
+
>>> MySin(MySin(x)).rewrite(cos)
|
1937 |
+
cos(-cos(-x + pi/2) + pi/2)
|
1938 |
+
>>> MySin(x).rewrite(sqrt)
|
1939 |
+
sqrt(1 - cos(x)**2)
|
1940 |
+
|
1941 |
+
Defining ``_eval_rewrite_as_[...]()`` method is supported for backwards
|
1942 |
+
compatibility reason. This may be removed in the future and using it is
|
1943 |
+
discouraged.
|
1944 |
+
|
1945 |
+
>>> class MySin(Expr):
|
1946 |
+
... def _eval_rewrite_as_cos(self, *args, **hints):
|
1947 |
+
... x, = args
|
1948 |
+
... return cos(pi/2 - x, evaluate=False)
|
1949 |
+
>>> MySin(x).rewrite(cos)
|
1950 |
+
cos(-x + pi/2)
|
1951 |
+
|
1952 |
+
"""
|
1953 |
+
if not args:
|
1954 |
+
return self
|
1955 |
+
|
1956 |
+
hints.update(deep=deep)
|
1957 |
+
|
1958 |
+
pattern = args[:-1]
|
1959 |
+
rule = args[-1]
|
1960 |
+
|
1961 |
+
# support old design by _eval_rewrite_as_[...] method
|
1962 |
+
if isinstance(rule, str):
|
1963 |
+
method = "_eval_rewrite_as_%s" % rule
|
1964 |
+
elif hasattr(rule, "__name__"):
|
1965 |
+
# rule is class or function
|
1966 |
+
clsname = rule.__name__
|
1967 |
+
method = "_eval_rewrite_as_%s" % clsname
|
1968 |
+
else:
|
1969 |
+
# rule is instance
|
1970 |
+
clsname = rule.__class__.__name__
|
1971 |
+
method = "_eval_rewrite_as_%s" % clsname
|
1972 |
+
|
1973 |
+
if pattern:
|
1974 |
+
if iterable(pattern[0]):
|
1975 |
+
pattern = pattern[0]
|
1976 |
+
pattern = tuple(p for p in pattern if self.has(p))
|
1977 |
+
if not pattern:
|
1978 |
+
return self
|
1979 |
+
# hereafter, empty pattern is interpreted as all pattern.
|
1980 |
+
|
1981 |
+
return self._rewrite(pattern, rule, method, **hints)
|
1982 |
+
|
1983 |
+
def _rewrite(self, pattern, rule, method, **hints):
|
1984 |
+
deep = hints.pop('deep', True)
|
1985 |
+
if deep:
|
1986 |
+
args = [a._rewrite(pattern, rule, method, **hints)
|
1987 |
+
for a in self.args]
|
1988 |
+
else:
|
1989 |
+
args = self.args
|
1990 |
+
if not pattern or any(isinstance(self, p) for p in pattern):
|
1991 |
+
meth = getattr(self, method, None)
|
1992 |
+
if meth is not None:
|
1993 |
+
rewritten = meth(*args, **hints)
|
1994 |
+
else:
|
1995 |
+
rewritten = self._eval_rewrite(rule, args, **hints)
|
1996 |
+
if rewritten is not None:
|
1997 |
+
return rewritten
|
1998 |
+
if not args:
|
1999 |
+
return self
|
2000 |
+
return self.func(*args)
|
2001 |
+
|
2002 |
+
def _eval_rewrite(self, rule, args, **hints):
|
2003 |
+
return None
|
2004 |
+
|
2005 |
+
_constructor_postprocessor_mapping = {} # type: ignore
|
2006 |
+
|
2007 |
+
@classmethod
|
2008 |
+
def _exec_constructor_postprocessors(cls, obj):
|
2009 |
+
# WARNING: This API is experimental.
|
2010 |
+
|
2011 |
+
# This is an experimental API that introduces constructor
|
2012 |
+
# postprosessors for SymPy Core elements. If an argument of a SymPy
|
2013 |
+
# expression has a `_constructor_postprocessor_mapping` attribute, it will
|
2014 |
+
# be interpreted as a dictionary containing lists of postprocessing
|
2015 |
+
# functions for matching expression node names.
|
2016 |
+
|
2017 |
+
clsname = obj.__class__.__name__
|
2018 |
+
postprocessors = defaultdict(list)
|
2019 |
+
for i in obj.args:
|
2020 |
+
try:
|
2021 |
+
postprocessor_mappings = (
|
2022 |
+
Basic._constructor_postprocessor_mapping[cls].items()
|
2023 |
+
for cls in type(i).mro()
|
2024 |
+
if cls in Basic._constructor_postprocessor_mapping
|
2025 |
+
)
|
2026 |
+
for k, v in chain.from_iterable(postprocessor_mappings):
|
2027 |
+
postprocessors[k].extend([j for j in v if j not in postprocessors[k]])
|
2028 |
+
except TypeError:
|
2029 |
+
pass
|
2030 |
+
|
2031 |
+
for f in postprocessors.get(clsname, []):
|
2032 |
+
obj = f(obj)
|
2033 |
+
|
2034 |
+
return obj
|
2035 |
+
|
2036 |
+
def _sage_(self):
|
2037 |
+
"""
|
2038 |
+
Convert *self* to a symbolic expression of SageMath.
|
2039 |
+
|
2040 |
+
This version of the method is merely a placeholder.
|
2041 |
+
"""
|
2042 |
+
old_method = self._sage_
|
2043 |
+
from sage.interfaces.sympy import sympy_init
|
2044 |
+
sympy_init() # may monkey-patch _sage_ method into self's class or superclasses
|
2045 |
+
if old_method == self._sage_:
|
2046 |
+
raise NotImplementedError('conversion to SageMath is not implemented')
|
2047 |
+
else:
|
2048 |
+
# call the freshly monkey-patched method
|
2049 |
+
return self._sage_()
|
2050 |
+
|
2051 |
+
def could_extract_minus_sign(self):
|
2052 |
+
return False # see Expr.could_extract_minus_sign
|
2053 |
+
|
2054 |
+
|
2055 |
+
# For all Basic subclasses _prepare_class_assumptions is called by
|
2056 |
+
# Basic.__init_subclass__ but that method is not called for Basic itself so we
|
2057 |
+
# call the function here instead.
|
2058 |
+
_prepare_class_assumptions(Basic)
|
2059 |
+
|
2060 |
+
|
2061 |
+
class Atom(Basic):
|
2062 |
+
"""
|
2063 |
+
A parent class for atomic things. An atom is an expression with no subexpressions.
|
2064 |
+
|
2065 |
+
Examples
|
2066 |
+
========
|
2067 |
+
|
2068 |
+
Symbol, Number, Rational, Integer, ...
|
2069 |
+
But not: Add, Mul, Pow, ...
|
2070 |
+
"""
|
2071 |
+
|
2072 |
+
is_Atom = True
|
2073 |
+
|
2074 |
+
__slots__ = ()
|
2075 |
+
|
2076 |
+
def matches(self, expr, repl_dict=None, old=False):
|
2077 |
+
if self == expr:
|
2078 |
+
if repl_dict is None:
|
2079 |
+
return {}
|
2080 |
+
return repl_dict.copy()
|
2081 |
+
|
2082 |
+
def xreplace(self, rule, hack2=False):
|
2083 |
+
return rule.get(self, self)
|
2084 |
+
|
2085 |
+
def doit(self, **hints):
|
2086 |
+
return self
|
2087 |
+
|
2088 |
+
@classmethod
|
2089 |
+
def class_key(cls):
|
2090 |
+
return 2, 0, cls.__name__
|
2091 |
+
|
2092 |
+
@cacheit
|
2093 |
+
def sort_key(self, order=None):
|
2094 |
+
return self.class_key(), (1, (str(self),)), S.One.sort_key(), S.One
|
2095 |
+
|
2096 |
+
def _eval_simplify(self, **kwargs):
|
2097 |
+
return self
|
2098 |
+
|
2099 |
+
@property
|
2100 |
+
def _sorted_args(self):
|
2101 |
+
# this is here as a safeguard against accidentally using _sorted_args
|
2102 |
+
# on Atoms -- they cannot be rebuilt as atom.func(*atom._sorted_args)
|
2103 |
+
# since there are no args. So the calling routine should be checking
|
2104 |
+
# to see that this property is not called for Atoms.
|
2105 |
+
raise AttributeError('Atoms have no args. It might be necessary'
|
2106 |
+
' to make a check for Atoms in the calling code.')
|
2107 |
+
|
2108 |
+
|
2109 |
+
def _aresame(a, b):
|
2110 |
+
"""Return True if a and b are structurally the same, else False.
|
2111 |
+
|
2112 |
+
Examples
|
2113 |
+
========
|
2114 |
+
|
2115 |
+
In SymPy (as in Python) two numbers compare the same if they
|
2116 |
+
have the same underlying base-2 representation even though
|
2117 |
+
they may not be the same type:
|
2118 |
+
|
2119 |
+
>>> from sympy import S
|
2120 |
+
>>> 2.0 == S(2)
|
2121 |
+
True
|
2122 |
+
>>> 0.5 == S.Half
|
2123 |
+
True
|
2124 |
+
|
2125 |
+
This routine was written to provide a query for such cases that
|
2126 |
+
would give false when the types do not match:
|
2127 |
+
|
2128 |
+
>>> from sympy.core.basic import _aresame
|
2129 |
+
>>> _aresame(S(2.0), S(2))
|
2130 |
+
False
|
2131 |
+
|
2132 |
+
"""
|
2133 |
+
from .numbers import Number
|
2134 |
+
from .function import AppliedUndef, UndefinedFunction as UndefFunc
|
2135 |
+
if isinstance(a, Number) and isinstance(b, Number):
|
2136 |
+
return a == b and a.__class__ == b.__class__
|
2137 |
+
for i, j in zip_longest(_preorder_traversal(a), _preorder_traversal(b)):
|
2138 |
+
if i != j or type(i) != type(j):
|
2139 |
+
if ((isinstance(i, UndefFunc) and isinstance(j, UndefFunc)) or
|
2140 |
+
(isinstance(i, AppliedUndef) and isinstance(j, AppliedUndef))):
|
2141 |
+
if i.class_key() != j.class_key():
|
2142 |
+
return False
|
2143 |
+
else:
|
2144 |
+
return False
|
2145 |
+
return True
|
2146 |
+
|
2147 |
+
|
2148 |
+
def _ne(a, b):
|
2149 |
+
# use this as a second test after `a != b` if you want to make
|
2150 |
+
# sure that things are truly equal, e.g.
|
2151 |
+
# a, b = 0.5, S.Half
|
2152 |
+
# a !=b or _ne(a, b) -> True
|
2153 |
+
from .numbers import Number
|
2154 |
+
# 0.5 == S.Half
|
2155 |
+
if isinstance(a, Number) and isinstance(b, Number):
|
2156 |
+
return a.__class__ != b.__class__
|
2157 |
+
|
2158 |
+
|
2159 |
+
def _atomic(e, recursive=False):
|
2160 |
+
"""Return atom-like quantities as far as substitution is
|
2161 |
+
concerned: Derivatives, Functions and Symbols. Do not
|
2162 |
+
return any 'atoms' that are inside such quantities unless
|
2163 |
+
they also appear outside, too, unless `recursive` is True.
|
2164 |
+
|
2165 |
+
Examples
|
2166 |
+
========
|
2167 |
+
|
2168 |
+
>>> from sympy import Derivative, Function, cos
|
2169 |
+
>>> from sympy.abc import x, y
|
2170 |
+
>>> from sympy.core.basic import _atomic
|
2171 |
+
>>> f = Function('f')
|
2172 |
+
>>> _atomic(x + y)
|
2173 |
+
{x, y}
|
2174 |
+
>>> _atomic(x + f(y))
|
2175 |
+
{x, f(y)}
|
2176 |
+
>>> _atomic(Derivative(f(x), x) + cos(x) + y)
|
2177 |
+
{y, cos(x), Derivative(f(x), x)}
|
2178 |
+
|
2179 |
+
"""
|
2180 |
+
pot = _preorder_traversal(e)
|
2181 |
+
seen = set()
|
2182 |
+
if isinstance(e, Basic):
|
2183 |
+
free = getattr(e, "free_symbols", None)
|
2184 |
+
if free is None:
|
2185 |
+
return {e}
|
2186 |
+
else:
|
2187 |
+
return set()
|
2188 |
+
from .symbol import Symbol
|
2189 |
+
from .function import Derivative, Function
|
2190 |
+
atoms = set()
|
2191 |
+
for p in pot:
|
2192 |
+
if p in seen:
|
2193 |
+
pot.skip()
|
2194 |
+
continue
|
2195 |
+
seen.add(p)
|
2196 |
+
if isinstance(p, Symbol) and p in free:
|
2197 |
+
atoms.add(p)
|
2198 |
+
elif isinstance(p, (Derivative, Function)):
|
2199 |
+
if not recursive:
|
2200 |
+
pot.skip()
|
2201 |
+
atoms.add(p)
|
2202 |
+
return atoms
|
2203 |
+
|
2204 |
+
|
2205 |
+
def _make_find_query(query):
|
2206 |
+
"""Convert the argument of Basic.find() into a callable"""
|
2207 |
+
try:
|
2208 |
+
query = _sympify(query)
|
2209 |
+
except SympifyError:
|
2210 |
+
pass
|
2211 |
+
if isinstance(query, type):
|
2212 |
+
return lambda expr: isinstance(expr, query)
|
2213 |
+
elif isinstance(query, Basic):
|
2214 |
+
return lambda expr: expr.match(query) is not None
|
2215 |
+
return query
|
2216 |
+
|
2217 |
+
# Delayed to avoid cyclic import
|
2218 |
+
from .singleton import S
|
2219 |
+
from .traversal import (preorder_traversal as _preorder_traversal,
|
2220 |
+
iterargs, iterfreeargs)
|
2221 |
+
|
2222 |
+
preorder_traversal = deprecated(
|
2223 |
+
"""
|
2224 |
+
Using preorder_traversal from the sympy.core.basic submodule is
|
2225 |
+
deprecated.
|
2226 |
+
|
2227 |
+
Instead, use preorder_traversal from the top-level sympy namespace, like
|
2228 |
+
|
2229 |
+
sympy.preorder_traversal
|
2230 |
+
""",
|
2231 |
+
deprecated_since_version="1.10",
|
2232 |
+
active_deprecations_target="deprecated-traversal-functions-moved",
|
2233 |
+
)(_preorder_traversal)
|
llmeval-env/lib/python3.10/site-packages/sympy/core/evalf.py
ADDED
@@ -0,0 +1,1801 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Adaptive numerical evaluation of SymPy expressions, using mpmath
|
3 |
+
for mathematical functions.
|
4 |
+
"""
|
5 |
+
from __future__ import annotations
|
6 |
+
from typing import Tuple as tTuple, Optional, Union as tUnion, Callable, List, Dict as tDict, Type, TYPE_CHECKING, \
|
7 |
+
Any, overload
|
8 |
+
|
9 |
+
import math
|
10 |
+
|
11 |
+
import mpmath.libmp as libmp
|
12 |
+
from mpmath import (
|
13 |
+
make_mpc, make_mpf, mp, mpc, mpf, nsum, quadts, quadosc, workprec)
|
14 |
+
from mpmath import inf as mpmath_inf
|
15 |
+
from mpmath.libmp import (from_int, from_man_exp, from_rational, fhalf,
|
16 |
+
fnan, finf, fninf, fnone, fone, fzero, mpf_abs, mpf_add,
|
17 |
+
mpf_atan, mpf_atan2, mpf_cmp, mpf_cos, mpf_e, mpf_exp, mpf_log, mpf_lt,
|
18 |
+
mpf_mul, mpf_neg, mpf_pi, mpf_pow, mpf_pow_int, mpf_shift, mpf_sin,
|
19 |
+
mpf_sqrt, normalize, round_nearest, to_int, to_str)
|
20 |
+
from mpmath.libmp import bitcount as mpmath_bitcount
|
21 |
+
from mpmath.libmp.backend import MPZ
|
22 |
+
from mpmath.libmp.libmpc import _infs_nan
|
23 |
+
from mpmath.libmp.libmpf import dps_to_prec, prec_to_dps
|
24 |
+
|
25 |
+
from .sympify import sympify
|
26 |
+
from .singleton import S
|
27 |
+
from sympy.external.gmpy import SYMPY_INTS
|
28 |
+
from sympy.utilities.iterables import is_sequence
|
29 |
+
from sympy.utilities.lambdify import lambdify
|
30 |
+
from sympy.utilities.misc import as_int
|
31 |
+
|
32 |
+
if TYPE_CHECKING:
|
33 |
+
from sympy.core.expr import Expr
|
34 |
+
from sympy.core.add import Add
|
35 |
+
from sympy.core.mul import Mul
|
36 |
+
from sympy.core.power import Pow
|
37 |
+
from sympy.core.symbol import Symbol
|
38 |
+
from sympy.integrals.integrals import Integral
|
39 |
+
from sympy.concrete.summations import Sum
|
40 |
+
from sympy.concrete.products import Product
|
41 |
+
from sympy.functions.elementary.exponential import exp, log
|
42 |
+
from sympy.functions.elementary.complexes import Abs, re, im
|
43 |
+
from sympy.functions.elementary.integers import ceiling, floor
|
44 |
+
from sympy.functions.elementary.trigonometric import atan
|
45 |
+
from .numbers import Float, Rational, Integer, AlgebraicNumber, Number
|
46 |
+
|
47 |
+
LG10 = math.log(10, 2)
|
48 |
+
rnd = round_nearest
|
49 |
+
|
50 |
+
|
51 |
+
def bitcount(n):
|
52 |
+
"""Return smallest integer, b, such that |n|/2**b < 1.
|
53 |
+
"""
|
54 |
+
return mpmath_bitcount(abs(int(n)))
|
55 |
+
|
56 |
+
# Used in a few places as placeholder values to denote exponents and
|
57 |
+
# precision levels, e.g. of exact numbers. Must be careful to avoid
|
58 |
+
# passing these to mpmath functions or returning them in final results.
|
59 |
+
INF = float(mpmath_inf)
|
60 |
+
MINUS_INF = float(-mpmath_inf)
|
61 |
+
|
62 |
+
# ~= 100 digits. Real men set this to INF.
|
63 |
+
DEFAULT_MAXPREC = 333
|
64 |
+
|
65 |
+
|
66 |
+
class PrecisionExhausted(ArithmeticError):
|
67 |
+
pass
|
68 |
+
|
69 |
+
#----------------------------------------------------------------------------#
|
70 |
+
# #
|
71 |
+
# Helper functions for arithmetic and complex parts #
|
72 |
+
# #
|
73 |
+
#----------------------------------------------------------------------------#
|
74 |
+
|
75 |
+
"""
|
76 |
+
An mpf value tuple is a tuple of integers (sign, man, exp, bc)
|
77 |
+
representing a floating-point number: [1, -1][sign]*man*2**exp where
|
78 |
+
sign is 0 or 1 and bc should correspond to the number of bits used to
|
79 |
+
represent the mantissa (man) in binary notation, e.g.
|
80 |
+
"""
|
81 |
+
MPF_TUP = tTuple[int, int, int, int] # mpf value tuple
|
82 |
+
|
83 |
+
"""
|
84 |
+
Explanation
|
85 |
+
===========
|
86 |
+
|
87 |
+
>>> from sympy.core.evalf import bitcount
|
88 |
+
>>> sign, man, exp, bc = 0, 5, 1, 3
|
89 |
+
>>> n = [1, -1][sign]*man*2**exp
|
90 |
+
>>> n, bitcount(man)
|
91 |
+
(10, 3)
|
92 |
+
|
93 |
+
A temporary result is a tuple (re, im, re_acc, im_acc) where
|
94 |
+
re and im are nonzero mpf value tuples representing approximate
|
95 |
+
numbers, or None to denote exact zeros.
|
96 |
+
|
97 |
+
re_acc, im_acc are integers denoting log2(e) where e is the estimated
|
98 |
+
relative accuracy of the respective complex part, but may be anything
|
99 |
+
if the corresponding complex part is None.
|
100 |
+
|
101 |
+
"""
|
102 |
+
TMP_RES = Any # temporary result, should be some variant of
|
103 |
+
# tUnion[tTuple[Optional[MPF_TUP], Optional[MPF_TUP],
|
104 |
+
# Optional[int], Optional[int]],
|
105 |
+
# 'ComplexInfinity']
|
106 |
+
# but mypy reports error because it doesn't know as we know
|
107 |
+
# 1. re and re_acc are either both None or both MPF_TUP
|
108 |
+
# 2. sometimes the result can't be zoo
|
109 |
+
|
110 |
+
# type of the "options" parameter in internal evalf functions
|
111 |
+
OPT_DICT = tDict[str, Any]
|
112 |
+
|
113 |
+
|
114 |
+
def fastlog(x: Optional[MPF_TUP]) -> tUnion[int, Any]:
|
115 |
+
"""Fast approximation of log2(x) for an mpf value tuple x.
|
116 |
+
|
117 |
+
Explanation
|
118 |
+
===========
|
119 |
+
|
120 |
+
Calculated as exponent + width of mantissa. This is an
|
121 |
+
approximation for two reasons: 1) it gives the ceil(log2(abs(x)))
|
122 |
+
value and 2) it is too high by 1 in the case that x is an exact
|
123 |
+
power of 2. Although this is easy to remedy by testing to see if
|
124 |
+
the odd mpf mantissa is 1 (indicating that one was dealing with
|
125 |
+
an exact power of 2) that would decrease the speed and is not
|
126 |
+
necessary as this is only being used as an approximation for the
|
127 |
+
number of bits in x. The correct return value could be written as
|
128 |
+
"x[2] + (x[3] if x[1] != 1 else 0)".
|
129 |
+
Since mpf tuples always have an odd mantissa, no check is done
|
130 |
+
to see if the mantissa is a multiple of 2 (in which case the
|
131 |
+
result would be too large by 1).
|
132 |
+
|
133 |
+
Examples
|
134 |
+
========
|
135 |
+
|
136 |
+
>>> from sympy import log
|
137 |
+
>>> from sympy.core.evalf import fastlog, bitcount
|
138 |
+
>>> s, m, e = 0, 5, 1
|
139 |
+
>>> bc = bitcount(m)
|
140 |
+
>>> n = [1, -1][s]*m*2**e
|
141 |
+
>>> n, (log(n)/log(2)).evalf(2), fastlog((s, m, e, bc))
|
142 |
+
(10, 3.3, 4)
|
143 |
+
"""
|
144 |
+
|
145 |
+
if not x or x == fzero:
|
146 |
+
return MINUS_INF
|
147 |
+
return x[2] + x[3]
|
148 |
+
|
149 |
+
|
150 |
+
def pure_complex(v: 'Expr', or_real=False) -> tuple['Number', 'Number'] | None:
|
151 |
+
"""Return a and b if v matches a + I*b where b is not zero and
|
152 |
+
a and b are Numbers, else None. If `or_real` is True then 0 will
|
153 |
+
be returned for `b` if `v` is a real number.
|
154 |
+
|
155 |
+
Examples
|
156 |
+
========
|
157 |
+
|
158 |
+
>>> from sympy.core.evalf import pure_complex
|
159 |
+
>>> from sympy import sqrt, I, S
|
160 |
+
>>> a, b, surd = S(2), S(3), sqrt(2)
|
161 |
+
>>> pure_complex(a)
|
162 |
+
>>> pure_complex(a, or_real=True)
|
163 |
+
(2, 0)
|
164 |
+
>>> pure_complex(surd)
|
165 |
+
>>> pure_complex(a + b*I)
|
166 |
+
(2, 3)
|
167 |
+
>>> pure_complex(I)
|
168 |
+
(0, 1)
|
169 |
+
"""
|
170 |
+
h, t = v.as_coeff_Add()
|
171 |
+
if t:
|
172 |
+
c, i = t.as_coeff_Mul()
|
173 |
+
if i is S.ImaginaryUnit:
|
174 |
+
return h, c
|
175 |
+
elif or_real:
|
176 |
+
return h, S.Zero
|
177 |
+
return None
|
178 |
+
|
179 |
+
|
180 |
+
# I don't know what this is, see function scaled_zero below
|
181 |
+
SCALED_ZERO_TUP = tTuple[List[int], int, int, int]
|
182 |
+
|
183 |
+
|
184 |
+
@overload
|
185 |
+
def scaled_zero(mag: SCALED_ZERO_TUP, sign=1) -> MPF_TUP:
|
186 |
+
...
|
187 |
+
@overload
|
188 |
+
def scaled_zero(mag: int, sign=1) -> tTuple[SCALED_ZERO_TUP, int]:
|
189 |
+
...
|
190 |
+
def scaled_zero(mag: tUnion[SCALED_ZERO_TUP, int], sign=1) -> \
|
191 |
+
tUnion[MPF_TUP, tTuple[SCALED_ZERO_TUP, int]]:
|
192 |
+
"""Return an mpf representing a power of two with magnitude ``mag``
|
193 |
+
and -1 for precision. Or, if ``mag`` is a scaled_zero tuple, then just
|
194 |
+
remove the sign from within the list that it was initially wrapped
|
195 |
+
in.
|
196 |
+
|
197 |
+
Examples
|
198 |
+
========
|
199 |
+
|
200 |
+
>>> from sympy.core.evalf import scaled_zero
|
201 |
+
>>> from sympy import Float
|
202 |
+
>>> z, p = scaled_zero(100)
|
203 |
+
>>> z, p
|
204 |
+
(([0], 1, 100, 1), -1)
|
205 |
+
>>> ok = scaled_zero(z)
|
206 |
+
>>> ok
|
207 |
+
(0, 1, 100, 1)
|
208 |
+
>>> Float(ok)
|
209 |
+
1.26765060022823e+30
|
210 |
+
>>> Float(ok, p)
|
211 |
+
0.e+30
|
212 |
+
>>> ok, p = scaled_zero(100, -1)
|
213 |
+
>>> Float(scaled_zero(ok), p)
|
214 |
+
-0.e+30
|
215 |
+
"""
|
216 |
+
if isinstance(mag, tuple) and len(mag) == 4 and iszero(mag, scaled=True):
|
217 |
+
return (mag[0][0],) + mag[1:]
|
218 |
+
elif isinstance(mag, SYMPY_INTS):
|
219 |
+
if sign not in [-1, 1]:
|
220 |
+
raise ValueError('sign must be +/-1')
|
221 |
+
rv, p = mpf_shift(fone, mag), -1
|
222 |
+
s = 0 if sign == 1 else 1
|
223 |
+
rv = ([s],) + rv[1:]
|
224 |
+
return rv, p
|
225 |
+
else:
|
226 |
+
raise ValueError('scaled zero expects int or scaled_zero tuple.')
|
227 |
+
|
228 |
+
|
229 |
+
def iszero(mpf: tUnion[MPF_TUP, SCALED_ZERO_TUP, None], scaled=False) -> Optional[bool]:
|
230 |
+
if not scaled:
|
231 |
+
return not mpf or not mpf[1] and not mpf[-1]
|
232 |
+
return mpf and isinstance(mpf[0], list) and mpf[1] == mpf[-1] == 1
|
233 |
+
|
234 |
+
|
235 |
+
def complex_accuracy(result: TMP_RES) -> tUnion[int, Any]:
|
236 |
+
"""
|
237 |
+
Returns relative accuracy of a complex number with given accuracies
|
238 |
+
for the real and imaginary parts. The relative accuracy is defined
|
239 |
+
in the complex norm sense as ||z|+|error|| / |z| where error
|
240 |
+
is equal to (real absolute error) + (imag absolute error)*i.
|
241 |
+
|
242 |
+
The full expression for the (logarithmic) error can be approximated
|
243 |
+
easily by using the max norm to approximate the complex norm.
|
244 |
+
|
245 |
+
In the worst case (re and im equal), this is wrong by a factor
|
246 |
+
sqrt(2), or by log2(sqrt(2)) = 0.5 bit.
|
247 |
+
"""
|
248 |
+
if result is S.ComplexInfinity:
|
249 |
+
return INF
|
250 |
+
re, im, re_acc, im_acc = result
|
251 |
+
if not im:
|
252 |
+
if not re:
|
253 |
+
return INF
|
254 |
+
return re_acc
|
255 |
+
if not re:
|
256 |
+
return im_acc
|
257 |
+
re_size = fastlog(re)
|
258 |
+
im_size = fastlog(im)
|
259 |
+
absolute_error = max(re_size - re_acc, im_size - im_acc)
|
260 |
+
relative_error = absolute_error - max(re_size, im_size)
|
261 |
+
return -relative_error
|
262 |
+
|
263 |
+
|
264 |
+
def get_abs(expr: 'Expr', prec: int, options: OPT_DICT) -> TMP_RES:
|
265 |
+
result = evalf(expr, prec + 2, options)
|
266 |
+
if result is S.ComplexInfinity:
|
267 |
+
return finf, None, prec, None
|
268 |
+
re, im, re_acc, im_acc = result
|
269 |
+
if not re:
|
270 |
+
re, re_acc, im, im_acc = im, im_acc, re, re_acc
|
271 |
+
if im:
|
272 |
+
if expr.is_number:
|
273 |
+
abs_expr, _, acc, _ = evalf(abs(N(expr, prec + 2)),
|
274 |
+
prec + 2, options)
|
275 |
+
return abs_expr, None, acc, None
|
276 |
+
else:
|
277 |
+
if 'subs' in options:
|
278 |
+
return libmp.mpc_abs((re, im), prec), None, re_acc, None
|
279 |
+
return abs(expr), None, prec, None
|
280 |
+
elif re:
|
281 |
+
return mpf_abs(re), None, re_acc, None
|
282 |
+
else:
|
283 |
+
return None, None, None, None
|
284 |
+
|
285 |
+
|
286 |
+
def get_complex_part(expr: 'Expr', no: int, prec: int, options: OPT_DICT) -> TMP_RES:
|
287 |
+
"""no = 0 for real part, no = 1 for imaginary part"""
|
288 |
+
workprec = prec
|
289 |
+
i = 0
|
290 |
+
while 1:
|
291 |
+
res = evalf(expr, workprec, options)
|
292 |
+
if res is S.ComplexInfinity:
|
293 |
+
return fnan, None, prec, None
|
294 |
+
value, accuracy = res[no::2]
|
295 |
+
# XXX is the last one correct? Consider re((1+I)**2).n()
|
296 |
+
if (not value) or accuracy >= prec or -value[2] > prec:
|
297 |
+
return value, None, accuracy, None
|
298 |
+
workprec += max(30, 2**i)
|
299 |
+
i += 1
|
300 |
+
|
301 |
+
|
302 |
+
def evalf_abs(expr: 'Abs', prec: int, options: OPT_DICT) -> TMP_RES:
|
303 |
+
return get_abs(expr.args[0], prec, options)
|
304 |
+
|
305 |
+
|
306 |
+
def evalf_re(expr: 're', prec: int, options: OPT_DICT) -> TMP_RES:
|
307 |
+
return get_complex_part(expr.args[0], 0, prec, options)
|
308 |
+
|
309 |
+
|
310 |
+
def evalf_im(expr: 'im', prec: int, options: OPT_DICT) -> TMP_RES:
|
311 |
+
return get_complex_part(expr.args[0], 1, prec, options)
|
312 |
+
|
313 |
+
|
314 |
+
def finalize_complex(re: MPF_TUP, im: MPF_TUP, prec: int) -> TMP_RES:
|
315 |
+
if re == fzero and im == fzero:
|
316 |
+
raise ValueError("got complex zero with unknown accuracy")
|
317 |
+
elif re == fzero:
|
318 |
+
return None, im, None, prec
|
319 |
+
elif im == fzero:
|
320 |
+
return re, None, prec, None
|
321 |
+
|
322 |
+
size_re = fastlog(re)
|
323 |
+
size_im = fastlog(im)
|
324 |
+
if size_re > size_im:
|
325 |
+
re_acc = prec
|
326 |
+
im_acc = prec + min(-(size_re - size_im), 0)
|
327 |
+
else:
|
328 |
+
im_acc = prec
|
329 |
+
re_acc = prec + min(-(size_im - size_re), 0)
|
330 |
+
return re, im, re_acc, im_acc
|
331 |
+
|
332 |
+
|
333 |
+
def chop_parts(value: TMP_RES, prec: int) -> TMP_RES:
|
334 |
+
"""
|
335 |
+
Chop off tiny real or complex parts.
|
336 |
+
"""
|
337 |
+
if value is S.ComplexInfinity:
|
338 |
+
return value
|
339 |
+
re, im, re_acc, im_acc = value
|
340 |
+
# Method 1: chop based on absolute value
|
341 |
+
if re and re not in _infs_nan and (fastlog(re) < -prec + 4):
|
342 |
+
re, re_acc = None, None
|
343 |
+
if im and im not in _infs_nan and (fastlog(im) < -prec + 4):
|
344 |
+
im, im_acc = None, None
|
345 |
+
# Method 2: chop if inaccurate and relatively small
|
346 |
+
if re and im:
|
347 |
+
delta = fastlog(re) - fastlog(im)
|
348 |
+
if re_acc < 2 and (delta - re_acc <= -prec + 4):
|
349 |
+
re, re_acc = None, None
|
350 |
+
if im_acc < 2 and (delta - im_acc >= prec - 4):
|
351 |
+
im, im_acc = None, None
|
352 |
+
return re, im, re_acc, im_acc
|
353 |
+
|
354 |
+
|
355 |
+
def check_target(expr: 'Expr', result: TMP_RES, prec: int):
|
356 |
+
a = complex_accuracy(result)
|
357 |
+
if a < prec:
|
358 |
+
raise PrecisionExhausted("Failed to distinguish the expression: \n\n%s\n\n"
|
359 |
+
"from zero. Try simplifying the input, using chop=True, or providing "
|
360 |
+
"a higher maxn for evalf" % (expr))
|
361 |
+
|
362 |
+
|
363 |
+
def get_integer_part(expr: 'Expr', no: int, options: OPT_DICT, return_ints=False) -> \
|
364 |
+
tUnion[TMP_RES, tTuple[int, int]]:
|
365 |
+
"""
|
366 |
+
With no = 1, computes ceiling(expr)
|
367 |
+
With no = -1, computes floor(expr)
|
368 |
+
|
369 |
+
Note: this function either gives the exact result or signals failure.
|
370 |
+
"""
|
371 |
+
from sympy.functions.elementary.complexes import re, im
|
372 |
+
# The expression is likely less than 2^30 or so
|
373 |
+
assumed_size = 30
|
374 |
+
result = evalf(expr, assumed_size, options)
|
375 |
+
if result is S.ComplexInfinity:
|
376 |
+
raise ValueError("Cannot get integer part of Complex Infinity")
|
377 |
+
ire, iim, ire_acc, iim_acc = result
|
378 |
+
|
379 |
+
# We now know the size, so we can calculate how much extra precision
|
380 |
+
# (if any) is needed to get within the nearest integer
|
381 |
+
if ire and iim:
|
382 |
+
gap = max(fastlog(ire) - ire_acc, fastlog(iim) - iim_acc)
|
383 |
+
elif ire:
|
384 |
+
gap = fastlog(ire) - ire_acc
|
385 |
+
elif iim:
|
386 |
+
gap = fastlog(iim) - iim_acc
|
387 |
+
else:
|
388 |
+
# ... or maybe the expression was exactly zero
|
389 |
+
if return_ints:
|
390 |
+
return 0, 0
|
391 |
+
else:
|
392 |
+
return None, None, None, None
|
393 |
+
|
394 |
+
margin = 10
|
395 |
+
|
396 |
+
if gap >= -margin:
|
397 |
+
prec = margin + assumed_size + gap
|
398 |
+
ire, iim, ire_acc, iim_acc = evalf(
|
399 |
+
expr, prec, options)
|
400 |
+
else:
|
401 |
+
prec = assumed_size
|
402 |
+
|
403 |
+
# We can now easily find the nearest integer, but to find floor/ceil, we
|
404 |
+
# must also calculate whether the difference to the nearest integer is
|
405 |
+
# positive or negative (which may fail if very close).
|
406 |
+
def calc_part(re_im: 'Expr', nexpr: MPF_TUP):
|
407 |
+
from .add import Add
|
408 |
+
_, _, exponent, _ = nexpr
|
409 |
+
is_int = exponent == 0
|
410 |
+
nint = int(to_int(nexpr, rnd))
|
411 |
+
if is_int:
|
412 |
+
# make sure that we had enough precision to distinguish
|
413 |
+
# between nint and the re or im part (re_im) of expr that
|
414 |
+
# was passed to calc_part
|
415 |
+
ire, iim, ire_acc, iim_acc = evalf(
|
416 |
+
re_im - nint, 10, options) # don't need much precision
|
417 |
+
assert not iim
|
418 |
+
size = -fastlog(ire) + 2 # -ve b/c ire is less than 1
|
419 |
+
if size > prec:
|
420 |
+
ire, iim, ire_acc, iim_acc = evalf(
|
421 |
+
re_im, size, options)
|
422 |
+
assert not iim
|
423 |
+
nexpr = ire
|
424 |
+
nint = int(to_int(nexpr, rnd))
|
425 |
+
_, _, new_exp, _ = ire
|
426 |
+
is_int = new_exp == 0
|
427 |
+
if not is_int:
|
428 |
+
# if there are subs and they all contain integer re/im parts
|
429 |
+
# then we can (hopefully) safely substitute them into the
|
430 |
+
# expression
|
431 |
+
s = options.get('subs', False)
|
432 |
+
if s:
|
433 |
+
doit = True
|
434 |
+
# use strict=False with as_int because we take
|
435 |
+
# 2.0 == 2
|
436 |
+
for v in s.values():
|
437 |
+
try:
|
438 |
+
as_int(v, strict=False)
|
439 |
+
except ValueError:
|
440 |
+
try:
|
441 |
+
[as_int(i, strict=False) for i in v.as_real_imag()]
|
442 |
+
continue
|
443 |
+
except (ValueError, AttributeError):
|
444 |
+
doit = False
|
445 |
+
break
|
446 |
+
if doit:
|
447 |
+
re_im = re_im.subs(s)
|
448 |
+
|
449 |
+
re_im = Add(re_im, -nint, evaluate=False)
|
450 |
+
x, _, x_acc, _ = evalf(re_im, 10, options)
|
451 |
+
try:
|
452 |
+
check_target(re_im, (x, None, x_acc, None), 3)
|
453 |
+
except PrecisionExhausted:
|
454 |
+
if not re_im.equals(0):
|
455 |
+
raise PrecisionExhausted
|
456 |
+
x = fzero
|
457 |
+
nint += int(no*(mpf_cmp(x or fzero, fzero) == no))
|
458 |
+
nint = from_int(nint)
|
459 |
+
return nint, INF
|
460 |
+
|
461 |
+
re_, im_, re_acc, im_acc = None, None, None, None
|
462 |
+
|
463 |
+
if ire:
|
464 |
+
re_, re_acc = calc_part(re(expr, evaluate=False), ire)
|
465 |
+
if iim:
|
466 |
+
im_, im_acc = calc_part(im(expr, evaluate=False), iim)
|
467 |
+
|
468 |
+
if return_ints:
|
469 |
+
return int(to_int(re_ or fzero)), int(to_int(im_ or fzero))
|
470 |
+
return re_, im_, re_acc, im_acc
|
471 |
+
|
472 |
+
|
473 |
+
def evalf_ceiling(expr: 'ceiling', prec: int, options: OPT_DICT) -> TMP_RES:
|
474 |
+
return get_integer_part(expr.args[0], 1, options)
|
475 |
+
|
476 |
+
|
477 |
+
def evalf_floor(expr: 'floor', prec: int, options: OPT_DICT) -> TMP_RES:
|
478 |
+
return get_integer_part(expr.args[0], -1, options)
|
479 |
+
|
480 |
+
|
481 |
+
def evalf_float(expr: 'Float', prec: int, options: OPT_DICT) -> TMP_RES:
|
482 |
+
return expr._mpf_, None, prec, None
|
483 |
+
|
484 |
+
|
485 |
+
def evalf_rational(expr: 'Rational', prec: int, options: OPT_DICT) -> TMP_RES:
|
486 |
+
return from_rational(expr.p, expr.q, prec), None, prec, None
|
487 |
+
|
488 |
+
|
489 |
+
def evalf_integer(expr: 'Integer', prec: int, options: OPT_DICT) -> TMP_RES:
|
490 |
+
return from_int(expr.p, prec), None, prec, None
|
491 |
+
|
492 |
+
#----------------------------------------------------------------------------#
|
493 |
+
# #
|
494 |
+
# Arithmetic operations #
|
495 |
+
# #
|
496 |
+
#----------------------------------------------------------------------------#
|
497 |
+
|
498 |
+
|
499 |
+
def add_terms(terms: list, prec: int, target_prec: int) -> \
|
500 |
+
tTuple[tUnion[MPF_TUP, SCALED_ZERO_TUP, None], Optional[int]]:
|
501 |
+
"""
|
502 |
+
Helper for evalf_add. Adds a list of (mpfval, accuracy) terms.
|
503 |
+
|
504 |
+
Returns
|
505 |
+
=======
|
506 |
+
|
507 |
+
- None, None if there are no non-zero terms;
|
508 |
+
- terms[0] if there is only 1 term;
|
509 |
+
- scaled_zero if the sum of the terms produces a zero by cancellation
|
510 |
+
e.g. mpfs representing 1 and -1 would produce a scaled zero which need
|
511 |
+
special handling since they are not actually zero and they are purposely
|
512 |
+
malformed to ensure that they cannot be used in anything but accuracy
|
513 |
+
calculations;
|
514 |
+
- a tuple that is scaled to target_prec that corresponds to the
|
515 |
+
sum of the terms.
|
516 |
+
|
517 |
+
The returned mpf tuple will be normalized to target_prec; the input
|
518 |
+
prec is used to define the working precision.
|
519 |
+
|
520 |
+
XXX explain why this is needed and why one cannot just loop using mpf_add
|
521 |
+
"""
|
522 |
+
|
523 |
+
terms = [t for t in terms if not iszero(t[0])]
|
524 |
+
if not terms:
|
525 |
+
return None, None
|
526 |
+
elif len(terms) == 1:
|
527 |
+
return terms[0]
|
528 |
+
|
529 |
+
# see if any argument is NaN or oo and thus warrants a special return
|
530 |
+
special = []
|
531 |
+
from .numbers import Float
|
532 |
+
for t in terms:
|
533 |
+
arg = Float._new(t[0], 1)
|
534 |
+
if arg is S.NaN or arg.is_infinite:
|
535 |
+
special.append(arg)
|
536 |
+
if special:
|
537 |
+
from .add import Add
|
538 |
+
rv = evalf(Add(*special), prec + 4, {})
|
539 |
+
return rv[0], rv[2]
|
540 |
+
|
541 |
+
working_prec = 2*prec
|
542 |
+
sum_man, sum_exp = 0, 0
|
543 |
+
absolute_err: List[int] = []
|
544 |
+
|
545 |
+
for x, accuracy in terms:
|
546 |
+
sign, man, exp, bc = x
|
547 |
+
if sign:
|
548 |
+
man = -man
|
549 |
+
absolute_err.append(bc + exp - accuracy)
|
550 |
+
delta = exp - sum_exp
|
551 |
+
if exp >= sum_exp:
|
552 |
+
# x much larger than existing sum?
|
553 |
+
# first: quick test
|
554 |
+
if ((delta > working_prec) and
|
555 |
+
((not sum_man) or
|
556 |
+
delta - bitcount(abs(sum_man)) > working_prec)):
|
557 |
+
sum_man = man
|
558 |
+
sum_exp = exp
|
559 |
+
else:
|
560 |
+
sum_man += (man << delta)
|
561 |
+
else:
|
562 |
+
delta = -delta
|
563 |
+
# x much smaller than existing sum?
|
564 |
+
if delta - bc > working_prec:
|
565 |
+
if not sum_man:
|
566 |
+
sum_man, sum_exp = man, exp
|
567 |
+
else:
|
568 |
+
sum_man = (sum_man << delta) + man
|
569 |
+
sum_exp = exp
|
570 |
+
absolute_error = max(absolute_err)
|
571 |
+
if not sum_man:
|
572 |
+
return scaled_zero(absolute_error)
|
573 |
+
if sum_man < 0:
|
574 |
+
sum_sign = 1
|
575 |
+
sum_man = -sum_man
|
576 |
+
else:
|
577 |
+
sum_sign = 0
|
578 |
+
sum_bc = bitcount(sum_man)
|
579 |
+
sum_accuracy = sum_exp + sum_bc - absolute_error
|
580 |
+
r = normalize(sum_sign, sum_man, sum_exp, sum_bc, target_prec,
|
581 |
+
rnd), sum_accuracy
|
582 |
+
return r
|
583 |
+
|
584 |
+
|
585 |
+
def evalf_add(v: 'Add', prec: int, options: OPT_DICT) -> TMP_RES:
|
586 |
+
res = pure_complex(v)
|
587 |
+
if res:
|
588 |
+
h, c = res
|
589 |
+
re, _, re_acc, _ = evalf(h, prec, options)
|
590 |
+
im, _, im_acc, _ = evalf(c, prec, options)
|
591 |
+
return re, im, re_acc, im_acc
|
592 |
+
|
593 |
+
oldmaxprec = options.get('maxprec', DEFAULT_MAXPREC)
|
594 |
+
|
595 |
+
i = 0
|
596 |
+
target_prec = prec
|
597 |
+
while 1:
|
598 |
+
options['maxprec'] = min(oldmaxprec, 2*prec)
|
599 |
+
|
600 |
+
terms = [evalf(arg, prec + 10, options) for arg in v.args]
|
601 |
+
n = terms.count(S.ComplexInfinity)
|
602 |
+
if n >= 2:
|
603 |
+
return fnan, None, prec, None
|
604 |
+
re, re_acc = add_terms(
|
605 |
+
[a[0::2] for a in terms if isinstance(a, tuple) and a[0]], prec, target_prec)
|
606 |
+
im, im_acc = add_terms(
|
607 |
+
[a[1::2] for a in terms if isinstance(a, tuple) and a[1]], prec, target_prec)
|
608 |
+
if n == 1:
|
609 |
+
if re in (finf, fninf, fnan) or im in (finf, fninf, fnan):
|
610 |
+
return fnan, None, prec, None
|
611 |
+
return S.ComplexInfinity
|
612 |
+
acc = complex_accuracy((re, im, re_acc, im_acc))
|
613 |
+
if acc >= target_prec:
|
614 |
+
if options.get('verbose'):
|
615 |
+
print("ADD: wanted", target_prec, "accurate bits, got", re_acc, im_acc)
|
616 |
+
break
|
617 |
+
else:
|
618 |
+
if (prec - target_prec) > options['maxprec']:
|
619 |
+
break
|
620 |
+
|
621 |
+
prec = prec + max(10 + 2**i, target_prec - acc)
|
622 |
+
i += 1
|
623 |
+
if options.get('verbose'):
|
624 |
+
print("ADD: restarting with prec", prec)
|
625 |
+
|
626 |
+
options['maxprec'] = oldmaxprec
|
627 |
+
if iszero(re, scaled=True):
|
628 |
+
re = scaled_zero(re)
|
629 |
+
if iszero(im, scaled=True):
|
630 |
+
im = scaled_zero(im)
|
631 |
+
return re, im, re_acc, im_acc
|
632 |
+
|
633 |
+
|
634 |
+
def evalf_mul(v: 'Mul', prec: int, options: OPT_DICT) -> TMP_RES:
|
635 |
+
res = pure_complex(v)
|
636 |
+
if res:
|
637 |
+
# the only pure complex that is a mul is h*I
|
638 |
+
_, h = res
|
639 |
+
im, _, im_acc, _ = evalf(h, prec, options)
|
640 |
+
return None, im, None, im_acc
|
641 |
+
args = list(v.args)
|
642 |
+
|
643 |
+
# see if any argument is NaN or oo and thus warrants a special return
|
644 |
+
has_zero = False
|
645 |
+
special = []
|
646 |
+
from .numbers import Float
|
647 |
+
for arg in args:
|
648 |
+
result = evalf(arg, prec, options)
|
649 |
+
if result is S.ComplexInfinity:
|
650 |
+
special.append(result)
|
651 |
+
continue
|
652 |
+
if result[0] is None:
|
653 |
+
if result[1] is None:
|
654 |
+
has_zero = True
|
655 |
+
continue
|
656 |
+
num = Float._new(result[0], 1)
|
657 |
+
if num is S.NaN:
|
658 |
+
return fnan, None, prec, None
|
659 |
+
if num.is_infinite:
|
660 |
+
special.append(num)
|
661 |
+
if special:
|
662 |
+
if has_zero:
|
663 |
+
return fnan, None, prec, None
|
664 |
+
from .mul import Mul
|
665 |
+
return evalf(Mul(*special), prec + 4, {})
|
666 |
+
if has_zero:
|
667 |
+
return None, None, None, None
|
668 |
+
|
669 |
+
# With guard digits, multiplication in the real case does not destroy
|
670 |
+
# accuracy. This is also true in the complex case when considering the
|
671 |
+
# total accuracy; however accuracy for the real or imaginary parts
|
672 |
+
# separately may be lower.
|
673 |
+
acc = prec
|
674 |
+
|
675 |
+
# XXX: big overestimate
|
676 |
+
working_prec = prec + len(args) + 5
|
677 |
+
|
678 |
+
# Empty product is 1
|
679 |
+
start = man, exp, bc = MPZ(1), 0, 1
|
680 |
+
|
681 |
+
# First, we multiply all pure real or pure imaginary numbers.
|
682 |
+
# direction tells us that the result should be multiplied by
|
683 |
+
# I**direction; all other numbers get put into complex_factors
|
684 |
+
# to be multiplied out after the first phase.
|
685 |
+
last = len(args)
|
686 |
+
direction = 0
|
687 |
+
args.append(S.One)
|
688 |
+
complex_factors = []
|
689 |
+
|
690 |
+
for i, arg in enumerate(args):
|
691 |
+
if i != last and pure_complex(arg):
|
692 |
+
args[-1] = (args[-1]*arg).expand()
|
693 |
+
continue
|
694 |
+
elif i == last and arg is S.One:
|
695 |
+
continue
|
696 |
+
re, im, re_acc, im_acc = evalf(arg, working_prec, options)
|
697 |
+
if re and im:
|
698 |
+
complex_factors.append((re, im, re_acc, im_acc))
|
699 |
+
continue
|
700 |
+
elif re:
|
701 |
+
(s, m, e, b), w_acc = re, re_acc
|
702 |
+
elif im:
|
703 |
+
(s, m, e, b), w_acc = im, im_acc
|
704 |
+
direction += 1
|
705 |
+
else:
|
706 |
+
return None, None, None, None
|
707 |
+
direction += 2*s
|
708 |
+
man *= m
|
709 |
+
exp += e
|
710 |
+
bc += b
|
711 |
+
while bc > 3*working_prec:
|
712 |
+
man >>= working_prec
|
713 |
+
exp += working_prec
|
714 |
+
bc -= working_prec
|
715 |
+
acc = min(acc, w_acc)
|
716 |
+
sign = (direction & 2) >> 1
|
717 |
+
if not complex_factors:
|
718 |
+
v = normalize(sign, man, exp, bitcount(man), prec, rnd)
|
719 |
+
# multiply by i
|
720 |
+
if direction & 1:
|
721 |
+
return None, v, None, acc
|
722 |
+
else:
|
723 |
+
return v, None, acc, None
|
724 |
+
else:
|
725 |
+
# initialize with the first term
|
726 |
+
if (man, exp, bc) != start:
|
727 |
+
# there was a real part; give it an imaginary part
|
728 |
+
re, im = (sign, man, exp, bitcount(man)), (0, MPZ(0), 0, 0)
|
729 |
+
i0 = 0
|
730 |
+
else:
|
731 |
+
# there is no real part to start (other than the starting 1)
|
732 |
+
wre, wim, wre_acc, wim_acc = complex_factors[0]
|
733 |
+
acc = min(acc,
|
734 |
+
complex_accuracy((wre, wim, wre_acc, wim_acc)))
|
735 |
+
re = wre
|
736 |
+
im = wim
|
737 |
+
i0 = 1
|
738 |
+
|
739 |
+
for wre, wim, wre_acc, wim_acc in complex_factors[i0:]:
|
740 |
+
# acc is the overall accuracy of the product; we aren't
|
741 |
+
# computing exact accuracies of the product.
|
742 |
+
acc = min(acc,
|
743 |
+
complex_accuracy((wre, wim, wre_acc, wim_acc)))
|
744 |
+
|
745 |
+
use_prec = working_prec
|
746 |
+
A = mpf_mul(re, wre, use_prec)
|
747 |
+
B = mpf_mul(mpf_neg(im), wim, use_prec)
|
748 |
+
C = mpf_mul(re, wim, use_prec)
|
749 |
+
D = mpf_mul(im, wre, use_prec)
|
750 |
+
re = mpf_add(A, B, use_prec)
|
751 |
+
im = mpf_add(C, D, use_prec)
|
752 |
+
if options.get('verbose'):
|
753 |
+
print("MUL: wanted", prec, "accurate bits, got", acc)
|
754 |
+
# multiply by I
|
755 |
+
if direction & 1:
|
756 |
+
re, im = mpf_neg(im), re
|
757 |
+
return re, im, acc, acc
|
758 |
+
|
759 |
+
|
760 |
+
def evalf_pow(v: 'Pow', prec: int, options) -> TMP_RES:
|
761 |
+
|
762 |
+
target_prec = prec
|
763 |
+
base, exp = v.args
|
764 |
+
|
765 |
+
# We handle x**n separately. This has two purposes: 1) it is much
|
766 |
+
# faster, because we avoid calling evalf on the exponent, and 2) it
|
767 |
+
# allows better handling of real/imaginary parts that are exactly zero
|
768 |
+
if exp.is_Integer:
|
769 |
+
p: int = exp.p # type: ignore
|
770 |
+
# Exact
|
771 |
+
if not p:
|
772 |
+
return fone, None, prec, None
|
773 |
+
# Exponentiation by p magnifies relative error by |p|, so the
|
774 |
+
# base must be evaluated with increased precision if p is large
|
775 |
+
prec += int(math.log(abs(p), 2))
|
776 |
+
result = evalf(base, prec + 5, options)
|
777 |
+
if result is S.ComplexInfinity:
|
778 |
+
if p < 0:
|
779 |
+
return None, None, None, None
|
780 |
+
return result
|
781 |
+
re, im, re_acc, im_acc = result
|
782 |
+
# Real to integer power
|
783 |
+
if re and not im:
|
784 |
+
return mpf_pow_int(re, p, target_prec), None, target_prec, None
|
785 |
+
# (x*I)**n = I**n * x**n
|
786 |
+
if im and not re:
|
787 |
+
z = mpf_pow_int(im, p, target_prec)
|
788 |
+
case = p % 4
|
789 |
+
if case == 0:
|
790 |
+
return z, None, target_prec, None
|
791 |
+
if case == 1:
|
792 |
+
return None, z, None, target_prec
|
793 |
+
if case == 2:
|
794 |
+
return mpf_neg(z), None, target_prec, None
|
795 |
+
if case == 3:
|
796 |
+
return None, mpf_neg(z), None, target_prec
|
797 |
+
# Zero raised to an integer power
|
798 |
+
if not re:
|
799 |
+
if p < 0:
|
800 |
+
return S.ComplexInfinity
|
801 |
+
return None, None, None, None
|
802 |
+
# General complex number to arbitrary integer power
|
803 |
+
re, im = libmp.mpc_pow_int((re, im), p, prec)
|
804 |
+
# Assumes full accuracy in input
|
805 |
+
return finalize_complex(re, im, target_prec)
|
806 |
+
|
807 |
+
result = evalf(base, prec + 5, options)
|
808 |
+
if result is S.ComplexInfinity:
|
809 |
+
if exp.is_Rational:
|
810 |
+
if exp < 0:
|
811 |
+
return None, None, None, None
|
812 |
+
return result
|
813 |
+
raise NotImplementedError
|
814 |
+
|
815 |
+
# Pure square root
|
816 |
+
if exp is S.Half:
|
817 |
+
xre, xim, _, _ = result
|
818 |
+
# General complex square root
|
819 |
+
if xim:
|
820 |
+
re, im = libmp.mpc_sqrt((xre or fzero, xim), prec)
|
821 |
+
return finalize_complex(re, im, prec)
|
822 |
+
if not xre:
|
823 |
+
return None, None, None, None
|
824 |
+
# Square root of a negative real number
|
825 |
+
if mpf_lt(xre, fzero):
|
826 |
+
return None, mpf_sqrt(mpf_neg(xre), prec), None, prec
|
827 |
+
# Positive square root
|
828 |
+
return mpf_sqrt(xre, prec), None, prec, None
|
829 |
+
|
830 |
+
# We first evaluate the exponent to find its magnitude
|
831 |
+
# This determines the working precision that must be used
|
832 |
+
prec += 10
|
833 |
+
result = evalf(exp, prec, options)
|
834 |
+
if result is S.ComplexInfinity:
|
835 |
+
return fnan, None, prec, None
|
836 |
+
yre, yim, _, _ = result
|
837 |
+
# Special cases: x**0
|
838 |
+
if not (yre or yim):
|
839 |
+
return fone, None, prec, None
|
840 |
+
|
841 |
+
ysize = fastlog(yre)
|
842 |
+
# Restart if too big
|
843 |
+
# XXX: prec + ysize might exceed maxprec
|
844 |
+
if ysize > 5:
|
845 |
+
prec += ysize
|
846 |
+
yre, yim, _, _ = evalf(exp, prec, options)
|
847 |
+
|
848 |
+
# Pure exponential function; no need to evalf the base
|
849 |
+
if base is S.Exp1:
|
850 |
+
if yim:
|
851 |
+
re, im = libmp.mpc_exp((yre or fzero, yim), prec)
|
852 |
+
return finalize_complex(re, im, target_prec)
|
853 |
+
return mpf_exp(yre, target_prec), None, target_prec, None
|
854 |
+
|
855 |
+
xre, xim, _, _ = evalf(base, prec + 5, options)
|
856 |
+
# 0**y
|
857 |
+
if not (xre or xim):
|
858 |
+
if yim:
|
859 |
+
return fnan, None, prec, None
|
860 |
+
if yre[0] == 1: # y < 0
|
861 |
+
return S.ComplexInfinity
|
862 |
+
return None, None, None, None
|
863 |
+
|
864 |
+
# (real ** complex) or (complex ** complex)
|
865 |
+
if yim:
|
866 |
+
re, im = libmp.mpc_pow(
|
867 |
+
(xre or fzero, xim or fzero), (yre or fzero, yim),
|
868 |
+
target_prec)
|
869 |
+
return finalize_complex(re, im, target_prec)
|
870 |
+
# complex ** real
|
871 |
+
if xim:
|
872 |
+
re, im = libmp.mpc_pow_mpf((xre or fzero, xim), yre, target_prec)
|
873 |
+
return finalize_complex(re, im, target_prec)
|
874 |
+
# negative ** real
|
875 |
+
elif mpf_lt(xre, fzero):
|
876 |
+
re, im = libmp.mpc_pow_mpf((xre, fzero), yre, target_prec)
|
877 |
+
return finalize_complex(re, im, target_prec)
|
878 |
+
# positive ** real
|
879 |
+
else:
|
880 |
+
return mpf_pow(xre, yre, target_prec), None, target_prec, None
|
881 |
+
|
882 |
+
|
883 |
+
#----------------------------------------------------------------------------#
|
884 |
+
# #
|
885 |
+
# Special functions #
|
886 |
+
# #
|
887 |
+
#----------------------------------------------------------------------------#
|
888 |
+
|
889 |
+
|
890 |
+
def evalf_exp(expr: 'exp', prec: int, options: OPT_DICT) -> TMP_RES:
|
891 |
+
from .power import Pow
|
892 |
+
return evalf_pow(Pow(S.Exp1, expr.exp, evaluate=False), prec, options)
|
893 |
+
|
894 |
+
|
895 |
+
def evalf_trig(v: 'Expr', prec: int, options: OPT_DICT) -> TMP_RES:
|
896 |
+
"""
|
897 |
+
This function handles sin and cos of complex arguments.
|
898 |
+
|
899 |
+
TODO: should also handle tan of complex arguments.
|
900 |
+
"""
|
901 |
+
from sympy.functions.elementary.trigonometric import cos, sin
|
902 |
+
if isinstance(v, cos):
|
903 |
+
func = mpf_cos
|
904 |
+
elif isinstance(v, sin):
|
905 |
+
func = mpf_sin
|
906 |
+
else:
|
907 |
+
raise NotImplementedError
|
908 |
+
arg = v.args[0]
|
909 |
+
# 20 extra bits is possibly overkill. It does make the need
|
910 |
+
# to restart very unlikely
|
911 |
+
xprec = prec + 20
|
912 |
+
re, im, re_acc, im_acc = evalf(arg, xprec, options)
|
913 |
+
if im:
|
914 |
+
if 'subs' in options:
|
915 |
+
v = v.subs(options['subs'])
|
916 |
+
return evalf(v._eval_evalf(prec), prec, options)
|
917 |
+
if not re:
|
918 |
+
if isinstance(v, cos):
|
919 |
+
return fone, None, prec, None
|
920 |
+
elif isinstance(v, sin):
|
921 |
+
return None, None, None, None
|
922 |
+
else:
|
923 |
+
raise NotImplementedError
|
924 |
+
# For trigonometric functions, we are interested in the
|
925 |
+
# fixed-point (absolute) accuracy of the argument.
|
926 |
+
xsize = fastlog(re)
|
927 |
+
# Magnitude <= 1.0. OK to compute directly, because there is no
|
928 |
+
# danger of hitting the first root of cos (with sin, magnitude
|
929 |
+
# <= 2.0 would actually be ok)
|
930 |
+
if xsize < 1:
|
931 |
+
return func(re, prec, rnd), None, prec, None
|
932 |
+
# Very large
|
933 |
+
if xsize >= 10:
|
934 |
+
xprec = prec + xsize
|
935 |
+
re, im, re_acc, im_acc = evalf(arg, xprec, options)
|
936 |
+
# Need to repeat in case the argument is very close to a
|
937 |
+
# multiple of pi (or pi/2), hitting close to a root
|
938 |
+
while 1:
|
939 |
+
y = func(re, prec, rnd)
|
940 |
+
ysize = fastlog(y)
|
941 |
+
gap = -ysize
|
942 |
+
accuracy = (xprec - xsize) - gap
|
943 |
+
if accuracy < prec:
|
944 |
+
if options.get('verbose'):
|
945 |
+
print("SIN/COS", accuracy, "wanted", prec, "gap", gap)
|
946 |
+
print(to_str(y, 10))
|
947 |
+
if xprec > options.get('maxprec', DEFAULT_MAXPREC):
|
948 |
+
return y, None, accuracy, None
|
949 |
+
xprec += gap
|
950 |
+
re, im, re_acc, im_acc = evalf(arg, xprec, options)
|
951 |
+
continue
|
952 |
+
else:
|
953 |
+
return y, None, prec, None
|
954 |
+
|
955 |
+
|
956 |
+
def evalf_log(expr: 'log', prec: int, options: OPT_DICT) -> TMP_RES:
|
957 |
+
if len(expr.args)>1:
|
958 |
+
expr = expr.doit()
|
959 |
+
return evalf(expr, prec, options)
|
960 |
+
arg = expr.args[0]
|
961 |
+
workprec = prec + 10
|
962 |
+
result = evalf(arg, workprec, options)
|
963 |
+
if result is S.ComplexInfinity:
|
964 |
+
return result
|
965 |
+
xre, xim, xacc, _ = result
|
966 |
+
|
967 |
+
# evalf can return NoneTypes if chop=True
|
968 |
+
# issue 18516, 19623
|
969 |
+
if xre is xim is None:
|
970 |
+
# Dear reviewer, I do not know what -inf is;
|
971 |
+
# it looks to be (1, 0, -789, -3)
|
972 |
+
# but I'm not sure in general,
|
973 |
+
# so we just let mpmath figure
|
974 |
+
# it out by taking log of 0 directly.
|
975 |
+
# It would be better to return -inf instead.
|
976 |
+
xre = fzero
|
977 |
+
|
978 |
+
if xim:
|
979 |
+
from sympy.functions.elementary.complexes import Abs
|
980 |
+
from sympy.functions.elementary.exponential import log
|
981 |
+
|
982 |
+
# XXX: use get_abs etc instead
|
983 |
+
re = evalf_log(
|
984 |
+
log(Abs(arg, evaluate=False), evaluate=False), prec, options)
|
985 |
+
im = mpf_atan2(xim, xre or fzero, prec)
|
986 |
+
return re[0], im, re[2], prec
|
987 |
+
|
988 |
+
imaginary_term = (mpf_cmp(xre, fzero) < 0)
|
989 |
+
|
990 |
+
re = mpf_log(mpf_abs(xre), prec, rnd)
|
991 |
+
size = fastlog(re)
|
992 |
+
if prec - size > workprec and re != fzero:
|
993 |
+
from .add import Add
|
994 |
+
# We actually need to compute 1+x accurately, not x
|
995 |
+
add = Add(S.NegativeOne, arg, evaluate=False)
|
996 |
+
xre, xim, _, _ = evalf_add(add, prec, options)
|
997 |
+
prec2 = workprec - fastlog(xre)
|
998 |
+
# xre is now x - 1 so we add 1 back here to calculate x
|
999 |
+
re = mpf_log(mpf_abs(mpf_add(xre, fone, prec2)), prec, rnd)
|
1000 |
+
|
1001 |
+
re_acc = prec
|
1002 |
+
|
1003 |
+
if imaginary_term:
|
1004 |
+
return re, mpf_pi(prec), re_acc, prec
|
1005 |
+
else:
|
1006 |
+
return re, None, re_acc, None
|
1007 |
+
|
1008 |
+
|
1009 |
+
def evalf_atan(v: 'atan', prec: int, options: OPT_DICT) -> TMP_RES:
|
1010 |
+
arg = v.args[0]
|
1011 |
+
xre, xim, reacc, imacc = evalf(arg, prec + 5, options)
|
1012 |
+
if xre is xim is None:
|
1013 |
+
return (None,)*4
|
1014 |
+
if xim:
|
1015 |
+
raise NotImplementedError
|
1016 |
+
return mpf_atan(xre, prec, rnd), None, prec, None
|
1017 |
+
|
1018 |
+
|
1019 |
+
def evalf_subs(prec: int, subs: dict) -> dict:
|
1020 |
+
""" Change all Float entries in `subs` to have precision prec. """
|
1021 |
+
newsubs = {}
|
1022 |
+
for a, b in subs.items():
|
1023 |
+
b = S(b)
|
1024 |
+
if b.is_Float:
|
1025 |
+
b = b._eval_evalf(prec)
|
1026 |
+
newsubs[a] = b
|
1027 |
+
return newsubs
|
1028 |
+
|
1029 |
+
|
1030 |
+
def evalf_piecewise(expr: 'Expr', prec: int, options: OPT_DICT) -> TMP_RES:
|
1031 |
+
from .numbers import Float, Integer
|
1032 |
+
if 'subs' in options:
|
1033 |
+
expr = expr.subs(evalf_subs(prec, options['subs']))
|
1034 |
+
newopts = options.copy()
|
1035 |
+
del newopts['subs']
|
1036 |
+
if hasattr(expr, 'func'):
|
1037 |
+
return evalf(expr, prec, newopts)
|
1038 |
+
if isinstance(expr, float):
|
1039 |
+
return evalf(Float(expr), prec, newopts)
|
1040 |
+
if isinstance(expr, int):
|
1041 |
+
return evalf(Integer(expr), prec, newopts)
|
1042 |
+
|
1043 |
+
# We still have undefined symbols
|
1044 |
+
raise NotImplementedError
|
1045 |
+
|
1046 |
+
|
1047 |
+
def evalf_alg_num(a: 'AlgebraicNumber', prec: int, options: OPT_DICT) -> TMP_RES:
|
1048 |
+
return evalf(a.to_root(), prec, options)
|
1049 |
+
|
1050 |
+
#----------------------------------------------------------------------------#
|
1051 |
+
# #
|
1052 |
+
# High-level operations #
|
1053 |
+
# #
|
1054 |
+
#----------------------------------------------------------------------------#
|
1055 |
+
|
1056 |
+
|
1057 |
+
def as_mpmath(x: Any, prec: int, options: OPT_DICT) -> tUnion[mpc, mpf]:
|
1058 |
+
from .numbers import Infinity, NegativeInfinity, Zero
|
1059 |
+
x = sympify(x)
|
1060 |
+
if isinstance(x, Zero) or x == 0.0:
|
1061 |
+
return mpf(0)
|
1062 |
+
if isinstance(x, Infinity):
|
1063 |
+
return mpf('inf')
|
1064 |
+
if isinstance(x, NegativeInfinity):
|
1065 |
+
return mpf('-inf')
|
1066 |
+
# XXX
|
1067 |
+
result = evalf(x, prec, options)
|
1068 |
+
return quad_to_mpmath(result)
|
1069 |
+
|
1070 |
+
|
1071 |
+
def do_integral(expr: 'Integral', prec: int, options: OPT_DICT) -> TMP_RES:
|
1072 |
+
func = expr.args[0]
|
1073 |
+
x, xlow, xhigh = expr.args[1]
|
1074 |
+
if xlow == xhigh:
|
1075 |
+
xlow = xhigh = 0
|
1076 |
+
elif x not in func.free_symbols:
|
1077 |
+
# only the difference in limits matters in this case
|
1078 |
+
# so if there is a symbol in common that will cancel
|
1079 |
+
# out when taking the difference, then use that
|
1080 |
+
# difference
|
1081 |
+
if xhigh.free_symbols & xlow.free_symbols:
|
1082 |
+
diff = xhigh - xlow
|
1083 |
+
if diff.is_number:
|
1084 |
+
xlow, xhigh = 0, diff
|
1085 |
+
|
1086 |
+
oldmaxprec = options.get('maxprec', DEFAULT_MAXPREC)
|
1087 |
+
options['maxprec'] = min(oldmaxprec, 2*prec)
|
1088 |
+
|
1089 |
+
with workprec(prec + 5):
|
1090 |
+
xlow = as_mpmath(xlow, prec + 15, options)
|
1091 |
+
xhigh = as_mpmath(xhigh, prec + 15, options)
|
1092 |
+
|
1093 |
+
# Integration is like summation, and we can phone home from
|
1094 |
+
# the integrand function to update accuracy summation style
|
1095 |
+
# Note that this accuracy is inaccurate, since it fails
|
1096 |
+
# to account for the variable quadrature weights,
|
1097 |
+
# but it is better than nothing
|
1098 |
+
|
1099 |
+
from sympy.functions.elementary.trigonometric import cos, sin
|
1100 |
+
from .symbol import Wild
|
1101 |
+
|
1102 |
+
have_part = [False, False]
|
1103 |
+
max_real_term: tUnion[float, int] = MINUS_INF
|
1104 |
+
max_imag_term: tUnion[float, int] = MINUS_INF
|
1105 |
+
|
1106 |
+
def f(t: 'Expr') -> tUnion[mpc, mpf]:
|
1107 |
+
nonlocal max_real_term, max_imag_term
|
1108 |
+
re, im, re_acc, im_acc = evalf(func, mp.prec, {'subs': {x: t}})
|
1109 |
+
|
1110 |
+
have_part[0] = re or have_part[0]
|
1111 |
+
have_part[1] = im or have_part[1]
|
1112 |
+
|
1113 |
+
max_real_term = max(max_real_term, fastlog(re))
|
1114 |
+
max_imag_term = max(max_imag_term, fastlog(im))
|
1115 |
+
|
1116 |
+
if im:
|
1117 |
+
return mpc(re or fzero, im)
|
1118 |
+
return mpf(re or fzero)
|
1119 |
+
|
1120 |
+
if options.get('quad') == 'osc':
|
1121 |
+
A = Wild('A', exclude=[x])
|
1122 |
+
B = Wild('B', exclude=[x])
|
1123 |
+
D = Wild('D')
|
1124 |
+
m = func.match(cos(A*x + B)*D)
|
1125 |
+
if not m:
|
1126 |
+
m = func.match(sin(A*x + B)*D)
|
1127 |
+
if not m:
|
1128 |
+
raise ValueError("An integrand of the form sin(A*x+B)*f(x) "
|
1129 |
+
"or cos(A*x+B)*f(x) is required for oscillatory quadrature")
|
1130 |
+
period = as_mpmath(2*S.Pi/m[A], prec + 15, options)
|
1131 |
+
result = quadosc(f, [xlow, xhigh], period=period)
|
1132 |
+
# XXX: quadosc does not do error detection yet
|
1133 |
+
quadrature_error = MINUS_INF
|
1134 |
+
else:
|
1135 |
+
result, quadrature_err = quadts(f, [xlow, xhigh], error=1)
|
1136 |
+
quadrature_error = fastlog(quadrature_err._mpf_)
|
1137 |
+
|
1138 |
+
options['maxprec'] = oldmaxprec
|
1139 |
+
|
1140 |
+
if have_part[0]:
|
1141 |
+
re: Optional[MPF_TUP] = result.real._mpf_
|
1142 |
+
re_acc: Optional[int]
|
1143 |
+
if re == fzero:
|
1144 |
+
re_s, re_acc = scaled_zero(int(-max(prec, max_real_term, quadrature_error)))
|
1145 |
+
re = scaled_zero(re_s) # handled ok in evalf_integral
|
1146 |
+
else:
|
1147 |
+
re_acc = int(-max(max_real_term - fastlog(re) - prec, quadrature_error))
|
1148 |
+
else:
|
1149 |
+
re, re_acc = None, None
|
1150 |
+
|
1151 |
+
if have_part[1]:
|
1152 |
+
im: Optional[MPF_TUP] = result.imag._mpf_
|
1153 |
+
im_acc: Optional[int]
|
1154 |
+
if im == fzero:
|
1155 |
+
im_s, im_acc = scaled_zero(int(-max(prec, max_imag_term, quadrature_error)))
|
1156 |
+
im = scaled_zero(im_s) # handled ok in evalf_integral
|
1157 |
+
else:
|
1158 |
+
im_acc = int(-max(max_imag_term - fastlog(im) - prec, quadrature_error))
|
1159 |
+
else:
|
1160 |
+
im, im_acc = None, None
|
1161 |
+
|
1162 |
+
result = re, im, re_acc, im_acc
|
1163 |
+
return result
|
1164 |
+
|
1165 |
+
|
1166 |
+
def evalf_integral(expr: 'Integral', prec: int, options: OPT_DICT) -> TMP_RES:
|
1167 |
+
limits = expr.limits
|
1168 |
+
if len(limits) != 1 or len(limits[0]) != 3:
|
1169 |
+
raise NotImplementedError
|
1170 |
+
workprec = prec
|
1171 |
+
i = 0
|
1172 |
+
maxprec = options.get('maxprec', INF)
|
1173 |
+
while 1:
|
1174 |
+
result = do_integral(expr, workprec, options)
|
1175 |
+
accuracy = complex_accuracy(result)
|
1176 |
+
if accuracy >= prec: # achieved desired precision
|
1177 |
+
break
|
1178 |
+
if workprec >= maxprec: # can't increase accuracy any more
|
1179 |
+
break
|
1180 |
+
if accuracy == -1:
|
1181 |
+
# maybe the answer really is zero and maybe we just haven't increased
|
1182 |
+
# the precision enough. So increase by doubling to not take too long
|
1183 |
+
# to get to maxprec.
|
1184 |
+
workprec *= 2
|
1185 |
+
else:
|
1186 |
+
workprec += max(prec, 2**i)
|
1187 |
+
workprec = min(workprec, maxprec)
|
1188 |
+
i += 1
|
1189 |
+
return result
|
1190 |
+
|
1191 |
+
|
1192 |
+
def check_convergence(numer: 'Expr', denom: 'Expr', n: 'Symbol') -> tTuple[int, Any, Any]:
|
1193 |
+
"""
|
1194 |
+
Returns
|
1195 |
+
=======
|
1196 |
+
|
1197 |
+
(h, g, p) where
|
1198 |
+
-- h is:
|
1199 |
+
> 0 for convergence of rate 1/factorial(n)**h
|
1200 |
+
< 0 for divergence of rate factorial(n)**(-h)
|
1201 |
+
= 0 for geometric or polynomial convergence or divergence
|
1202 |
+
|
1203 |
+
-- abs(g) is:
|
1204 |
+
> 1 for geometric convergence of rate 1/h**n
|
1205 |
+
< 1 for geometric divergence of rate h**n
|
1206 |
+
= 1 for polynomial convergence or divergence
|
1207 |
+
|
1208 |
+
(g < 0 indicates an alternating series)
|
1209 |
+
|
1210 |
+
-- p is:
|
1211 |
+
> 1 for polynomial convergence of rate 1/n**h
|
1212 |
+
<= 1 for polynomial divergence of rate n**(-h)
|
1213 |
+
|
1214 |
+
"""
|
1215 |
+
from sympy.polys.polytools import Poly
|
1216 |
+
npol = Poly(numer, n)
|
1217 |
+
dpol = Poly(denom, n)
|
1218 |
+
p = npol.degree()
|
1219 |
+
q = dpol.degree()
|
1220 |
+
rate = q - p
|
1221 |
+
if rate:
|
1222 |
+
return rate, None, None
|
1223 |
+
constant = dpol.LC() / npol.LC()
|
1224 |
+
from .numbers import equal_valued
|
1225 |
+
if not equal_valued(abs(constant), 1):
|
1226 |
+
return rate, constant, None
|
1227 |
+
if npol.degree() == dpol.degree() == 0:
|
1228 |
+
return rate, constant, 0
|
1229 |
+
pc = npol.all_coeffs()[1]
|
1230 |
+
qc = dpol.all_coeffs()[1]
|
1231 |
+
return rate, constant, (qc - pc)/dpol.LC()
|
1232 |
+
|
1233 |
+
|
1234 |
+
def hypsum(expr: 'Expr', n: 'Symbol', start: int, prec: int) -> mpf:
|
1235 |
+
"""
|
1236 |
+
Sum a rapidly convergent infinite hypergeometric series with
|
1237 |
+
given general term, e.g. e = hypsum(1/factorial(n), n). The
|
1238 |
+
quotient between successive terms must be a quotient of integer
|
1239 |
+
polynomials.
|
1240 |
+
"""
|
1241 |
+
from .numbers import Float, equal_valued
|
1242 |
+
from sympy.simplify.simplify import hypersimp
|
1243 |
+
|
1244 |
+
if prec == float('inf'):
|
1245 |
+
raise NotImplementedError('does not support inf prec')
|
1246 |
+
|
1247 |
+
if start:
|
1248 |
+
expr = expr.subs(n, n + start)
|
1249 |
+
hs = hypersimp(expr, n)
|
1250 |
+
if hs is None:
|
1251 |
+
raise NotImplementedError("a hypergeometric series is required")
|
1252 |
+
num, den = hs.as_numer_denom()
|
1253 |
+
|
1254 |
+
func1 = lambdify(n, num)
|
1255 |
+
func2 = lambdify(n, den)
|
1256 |
+
|
1257 |
+
h, g, p = check_convergence(num, den, n)
|
1258 |
+
|
1259 |
+
if h < 0:
|
1260 |
+
raise ValueError("Sum diverges like (n!)^%i" % (-h))
|
1261 |
+
|
1262 |
+
term = expr.subs(n, 0)
|
1263 |
+
if not term.is_Rational:
|
1264 |
+
raise NotImplementedError("Non rational term functionality is not implemented.")
|
1265 |
+
|
1266 |
+
# Direct summation if geometric or faster
|
1267 |
+
if h > 0 or (h == 0 and abs(g) > 1):
|
1268 |
+
term = (MPZ(term.p) << prec) // term.q
|
1269 |
+
s = term
|
1270 |
+
k = 1
|
1271 |
+
while abs(term) > 5:
|
1272 |
+
term *= MPZ(func1(k - 1))
|
1273 |
+
term //= MPZ(func2(k - 1))
|
1274 |
+
s += term
|
1275 |
+
k += 1
|
1276 |
+
return from_man_exp(s, -prec)
|
1277 |
+
else:
|
1278 |
+
alt = g < 0
|
1279 |
+
if abs(g) < 1:
|
1280 |
+
raise ValueError("Sum diverges like (%i)^n" % abs(1/g))
|
1281 |
+
if p < 1 or (equal_valued(p, 1) and not alt):
|
1282 |
+
raise ValueError("Sum diverges like n^%i" % (-p))
|
1283 |
+
# We have polynomial convergence: use Richardson extrapolation
|
1284 |
+
vold = None
|
1285 |
+
ndig = prec_to_dps(prec)
|
1286 |
+
while True:
|
1287 |
+
# Need to use at least quad precision because a lot of cancellation
|
1288 |
+
# might occur in the extrapolation process; we check the answer to
|
1289 |
+
# make sure that the desired precision has been reached, too.
|
1290 |
+
prec2 = 4*prec
|
1291 |
+
term0 = (MPZ(term.p) << prec2) // term.q
|
1292 |
+
|
1293 |
+
def summand(k, _term=[term0]):
|
1294 |
+
if k:
|
1295 |
+
k = int(k)
|
1296 |
+
_term[0] *= MPZ(func1(k - 1))
|
1297 |
+
_term[0] //= MPZ(func2(k - 1))
|
1298 |
+
return make_mpf(from_man_exp(_term[0], -prec2))
|
1299 |
+
|
1300 |
+
with workprec(prec):
|
1301 |
+
v = nsum(summand, [0, mpmath_inf], method='richardson')
|
1302 |
+
vf = Float(v, ndig)
|
1303 |
+
if vold is not None and vold == vf:
|
1304 |
+
break
|
1305 |
+
prec += prec # double precision each time
|
1306 |
+
vold = vf
|
1307 |
+
|
1308 |
+
return v._mpf_
|
1309 |
+
|
1310 |
+
|
1311 |
+
def evalf_prod(expr: 'Product', prec: int, options: OPT_DICT) -> TMP_RES:
|
1312 |
+
if all((l[1] - l[2]).is_Integer for l in expr.limits):
|
1313 |
+
result = evalf(expr.doit(), prec=prec, options=options)
|
1314 |
+
else:
|
1315 |
+
from sympy.concrete.summations import Sum
|
1316 |
+
result = evalf(expr.rewrite(Sum), prec=prec, options=options)
|
1317 |
+
return result
|
1318 |
+
|
1319 |
+
|
1320 |
+
def evalf_sum(expr: 'Sum', prec: int, options: OPT_DICT) -> TMP_RES:
|
1321 |
+
from .numbers import Float
|
1322 |
+
if 'subs' in options:
|
1323 |
+
expr = expr.subs(options['subs'])
|
1324 |
+
func = expr.function
|
1325 |
+
limits = expr.limits
|
1326 |
+
if len(limits) != 1 or len(limits[0]) != 3:
|
1327 |
+
raise NotImplementedError
|
1328 |
+
if func.is_zero:
|
1329 |
+
return None, None, prec, None
|
1330 |
+
prec2 = prec + 10
|
1331 |
+
try:
|
1332 |
+
n, a, b = limits[0]
|
1333 |
+
if b is not S.Infinity or a is S.NegativeInfinity or a != int(a):
|
1334 |
+
raise NotImplementedError
|
1335 |
+
# Use fast hypergeometric summation if possible
|
1336 |
+
v = hypsum(func, n, int(a), prec2)
|
1337 |
+
delta = prec - fastlog(v)
|
1338 |
+
if fastlog(v) < -10:
|
1339 |
+
v = hypsum(func, n, int(a), delta)
|
1340 |
+
return v, None, min(prec, delta), None
|
1341 |
+
except NotImplementedError:
|
1342 |
+
# Euler-Maclaurin summation for general series
|
1343 |
+
eps = Float(2.0)**(-prec)
|
1344 |
+
for i in range(1, 5):
|
1345 |
+
m = n = 2**i * prec
|
1346 |
+
s, err = expr.euler_maclaurin(m=m, n=n, eps=eps,
|
1347 |
+
eval_integral=False)
|
1348 |
+
err = err.evalf()
|
1349 |
+
if err is S.NaN:
|
1350 |
+
raise NotImplementedError
|
1351 |
+
if err <= eps:
|
1352 |
+
break
|
1353 |
+
err = fastlog(evalf(abs(err), 20, options)[0])
|
1354 |
+
re, im, re_acc, im_acc = evalf(s, prec2, options)
|
1355 |
+
if re_acc is None:
|
1356 |
+
re_acc = -err
|
1357 |
+
if im_acc is None:
|
1358 |
+
im_acc = -err
|
1359 |
+
return re, im, re_acc, im_acc
|
1360 |
+
|
1361 |
+
|
1362 |
+
#----------------------------------------------------------------------------#
|
1363 |
+
# #
|
1364 |
+
# Symbolic interface #
|
1365 |
+
# #
|
1366 |
+
#----------------------------------------------------------------------------#
|
1367 |
+
|
1368 |
+
def evalf_symbol(x: 'Expr', prec: int, options: OPT_DICT) -> TMP_RES:
|
1369 |
+
val = options['subs'][x]
|
1370 |
+
if isinstance(val, mpf):
|
1371 |
+
if not val:
|
1372 |
+
return None, None, None, None
|
1373 |
+
return val._mpf_, None, prec, None
|
1374 |
+
else:
|
1375 |
+
if '_cache' not in options:
|
1376 |
+
options['_cache'] = {}
|
1377 |
+
cache = options['_cache']
|
1378 |
+
cached, cached_prec = cache.get(x, (None, MINUS_INF))
|
1379 |
+
if cached_prec >= prec:
|
1380 |
+
return cached
|
1381 |
+
v = evalf(sympify(val), prec, options)
|
1382 |
+
cache[x] = (v, prec)
|
1383 |
+
return v
|
1384 |
+
|
1385 |
+
|
1386 |
+
evalf_table: tDict[Type['Expr'], Callable[['Expr', int, OPT_DICT], TMP_RES]] = {}
|
1387 |
+
|
1388 |
+
|
1389 |
+
def _create_evalf_table():
|
1390 |
+
global evalf_table
|
1391 |
+
from sympy.concrete.products import Product
|
1392 |
+
from sympy.concrete.summations import Sum
|
1393 |
+
from .add import Add
|
1394 |
+
from .mul import Mul
|
1395 |
+
from .numbers import Exp1, Float, Half, ImaginaryUnit, Integer, NaN, NegativeOne, One, Pi, Rational, \
|
1396 |
+
Zero, ComplexInfinity, AlgebraicNumber
|
1397 |
+
from .power import Pow
|
1398 |
+
from .symbol import Dummy, Symbol
|
1399 |
+
from sympy.functions.elementary.complexes import Abs, im, re
|
1400 |
+
from sympy.functions.elementary.exponential import exp, log
|
1401 |
+
from sympy.functions.elementary.integers import ceiling, floor
|
1402 |
+
from sympy.functions.elementary.piecewise import Piecewise
|
1403 |
+
from sympy.functions.elementary.trigonometric import atan, cos, sin
|
1404 |
+
from sympy.integrals.integrals import Integral
|
1405 |
+
evalf_table = {
|
1406 |
+
Symbol: evalf_symbol,
|
1407 |
+
Dummy: evalf_symbol,
|
1408 |
+
Float: evalf_float,
|
1409 |
+
Rational: evalf_rational,
|
1410 |
+
Integer: evalf_integer,
|
1411 |
+
Zero: lambda x, prec, options: (None, None, prec, None),
|
1412 |
+
One: lambda x, prec, options: (fone, None, prec, None),
|
1413 |
+
Half: lambda x, prec, options: (fhalf, None, prec, None),
|
1414 |
+
Pi: lambda x, prec, options: (mpf_pi(prec), None, prec, None),
|
1415 |
+
Exp1: lambda x, prec, options: (mpf_e(prec), None, prec, None),
|
1416 |
+
ImaginaryUnit: lambda x, prec, options: (None, fone, None, prec),
|
1417 |
+
NegativeOne: lambda x, prec, options: (fnone, None, prec, None),
|
1418 |
+
ComplexInfinity: lambda x, prec, options: S.ComplexInfinity,
|
1419 |
+
NaN: lambda x, prec, options: (fnan, None, prec, None),
|
1420 |
+
|
1421 |
+
exp: evalf_exp,
|
1422 |
+
|
1423 |
+
cos: evalf_trig,
|
1424 |
+
sin: evalf_trig,
|
1425 |
+
|
1426 |
+
Add: evalf_add,
|
1427 |
+
Mul: evalf_mul,
|
1428 |
+
Pow: evalf_pow,
|
1429 |
+
|
1430 |
+
log: evalf_log,
|
1431 |
+
atan: evalf_atan,
|
1432 |
+
Abs: evalf_abs,
|
1433 |
+
|
1434 |
+
re: evalf_re,
|
1435 |
+
im: evalf_im,
|
1436 |
+
floor: evalf_floor,
|
1437 |
+
ceiling: evalf_ceiling,
|
1438 |
+
|
1439 |
+
Integral: evalf_integral,
|
1440 |
+
Sum: evalf_sum,
|
1441 |
+
Product: evalf_prod,
|
1442 |
+
Piecewise: evalf_piecewise,
|
1443 |
+
|
1444 |
+
AlgebraicNumber: evalf_alg_num,
|
1445 |
+
}
|
1446 |
+
|
1447 |
+
|
1448 |
+
def evalf(x: 'Expr', prec: int, options: OPT_DICT) -> TMP_RES:
|
1449 |
+
"""
|
1450 |
+
Evaluate the ``Expr`` instance, ``x``
|
1451 |
+
to a binary precision of ``prec``. This
|
1452 |
+
function is supposed to be used internally.
|
1453 |
+
|
1454 |
+
Parameters
|
1455 |
+
==========
|
1456 |
+
|
1457 |
+
x : Expr
|
1458 |
+
The formula to evaluate to a float.
|
1459 |
+
prec : int
|
1460 |
+
The binary precision that the output should have.
|
1461 |
+
options : dict
|
1462 |
+
A dictionary with the same entries as
|
1463 |
+
``EvalfMixin.evalf`` and in addition,
|
1464 |
+
``maxprec`` which is the maximum working precision.
|
1465 |
+
|
1466 |
+
Returns
|
1467 |
+
=======
|
1468 |
+
|
1469 |
+
An optional tuple, ``(re, im, re_acc, im_acc)``
|
1470 |
+
which are the real, imaginary, real accuracy
|
1471 |
+
and imaginary accuracy respectively. ``re`` is
|
1472 |
+
an mpf value tuple and so is ``im``. ``re_acc``
|
1473 |
+
and ``im_acc`` are ints.
|
1474 |
+
|
1475 |
+
NB: all these return values can be ``None``.
|
1476 |
+
If all values are ``None``, then that represents 0.
|
1477 |
+
Note that 0 is also represented as ``fzero = (0, 0, 0, 0)``.
|
1478 |
+
"""
|
1479 |
+
from sympy.functions.elementary.complexes import re as re_, im as im_
|
1480 |
+
try:
|
1481 |
+
rf = evalf_table[type(x)]
|
1482 |
+
r = rf(x, prec, options)
|
1483 |
+
except KeyError:
|
1484 |
+
# Fall back to ordinary evalf if possible
|
1485 |
+
if 'subs' in options:
|
1486 |
+
x = x.subs(evalf_subs(prec, options['subs']))
|
1487 |
+
xe = x._eval_evalf(prec)
|
1488 |
+
if xe is None:
|
1489 |
+
raise NotImplementedError
|
1490 |
+
as_real_imag = getattr(xe, "as_real_imag", None)
|
1491 |
+
if as_real_imag is None:
|
1492 |
+
raise NotImplementedError # e.g. FiniteSet(-1.0, 1.0).evalf()
|
1493 |
+
re, im = as_real_imag()
|
1494 |
+
if re.has(re_) or im.has(im_):
|
1495 |
+
raise NotImplementedError
|
1496 |
+
if re == 0.0:
|
1497 |
+
re = None
|
1498 |
+
reprec = None
|
1499 |
+
elif re.is_number:
|
1500 |
+
re = re._to_mpmath(prec, allow_ints=False)._mpf_
|
1501 |
+
reprec = prec
|
1502 |
+
else:
|
1503 |
+
raise NotImplementedError
|
1504 |
+
if im == 0.0:
|
1505 |
+
im = None
|
1506 |
+
imprec = None
|
1507 |
+
elif im.is_number:
|
1508 |
+
im = im._to_mpmath(prec, allow_ints=False)._mpf_
|
1509 |
+
imprec = prec
|
1510 |
+
else:
|
1511 |
+
raise NotImplementedError
|
1512 |
+
r = re, im, reprec, imprec
|
1513 |
+
|
1514 |
+
if options.get("verbose"):
|
1515 |
+
print("### input", x)
|
1516 |
+
print("### output", to_str(r[0] or fzero, 50) if isinstance(r, tuple) else r)
|
1517 |
+
print("### raw", r) # r[0], r[2]
|
1518 |
+
print()
|
1519 |
+
chop = options.get('chop', False)
|
1520 |
+
if chop:
|
1521 |
+
if chop is True:
|
1522 |
+
chop_prec = prec
|
1523 |
+
else:
|
1524 |
+
# convert (approximately) from given tolerance;
|
1525 |
+
# the formula here will will make 1e-i rounds to 0 for
|
1526 |
+
# i in the range +/-27 while 2e-i will not be chopped
|
1527 |
+
chop_prec = int(round(-3.321*math.log10(chop) + 2.5))
|
1528 |
+
if chop_prec == 3:
|
1529 |
+
chop_prec -= 1
|
1530 |
+
r = chop_parts(r, chop_prec)
|
1531 |
+
if options.get("strict"):
|
1532 |
+
check_target(x, r, prec)
|
1533 |
+
return r
|
1534 |
+
|
1535 |
+
|
1536 |
+
def quad_to_mpmath(q, ctx=None):
|
1537 |
+
"""Turn the quad returned by ``evalf`` into an ``mpf`` or ``mpc``. """
|
1538 |
+
mpc = make_mpc if ctx is None else ctx.make_mpc
|
1539 |
+
mpf = make_mpf if ctx is None else ctx.make_mpf
|
1540 |
+
if q is S.ComplexInfinity:
|
1541 |
+
raise NotImplementedError
|
1542 |
+
re, im, _, _ = q
|
1543 |
+
if im:
|
1544 |
+
if not re:
|
1545 |
+
re = fzero
|
1546 |
+
return mpc((re, im))
|
1547 |
+
elif re:
|
1548 |
+
return mpf(re)
|
1549 |
+
else:
|
1550 |
+
return mpf(fzero)
|
1551 |
+
|
1552 |
+
|
1553 |
+
class EvalfMixin:
|
1554 |
+
"""Mixin class adding evalf capability."""
|
1555 |
+
|
1556 |
+
__slots__ = () # type: tTuple[str, ...]
|
1557 |
+
|
1558 |
+
def evalf(self, n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False):
|
1559 |
+
"""
|
1560 |
+
Evaluate the given formula to an accuracy of *n* digits.
|
1561 |
+
|
1562 |
+
Parameters
|
1563 |
+
==========
|
1564 |
+
|
1565 |
+
subs : dict, optional
|
1566 |
+
Substitute numerical values for symbols, e.g.
|
1567 |
+
``subs={x:3, y:1+pi}``. The substitutions must be given as a
|
1568 |
+
dictionary.
|
1569 |
+
|
1570 |
+
maxn : int, optional
|
1571 |
+
Allow a maximum temporary working precision of maxn digits.
|
1572 |
+
|
1573 |
+
chop : bool or number, optional
|
1574 |
+
Specifies how to replace tiny real or imaginary parts in
|
1575 |
+
subresults by exact zeros.
|
1576 |
+
|
1577 |
+
When ``True`` the chop value defaults to standard precision.
|
1578 |
+
|
1579 |
+
Otherwise the chop value is used to determine the
|
1580 |
+
magnitude of "small" for purposes of chopping.
|
1581 |
+
|
1582 |
+
>>> from sympy import N
|
1583 |
+
>>> x = 1e-4
|
1584 |
+
>>> N(x, chop=True)
|
1585 |
+
0.000100000000000000
|
1586 |
+
>>> N(x, chop=1e-5)
|
1587 |
+
0.000100000000000000
|
1588 |
+
>>> N(x, chop=1e-4)
|
1589 |
+
0
|
1590 |
+
|
1591 |
+
strict : bool, optional
|
1592 |
+
Raise ``PrecisionExhausted`` if any subresult fails to
|
1593 |
+
evaluate to full accuracy, given the available maxprec.
|
1594 |
+
|
1595 |
+
quad : str, optional
|
1596 |
+
Choose algorithm for numerical quadrature. By default,
|
1597 |
+
tanh-sinh quadrature is used. For oscillatory
|
1598 |
+
integrals on an infinite interval, try ``quad='osc'``.
|
1599 |
+
|
1600 |
+
verbose : bool, optional
|
1601 |
+
Print debug information.
|
1602 |
+
|
1603 |
+
Notes
|
1604 |
+
=====
|
1605 |
+
|
1606 |
+
When Floats are naively substituted into an expression,
|
1607 |
+
precision errors may adversely affect the result. For example,
|
1608 |
+
adding 1e16 (a Float) to 1 will truncate to 1e16; if 1e16 is
|
1609 |
+
then subtracted, the result will be 0.
|
1610 |
+
That is exactly what happens in the following:
|
1611 |
+
|
1612 |
+
>>> from sympy.abc import x, y, z
|
1613 |
+
>>> values = {x: 1e16, y: 1, z: 1e16}
|
1614 |
+
>>> (x + y - z).subs(values)
|
1615 |
+
0
|
1616 |
+
|
1617 |
+
Using the subs argument for evalf is the accurate way to
|
1618 |
+
evaluate such an expression:
|
1619 |
+
|
1620 |
+
>>> (x + y - z).evalf(subs=values)
|
1621 |
+
1.00000000000000
|
1622 |
+
"""
|
1623 |
+
from .numbers import Float, Number
|
1624 |
+
n = n if n is not None else 15
|
1625 |
+
|
1626 |
+
if subs and is_sequence(subs):
|
1627 |
+
raise TypeError('subs must be given as a dictionary')
|
1628 |
+
|
1629 |
+
# for sake of sage that doesn't like evalf(1)
|
1630 |
+
if n == 1 and isinstance(self, Number):
|
1631 |
+
from .expr import _mag
|
1632 |
+
rv = self.evalf(2, subs, maxn, chop, strict, quad, verbose)
|
1633 |
+
m = _mag(rv)
|
1634 |
+
rv = rv.round(1 - m)
|
1635 |
+
return rv
|
1636 |
+
|
1637 |
+
if not evalf_table:
|
1638 |
+
_create_evalf_table()
|
1639 |
+
prec = dps_to_prec(n)
|
1640 |
+
options = {'maxprec': max(prec, int(maxn*LG10)), 'chop': chop,
|
1641 |
+
'strict': strict, 'verbose': verbose}
|
1642 |
+
if subs is not None:
|
1643 |
+
options['subs'] = subs
|
1644 |
+
if quad is not None:
|
1645 |
+
options['quad'] = quad
|
1646 |
+
try:
|
1647 |
+
result = evalf(self, prec + 4, options)
|
1648 |
+
except NotImplementedError:
|
1649 |
+
# Fall back to the ordinary evalf
|
1650 |
+
if hasattr(self, 'subs') and subs is not None: # issue 20291
|
1651 |
+
v = self.subs(subs)._eval_evalf(prec)
|
1652 |
+
else:
|
1653 |
+
v = self._eval_evalf(prec)
|
1654 |
+
if v is None:
|
1655 |
+
return self
|
1656 |
+
elif not v.is_number:
|
1657 |
+
return v
|
1658 |
+
try:
|
1659 |
+
# If the result is numerical, normalize it
|
1660 |
+
result = evalf(v, prec, options)
|
1661 |
+
except NotImplementedError:
|
1662 |
+
# Probably contains symbols or unknown functions
|
1663 |
+
return v
|
1664 |
+
if result is S.ComplexInfinity:
|
1665 |
+
return result
|
1666 |
+
re, im, re_acc, im_acc = result
|
1667 |
+
if re is S.NaN or im is S.NaN:
|
1668 |
+
return S.NaN
|
1669 |
+
if re:
|
1670 |
+
p = max(min(prec, re_acc), 1)
|
1671 |
+
re = Float._new(re, p)
|
1672 |
+
else:
|
1673 |
+
re = S.Zero
|
1674 |
+
if im:
|
1675 |
+
p = max(min(prec, im_acc), 1)
|
1676 |
+
im = Float._new(im, p)
|
1677 |
+
return re + im*S.ImaginaryUnit
|
1678 |
+
else:
|
1679 |
+
return re
|
1680 |
+
|
1681 |
+
n = evalf
|
1682 |
+
|
1683 |
+
def _evalf(self, prec):
|
1684 |
+
"""Helper for evalf. Does the same thing but takes binary precision"""
|
1685 |
+
r = self._eval_evalf(prec)
|
1686 |
+
if r is None:
|
1687 |
+
r = self
|
1688 |
+
return r
|
1689 |
+
|
1690 |
+
def _eval_evalf(self, prec):
|
1691 |
+
return
|
1692 |
+
|
1693 |
+
def _to_mpmath(self, prec, allow_ints=True):
|
1694 |
+
# mpmath functions accept ints as input
|
1695 |
+
errmsg = "cannot convert to mpmath number"
|
1696 |
+
if allow_ints and self.is_Integer:
|
1697 |
+
return self.p
|
1698 |
+
if hasattr(self, '_as_mpf_val'):
|
1699 |
+
return make_mpf(self._as_mpf_val(prec))
|
1700 |
+
try:
|
1701 |
+
result = evalf(self, prec, {})
|
1702 |
+
return quad_to_mpmath(result)
|
1703 |
+
except NotImplementedError:
|
1704 |
+
v = self._eval_evalf(prec)
|
1705 |
+
if v is None:
|
1706 |
+
raise ValueError(errmsg)
|
1707 |
+
if v.is_Float:
|
1708 |
+
return make_mpf(v._mpf_)
|
1709 |
+
# Number + Number*I is also fine
|
1710 |
+
re, im = v.as_real_imag()
|
1711 |
+
if allow_ints and re.is_Integer:
|
1712 |
+
re = from_int(re.p)
|
1713 |
+
elif re.is_Float:
|
1714 |
+
re = re._mpf_
|
1715 |
+
else:
|
1716 |
+
raise ValueError(errmsg)
|
1717 |
+
if allow_ints and im.is_Integer:
|
1718 |
+
im = from_int(im.p)
|
1719 |
+
elif im.is_Float:
|
1720 |
+
im = im._mpf_
|
1721 |
+
else:
|
1722 |
+
raise ValueError(errmsg)
|
1723 |
+
return make_mpc((re, im))
|
1724 |
+
|
1725 |
+
|
1726 |
+
def N(x, n=15, **options):
|
1727 |
+
r"""
|
1728 |
+
Calls x.evalf(n, \*\*options).
|
1729 |
+
|
1730 |
+
Explanations
|
1731 |
+
============
|
1732 |
+
|
1733 |
+
Both .n() and N() are equivalent to .evalf(); use the one that you like better.
|
1734 |
+
See also the docstring of .evalf() for information on the options.
|
1735 |
+
|
1736 |
+
Examples
|
1737 |
+
========
|
1738 |
+
|
1739 |
+
>>> from sympy import Sum, oo, N
|
1740 |
+
>>> from sympy.abc import k
|
1741 |
+
>>> Sum(1/k**k, (k, 1, oo))
|
1742 |
+
Sum(k**(-k), (k, 1, oo))
|
1743 |
+
>>> N(_, 4)
|
1744 |
+
1.291
|
1745 |
+
|
1746 |
+
"""
|
1747 |
+
# by using rational=True, any evaluation of a string
|
1748 |
+
# will be done using exact values for the Floats
|
1749 |
+
return sympify(x, rational=True).evalf(n, **options)
|
1750 |
+
|
1751 |
+
|
1752 |
+
def _evalf_with_bounded_error(x: 'Expr', eps: 'Optional[Expr]' = None,
|
1753 |
+
m: int = 0,
|
1754 |
+
options: Optional[OPT_DICT] = None) -> TMP_RES:
|
1755 |
+
"""
|
1756 |
+
Evaluate *x* to within a bounded absolute error.
|
1757 |
+
|
1758 |
+
Parameters
|
1759 |
+
==========
|
1760 |
+
|
1761 |
+
x : Expr
|
1762 |
+
The quantity to be evaluated.
|
1763 |
+
eps : Expr, None, optional (default=None)
|
1764 |
+
Positive real upper bound on the acceptable error.
|
1765 |
+
m : int, optional (default=0)
|
1766 |
+
If *eps* is None, then use 2**(-m) as the upper bound on the error.
|
1767 |
+
options: OPT_DICT
|
1768 |
+
As in the ``evalf`` function.
|
1769 |
+
|
1770 |
+
Returns
|
1771 |
+
=======
|
1772 |
+
|
1773 |
+
A tuple ``(re, im, re_acc, im_acc)``, as returned by ``evalf``.
|
1774 |
+
|
1775 |
+
See Also
|
1776 |
+
========
|
1777 |
+
|
1778 |
+
evalf
|
1779 |
+
|
1780 |
+
"""
|
1781 |
+
if eps is not None:
|
1782 |
+
if not (eps.is_Rational or eps.is_Float) or not eps > 0:
|
1783 |
+
raise ValueError("eps must be positive")
|
1784 |
+
r, _, _, _ = evalf(1/eps, 1, {})
|
1785 |
+
m = fastlog(r)
|
1786 |
+
|
1787 |
+
c, d, _, _ = evalf(x, 1, {})
|
1788 |
+
# Note: If x = a + b*I, then |a| <= 2|c| and |b| <= 2|d|, with equality
|
1789 |
+
# only in the zero case.
|
1790 |
+
# If a is non-zero, then |c| = 2**nc for some integer nc, and c has
|
1791 |
+
# bitcount 1. Therefore 2**fastlog(c) = 2**(nc+1) = 2|c| is an upper bound
|
1792 |
+
# on |a|. Likewise for b and d.
|
1793 |
+
nr, ni = fastlog(c), fastlog(d)
|
1794 |
+
n = max(nr, ni) + 1
|
1795 |
+
# If x is 0, then n is MINUS_INF, and p will be 1. Otherwise,
|
1796 |
+
# n - 1 bits get us past the integer parts of a and b, and +1 accounts for
|
1797 |
+
# the factor of <= sqrt(2) that is |x|/max(|a|, |b|).
|
1798 |
+
p = max(1, m + n + 1)
|
1799 |
+
|
1800 |
+
options = options or {}
|
1801 |
+
return evalf(x, p, options)
|
llmeval-env/lib/python3.10/site-packages/sympy/core/exprtools.py
ADDED
@@ -0,0 +1,1569 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
1 |
+
"""Tools for manipulating of large commutative expressions. """
|
2 |
+
|
3 |
+
from .add import Add
|
4 |
+
from .mul import Mul, _keep_coeff
|
5 |
+
from .power import Pow
|
6 |
+
from .basic import Basic
|
7 |
+
from .expr import Expr
|
8 |
+
from .function import expand_power_exp
|
9 |
+
from .sympify import sympify
|
10 |
+
from .numbers import Rational, Integer, Number, I, equal_valued
|
11 |
+
from .singleton import S
|
12 |
+
from .sorting import default_sort_key, ordered
|
13 |
+
from .symbol import Dummy
|
14 |
+
from .traversal import preorder_traversal
|
15 |
+
from .coreerrors import NonCommutativeExpression
|
16 |
+
from .containers import Tuple, Dict
|
17 |
+
from sympy.external.gmpy import SYMPY_INTS
|
18 |
+
from sympy.utilities.iterables import (common_prefix, common_suffix,
|
19 |
+
variations, iterable, is_sequence)
|
20 |
+
|
21 |
+
from collections import defaultdict
|
22 |
+
from typing import Tuple as tTuple
|
23 |
+
|
24 |
+
|
25 |
+
_eps = Dummy(positive=True)
|
26 |
+
|
27 |
+
|
28 |
+
def _isnumber(i):
|
29 |
+
return isinstance(i, (SYMPY_INTS, float)) or i.is_Number
|
30 |
+
|
31 |
+
|
32 |
+
def _monotonic_sign(self):
|
33 |
+
"""Return the value closest to 0 that ``self`` may have if all symbols
|
34 |
+
are signed and the result is uniformly the same sign for all values of symbols.
|
35 |
+
If a symbol is only signed but not known to be an
|
36 |
+
integer or the result is 0 then a symbol representative of the sign of self
|
37 |
+
will be returned. Otherwise, None is returned if a) the sign could be positive
|
38 |
+
or negative or b) self is not in one of the following forms:
|
39 |
+
|
40 |
+
- L(x, y, ...) + A: a function linear in all symbols x, y, ... with an
|
41 |
+
additive constant; if A is zero then the function can be a monomial whose
|
42 |
+
sign is monotonic over the range of the variables, e.g. (x + 1)**3 if x is
|
43 |
+
nonnegative.
|
44 |
+
- A/L(x, y, ...) + B: the inverse of a function linear in all symbols x, y, ...
|
45 |
+
that does not have a sign change from positive to negative for any set
|
46 |
+
of values for the variables.
|
47 |
+
- M(x, y, ...) + A: a monomial M whose factors are all signed and a constant, A.
|
48 |
+
- A/M(x, y, ...) + B: the inverse of a monomial and constants A and B.
|
49 |
+
- P(x): a univariate polynomial
|
50 |
+
|
51 |
+
Examples
|
52 |
+
========
|
53 |
+
|
54 |
+
>>> from sympy.core.exprtools import _monotonic_sign as F
|
55 |
+
>>> from sympy import Dummy
|
56 |
+
>>> nn = Dummy(integer=True, nonnegative=True)
|
57 |
+
>>> p = Dummy(integer=True, positive=True)
|
58 |
+
>>> p2 = Dummy(integer=True, positive=True)
|
59 |
+
>>> F(nn + 1)
|
60 |
+
1
|
61 |
+
>>> F(p - 1)
|
62 |
+
_nneg
|
63 |
+
>>> F(nn*p + 1)
|
64 |
+
1
|
65 |
+
>>> F(p2*p + 1)
|
66 |
+
2
|
67 |
+
>>> F(nn - 1) # could be negative, zero or positive
|
68 |
+
"""
|
69 |
+
if not self.is_extended_real:
|
70 |
+
return
|
71 |
+
|
72 |
+
if (-self).is_Symbol:
|
73 |
+
rv = _monotonic_sign(-self)
|
74 |
+
return rv if rv is None else -rv
|
75 |
+
|
76 |
+
if not self.is_Add and self.as_numer_denom()[1].is_number:
|
77 |
+
s = self
|
78 |
+
if s.is_prime:
|
79 |
+
if s.is_odd:
|
80 |
+
return Integer(3)
|
81 |
+
else:
|
82 |
+
return Integer(2)
|
83 |
+
elif s.is_composite:
|
84 |
+
if s.is_odd:
|
85 |
+
return Integer(9)
|
86 |
+
else:
|
87 |
+
return Integer(4)
|
88 |
+
elif s.is_positive:
|
89 |
+
if s.is_even:
|
90 |
+
if s.is_prime is False:
|
91 |
+
return Integer(4)
|
92 |
+
else:
|
93 |
+
return Integer(2)
|
94 |
+
elif s.is_integer:
|
95 |
+
return S.One
|
96 |
+
else:
|
97 |
+
return _eps
|
98 |
+
elif s.is_extended_negative:
|
99 |
+
if s.is_even:
|
100 |
+
return Integer(-2)
|
101 |
+
elif s.is_integer:
|
102 |
+
return S.NegativeOne
|
103 |
+
else:
|
104 |
+
return -_eps
|
105 |
+
if s.is_zero or s.is_extended_nonpositive or s.is_extended_nonnegative:
|
106 |
+
return S.Zero
|
107 |
+
return None
|
108 |
+
|
109 |
+
# univariate polynomial
|
110 |
+
free = self.free_symbols
|
111 |
+
if len(free) == 1:
|
112 |
+
if self.is_polynomial():
|
113 |
+
from sympy.polys.polytools import real_roots
|
114 |
+
from sympy.polys.polyroots import roots
|
115 |
+
from sympy.polys.polyerrors import PolynomialError
|
116 |
+
x = free.pop()
|
117 |
+
x0 = _monotonic_sign(x)
|
118 |
+
if x0 in (_eps, -_eps):
|
119 |
+
x0 = S.Zero
|
120 |
+
if x0 is not None:
|
121 |
+
d = self.diff(x)
|
122 |
+
if d.is_number:
|
123 |
+
currentroots = []
|
124 |
+
else:
|
125 |
+
try:
|
126 |
+
currentroots = real_roots(d)
|
127 |
+
except (PolynomialError, NotImplementedError):
|
128 |
+
currentroots = [r for r in roots(d, x) if r.is_extended_real]
|
129 |
+
y = self.subs(x, x0)
|
130 |
+
if x.is_nonnegative and all(
|
131 |
+
(r - x0).is_nonpositive for r in currentroots):
|
132 |
+
if y.is_nonnegative and d.is_positive:
|
133 |
+
if y:
|
134 |
+
return y if y.is_positive else Dummy('pos', positive=True)
|
135 |
+
else:
|
136 |
+
return Dummy('nneg', nonnegative=True)
|
137 |
+
if y.is_nonpositive and d.is_negative:
|
138 |
+
if y:
|
139 |
+
return y if y.is_negative else Dummy('neg', negative=True)
|
140 |
+
else:
|
141 |
+
return Dummy('npos', nonpositive=True)
|
142 |
+
elif x.is_nonpositive and all(
|
143 |
+
(r - x0).is_nonnegative for r in currentroots):
|
144 |
+
if y.is_nonnegative and d.is_negative:
|
145 |
+
if y:
|
146 |
+
return Dummy('pos', positive=True)
|
147 |
+
else:
|
148 |
+
return Dummy('nneg', nonnegative=True)
|
149 |
+
if y.is_nonpositive and d.is_positive:
|
150 |
+
if y:
|
151 |
+
return Dummy('neg', negative=True)
|
152 |
+
else:
|
153 |
+
return Dummy('npos', nonpositive=True)
|
154 |
+
else:
|
155 |
+
n, d = self.as_numer_denom()
|
156 |
+
den = None
|
157 |
+
if n.is_number:
|
158 |
+
den = _monotonic_sign(d)
|
159 |
+
elif not d.is_number:
|
160 |
+
if _monotonic_sign(n) is not None:
|
161 |
+
den = _monotonic_sign(d)
|
162 |
+
if den is not None and (den.is_positive or den.is_negative):
|
163 |
+
v = n*den
|
164 |
+
if v.is_positive:
|
165 |
+
return Dummy('pos', positive=True)
|
166 |
+
elif v.is_nonnegative:
|
167 |
+
return Dummy('nneg', nonnegative=True)
|
168 |
+
elif v.is_negative:
|
169 |
+
return Dummy('neg', negative=True)
|
170 |
+
elif v.is_nonpositive:
|
171 |
+
return Dummy('npos', nonpositive=True)
|
172 |
+
return None
|
173 |
+
|
174 |
+
# multivariate
|
175 |
+
c, a = self.as_coeff_Add()
|
176 |
+
v = None
|
177 |
+
if not a.is_polynomial():
|
178 |
+
# F/A or A/F where A is a number and F is a signed, rational monomial
|
179 |
+
n, d = a.as_numer_denom()
|
180 |
+
if not (n.is_number or d.is_number):
|
181 |
+
return
|
182 |
+
if (
|
183 |
+
a.is_Mul or a.is_Pow) and \
|
184 |
+
a.is_rational and \
|
185 |
+
all(p.exp.is_Integer for p in a.atoms(Pow) if p.is_Pow) and \
|
186 |
+
(a.is_positive or a.is_negative):
|
187 |
+
v = S.One
|
188 |
+
for ai in Mul.make_args(a):
|
189 |
+
if ai.is_number:
|
190 |
+
v *= ai
|
191 |
+
continue
|
192 |
+
reps = {}
|
193 |
+
for x in ai.free_symbols:
|
194 |
+
reps[x] = _monotonic_sign(x)
|
195 |
+
if reps[x] is None:
|
196 |
+
return
|
197 |
+
v *= ai.subs(reps)
|
198 |
+
elif c:
|
199 |
+
# signed linear expression
|
200 |
+
if not any(p for p in a.atoms(Pow) if not p.is_number) and (a.is_nonpositive or a.is_nonnegative):
|
201 |
+
free = list(a.free_symbols)
|
202 |
+
p = {}
|
203 |
+
for i in free:
|
204 |
+
v = _monotonic_sign(i)
|
205 |
+
if v is None:
|
206 |
+
return
|
207 |
+
p[i] = v or (_eps if i.is_nonnegative else -_eps)
|
208 |
+
v = a.xreplace(p)
|
209 |
+
if v is not None:
|
210 |
+
rv = v + c
|
211 |
+
if v.is_nonnegative and rv.is_positive:
|
212 |
+
return rv.subs(_eps, 0)
|
213 |
+
if v.is_nonpositive and rv.is_negative:
|
214 |
+
return rv.subs(_eps, 0)
|
215 |
+
|
216 |
+
|
217 |
+
def decompose_power(expr: Expr) -> tTuple[Expr, int]:
|
218 |
+
"""
|
219 |
+
Decompose power into symbolic base and integer exponent.
|
220 |
+
|
221 |
+
Examples
|
222 |
+
========
|
223 |
+
|
224 |
+
>>> from sympy.core.exprtools import decompose_power
|
225 |
+
>>> from sympy.abc import x, y
|
226 |
+
>>> from sympy import exp
|
227 |
+
|
228 |
+
>>> decompose_power(x)
|
229 |
+
(x, 1)
|
230 |
+
>>> decompose_power(x**2)
|
231 |
+
(x, 2)
|
232 |
+
>>> decompose_power(exp(2*y/3))
|
233 |
+
(exp(y/3), 2)
|
234 |
+
|
235 |
+
"""
|
236 |
+
base, exp = expr.as_base_exp()
|
237 |
+
|
238 |
+
if exp.is_Number:
|
239 |
+
if exp.is_Rational:
|
240 |
+
if not exp.is_Integer:
|
241 |
+
base = Pow(base, Rational(1, exp.q)) # type: ignore
|
242 |
+
e = exp.p # type: ignore
|
243 |
+
else:
|
244 |
+
base, e = expr, 1
|
245 |
+
else:
|
246 |
+
exp, tail = exp.as_coeff_Mul(rational=True)
|
247 |
+
|
248 |
+
if exp is S.NegativeOne:
|
249 |
+
base, e = Pow(base, tail), -1
|
250 |
+
elif exp is not S.One:
|
251 |
+
# todo: after dropping python 3.7 support, use overload and Literal
|
252 |
+
# in as_coeff_Mul to make exp Rational, and remove these 2 ignores
|
253 |
+
tail = _keep_coeff(Rational(1, exp.q), tail) # type: ignore
|
254 |
+
base, e = Pow(base, tail), exp.p # type: ignore
|
255 |
+
else:
|
256 |
+
base, e = expr, 1
|
257 |
+
|
258 |
+
return base, e
|
259 |
+
|
260 |
+
|
261 |
+
def decompose_power_rat(expr: Expr) -> tTuple[Expr, Rational]:
|
262 |
+
"""
|
263 |
+
Decompose power into symbolic base and rational exponent;
|
264 |
+
if the exponent is not a Rational, then separate only the
|
265 |
+
integer coefficient.
|
266 |
+
|
267 |
+
Examples
|
268 |
+
========
|
269 |
+
|
270 |
+
>>> from sympy.core.exprtools import decompose_power_rat
|
271 |
+
>>> from sympy.abc import x
|
272 |
+
>>> from sympy import sqrt, exp
|
273 |
+
|
274 |
+
>>> decompose_power_rat(sqrt(x))
|
275 |
+
(x, 1/2)
|
276 |
+
>>> decompose_power_rat(exp(-3*x/2))
|
277 |
+
(exp(x/2), -3)
|
278 |
+
|
279 |
+
"""
|
280 |
+
_ = base, exp = expr.as_base_exp()
|
281 |
+
return _ if exp.is_Rational else decompose_power(expr)
|
282 |
+
|
283 |
+
|
284 |
+
class Factors:
|
285 |
+
"""Efficient representation of ``f_1*f_2*...*f_n``."""
|
286 |
+
|
287 |
+
__slots__ = ('factors', 'gens')
|
288 |
+
|
289 |
+
def __init__(self, factors=None): # Factors
|
290 |
+
"""Initialize Factors from dict or expr.
|
291 |
+
|
292 |
+
Examples
|
293 |
+
========
|
294 |
+
|
295 |
+
>>> from sympy.core.exprtools import Factors
|
296 |
+
>>> from sympy.abc import x
|
297 |
+
>>> from sympy import I
|
298 |
+
>>> e = 2*x**3
|
299 |
+
>>> Factors(e)
|
300 |
+
Factors({2: 1, x: 3})
|
301 |
+
>>> Factors(e.as_powers_dict())
|
302 |
+
Factors({2: 1, x: 3})
|
303 |
+
>>> f = _
|
304 |
+
>>> f.factors # underlying dictionary
|
305 |
+
{2: 1, x: 3}
|
306 |
+
>>> f.gens # base of each factor
|
307 |
+
frozenset({2, x})
|
308 |
+
>>> Factors(0)
|
309 |
+
Factors({0: 1})
|
310 |
+
>>> Factors(I)
|
311 |
+
Factors({I: 1})
|
312 |
+
|
313 |
+
Notes
|
314 |
+
=====
|
315 |
+
|
316 |
+
Although a dictionary can be passed, only minimal checking is
|
317 |
+
performed: powers of -1 and I are made canonical.
|
318 |
+
|
319 |
+
"""
|
320 |
+
if isinstance(factors, (SYMPY_INTS, float)):
|
321 |
+
factors = S(factors)
|
322 |
+
if isinstance(factors, Factors):
|
323 |
+
factors = factors.factors.copy()
|
324 |
+
elif factors in (None, S.One):
|
325 |
+
factors = {}
|
326 |
+
elif factors is S.Zero or factors == 0:
|
327 |
+
factors = {S.Zero: S.One}
|
328 |
+
elif isinstance(factors, Number):
|
329 |
+
n = factors
|
330 |
+
factors = {}
|
331 |
+
if n < 0:
|
332 |
+
factors[S.NegativeOne] = S.One
|
333 |
+
n = -n
|
334 |
+
if n is not S.One:
|
335 |
+
if n.is_Float or n.is_Integer or n is S.Infinity:
|
336 |
+
factors[n] = S.One
|
337 |
+
elif n.is_Rational:
|
338 |
+
# since we're processing Numbers, the denominator is
|
339 |
+
# stored with a negative exponent; all other factors
|
340 |
+
# are left .
|
341 |
+
if n.p != 1:
|
342 |
+
factors[Integer(n.p)] = S.One
|
343 |
+
factors[Integer(n.q)] = S.NegativeOne
|
344 |
+
else:
|
345 |
+
raise ValueError('Expected Float|Rational|Integer, not %s' % n)
|
346 |
+
elif isinstance(factors, Basic) and not factors.args:
|
347 |
+
factors = {factors: S.One}
|
348 |
+
elif isinstance(factors, Expr):
|
349 |
+
c, nc = factors.args_cnc()
|
350 |
+
i = c.count(I)
|
351 |
+
for _ in range(i):
|
352 |
+
c.remove(I)
|
353 |
+
factors = dict(Mul._from_args(c).as_powers_dict())
|
354 |
+
# Handle all rational Coefficients
|
355 |
+
for f in list(factors.keys()):
|
356 |
+
if isinstance(f, Rational) and not isinstance(f, Integer):
|
357 |
+
p, q = Integer(f.p), Integer(f.q)
|
358 |
+
factors[p] = (factors[p] if p in factors else S.Zero) + factors[f]
|
359 |
+
factors[q] = (factors[q] if q in factors else S.Zero) - factors[f]
|
360 |
+
factors.pop(f)
|
361 |
+
if i:
|
362 |
+
factors[I] = factors.get(I, S.Zero) + i
|
363 |
+
if nc:
|
364 |
+
factors[Mul(*nc, evaluate=False)] = S.One
|
365 |
+
else:
|
366 |
+
factors = factors.copy() # /!\ should be dict-like
|
367 |
+
|
368 |
+
# tidy up -/+1 and I exponents if Rational
|
369 |
+
|
370 |
+
handle = [k for k in factors if k is I or k in (-1, 1)]
|
371 |
+
if handle:
|
372 |
+
i1 = S.One
|
373 |
+
for k in handle:
|
374 |
+
if not _isnumber(factors[k]):
|
375 |
+
continue
|
376 |
+
i1 *= k**factors.pop(k)
|
377 |
+
if i1 is not S.One:
|
378 |
+
for a in i1.args if i1.is_Mul else [i1]: # at worst, -1.0*I*(-1)**e
|
379 |
+
if a is S.NegativeOne:
|
380 |
+
factors[a] = S.One
|
381 |
+
elif a is I:
|
382 |
+
factors[I] = S.One
|
383 |
+
elif a.is_Pow:
|
384 |
+
factors[a.base] = factors.get(a.base, S.Zero) + a.exp
|
385 |
+
elif equal_valued(a, 1):
|
386 |
+
factors[a] = S.One
|
387 |
+
elif equal_valued(a, -1):
|
388 |
+
factors[-a] = S.One
|
389 |
+
factors[S.NegativeOne] = S.One
|
390 |
+
else:
|
391 |
+
raise ValueError('unexpected factor in i1: %s' % a)
|
392 |
+
|
393 |
+
self.factors = factors
|
394 |
+
keys = getattr(factors, 'keys', None)
|
395 |
+
if keys is None:
|
396 |
+
raise TypeError('expecting Expr or dictionary')
|
397 |
+
self.gens = frozenset(keys())
|
398 |
+
|
399 |
+
def __hash__(self): # Factors
|
400 |
+
keys = tuple(ordered(self.factors.keys()))
|
401 |
+
values = [self.factors[k] for k in keys]
|
402 |
+
return hash((keys, values))
|
403 |
+
|
404 |
+
def __repr__(self): # Factors
|
405 |
+
return "Factors({%s})" % ', '.join(
|
406 |
+
['%s: %s' % (k, v) for k, v in ordered(self.factors.items())])
|
407 |
+
|
408 |
+
@property
|
409 |
+
def is_zero(self): # Factors
|
410 |
+
"""
|
411 |
+
>>> from sympy.core.exprtools import Factors
|
412 |
+
>>> Factors(0).is_zero
|
413 |
+
True
|
414 |
+
"""
|
415 |
+
f = self.factors
|
416 |
+
return len(f) == 1 and S.Zero in f
|
417 |
+
|
418 |
+
@property
|
419 |
+
def is_one(self): # Factors
|
420 |
+
"""
|
421 |
+
>>> from sympy.core.exprtools import Factors
|
422 |
+
>>> Factors(1).is_one
|
423 |
+
True
|
424 |
+
"""
|
425 |
+
return not self.factors
|
426 |
+
|
427 |
+
def as_expr(self): # Factors
|
428 |
+
"""Return the underlying expression.
|
429 |
+
|
430 |
+
Examples
|
431 |
+
========
|
432 |
+
|
433 |
+
>>> from sympy.core.exprtools import Factors
|
434 |
+
>>> from sympy.abc import x, y
|
435 |
+
>>> Factors((x*y**2).as_powers_dict()).as_expr()
|
436 |
+
x*y**2
|
437 |
+
|
438 |
+
"""
|
439 |
+
|
440 |
+
args = []
|
441 |
+
for factor, exp in self.factors.items():
|
442 |
+
if exp != 1:
|
443 |
+
if isinstance(exp, Integer):
|
444 |
+
b, e = factor.as_base_exp()
|
445 |
+
e = _keep_coeff(exp, e)
|
446 |
+
args.append(b**e)
|
447 |
+
else:
|
448 |
+
args.append(factor**exp)
|
449 |
+
else:
|
450 |
+
args.append(factor)
|
451 |
+
return Mul(*args)
|
452 |
+
|
453 |
+
def mul(self, other): # Factors
|
454 |
+
"""Return Factors of ``self * other``.
|
455 |
+
|
456 |
+
Examples
|
457 |
+
========
|
458 |
+
|
459 |
+
>>> from sympy.core.exprtools import Factors
|
460 |
+
>>> from sympy.abc import x, y, z
|
461 |
+
>>> a = Factors((x*y**2).as_powers_dict())
|
462 |
+
>>> b = Factors((x*y/z).as_powers_dict())
|
463 |
+
>>> a.mul(b)
|
464 |
+
Factors({x: 2, y: 3, z: -1})
|
465 |
+
>>> a*b
|
466 |
+
Factors({x: 2, y: 3, z: -1})
|
467 |
+
"""
|
468 |
+
if not isinstance(other, Factors):
|
469 |
+
other = Factors(other)
|
470 |
+
if any(f.is_zero for f in (self, other)):
|
471 |
+
return Factors(S.Zero)
|
472 |
+
factors = dict(self.factors)
|
473 |
+
|
474 |
+
for factor, exp in other.factors.items():
|
475 |
+
if factor in factors:
|
476 |
+
exp = factors[factor] + exp
|
477 |
+
|
478 |
+
if not exp:
|
479 |
+
del factors[factor]
|
480 |
+
continue
|
481 |
+
|
482 |
+
factors[factor] = exp
|
483 |
+
|
484 |
+
return Factors(factors)
|
485 |
+
|
486 |
+
def normal(self, other):
|
487 |
+
"""Return ``self`` and ``other`` with ``gcd`` removed from each.
|
488 |
+
The only differences between this and method ``div`` is that this
|
489 |
+
is 1) optimized for the case when there are few factors in common and
|
490 |
+
2) this does not raise an error if ``other`` is zero.
|
491 |
+
|
492 |
+
See Also
|
493 |
+
========
|
494 |
+
div
|
495 |
+
|
496 |
+
"""
|
497 |
+
if not isinstance(other, Factors):
|
498 |
+
other = Factors(other)
|
499 |
+
if other.is_zero:
|
500 |
+
return (Factors(), Factors(S.Zero))
|
501 |
+
if self.is_zero:
|
502 |
+
return (Factors(S.Zero), Factors())
|
503 |
+
|
504 |
+
self_factors = dict(self.factors)
|
505 |
+
other_factors = dict(other.factors)
|
506 |
+
|
507 |
+
for factor, self_exp in self.factors.items():
|
508 |
+
try:
|
509 |
+
other_exp = other.factors[factor]
|
510 |
+
except KeyError:
|
511 |
+
continue
|
512 |
+
|
513 |
+
exp = self_exp - other_exp
|
514 |
+
|
515 |
+
if not exp:
|
516 |
+
del self_factors[factor]
|
517 |
+
del other_factors[factor]
|
518 |
+
elif _isnumber(exp):
|
519 |
+
if exp > 0:
|
520 |
+
self_factors[factor] = exp
|
521 |
+
del other_factors[factor]
|
522 |
+
else:
|
523 |
+
del self_factors[factor]
|
524 |
+
other_factors[factor] = -exp
|
525 |
+
else:
|
526 |
+
r = self_exp.extract_additively(other_exp)
|
527 |
+
if r is not None:
|
528 |
+
if r:
|
529 |
+
self_factors[factor] = r
|
530 |
+
del other_factors[factor]
|
531 |
+
else: # should be handled already
|
532 |
+
del self_factors[factor]
|
533 |
+
del other_factors[factor]
|
534 |
+
else:
|
535 |
+
sc, sa = self_exp.as_coeff_Add()
|
536 |
+
if sc:
|
537 |
+
oc, oa = other_exp.as_coeff_Add()
|
538 |
+
diff = sc - oc
|
539 |
+
if diff > 0:
|
540 |
+
self_factors[factor] -= oc
|
541 |
+
other_exp = oa
|
542 |
+
elif diff < 0:
|
543 |
+
self_factors[factor] -= sc
|
544 |
+
other_factors[factor] -= sc
|
545 |
+
other_exp = oa - diff
|
546 |
+
else:
|
547 |
+
self_factors[factor] = sa
|
548 |
+
other_exp = oa
|
549 |
+
if other_exp:
|
550 |
+
other_factors[factor] = other_exp
|
551 |
+
else:
|
552 |
+
del other_factors[factor]
|
553 |
+
|
554 |
+
return Factors(self_factors), Factors(other_factors)
|
555 |
+
|
556 |
+
def div(self, other): # Factors
|
557 |
+
"""Return ``self`` and ``other`` with ``gcd`` removed from each.
|
558 |
+
This is optimized for the case when there are many factors in common.
|
559 |
+
|
560 |
+
Examples
|
561 |
+
========
|
562 |
+
|
563 |
+
>>> from sympy.core.exprtools import Factors
|
564 |
+
>>> from sympy.abc import x, y, z
|
565 |
+
>>> from sympy import S
|
566 |
+
|
567 |
+
>>> a = Factors((x*y**2).as_powers_dict())
|
568 |
+
>>> a.div(a)
|
569 |
+
(Factors({}), Factors({}))
|
570 |
+
>>> a.div(x*z)
|
571 |
+
(Factors({y: 2}), Factors({z: 1}))
|
572 |
+
|
573 |
+
The ``/`` operator only gives ``quo``:
|
574 |
+
|
575 |
+
>>> a/x
|
576 |
+
Factors({y: 2})
|
577 |
+
|
578 |
+
Factors treats its factors as though they are all in the numerator, so
|
579 |
+
if you violate this assumption the results will be correct but will
|
580 |
+
not strictly correspond to the numerator and denominator of the ratio:
|
581 |
+
|
582 |
+
>>> a.div(x/z)
|
583 |
+
(Factors({y: 2}), Factors({z: -1}))
|
584 |
+
|
585 |
+
Factors is also naive about bases: it does not attempt any denesting
|
586 |
+
of Rational-base terms, for example the following does not become
|
587 |
+
2**(2*x)/2.
|
588 |
+
|
589 |
+
>>> Factors(2**(2*x + 2)).div(S(8))
|
590 |
+
(Factors({2: 2*x + 2}), Factors({8: 1}))
|
591 |
+
|
592 |
+
factor_terms can clean up such Rational-bases powers:
|
593 |
+
|
594 |
+
>>> from sympy import factor_terms
|
595 |
+
>>> n, d = Factors(2**(2*x + 2)).div(S(8))
|
596 |
+
>>> n.as_expr()/d.as_expr()
|
597 |
+
2**(2*x + 2)/8
|
598 |
+
>>> factor_terms(_)
|
599 |
+
2**(2*x)/2
|
600 |
+
|
601 |
+
"""
|
602 |
+
quo, rem = dict(self.factors), {}
|
603 |
+
|
604 |
+
if not isinstance(other, Factors):
|
605 |
+
other = Factors(other)
|
606 |
+
if other.is_zero:
|
607 |
+
raise ZeroDivisionError
|
608 |
+
if self.is_zero:
|
609 |
+
return (Factors(S.Zero), Factors())
|
610 |
+
|
611 |
+
for factor, exp in other.factors.items():
|
612 |
+
if factor in quo:
|
613 |
+
d = quo[factor] - exp
|
614 |
+
if _isnumber(d):
|
615 |
+
if d <= 0:
|
616 |
+
del quo[factor]
|
617 |
+
|
618 |
+
if d >= 0:
|
619 |
+
if d:
|
620 |
+
quo[factor] = d
|
621 |
+
|
622 |
+
continue
|
623 |
+
|
624 |
+
exp = -d
|
625 |
+
|
626 |
+
else:
|
627 |
+
r = quo[factor].extract_additively(exp)
|
628 |
+
if r is not None:
|
629 |
+
if r:
|
630 |
+
quo[factor] = r
|
631 |
+
else: # should be handled already
|
632 |
+
del quo[factor]
|
633 |
+
else:
|
634 |
+
other_exp = exp
|
635 |
+
sc, sa = quo[factor].as_coeff_Add()
|
636 |
+
if sc:
|
637 |
+
oc, oa = other_exp.as_coeff_Add()
|
638 |
+
diff = sc - oc
|
639 |
+
if diff > 0:
|
640 |
+
quo[factor] -= oc
|
641 |
+
other_exp = oa
|
642 |
+
elif diff < 0:
|
643 |
+
quo[factor] -= sc
|
644 |
+
other_exp = oa - diff
|
645 |
+
else:
|
646 |
+
quo[factor] = sa
|
647 |
+
other_exp = oa
|
648 |
+
if other_exp:
|
649 |
+
rem[factor] = other_exp
|
650 |
+
else:
|
651 |
+
assert factor not in rem
|
652 |
+
continue
|
653 |
+
|
654 |
+
rem[factor] = exp
|
655 |
+
|
656 |
+
return Factors(quo), Factors(rem)
|
657 |
+
|
658 |
+
def quo(self, other): # Factors
|
659 |
+
"""Return numerator Factor of ``self / other``.
|
660 |
+
|
661 |
+
Examples
|
662 |
+
========
|
663 |
+
|
664 |
+
>>> from sympy.core.exprtools import Factors
|
665 |
+
>>> from sympy.abc import x, y, z
|
666 |
+
>>> a = Factors((x*y**2).as_powers_dict())
|
667 |
+
>>> b = Factors((x*y/z).as_powers_dict())
|
668 |
+
>>> a.quo(b) # same as a/b
|
669 |
+
Factors({y: 1})
|
670 |
+
"""
|
671 |
+
return self.div(other)[0]
|
672 |
+
|
673 |
+
def rem(self, other): # Factors
|
674 |
+
"""Return denominator Factors of ``self / other``.
|
675 |
+
|
676 |
+
Examples
|
677 |
+
========
|
678 |
+
|
679 |
+
>>> from sympy.core.exprtools import Factors
|
680 |
+
>>> from sympy.abc import x, y, z
|
681 |
+
>>> a = Factors((x*y**2).as_powers_dict())
|
682 |
+
>>> b = Factors((x*y/z).as_powers_dict())
|
683 |
+
>>> a.rem(b)
|
684 |
+
Factors({z: -1})
|
685 |
+
>>> a.rem(a)
|
686 |
+
Factors({})
|
687 |
+
"""
|
688 |
+
return self.div(other)[1]
|
689 |
+
|
690 |
+
def pow(self, other): # Factors
|
691 |
+
"""Return self raised to a non-negative integer power.
|
692 |
+
|
693 |
+
Examples
|
694 |
+
========
|
695 |
+
|
696 |
+
>>> from sympy.core.exprtools import Factors
|
697 |
+
>>> from sympy.abc import x, y
|
698 |
+
>>> a = Factors((x*y**2).as_powers_dict())
|
699 |
+
>>> a**2
|
700 |
+
Factors({x: 2, y: 4})
|
701 |
+
|
702 |
+
"""
|
703 |
+
if isinstance(other, Factors):
|
704 |
+
other = other.as_expr()
|
705 |
+
if other.is_Integer:
|
706 |
+
other = int(other)
|
707 |
+
if isinstance(other, SYMPY_INTS) and other >= 0:
|
708 |
+
factors = {}
|
709 |
+
|
710 |
+
if other:
|
711 |
+
for factor, exp in self.factors.items():
|
712 |
+
factors[factor] = exp*other
|
713 |
+
|
714 |
+
return Factors(factors)
|
715 |
+
else:
|
716 |
+
raise ValueError("expected non-negative integer, got %s" % other)
|
717 |
+
|
718 |
+
def gcd(self, other): # Factors
|
719 |
+
"""Return Factors of ``gcd(self, other)``. The keys are
|
720 |
+
the intersection of factors with the minimum exponent for
|
721 |
+
each factor.
|
722 |
+
|
723 |
+
Examples
|
724 |
+
========
|
725 |
+
|
726 |
+
>>> from sympy.core.exprtools import Factors
|
727 |
+
>>> from sympy.abc import x, y, z
|
728 |
+
>>> a = Factors((x*y**2).as_powers_dict())
|
729 |
+
>>> b = Factors((x*y/z).as_powers_dict())
|
730 |
+
>>> a.gcd(b)
|
731 |
+
Factors({x: 1, y: 1})
|
732 |
+
"""
|
733 |
+
if not isinstance(other, Factors):
|
734 |
+
other = Factors(other)
|
735 |
+
if other.is_zero:
|
736 |
+
return Factors(self.factors)
|
737 |
+
|
738 |
+
factors = {}
|
739 |
+
|
740 |
+
for factor, exp in self.factors.items():
|
741 |
+
factor, exp = sympify(factor), sympify(exp)
|
742 |
+
if factor in other.factors:
|
743 |
+
lt = (exp - other.factors[factor]).is_negative
|
744 |
+
if lt == True:
|
745 |
+
factors[factor] = exp
|
746 |
+
elif lt == False:
|
747 |
+
factors[factor] = other.factors[factor]
|
748 |
+
|
749 |
+
return Factors(factors)
|
750 |
+
|
751 |
+
def lcm(self, other): # Factors
|
752 |
+
"""Return Factors of ``lcm(self, other)`` which are
|
753 |
+
the union of factors with the maximum exponent for
|
754 |
+
each factor.
|
755 |
+
|
756 |
+
Examples
|
757 |
+
========
|
758 |
+
|
759 |
+
>>> from sympy.core.exprtools import Factors
|
760 |
+
>>> from sympy.abc import x, y, z
|
761 |
+
>>> a = Factors((x*y**2).as_powers_dict())
|
762 |
+
>>> b = Factors((x*y/z).as_powers_dict())
|
763 |
+
>>> a.lcm(b)
|
764 |
+
Factors({x: 1, y: 2, z: -1})
|
765 |
+
"""
|
766 |
+
if not isinstance(other, Factors):
|
767 |
+
other = Factors(other)
|
768 |
+
if any(f.is_zero for f in (self, other)):
|
769 |
+
return Factors(S.Zero)
|
770 |
+
|
771 |
+
factors = dict(self.factors)
|
772 |
+
|
773 |
+
for factor, exp in other.factors.items():
|
774 |
+
if factor in factors:
|
775 |
+
exp = max(exp, factors[factor])
|
776 |
+
|
777 |
+
factors[factor] = exp
|
778 |
+
|
779 |
+
return Factors(factors)
|
780 |
+
|
781 |
+
def __mul__(self, other): # Factors
|
782 |
+
return self.mul(other)
|
783 |
+
|
784 |
+
def __divmod__(self, other): # Factors
|
785 |
+
return self.div(other)
|
786 |
+
|
787 |
+
def __truediv__(self, other): # Factors
|
788 |
+
return self.quo(other)
|
789 |
+
|
790 |
+
def __mod__(self, other): # Factors
|
791 |
+
return self.rem(other)
|
792 |
+
|
793 |
+
def __pow__(self, other): # Factors
|
794 |
+
return self.pow(other)
|
795 |
+
|
796 |
+
def __eq__(self, other): # Factors
|
797 |
+
if not isinstance(other, Factors):
|
798 |
+
other = Factors(other)
|
799 |
+
return self.factors == other.factors
|
800 |
+
|
801 |
+
def __ne__(self, other): # Factors
|
802 |
+
return not self == other
|
803 |
+
|
804 |
+
|
805 |
+
class Term:
|
806 |
+
"""Efficient representation of ``coeff*(numer/denom)``. """
|
807 |
+
|
808 |
+
__slots__ = ('coeff', 'numer', 'denom')
|
809 |
+
|
810 |
+
def __init__(self, term, numer=None, denom=None): # Term
|
811 |
+
if numer is None and denom is None:
|
812 |
+
if not term.is_commutative:
|
813 |
+
raise NonCommutativeExpression(
|
814 |
+
'commutative expression expected')
|
815 |
+
|
816 |
+
coeff, factors = term.as_coeff_mul()
|
817 |
+
numer, denom = defaultdict(int), defaultdict(int)
|
818 |
+
|
819 |
+
for factor in factors:
|
820 |
+
base, exp = decompose_power(factor)
|
821 |
+
|
822 |
+
if base.is_Add:
|
823 |
+
cont, base = base.primitive()
|
824 |
+
coeff *= cont**exp
|
825 |
+
|
826 |
+
if exp > 0:
|
827 |
+
numer[base] += exp
|
828 |
+
else:
|
829 |
+
denom[base] += -exp
|
830 |
+
|
831 |
+
numer = Factors(numer)
|
832 |
+
denom = Factors(denom)
|
833 |
+
else:
|
834 |
+
coeff = term
|
835 |
+
|
836 |
+
if numer is None:
|
837 |
+
numer = Factors()
|
838 |
+
|
839 |
+
if denom is None:
|
840 |
+
denom = Factors()
|
841 |
+
|
842 |
+
self.coeff = coeff
|
843 |
+
self.numer = numer
|
844 |
+
self.denom = denom
|
845 |
+
|
846 |
+
def __hash__(self): # Term
|
847 |
+
return hash((self.coeff, self.numer, self.denom))
|
848 |
+
|
849 |
+
def __repr__(self): # Term
|
850 |
+
return "Term(%s, %s, %s)" % (self.coeff, self.numer, self.denom)
|
851 |
+
|
852 |
+
def as_expr(self): # Term
|
853 |
+
return self.coeff*(self.numer.as_expr()/self.denom.as_expr())
|
854 |
+
|
855 |
+
def mul(self, other): # Term
|
856 |
+
coeff = self.coeff*other.coeff
|
857 |
+
numer = self.numer.mul(other.numer)
|
858 |
+
denom = self.denom.mul(other.denom)
|
859 |
+
|
860 |
+
numer, denom = numer.normal(denom)
|
861 |
+
|
862 |
+
return Term(coeff, numer, denom)
|
863 |
+
|
864 |
+
def inv(self): # Term
|
865 |
+
return Term(1/self.coeff, self.denom, self.numer)
|
866 |
+
|
867 |
+
def quo(self, other): # Term
|
868 |
+
return self.mul(other.inv())
|
869 |
+
|
870 |
+
def pow(self, other): # Term
|
871 |
+
if other < 0:
|
872 |
+
return self.inv().pow(-other)
|
873 |
+
else:
|
874 |
+
return Term(self.coeff ** other,
|
875 |
+
self.numer.pow(other),
|
876 |
+
self.denom.pow(other))
|
877 |
+
|
878 |
+
def gcd(self, other): # Term
|
879 |
+
return Term(self.coeff.gcd(other.coeff),
|
880 |
+
self.numer.gcd(other.numer),
|
881 |
+
self.denom.gcd(other.denom))
|
882 |
+
|
883 |
+
def lcm(self, other): # Term
|
884 |
+
return Term(self.coeff.lcm(other.coeff),
|
885 |
+
self.numer.lcm(other.numer),
|
886 |
+
self.denom.lcm(other.denom))
|
887 |
+
|
888 |
+
def __mul__(self, other): # Term
|
889 |
+
if isinstance(other, Term):
|
890 |
+
return self.mul(other)
|
891 |
+
else:
|
892 |
+
return NotImplemented
|
893 |
+
|
894 |
+
def __truediv__(self, other): # Term
|
895 |
+
if isinstance(other, Term):
|
896 |
+
return self.quo(other)
|
897 |
+
else:
|
898 |
+
return NotImplemented
|
899 |
+
|
900 |
+
def __pow__(self, other): # Term
|
901 |
+
if isinstance(other, SYMPY_INTS):
|
902 |
+
return self.pow(other)
|
903 |
+
else:
|
904 |
+
return NotImplemented
|
905 |
+
|
906 |
+
def __eq__(self, other): # Term
|
907 |
+
return (self.coeff == other.coeff and
|
908 |
+
self.numer == other.numer and
|
909 |
+
self.denom == other.denom)
|
910 |
+
|
911 |
+
def __ne__(self, other): # Term
|
912 |
+
return not self == other
|
913 |
+
|
914 |
+
|
915 |
+
def _gcd_terms(terms, isprimitive=False, fraction=True):
|
916 |
+
"""Helper function for :func:`gcd_terms`.
|
917 |
+
|
918 |
+
Parameters
|
919 |
+
==========
|
920 |
+
|
921 |
+
isprimitive : boolean, optional
|
922 |
+
If ``isprimitive`` is True then the call to primitive
|
923 |
+
for an Add will be skipped. This is useful when the
|
924 |
+
content has already been extracted.
|
925 |
+
|
926 |
+
fraction : boolean, optional
|
927 |
+
If ``fraction`` is True then the expression will appear over a common
|
928 |
+
denominator, the lcm of all term denominators.
|
929 |
+
"""
|
930 |
+
|
931 |
+
if isinstance(terms, Basic) and not isinstance(terms, Tuple):
|
932 |
+
terms = Add.make_args(terms)
|
933 |
+
|
934 |
+
terms = list(map(Term, [t for t in terms if t]))
|
935 |
+
|
936 |
+
# there is some simplification that may happen if we leave this
|
937 |
+
# here rather than duplicate it before the mapping of Term onto
|
938 |
+
# the terms
|
939 |
+
if len(terms) == 0:
|
940 |
+
return S.Zero, S.Zero, S.One
|
941 |
+
|
942 |
+
if len(terms) == 1:
|
943 |
+
cont = terms[0].coeff
|
944 |
+
numer = terms[0].numer.as_expr()
|
945 |
+
denom = terms[0].denom.as_expr()
|
946 |
+
|
947 |
+
else:
|
948 |
+
cont = terms[0]
|
949 |
+
for term in terms[1:]:
|
950 |
+
cont = cont.gcd(term)
|
951 |
+
|
952 |
+
for i, term in enumerate(terms):
|
953 |
+
terms[i] = term.quo(cont)
|
954 |
+
|
955 |
+
if fraction:
|
956 |
+
denom = terms[0].denom
|
957 |
+
|
958 |
+
for term in terms[1:]:
|
959 |
+
denom = denom.lcm(term.denom)
|
960 |
+
|
961 |
+
numers = []
|
962 |
+
for term in terms:
|
963 |
+
numer = term.numer.mul(denom.quo(term.denom))
|
964 |
+
numers.append(term.coeff*numer.as_expr())
|
965 |
+
else:
|
966 |
+
numers = [t.as_expr() for t in terms]
|
967 |
+
denom = Term(S.One).numer
|
968 |
+
|
969 |
+
cont = cont.as_expr()
|
970 |
+
numer = Add(*numers)
|
971 |
+
denom = denom.as_expr()
|
972 |
+
|
973 |
+
if not isprimitive and numer.is_Add:
|
974 |
+
_cont, numer = numer.primitive()
|
975 |
+
cont *= _cont
|
976 |
+
|
977 |
+
return cont, numer, denom
|
978 |
+
|
979 |
+
|
980 |
+
def gcd_terms(terms, isprimitive=False, clear=True, fraction=True):
|
981 |
+
"""Compute the GCD of ``terms`` and put them together.
|
982 |
+
|
983 |
+
Parameters
|
984 |
+
==========
|
985 |
+
|
986 |
+
terms : Expr
|
987 |
+
Can be an expression or a non-Basic sequence of expressions
|
988 |
+
which will be handled as though they are terms from a sum.
|
989 |
+
|
990 |
+
isprimitive : bool, optional
|
991 |
+
If ``isprimitive`` is True the _gcd_terms will not run the primitive
|
992 |
+
method on the terms.
|
993 |
+
|
994 |
+
clear : bool, optional
|
995 |
+
It controls the removal of integers from the denominator of an Add
|
996 |
+
expression. When True (default), all numerical denominator will be cleared;
|
997 |
+
when False the denominators will be cleared only if all terms had numerical
|
998 |
+
denominators other than 1.
|
999 |
+
|
1000 |
+
fraction : bool, optional
|
1001 |
+
When True (default), will put the expression over a common
|
1002 |
+
denominator.
|
1003 |
+
|
1004 |
+
Examples
|
1005 |
+
========
|
1006 |
+
|
1007 |
+
>>> from sympy import gcd_terms
|
1008 |
+
>>> from sympy.abc import x, y
|
1009 |
+
|
1010 |
+
>>> gcd_terms((x + 1)**2*y + (x + 1)*y**2)
|
1011 |
+
y*(x + 1)*(x + y + 1)
|
1012 |
+
>>> gcd_terms(x/2 + 1)
|
1013 |
+
(x + 2)/2
|
1014 |
+
>>> gcd_terms(x/2 + 1, clear=False)
|
1015 |
+
x/2 + 1
|
1016 |
+
>>> gcd_terms(x/2 + y/2, clear=False)
|
1017 |
+
(x + y)/2
|
1018 |
+
>>> gcd_terms(x/2 + 1/x)
|
1019 |
+
(x**2 + 2)/(2*x)
|
1020 |
+
>>> gcd_terms(x/2 + 1/x, fraction=False)
|
1021 |
+
(x + 2/x)/2
|
1022 |
+
>>> gcd_terms(x/2 + 1/x, fraction=False, clear=False)
|
1023 |
+
x/2 + 1/x
|
1024 |
+
|
1025 |
+
>>> gcd_terms(x/2/y + 1/x/y)
|
1026 |
+
(x**2 + 2)/(2*x*y)
|
1027 |
+
>>> gcd_terms(x/2/y + 1/x/y, clear=False)
|
1028 |
+
(x**2/2 + 1)/(x*y)
|
1029 |
+
>>> gcd_terms(x/2/y + 1/x/y, clear=False, fraction=False)
|
1030 |
+
(x/2 + 1/x)/y
|
1031 |
+
|
1032 |
+
The ``clear`` flag was ignored in this case because the returned
|
1033 |
+
expression was a rational expression, not a simple sum.
|
1034 |
+
|
1035 |
+
See Also
|
1036 |
+
========
|
1037 |
+
|
1038 |
+
factor_terms, sympy.polys.polytools.terms_gcd
|
1039 |
+
|
1040 |
+
"""
|
1041 |
+
def mask(terms):
|
1042 |
+
"""replace nc portions of each term with a unique Dummy symbols
|
1043 |
+
and return the replacements to restore them"""
|
1044 |
+
args = [(a, []) if a.is_commutative else a.args_cnc() for a in terms]
|
1045 |
+
reps = []
|
1046 |
+
for i, (c, nc) in enumerate(args):
|
1047 |
+
if nc:
|
1048 |
+
nc = Mul(*nc)
|
1049 |
+
d = Dummy()
|
1050 |
+
reps.append((d, nc))
|
1051 |
+
c.append(d)
|
1052 |
+
args[i] = Mul(*c)
|
1053 |
+
else:
|
1054 |
+
args[i] = c
|
1055 |
+
return args, dict(reps)
|
1056 |
+
|
1057 |
+
isadd = isinstance(terms, Add)
|
1058 |
+
addlike = isadd or not isinstance(terms, Basic) and \
|
1059 |
+
is_sequence(terms, include=set) and \
|
1060 |
+
not isinstance(terms, Dict)
|
1061 |
+
|
1062 |
+
if addlike:
|
1063 |
+
if isadd: # i.e. an Add
|
1064 |
+
terms = list(terms.args)
|
1065 |
+
else:
|
1066 |
+
terms = sympify(terms)
|
1067 |
+
terms, reps = mask(terms)
|
1068 |
+
cont, numer, denom = _gcd_terms(terms, isprimitive, fraction)
|
1069 |
+
numer = numer.xreplace(reps)
|
1070 |
+
coeff, factors = cont.as_coeff_Mul()
|
1071 |
+
if not clear:
|
1072 |
+
c, _coeff = coeff.as_coeff_Mul()
|
1073 |
+
if not c.is_Integer and not clear and numer.is_Add:
|
1074 |
+
n, d = c.as_numer_denom()
|
1075 |
+
_numer = numer/d
|
1076 |
+
if any(a.as_coeff_Mul()[0].is_Integer
|
1077 |
+
for a in _numer.args):
|
1078 |
+
numer = _numer
|
1079 |
+
coeff = n*_coeff
|
1080 |
+
return _keep_coeff(coeff, factors*numer/denom, clear=clear)
|
1081 |
+
|
1082 |
+
if not isinstance(terms, Basic):
|
1083 |
+
return terms
|
1084 |
+
|
1085 |
+
if terms.is_Atom:
|
1086 |
+
return terms
|
1087 |
+
|
1088 |
+
if terms.is_Mul:
|
1089 |
+
c, args = terms.as_coeff_mul()
|
1090 |
+
return _keep_coeff(c, Mul(*[gcd_terms(i, isprimitive, clear, fraction)
|
1091 |
+
for i in args]), clear=clear)
|
1092 |
+
|
1093 |
+
def handle(a):
|
1094 |
+
# don't treat internal args like terms of an Add
|
1095 |
+
if not isinstance(a, Expr):
|
1096 |
+
if isinstance(a, Basic):
|
1097 |
+
if not a.args:
|
1098 |
+
return a
|
1099 |
+
return a.func(*[handle(i) for i in a.args])
|
1100 |
+
return type(a)([handle(i) for i in a])
|
1101 |
+
return gcd_terms(a, isprimitive, clear, fraction)
|
1102 |
+
|
1103 |
+
if isinstance(terms, Dict):
|
1104 |
+
return Dict(*[(k, handle(v)) for k, v in terms.args])
|
1105 |
+
return terms.func(*[handle(i) for i in terms.args])
|
1106 |
+
|
1107 |
+
|
1108 |
+
def _factor_sum_int(expr, **kwargs):
|
1109 |
+
"""Return Sum or Integral object with factors that are not
|
1110 |
+
in the wrt variables removed. In cases where there are additive
|
1111 |
+
terms in the function of the object that are independent, the
|
1112 |
+
object will be separated into two objects.
|
1113 |
+
|
1114 |
+
Examples
|
1115 |
+
========
|
1116 |
+
|
1117 |
+
>>> from sympy import Sum, factor_terms
|
1118 |
+
>>> from sympy.abc import x, y
|
1119 |
+
>>> factor_terms(Sum(x + y, (x, 1, 3)))
|
1120 |
+
y*Sum(1, (x, 1, 3)) + Sum(x, (x, 1, 3))
|
1121 |
+
>>> factor_terms(Sum(x*y, (x, 1, 3)))
|
1122 |
+
y*Sum(x, (x, 1, 3))
|
1123 |
+
|
1124 |
+
Notes
|
1125 |
+
=====
|
1126 |
+
|
1127 |
+
If a function in the summand or integrand is replaced
|
1128 |
+
with a symbol, then this simplification should not be
|
1129 |
+
done or else an incorrect result will be obtained when
|
1130 |
+
the symbol is replaced with an expression that depends
|
1131 |
+
on the variables of summation/integration:
|
1132 |
+
|
1133 |
+
>>> eq = Sum(y, (x, 1, 3))
|
1134 |
+
>>> factor_terms(eq).subs(y, x).doit()
|
1135 |
+
3*x
|
1136 |
+
>>> eq.subs(y, x).doit()
|
1137 |
+
6
|
1138 |
+
"""
|
1139 |
+
result = expr.function
|
1140 |
+
if result == 0:
|
1141 |
+
return S.Zero
|
1142 |
+
limits = expr.limits
|
1143 |
+
|
1144 |
+
# get the wrt variables
|
1145 |
+
wrt = {i.args[0] for i in limits}
|
1146 |
+
|
1147 |
+
# factor out any common terms that are independent of wrt
|
1148 |
+
f = factor_terms(result, **kwargs)
|
1149 |
+
i, d = f.as_independent(*wrt)
|
1150 |
+
if isinstance(f, Add):
|
1151 |
+
return i * expr.func(1, *limits) + expr.func(d, *limits)
|
1152 |
+
else:
|
1153 |
+
return i * expr.func(d, *limits)
|
1154 |
+
|
1155 |
+
|
1156 |
+
def factor_terms(expr, radical=False, clear=False, fraction=False, sign=True):
|
1157 |
+
"""Remove common factors from terms in all arguments without
|
1158 |
+
changing the underlying structure of the expr. No expansion or
|
1159 |
+
simplification (and no processing of non-commutatives) is performed.
|
1160 |
+
|
1161 |
+
Parameters
|
1162 |
+
==========
|
1163 |
+
|
1164 |
+
radical: bool, optional
|
1165 |
+
If radical=True then a radical common to all terms will be factored
|
1166 |
+
out of any Add sub-expressions of the expr.
|
1167 |
+
|
1168 |
+
clear : bool, optional
|
1169 |
+
If clear=False (default) then coefficients will not be separated
|
1170 |
+
from a single Add if they can be distributed to leave one or more
|
1171 |
+
terms with integer coefficients.
|
1172 |
+
|
1173 |
+
fraction : bool, optional
|
1174 |
+
If fraction=True (default is False) then a common denominator will be
|
1175 |
+
constructed for the expression.
|
1176 |
+
|
1177 |
+
sign : bool, optional
|
1178 |
+
If sign=True (default) then even if the only factor in common is a -1,
|
1179 |
+
it will be factored out of the expression.
|
1180 |
+
|
1181 |
+
Examples
|
1182 |
+
========
|
1183 |
+
|
1184 |
+
>>> from sympy import factor_terms, Symbol
|
1185 |
+
>>> from sympy.abc import x, y
|
1186 |
+
>>> factor_terms(x + x*(2 + 4*y)**3)
|
1187 |
+
x*(8*(2*y + 1)**3 + 1)
|
1188 |
+
>>> A = Symbol('A', commutative=False)
|
1189 |
+
>>> factor_terms(x*A + x*A + x*y*A)
|
1190 |
+
x*(y*A + 2*A)
|
1191 |
+
|
1192 |
+
When ``clear`` is False, a rational will only be factored out of an
|
1193 |
+
Add expression if all terms of the Add have coefficients that are
|
1194 |
+
fractions:
|
1195 |
+
|
1196 |
+
>>> factor_terms(x/2 + 1, clear=False)
|
1197 |
+
x/2 + 1
|
1198 |
+
>>> factor_terms(x/2 + 1, clear=True)
|
1199 |
+
(x + 2)/2
|
1200 |
+
|
1201 |
+
If a -1 is all that can be factored out, to *not* factor it out, the
|
1202 |
+
flag ``sign`` must be False:
|
1203 |
+
|
1204 |
+
>>> factor_terms(-x - y)
|
1205 |
+
-(x + y)
|
1206 |
+
>>> factor_terms(-x - y, sign=False)
|
1207 |
+
-x - y
|
1208 |
+
>>> factor_terms(-2*x - 2*y, sign=False)
|
1209 |
+
-2*(x + y)
|
1210 |
+
|
1211 |
+
See Also
|
1212 |
+
========
|
1213 |
+
|
1214 |
+
gcd_terms, sympy.polys.polytools.terms_gcd
|
1215 |
+
|
1216 |
+
"""
|
1217 |
+
def do(expr):
|
1218 |
+
from sympy.concrete.summations import Sum
|
1219 |
+
from sympy.integrals.integrals import Integral
|
1220 |
+
is_iterable = iterable(expr)
|
1221 |
+
|
1222 |
+
if not isinstance(expr, Basic) or expr.is_Atom:
|
1223 |
+
if is_iterable:
|
1224 |
+
return type(expr)([do(i) for i in expr])
|
1225 |
+
return expr
|
1226 |
+
|
1227 |
+
if expr.is_Pow or expr.is_Function or \
|
1228 |
+
is_iterable or not hasattr(expr, 'args_cnc'):
|
1229 |
+
args = expr.args
|
1230 |
+
newargs = tuple([do(i) for i in args])
|
1231 |
+
if newargs == args:
|
1232 |
+
return expr
|
1233 |
+
return expr.func(*newargs)
|
1234 |
+
|
1235 |
+
if isinstance(expr, (Sum, Integral)):
|
1236 |
+
return _factor_sum_int(expr,
|
1237 |
+
radical=radical, clear=clear,
|
1238 |
+
fraction=fraction, sign=sign)
|
1239 |
+
|
1240 |
+
cont, p = expr.as_content_primitive(radical=radical, clear=clear)
|
1241 |
+
if p.is_Add:
|
1242 |
+
list_args = [do(a) for a in Add.make_args(p)]
|
1243 |
+
# get a common negative (if there) which gcd_terms does not remove
|
1244 |
+
if not any(a.as_coeff_Mul()[0].extract_multiplicatively(-1) is None
|
1245 |
+
for a in list_args):
|
1246 |
+
cont = -cont
|
1247 |
+
list_args = [-a for a in list_args]
|
1248 |
+
# watch out for exp(-(x+2)) which gcd_terms will change to exp(-x-2)
|
1249 |
+
special = {}
|
1250 |
+
for i, a in enumerate(list_args):
|
1251 |
+
b, e = a.as_base_exp()
|
1252 |
+
if e.is_Mul and e != Mul(*e.args):
|
1253 |
+
list_args[i] = Dummy()
|
1254 |
+
special[list_args[i]] = a
|
1255 |
+
# rebuild p not worrying about the order which gcd_terms will fix
|
1256 |
+
p = Add._from_args(list_args)
|
1257 |
+
p = gcd_terms(p,
|
1258 |
+
isprimitive=True,
|
1259 |
+
clear=clear,
|
1260 |
+
fraction=fraction).xreplace(special)
|
1261 |
+
elif p.args:
|
1262 |
+
p = p.func(
|
1263 |
+
*[do(a) for a in p.args])
|
1264 |
+
rv = _keep_coeff(cont, p, clear=clear, sign=sign)
|
1265 |
+
return rv
|
1266 |
+
expr = sympify(expr)
|
1267 |
+
return do(expr)
|
1268 |
+
|
1269 |
+
|
1270 |
+
def _mask_nc(eq, name=None):
|
1271 |
+
"""
|
1272 |
+
Return ``eq`` with non-commutative objects replaced with Dummy
|
1273 |
+
symbols. A dictionary that can be used to restore the original
|
1274 |
+
values is returned: if it is None, the expression is noncommutative
|
1275 |
+
and cannot be made commutative. The third value returned is a list
|
1276 |
+
of any non-commutative symbols that appear in the returned equation.
|
1277 |
+
|
1278 |
+
Explanation
|
1279 |
+
===========
|
1280 |
+
|
1281 |
+
All non-commutative objects other than Symbols are replaced with
|
1282 |
+
a non-commutative Symbol. Identical objects will be identified
|
1283 |
+
by identical symbols.
|
1284 |
+
|
1285 |
+
If there is only 1 non-commutative object in an expression it will
|
1286 |
+
be replaced with a commutative symbol. Otherwise, the non-commutative
|
1287 |
+
entities are retained and the calling routine should handle
|
1288 |
+
replacements in this case since some care must be taken to keep
|
1289 |
+
track of the ordering of symbols when they occur within Muls.
|
1290 |
+
|
1291 |
+
Parameters
|
1292 |
+
==========
|
1293 |
+
|
1294 |
+
name : str
|
1295 |
+
``name``, if given, is the name that will be used with numbered Dummy
|
1296 |
+
variables that will replace the non-commutative objects and is mainly
|
1297 |
+
used for doctesting purposes.
|
1298 |
+
|
1299 |
+
Examples
|
1300 |
+
========
|
1301 |
+
|
1302 |
+
>>> from sympy.physics.secondquant import Commutator, NO, F, Fd
|
1303 |
+
>>> from sympy import symbols
|
1304 |
+
>>> from sympy.core.exprtools import _mask_nc
|
1305 |
+
>>> from sympy.abc import x, y
|
1306 |
+
>>> A, B, C = symbols('A,B,C', commutative=False)
|
1307 |
+
|
1308 |
+
One nc-symbol:
|
1309 |
+
|
1310 |
+
>>> _mask_nc(A**2 - x**2, 'd')
|
1311 |
+
(_d0**2 - x**2, {_d0: A}, [])
|
1312 |
+
|
1313 |
+
Multiple nc-symbols:
|
1314 |
+
|
1315 |
+
>>> _mask_nc(A**2 - B**2, 'd')
|
1316 |
+
(A**2 - B**2, {}, [A, B])
|
1317 |
+
|
1318 |
+
An nc-object with nc-symbols but no others outside of it:
|
1319 |
+
|
1320 |
+
>>> _mask_nc(1 + x*Commutator(A, B), 'd')
|
1321 |
+
(_d0*x + 1, {_d0: Commutator(A, B)}, [])
|
1322 |
+
>>> _mask_nc(NO(Fd(x)*F(y)), 'd')
|
1323 |
+
(_d0, {_d0: NO(CreateFermion(x)*AnnihilateFermion(y))}, [])
|
1324 |
+
|
1325 |
+
Multiple nc-objects:
|
1326 |
+
|
1327 |
+
>>> eq = x*Commutator(A, B) + x*Commutator(A, C)*Commutator(A, B)
|
1328 |
+
>>> _mask_nc(eq, 'd')
|
1329 |
+
(x*_d0 + x*_d1*_d0, {_d0: Commutator(A, B), _d1: Commutator(A, C)}, [_d0, _d1])
|
1330 |
+
|
1331 |
+
Multiple nc-objects and nc-symbols:
|
1332 |
+
|
1333 |
+
>>> eq = A*Commutator(A, B) + B*Commutator(A, C)
|
1334 |
+
>>> _mask_nc(eq, 'd')
|
1335 |
+
(A*_d0 + B*_d1, {_d0: Commutator(A, B), _d1: Commutator(A, C)}, [_d0, _d1, A, B])
|
1336 |
+
|
1337 |
+
"""
|
1338 |
+
name = name or 'mask'
|
1339 |
+
# Make Dummy() append sequential numbers to the name
|
1340 |
+
|
1341 |
+
def numbered_names():
|
1342 |
+
i = 0
|
1343 |
+
while True:
|
1344 |
+
yield name + str(i)
|
1345 |
+
i += 1
|
1346 |
+
|
1347 |
+
names = numbered_names()
|
1348 |
+
|
1349 |
+
def Dummy(*args, **kwargs):
|
1350 |
+
from .symbol import Dummy
|
1351 |
+
return Dummy(next(names), *args, **kwargs)
|
1352 |
+
|
1353 |
+
expr = eq
|
1354 |
+
if expr.is_commutative:
|
1355 |
+
return eq, {}, []
|
1356 |
+
|
1357 |
+
# identify nc-objects; symbols and other
|
1358 |
+
rep = []
|
1359 |
+
nc_obj = set()
|
1360 |
+
nc_syms = set()
|
1361 |
+
pot = preorder_traversal(expr, keys=default_sort_key)
|
1362 |
+
for i, a in enumerate(pot):
|
1363 |
+
if any(a == r[0] for r in rep):
|
1364 |
+
pot.skip()
|
1365 |
+
elif not a.is_commutative:
|
1366 |
+
if a.is_symbol:
|
1367 |
+
nc_syms.add(a)
|
1368 |
+
pot.skip()
|
1369 |
+
elif not (a.is_Add or a.is_Mul or a.is_Pow):
|
1370 |
+
nc_obj.add(a)
|
1371 |
+
pot.skip()
|
1372 |
+
|
1373 |
+
# If there is only one nc symbol or object, it can be factored regularly
|
1374 |
+
# but polys is going to complain, so replace it with a Dummy.
|
1375 |
+
if len(nc_obj) == 1 and not nc_syms:
|
1376 |
+
rep.append((nc_obj.pop(), Dummy()))
|
1377 |
+
elif len(nc_syms) == 1 and not nc_obj:
|
1378 |
+
rep.append((nc_syms.pop(), Dummy()))
|
1379 |
+
|
1380 |
+
# Any remaining nc-objects will be replaced with an nc-Dummy and
|
1381 |
+
# identified as an nc-Symbol to watch out for
|
1382 |
+
nc_obj = sorted(nc_obj, key=default_sort_key)
|
1383 |
+
for n in nc_obj:
|
1384 |
+
nc = Dummy(commutative=False)
|
1385 |
+
rep.append((n, nc))
|
1386 |
+
nc_syms.add(nc)
|
1387 |
+
expr = expr.subs(rep)
|
1388 |
+
|
1389 |
+
nc_syms = list(nc_syms)
|
1390 |
+
nc_syms.sort(key=default_sort_key)
|
1391 |
+
return expr, {v: k for k, v in rep}, nc_syms
|
1392 |
+
|
1393 |
+
|
1394 |
+
def factor_nc(expr):
|
1395 |
+
"""Return the factored form of ``expr`` while handling non-commutative
|
1396 |
+
expressions.
|
1397 |
+
|
1398 |
+
Examples
|
1399 |
+
========
|
1400 |
+
|
1401 |
+
>>> from sympy import factor_nc, Symbol
|
1402 |
+
>>> from sympy.abc import x
|
1403 |
+
>>> A = Symbol('A', commutative=False)
|
1404 |
+
>>> B = Symbol('B', commutative=False)
|
1405 |
+
>>> factor_nc((x**2 + 2*A*x + A**2).expand())
|
1406 |
+
(x + A)**2
|
1407 |
+
>>> factor_nc(((x + A)*(x + B)).expand())
|
1408 |
+
(x + A)*(x + B)
|
1409 |
+
"""
|
1410 |
+
expr = sympify(expr)
|
1411 |
+
if not isinstance(expr, Expr) or not expr.args:
|
1412 |
+
return expr
|
1413 |
+
if not expr.is_Add:
|
1414 |
+
return expr.func(*[factor_nc(a) for a in expr.args])
|
1415 |
+
expr = expr.func(*[expand_power_exp(i) for i in expr.args])
|
1416 |
+
|
1417 |
+
from sympy.polys.polytools import gcd, factor
|
1418 |
+
expr, rep, nc_symbols = _mask_nc(expr)
|
1419 |
+
|
1420 |
+
if rep:
|
1421 |
+
return factor(expr).subs(rep)
|
1422 |
+
else:
|
1423 |
+
args = [a.args_cnc() for a in Add.make_args(expr)]
|
1424 |
+
c = g = l = r = S.One
|
1425 |
+
hit = False
|
1426 |
+
# find any commutative gcd term
|
1427 |
+
for i, a in enumerate(args):
|
1428 |
+
if i == 0:
|
1429 |
+
c = Mul._from_args(a[0])
|
1430 |
+
elif a[0]:
|
1431 |
+
c = gcd(c, Mul._from_args(a[0]))
|
1432 |
+
else:
|
1433 |
+
c = S.One
|
1434 |
+
if c is not S.One:
|
1435 |
+
hit = True
|
1436 |
+
c, g = c.as_coeff_Mul()
|
1437 |
+
if g is not S.One:
|
1438 |
+
for i, (cc, _) in enumerate(args):
|
1439 |
+
cc = list(Mul.make_args(Mul._from_args(list(cc))/g))
|
1440 |
+
args[i][0] = cc
|
1441 |
+
for i, (cc, _) in enumerate(args):
|
1442 |
+
if cc:
|
1443 |
+
cc[0] = cc[0]/c
|
1444 |
+
else:
|
1445 |
+
cc = [1/c]
|
1446 |
+
args[i][0] = cc
|
1447 |
+
# find any noncommutative common prefix
|
1448 |
+
for i, a in enumerate(args):
|
1449 |
+
if i == 0:
|
1450 |
+
n = a[1][:]
|
1451 |
+
else:
|
1452 |
+
n = common_prefix(n, a[1])
|
1453 |
+
if not n:
|
1454 |
+
# is there a power that can be extracted?
|
1455 |
+
if not args[0][1]:
|
1456 |
+
break
|
1457 |
+
b, e = args[0][1][0].as_base_exp()
|
1458 |
+
ok = False
|
1459 |
+
if e.is_Integer:
|
1460 |
+
for t in args:
|
1461 |
+
if not t[1]:
|
1462 |
+
break
|
1463 |
+
bt, et = t[1][0].as_base_exp()
|
1464 |
+
if et.is_Integer and bt == b:
|
1465 |
+
e = min(e, et)
|
1466 |
+
else:
|
1467 |
+
break
|
1468 |
+
else:
|
1469 |
+
ok = hit = True
|
1470 |
+
l = b**e
|
1471 |
+
il = b**-e
|
1472 |
+
for _ in args:
|
1473 |
+
_[1][0] = il*_[1][0]
|
1474 |
+
break
|
1475 |
+
if not ok:
|
1476 |
+
break
|
1477 |
+
else:
|
1478 |
+
hit = True
|
1479 |
+
lenn = len(n)
|
1480 |
+
l = Mul(*n)
|
1481 |
+
for _ in args:
|
1482 |
+
_[1] = _[1][lenn:]
|
1483 |
+
# find any noncommutative common suffix
|
1484 |
+
for i, a in enumerate(args):
|
1485 |
+
if i == 0:
|
1486 |
+
n = a[1][:]
|
1487 |
+
else:
|
1488 |
+
n = common_suffix(n, a[1])
|
1489 |
+
if not n:
|
1490 |
+
# is there a power that can be extracted?
|
1491 |
+
if not args[0][1]:
|
1492 |
+
break
|
1493 |
+
b, e = args[0][1][-1].as_base_exp()
|
1494 |
+
ok = False
|
1495 |
+
if e.is_Integer:
|
1496 |
+
for t in args:
|
1497 |
+
if not t[1]:
|
1498 |
+
break
|
1499 |
+
bt, et = t[1][-1].as_base_exp()
|
1500 |
+
if et.is_Integer and bt == b:
|
1501 |
+
e = min(e, et)
|
1502 |
+
else:
|
1503 |
+
break
|
1504 |
+
else:
|
1505 |
+
ok = hit = True
|
1506 |
+
r = b**e
|
1507 |
+
il = b**-e
|
1508 |
+
for _ in args:
|
1509 |
+
_[1][-1] = _[1][-1]*il
|
1510 |
+
break
|
1511 |
+
if not ok:
|
1512 |
+
break
|
1513 |
+
else:
|
1514 |
+
hit = True
|
1515 |
+
lenn = len(n)
|
1516 |
+
r = Mul(*n)
|
1517 |
+
for _ in args:
|
1518 |
+
_[1] = _[1][:len(_[1]) - lenn]
|
1519 |
+
if hit:
|
1520 |
+
mid = Add(*[Mul(*cc)*Mul(*nc) for cc, nc in args])
|
1521 |
+
else:
|
1522 |
+
mid = expr
|
1523 |
+
|
1524 |
+
from sympy.simplify.powsimp import powsimp
|
1525 |
+
|
1526 |
+
# sort the symbols so the Dummys would appear in the same
|
1527 |
+
# order as the original symbols, otherwise you may introduce
|
1528 |
+
# a factor of -1, e.g. A**2 - B**2) -- {A:y, B:x} --> y**2 - x**2
|
1529 |
+
# and the former factors into two terms, (A - B)*(A + B) while the
|
1530 |
+
# latter factors into 3 terms, (-1)*(x - y)*(x + y)
|
1531 |
+
rep1 = [(n, Dummy()) for n in sorted(nc_symbols, key=default_sort_key)]
|
1532 |
+
unrep1 = [(v, k) for k, v in rep1]
|
1533 |
+
unrep1.reverse()
|
1534 |
+
new_mid, r2, _ = _mask_nc(mid.subs(rep1))
|
1535 |
+
new_mid = powsimp(factor(new_mid))
|
1536 |
+
|
1537 |
+
new_mid = new_mid.subs(r2).subs(unrep1)
|
1538 |
+
|
1539 |
+
if new_mid.is_Pow:
|
1540 |
+
return _keep_coeff(c, g*l*new_mid*r)
|
1541 |
+
|
1542 |
+
if new_mid.is_Mul:
|
1543 |
+
def _pemexpand(expr):
|
1544 |
+
"Expand with the minimal set of hints necessary to check the result."
|
1545 |
+
return expr.expand(deep=True, mul=True, power_exp=True,
|
1546 |
+
power_base=False, basic=False, multinomial=True, log=False)
|
1547 |
+
# XXX TODO there should be a way to inspect what order the terms
|
1548 |
+
# must be in and just select the plausible ordering without
|
1549 |
+
# checking permutations
|
1550 |
+
cfac = []
|
1551 |
+
ncfac = []
|
1552 |
+
for f in new_mid.args:
|
1553 |
+
if f.is_commutative:
|
1554 |
+
cfac.append(f)
|
1555 |
+
else:
|
1556 |
+
b, e = f.as_base_exp()
|
1557 |
+
if e.is_Integer:
|
1558 |
+
ncfac.extend([b]*e)
|
1559 |
+
else:
|
1560 |
+
ncfac.append(f)
|
1561 |
+
pre_mid = g*Mul(*cfac)*l
|
1562 |
+
target = _pemexpand(expr/c)
|
1563 |
+
for s in variations(ncfac, len(ncfac)):
|
1564 |
+
ok = pre_mid*Mul(*s)*r
|
1565 |
+
if _pemexpand(ok) == target:
|
1566 |
+
return _keep_coeff(c, ok)
|
1567 |
+
|
1568 |
+
# mid was an Add that didn't factor successfully
|
1569 |
+
return _keep_coeff(c, g*l*mid*r)
|
llmeval-env/lib/python3.10/site-packages/sympy/core/facts.py
ADDED
@@ -0,0 +1,634 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
r"""This is rule-based deduction system for SymPy
|
2 |
+
|
3 |
+
The whole thing is split into two parts
|
4 |
+
|
5 |
+
- rules compilation and preparation of tables
|
6 |
+
- runtime inference
|
7 |
+
|
8 |
+
For rule-based inference engines, the classical work is RETE algorithm [1],
|
9 |
+
[2] Although we are not implementing it in full (or even significantly)
|
10 |
+
it's still worth a read to understand the underlying ideas.
|
11 |
+
|
12 |
+
In short, every rule in a system of rules is one of two forms:
|
13 |
+
|
14 |
+
- atom -> ... (alpha rule)
|
15 |
+
- And(atom1, atom2, ...) -> ... (beta rule)
|
16 |
+
|
17 |
+
|
18 |
+
The major complexity is in efficient beta-rules processing and usually for an
|
19 |
+
expert system a lot of effort goes into code that operates on beta-rules.
|
20 |
+
|
21 |
+
|
22 |
+
Here we take minimalistic approach to get something usable first.
|
23 |
+
|
24 |
+
- (preparation) of alpha- and beta- networks, everything except
|
25 |
+
- (runtime) FactRules.deduce_all_facts
|
26 |
+
|
27 |
+
_____________________________________
|
28 |
+
( Kirr: I've never thought that doing )
|
29 |
+
( logic stuff is that difficult... )
|
30 |
+
-------------------------------------
|
31 |
+
o ^__^
|
32 |
+
o (oo)\_______
|
33 |
+
(__)\ )\/\
|
34 |
+
||----w |
|
35 |
+
|| ||
|
36 |
+
|
37 |
+
|
38 |
+
Some references on the topic
|
39 |
+
----------------------------
|
40 |
+
|
41 |
+
[1] https://en.wikipedia.org/wiki/Rete_algorithm
|
42 |
+
[2] http://reports-archive.adm.cs.cmu.edu/anon/1995/CMU-CS-95-113.pdf
|
43 |
+
|
44 |
+
https://en.wikipedia.org/wiki/Propositional_formula
|
45 |
+
https://en.wikipedia.org/wiki/Inference_rule
|
46 |
+
https://en.wikipedia.org/wiki/List_of_rules_of_inference
|
47 |
+
"""
|
48 |
+
|
49 |
+
from collections import defaultdict
|
50 |
+
from typing import Iterator
|
51 |
+
|
52 |
+
from .logic import Logic, And, Or, Not
|
53 |
+
|
54 |
+
|
55 |
+
def _base_fact(atom):
|
56 |
+
"""Return the literal fact of an atom.
|
57 |
+
|
58 |
+
Effectively, this merely strips the Not around a fact.
|
59 |
+
"""
|
60 |
+
if isinstance(atom, Not):
|
61 |
+
return atom.arg
|
62 |
+
else:
|
63 |
+
return atom
|
64 |
+
|
65 |
+
|
66 |
+
def _as_pair(atom):
|
67 |
+
if isinstance(atom, Not):
|
68 |
+
return (atom.arg, False)
|
69 |
+
else:
|
70 |
+
return (atom, True)
|
71 |
+
|
72 |
+
# XXX this prepares forward-chaining rules for alpha-network
|
73 |
+
|
74 |
+
|
75 |
+
def transitive_closure(implications):
|
76 |
+
"""
|
77 |
+
Computes the transitive closure of a list of implications
|
78 |
+
|
79 |
+
Uses Warshall's algorithm, as described at
|
80 |
+
http://www.cs.hope.edu/~cusack/Notes/Notes/DiscreteMath/Warshall.pdf.
|
81 |
+
"""
|
82 |
+
full_implications = set(implications)
|
83 |
+
literals = set().union(*map(set, full_implications))
|
84 |
+
|
85 |
+
for k in literals:
|
86 |
+
for i in literals:
|
87 |
+
if (i, k) in full_implications:
|
88 |
+
for j in literals:
|
89 |
+
if (k, j) in full_implications:
|
90 |
+
full_implications.add((i, j))
|
91 |
+
|
92 |
+
return full_implications
|
93 |
+
|
94 |
+
|
95 |
+
def deduce_alpha_implications(implications):
|
96 |
+
"""deduce all implications
|
97 |
+
|
98 |
+
Description by example
|
99 |
+
----------------------
|
100 |
+
|
101 |
+
given set of logic rules:
|
102 |
+
|
103 |
+
a -> b
|
104 |
+
b -> c
|
105 |
+
|
106 |
+
we deduce all possible rules:
|
107 |
+
|
108 |
+
a -> b, c
|
109 |
+
b -> c
|
110 |
+
|
111 |
+
|
112 |
+
implications: [] of (a,b)
|
113 |
+
return: {} of a -> set([b, c, ...])
|
114 |
+
"""
|
115 |
+
implications = implications + [(Not(j), Not(i)) for (i, j) in implications]
|
116 |
+
res = defaultdict(set)
|
117 |
+
full_implications = transitive_closure(implications)
|
118 |
+
for a, b in full_implications:
|
119 |
+
if a == b:
|
120 |
+
continue # skip a->a cyclic input
|
121 |
+
|
122 |
+
res[a].add(b)
|
123 |
+
|
124 |
+
# Clean up tautologies and check consistency
|
125 |
+
for a, impl in res.items():
|
126 |
+
impl.discard(a)
|
127 |
+
na = Not(a)
|
128 |
+
if na in impl:
|
129 |
+
raise ValueError(
|
130 |
+
'implications are inconsistent: %s -> %s %s' % (a, na, impl))
|
131 |
+
|
132 |
+
return res
|
133 |
+
|
134 |
+
|
135 |
+
def apply_beta_to_alpha_route(alpha_implications, beta_rules):
|
136 |
+
"""apply additional beta-rules (And conditions) to already-built
|
137 |
+
alpha implication tables
|
138 |
+
|
139 |
+
TODO: write about
|
140 |
+
|
141 |
+
- static extension of alpha-chains
|
142 |
+
- attaching refs to beta-nodes to alpha chains
|
143 |
+
|
144 |
+
|
145 |
+
e.g.
|
146 |
+
|
147 |
+
alpha_implications:
|
148 |
+
|
149 |
+
a -> [b, !c, d]
|
150 |
+
b -> [d]
|
151 |
+
...
|
152 |
+
|
153 |
+
|
154 |
+
beta_rules:
|
155 |
+
|
156 |
+
&(b,d) -> e
|
157 |
+
|
158 |
+
|
159 |
+
then we'll extend a's rule to the following
|
160 |
+
|
161 |
+
a -> [b, !c, d, e]
|
162 |
+
"""
|
163 |
+
x_impl = {}
|
164 |
+
for x in alpha_implications.keys():
|
165 |
+
x_impl[x] = (set(alpha_implications[x]), [])
|
166 |
+
for bcond, bimpl in beta_rules:
|
167 |
+
for bk in bcond.args:
|
168 |
+
if bk in x_impl:
|
169 |
+
continue
|
170 |
+
x_impl[bk] = (set(), [])
|
171 |
+
|
172 |
+
# static extensions to alpha rules:
|
173 |
+
# A: x -> a,b B: &(a,b) -> c ==> A: x -> a,b,c
|
174 |
+
seen_static_extension = True
|
175 |
+
while seen_static_extension:
|
176 |
+
seen_static_extension = False
|
177 |
+
|
178 |
+
for bcond, bimpl in beta_rules:
|
179 |
+
if not isinstance(bcond, And):
|
180 |
+
raise TypeError("Cond is not And")
|
181 |
+
bargs = set(bcond.args)
|
182 |
+
for x, (ximpls, bb) in x_impl.items():
|
183 |
+
x_all = ximpls | {x}
|
184 |
+
# A: ... -> a B: &(...) -> a is non-informative
|
185 |
+
if bimpl not in x_all and bargs.issubset(x_all):
|
186 |
+
ximpls.add(bimpl)
|
187 |
+
|
188 |
+
# we introduced new implication - now we have to restore
|
189 |
+
# completeness of the whole set.
|
190 |
+
bimpl_impl = x_impl.get(bimpl)
|
191 |
+
if bimpl_impl is not None:
|
192 |
+
ximpls |= bimpl_impl[0]
|
193 |
+
seen_static_extension = True
|
194 |
+
|
195 |
+
# attach beta-nodes which can be possibly triggered by an alpha-chain
|
196 |
+
for bidx, (bcond, bimpl) in enumerate(beta_rules):
|
197 |
+
bargs = set(bcond.args)
|
198 |
+
for x, (ximpls, bb) in x_impl.items():
|
199 |
+
x_all = ximpls | {x}
|
200 |
+
# A: ... -> a B: &(...) -> a (non-informative)
|
201 |
+
if bimpl in x_all:
|
202 |
+
continue
|
203 |
+
# A: x -> a... B: &(!a,...) -> ... (will never trigger)
|
204 |
+
# A: x -> a... B: &(...) -> !a (will never trigger)
|
205 |
+
if any(Not(xi) in bargs or Not(xi) == bimpl for xi in x_all):
|
206 |
+
continue
|
207 |
+
|
208 |
+
if bargs & x_all:
|
209 |
+
bb.append(bidx)
|
210 |
+
|
211 |
+
return x_impl
|
212 |
+
|
213 |
+
|
214 |
+
def rules_2prereq(rules):
|
215 |
+
"""build prerequisites table from rules
|
216 |
+
|
217 |
+
Description by example
|
218 |
+
----------------------
|
219 |
+
|
220 |
+
given set of logic rules:
|
221 |
+
|
222 |
+
a -> b, c
|
223 |
+
b -> c
|
224 |
+
|
225 |
+
we build prerequisites (from what points something can be deduced):
|
226 |
+
|
227 |
+
b <- a
|
228 |
+
c <- a, b
|
229 |
+
|
230 |
+
rules: {} of a -> [b, c, ...]
|
231 |
+
return: {} of c <- [a, b, ...]
|
232 |
+
|
233 |
+
Note however, that this prerequisites may be *not* enough to prove a
|
234 |
+
fact. An example is 'a -> b' rule, where prereq(a) is b, and prereq(b)
|
235 |
+
is a. That's because a=T -> b=T, and b=F -> a=F, but a=F -> b=?
|
236 |
+
"""
|
237 |
+
prereq = defaultdict(set)
|
238 |
+
for (a, _), impl in rules.items():
|
239 |
+
if isinstance(a, Not):
|
240 |
+
a = a.args[0]
|
241 |
+
for (i, _) in impl:
|
242 |
+
if isinstance(i, Not):
|
243 |
+
i = i.args[0]
|
244 |
+
prereq[i].add(a)
|
245 |
+
return prereq
|
246 |
+
|
247 |
+
################
|
248 |
+
# RULES PROVER #
|
249 |
+
################
|
250 |
+
|
251 |
+
|
252 |
+
class TautologyDetected(Exception):
|
253 |
+
"""(internal) Prover uses it for reporting detected tautology"""
|
254 |
+
pass
|
255 |
+
|
256 |
+
|
257 |
+
class Prover:
|
258 |
+
"""ai - prover of logic rules
|
259 |
+
|
260 |
+
given a set of initial rules, Prover tries to prove all possible rules
|
261 |
+
which follow from given premises.
|
262 |
+
|
263 |
+
As a result proved_rules are always either in one of two forms: alpha or
|
264 |
+
beta:
|
265 |
+
|
266 |
+
Alpha rules
|
267 |
+
-----------
|
268 |
+
|
269 |
+
This are rules of the form::
|
270 |
+
|
271 |
+
a -> b & c & d & ...
|
272 |
+
|
273 |
+
|
274 |
+
Beta rules
|
275 |
+
----------
|
276 |
+
|
277 |
+
This are rules of the form::
|
278 |
+
|
279 |
+
&(a,b,...) -> c & d & ...
|
280 |
+
|
281 |
+
|
282 |
+
i.e. beta rules are join conditions that say that something follows when
|
283 |
+
*several* facts are true at the same time.
|
284 |
+
"""
|
285 |
+
|
286 |
+
def __init__(self):
|
287 |
+
self.proved_rules = []
|
288 |
+
self._rules_seen = set()
|
289 |
+
|
290 |
+
def split_alpha_beta(self):
|
291 |
+
"""split proved rules into alpha and beta chains"""
|
292 |
+
rules_alpha = [] # a -> b
|
293 |
+
rules_beta = [] # &(...) -> b
|
294 |
+
for a, b in self.proved_rules:
|
295 |
+
if isinstance(a, And):
|
296 |
+
rules_beta.append((a, b))
|
297 |
+
else:
|
298 |
+
rules_alpha.append((a, b))
|
299 |
+
return rules_alpha, rules_beta
|
300 |
+
|
301 |
+
@property
|
302 |
+
def rules_alpha(self):
|
303 |
+
return self.split_alpha_beta()[0]
|
304 |
+
|
305 |
+
@property
|
306 |
+
def rules_beta(self):
|
307 |
+
return self.split_alpha_beta()[1]
|
308 |
+
|
309 |
+
def process_rule(self, a, b):
|
310 |
+
"""process a -> b rule""" # TODO write more?
|
311 |
+
if (not a) or isinstance(b, bool):
|
312 |
+
return
|
313 |
+
if isinstance(a, bool):
|
314 |
+
return
|
315 |
+
if (a, b) in self._rules_seen:
|
316 |
+
return
|
317 |
+
else:
|
318 |
+
self._rules_seen.add((a, b))
|
319 |
+
|
320 |
+
# this is the core of processing
|
321 |
+
try:
|
322 |
+
self._process_rule(a, b)
|
323 |
+
except TautologyDetected:
|
324 |
+
pass
|
325 |
+
|
326 |
+
def _process_rule(self, a, b):
|
327 |
+
# right part first
|
328 |
+
|
329 |
+
# a -> b & c --> a -> b ; a -> c
|
330 |
+
# (?) FIXME this is only correct when b & c != null !
|
331 |
+
|
332 |
+
if isinstance(b, And):
|
333 |
+
sorted_bargs = sorted(b.args, key=str)
|
334 |
+
for barg in sorted_bargs:
|
335 |
+
self.process_rule(a, barg)
|
336 |
+
|
337 |
+
# a -> b | c --> !b & !c -> !a
|
338 |
+
# --> a & !b -> c
|
339 |
+
# --> a & !c -> b
|
340 |
+
elif isinstance(b, Or):
|
341 |
+
sorted_bargs = sorted(b.args, key=str)
|
342 |
+
# detect tautology first
|
343 |
+
if not isinstance(a, Logic): # Atom
|
344 |
+
# tautology: a -> a|c|...
|
345 |
+
if a in sorted_bargs:
|
346 |
+
raise TautologyDetected(a, b, 'a -> a|c|...')
|
347 |
+
self.process_rule(And(*[Not(barg) for barg in b.args]), Not(a))
|
348 |
+
|
349 |
+
for bidx in range(len(sorted_bargs)):
|
350 |
+
barg = sorted_bargs[bidx]
|
351 |
+
brest = sorted_bargs[:bidx] + sorted_bargs[bidx + 1:]
|
352 |
+
self.process_rule(And(a, Not(barg)), Or(*brest))
|
353 |
+
|
354 |
+
# left part
|
355 |
+
|
356 |
+
# a & b -> c --> IRREDUCIBLE CASE -- WE STORE IT AS IS
|
357 |
+
# (this will be the basis of beta-network)
|
358 |
+
elif isinstance(a, And):
|
359 |
+
sorted_aargs = sorted(a.args, key=str)
|
360 |
+
if b in sorted_aargs:
|
361 |
+
raise TautologyDetected(a, b, 'a & b -> a')
|
362 |
+
self.proved_rules.append((a, b))
|
363 |
+
# XXX NOTE at present we ignore !c -> !a | !b
|
364 |
+
|
365 |
+
elif isinstance(a, Or):
|
366 |
+
sorted_aargs = sorted(a.args, key=str)
|
367 |
+
if b in sorted_aargs:
|
368 |
+
raise TautologyDetected(a, b, 'a | b -> a')
|
369 |
+
for aarg in sorted_aargs:
|
370 |
+
self.process_rule(aarg, b)
|
371 |
+
|
372 |
+
else:
|
373 |
+
# both `a` and `b` are atoms
|
374 |
+
self.proved_rules.append((a, b)) # a -> b
|
375 |
+
self.proved_rules.append((Not(b), Not(a))) # !b -> !a
|
376 |
+
|
377 |
+
########################################
|
378 |
+
|
379 |
+
|
380 |
+
class FactRules:
|
381 |
+
"""Rules that describe how to deduce facts in logic space
|
382 |
+
|
383 |
+
When defined, these rules allow implications to quickly be determined
|
384 |
+
for a set of facts. For this precomputed deduction tables are used.
|
385 |
+
see `deduce_all_facts` (forward-chaining)
|
386 |
+
|
387 |
+
Also it is possible to gather prerequisites for a fact, which is tried
|
388 |
+
to be proven. (backward-chaining)
|
389 |
+
|
390 |
+
|
391 |
+
Definition Syntax
|
392 |
+
-----------------
|
393 |
+
|
394 |
+
a -> b -- a=T -> b=T (and automatically b=F -> a=F)
|
395 |
+
a -> !b -- a=T -> b=F
|
396 |
+
a == b -- a -> b & b -> a
|
397 |
+
a -> b & c -- a=T -> b=T & c=T
|
398 |
+
# TODO b | c
|
399 |
+
|
400 |
+
|
401 |
+
Internals
|
402 |
+
---------
|
403 |
+
|
404 |
+
.full_implications[k, v]: all the implications of fact k=v
|
405 |
+
.beta_triggers[k, v]: beta rules that might be triggered when k=v
|
406 |
+
.prereq -- {} k <- [] of k's prerequisites
|
407 |
+
|
408 |
+
.defined_facts -- set of defined fact names
|
409 |
+
"""
|
410 |
+
|
411 |
+
def __init__(self, rules):
|
412 |
+
"""Compile rules into internal lookup tables"""
|
413 |
+
|
414 |
+
if isinstance(rules, str):
|
415 |
+
rules = rules.splitlines()
|
416 |
+
|
417 |
+
# --- parse and process rules ---
|
418 |
+
P = Prover()
|
419 |
+
|
420 |
+
for rule in rules:
|
421 |
+
# XXX `a` is hardcoded to be always atom
|
422 |
+
a, op, b = rule.split(None, 2)
|
423 |
+
|
424 |
+
a = Logic.fromstring(a)
|
425 |
+
b = Logic.fromstring(b)
|
426 |
+
|
427 |
+
if op == '->':
|
428 |
+
P.process_rule(a, b)
|
429 |
+
elif op == '==':
|
430 |
+
P.process_rule(a, b)
|
431 |
+
P.process_rule(b, a)
|
432 |
+
else:
|
433 |
+
raise ValueError('unknown op %r' % op)
|
434 |
+
|
435 |
+
# --- build deduction networks ---
|
436 |
+
self.beta_rules = []
|
437 |
+
for bcond, bimpl in P.rules_beta:
|
438 |
+
self.beta_rules.append(
|
439 |
+
({_as_pair(a) for a in bcond.args}, _as_pair(bimpl)))
|
440 |
+
|
441 |
+
# deduce alpha implications
|
442 |
+
impl_a = deduce_alpha_implications(P.rules_alpha)
|
443 |
+
|
444 |
+
# now:
|
445 |
+
# - apply beta rules to alpha chains (static extension), and
|
446 |
+
# - further associate beta rules to alpha chain (for inference
|
447 |
+
# at runtime)
|
448 |
+
impl_ab = apply_beta_to_alpha_route(impl_a, P.rules_beta)
|
449 |
+
|
450 |
+
# extract defined fact names
|
451 |
+
self.defined_facts = {_base_fact(k) for k in impl_ab.keys()}
|
452 |
+
|
453 |
+
# build rels (forward chains)
|
454 |
+
full_implications = defaultdict(set)
|
455 |
+
beta_triggers = defaultdict(set)
|
456 |
+
for k, (impl, betaidxs) in impl_ab.items():
|
457 |
+
full_implications[_as_pair(k)] = {_as_pair(i) for i in impl}
|
458 |
+
beta_triggers[_as_pair(k)] = betaidxs
|
459 |
+
|
460 |
+
self.full_implications = full_implications
|
461 |
+
self.beta_triggers = beta_triggers
|
462 |
+
|
463 |
+
# build prereq (backward chains)
|
464 |
+
prereq = defaultdict(set)
|
465 |
+
rel_prereq = rules_2prereq(full_implications)
|
466 |
+
for k, pitems in rel_prereq.items():
|
467 |
+
prereq[k] |= pitems
|
468 |
+
self.prereq = prereq
|
469 |
+
|
470 |
+
def _to_python(self) -> str:
|
471 |
+
""" Generate a string with plain python representation of the instance """
|
472 |
+
return '\n'.join(self.print_rules())
|
473 |
+
|
474 |
+
@classmethod
|
475 |
+
def _from_python(cls, data : dict):
|
476 |
+
""" Generate an instance from the plain python representation """
|
477 |
+
self = cls('')
|
478 |
+
for key in ['full_implications', 'beta_triggers', 'prereq']:
|
479 |
+
d=defaultdict(set)
|
480 |
+
d.update(data[key])
|
481 |
+
setattr(self, key, d)
|
482 |
+
self.beta_rules = data['beta_rules']
|
483 |
+
self.defined_facts = set(data['defined_facts'])
|
484 |
+
|
485 |
+
return self
|
486 |
+
|
487 |
+
def _defined_facts_lines(self):
|
488 |
+
yield 'defined_facts = ['
|
489 |
+
for fact in sorted(self.defined_facts):
|
490 |
+
yield f' {fact!r},'
|
491 |
+
yield '] # defined_facts'
|
492 |
+
|
493 |
+
def _full_implications_lines(self):
|
494 |
+
yield 'full_implications = dict( ['
|
495 |
+
for fact in sorted(self.defined_facts):
|
496 |
+
for value in (True, False):
|
497 |
+
yield f' # Implications of {fact} = {value}:'
|
498 |
+
yield f' (({fact!r}, {value!r}), set( ('
|
499 |
+
implications = self.full_implications[(fact, value)]
|
500 |
+
for implied in sorted(implications):
|
501 |
+
yield f' {implied!r},'
|
502 |
+
yield ' ) ),'
|
503 |
+
yield ' ),'
|
504 |
+
yield ' ] ) # full_implications'
|
505 |
+
|
506 |
+
def _prereq_lines(self):
|
507 |
+
yield 'prereq = {'
|
508 |
+
yield ''
|
509 |
+
for fact in sorted(self.prereq):
|
510 |
+
yield f' # facts that could determine the value of {fact}'
|
511 |
+
yield f' {fact!r}: {{'
|
512 |
+
for pfact in sorted(self.prereq[fact]):
|
513 |
+
yield f' {pfact!r},'
|
514 |
+
yield ' },'
|
515 |
+
yield ''
|
516 |
+
yield '} # prereq'
|
517 |
+
|
518 |
+
def _beta_rules_lines(self):
|
519 |
+
reverse_implications = defaultdict(list)
|
520 |
+
for n, (pre, implied) in enumerate(self.beta_rules):
|
521 |
+
reverse_implications[implied].append((pre, n))
|
522 |
+
|
523 |
+
yield '# Note: the order of the beta rules is used in the beta_triggers'
|
524 |
+
yield 'beta_rules = ['
|
525 |
+
yield ''
|
526 |
+
m = 0
|
527 |
+
indices = {}
|
528 |
+
for implied in sorted(reverse_implications):
|
529 |
+
fact, value = implied
|
530 |
+
yield f' # Rules implying {fact} = {value}'
|
531 |
+
for pre, n in reverse_implications[implied]:
|
532 |
+
indices[n] = m
|
533 |
+
m += 1
|
534 |
+
setstr = ", ".join(map(str, sorted(pre)))
|
535 |
+
yield f' ({{{setstr}}},'
|
536 |
+
yield f' {implied!r}),'
|
537 |
+
yield ''
|
538 |
+
yield '] # beta_rules'
|
539 |
+
|
540 |
+
yield 'beta_triggers = {'
|
541 |
+
for query in sorted(self.beta_triggers):
|
542 |
+
fact, value = query
|
543 |
+
triggers = [indices[n] for n in self.beta_triggers[query]]
|
544 |
+
yield f' {query!r}: {triggers!r},'
|
545 |
+
yield '} # beta_triggers'
|
546 |
+
|
547 |
+
def print_rules(self) -> Iterator[str]:
|
548 |
+
""" Returns a generator with lines to represent the facts and rules """
|
549 |
+
yield from self._defined_facts_lines()
|
550 |
+
yield ''
|
551 |
+
yield ''
|
552 |
+
yield from self._full_implications_lines()
|
553 |
+
yield ''
|
554 |
+
yield ''
|
555 |
+
yield from self._prereq_lines()
|
556 |
+
yield ''
|
557 |
+
yield ''
|
558 |
+
yield from self._beta_rules_lines()
|
559 |
+
yield ''
|
560 |
+
yield ''
|
561 |
+
yield "generated_assumptions = {'defined_facts': defined_facts, 'full_implications': full_implications,"
|
562 |
+
yield " 'prereq': prereq, 'beta_rules': beta_rules, 'beta_triggers': beta_triggers}"
|
563 |
+
|
564 |
+
|
565 |
+
class InconsistentAssumptions(ValueError):
|
566 |
+
def __str__(self):
|
567 |
+
kb, fact, value = self.args
|
568 |
+
return "%s, %s=%s" % (kb, fact, value)
|
569 |
+
|
570 |
+
|
571 |
+
class FactKB(dict):
|
572 |
+
"""
|
573 |
+
A simple propositional knowledge base relying on compiled inference rules.
|
574 |
+
"""
|
575 |
+
def __str__(self):
|
576 |
+
return '{\n%s}' % ',\n'.join(
|
577 |
+
["\t%s: %s" % i for i in sorted(self.items())])
|
578 |
+
|
579 |
+
def __init__(self, rules):
|
580 |
+
self.rules = rules
|
581 |
+
|
582 |
+
def _tell(self, k, v):
|
583 |
+
"""Add fact k=v to the knowledge base.
|
584 |
+
|
585 |
+
Returns True if the KB has actually been updated, False otherwise.
|
586 |
+
"""
|
587 |
+
if k in self and self[k] is not None:
|
588 |
+
if self[k] == v:
|
589 |
+
return False
|
590 |
+
else:
|
591 |
+
raise InconsistentAssumptions(self, k, v)
|
592 |
+
else:
|
593 |
+
self[k] = v
|
594 |
+
return True
|
595 |
+
|
596 |
+
# *********************************************
|
597 |
+
# * This is the workhorse, so keep it *fast*. *
|
598 |
+
# *********************************************
|
599 |
+
def deduce_all_facts(self, facts):
|
600 |
+
"""
|
601 |
+
Update the KB with all the implications of a list of facts.
|
602 |
+
|
603 |
+
Facts can be specified as a dictionary or as a list of (key, value)
|
604 |
+
pairs.
|
605 |
+
"""
|
606 |
+
# keep frequently used attributes locally, so we'll avoid extra
|
607 |
+
# attribute access overhead
|
608 |
+
full_implications = self.rules.full_implications
|
609 |
+
beta_triggers = self.rules.beta_triggers
|
610 |
+
beta_rules = self.rules.beta_rules
|
611 |
+
|
612 |
+
if isinstance(facts, dict):
|
613 |
+
facts = facts.items()
|
614 |
+
|
615 |
+
while facts:
|
616 |
+
beta_maytrigger = set()
|
617 |
+
|
618 |
+
# --- alpha chains ---
|
619 |
+
for k, v in facts:
|
620 |
+
if not self._tell(k, v) or v is None:
|
621 |
+
continue
|
622 |
+
|
623 |
+
# lookup routing tables
|
624 |
+
for key, value in full_implications[k, v]:
|
625 |
+
self._tell(key, value)
|
626 |
+
|
627 |
+
beta_maytrigger.update(beta_triggers[k, v])
|
628 |
+
|
629 |
+
# --- beta chains ---
|
630 |
+
facts = []
|
631 |
+
for bidx in beta_maytrigger:
|
632 |
+
bcond, bimpl = beta_rules[bidx]
|
633 |
+
if all(self.get(k) is v for k, v in bcond):
|
634 |
+
facts.append(bimpl)
|
llmeval-env/lib/python3.10/site-packages/sympy/core/kind.py
ADDED
@@ -0,0 +1,388 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Module to efficiently partition SymPy objects.
|
3 |
+
|
4 |
+
This system is introduced because class of SymPy object does not always
|
5 |
+
represent the mathematical classification of the entity. For example,
|
6 |
+
``Integral(1, x)`` and ``Integral(Matrix([1,2]), x)`` are both instance
|
7 |
+
of ``Integral`` class. However the former is number and the latter is
|
8 |
+
matrix.
|
9 |
+
|
10 |
+
One way to resolve this is defining subclass for each mathematical type,
|
11 |
+
such as ``MatAdd`` for the addition between matrices. Basic algebraic
|
12 |
+
operation such as addition or multiplication take this approach, but
|
13 |
+
defining every class for every mathematical object is not scalable.
|
14 |
+
|
15 |
+
Therefore, we define the "kind" of the object and let the expression
|
16 |
+
infer the kind of itself from its arguments. Function and class can
|
17 |
+
filter the arguments by their kind, and behave differently according to
|
18 |
+
the type of itself.
|
19 |
+
|
20 |
+
This module defines basic kinds for core objects. Other kinds such as
|
21 |
+
``ArrayKind`` or ``MatrixKind`` can be found in corresponding modules.
|
22 |
+
|
23 |
+
.. notes::
|
24 |
+
This approach is experimental, and can be replaced or deleted in the future.
|
25 |
+
See https://github.com/sympy/sympy/pull/20549.
|
26 |
+
"""
|
27 |
+
|
28 |
+
from collections import defaultdict
|
29 |
+
|
30 |
+
from .cache import cacheit
|
31 |
+
from sympy.multipledispatch.dispatcher import (Dispatcher,
|
32 |
+
ambiguity_warn, ambiguity_register_error_ignore_dup,
|
33 |
+
str_signature, RaiseNotImplementedError)
|
34 |
+
|
35 |
+
|
36 |
+
class KindMeta(type):
|
37 |
+
"""
|
38 |
+
Metaclass for ``Kind``.
|
39 |
+
|
40 |
+
Assigns empty ``dict`` as class attribute ``_inst`` for every class,
|
41 |
+
in order to endow singleton-like behavior.
|
42 |
+
"""
|
43 |
+
def __new__(cls, clsname, bases, dct):
|
44 |
+
dct['_inst'] = {}
|
45 |
+
return super().__new__(cls, clsname, bases, dct)
|
46 |
+
|
47 |
+
|
48 |
+
class Kind(object, metaclass=KindMeta):
|
49 |
+
"""
|
50 |
+
Base class for kinds.
|
51 |
+
|
52 |
+
Kind of the object represents the mathematical classification that
|
53 |
+
the entity falls into. It is expected that functions and classes
|
54 |
+
recognize and filter the argument by its kind.
|
55 |
+
|
56 |
+
Kind of every object must be carefully selected so that it shows the
|
57 |
+
intention of design. Expressions may have different kind according
|
58 |
+
to the kind of its arguments. For example, arguments of ``Add``
|
59 |
+
must have common kind since addition is group operator, and the
|
60 |
+
resulting ``Add()`` has the same kind.
|
61 |
+
|
62 |
+
For the performance, each kind is as broad as possible and is not
|
63 |
+
based on set theory. For example, ``NumberKind`` includes not only
|
64 |
+
complex number but expression containing ``S.Infinity`` or ``S.NaN``
|
65 |
+
which are not strictly number.
|
66 |
+
|
67 |
+
Kind may have arguments as parameter. For example, ``MatrixKind()``
|
68 |
+
may be constructed with one element which represents the kind of its
|
69 |
+
elements.
|
70 |
+
|
71 |
+
``Kind`` behaves in singleton-like fashion. Same signature will
|
72 |
+
return the same object.
|
73 |
+
|
74 |
+
"""
|
75 |
+
def __new__(cls, *args):
|
76 |
+
if args in cls._inst:
|
77 |
+
inst = cls._inst[args]
|
78 |
+
else:
|
79 |
+
inst = super().__new__(cls)
|
80 |
+
cls._inst[args] = inst
|
81 |
+
return inst
|
82 |
+
|
83 |
+
|
84 |
+
class _UndefinedKind(Kind):
|
85 |
+
"""
|
86 |
+
Default kind for all SymPy object. If the kind is not defined for
|
87 |
+
the object, or if the object cannot infer the kind from its
|
88 |
+
arguments, this will be returned.
|
89 |
+
|
90 |
+
Examples
|
91 |
+
========
|
92 |
+
|
93 |
+
>>> from sympy import Expr
|
94 |
+
>>> Expr().kind
|
95 |
+
UndefinedKind
|
96 |
+
"""
|
97 |
+
def __new__(cls):
|
98 |
+
return super().__new__(cls)
|
99 |
+
|
100 |
+
def __repr__(self):
|
101 |
+
return "UndefinedKind"
|
102 |
+
|
103 |
+
UndefinedKind = _UndefinedKind()
|
104 |
+
|
105 |
+
|
106 |
+
class _NumberKind(Kind):
|
107 |
+
"""
|
108 |
+
Kind for all numeric object.
|
109 |
+
|
110 |
+
This kind represents every number, including complex numbers,
|
111 |
+
infinity and ``S.NaN``. Other objects such as quaternions do not
|
112 |
+
have this kind.
|
113 |
+
|
114 |
+
Most ``Expr`` are initially designed to represent the number, so
|
115 |
+
this will be the most common kind in SymPy core. For example
|
116 |
+
``Symbol()``, which represents a scalar, has this kind as long as it
|
117 |
+
is commutative.
|
118 |
+
|
119 |
+
Numbers form a field. Any operation between number-kind objects will
|
120 |
+
result this kind as well.
|
121 |
+
|
122 |
+
Examples
|
123 |
+
========
|
124 |
+
|
125 |
+
>>> from sympy import S, oo, Symbol
|
126 |
+
>>> S.One.kind
|
127 |
+
NumberKind
|
128 |
+
>>> (-oo).kind
|
129 |
+
NumberKind
|
130 |
+
>>> S.NaN.kind
|
131 |
+
NumberKind
|
132 |
+
|
133 |
+
Commutative symbol are treated as number.
|
134 |
+
|
135 |
+
>>> x = Symbol('x')
|
136 |
+
>>> x.kind
|
137 |
+
NumberKind
|
138 |
+
>>> Symbol('y', commutative=False).kind
|
139 |
+
UndefinedKind
|
140 |
+
|
141 |
+
Operation between numbers results number.
|
142 |
+
|
143 |
+
>>> (x+1).kind
|
144 |
+
NumberKind
|
145 |
+
|
146 |
+
See Also
|
147 |
+
========
|
148 |
+
|
149 |
+
sympy.core.expr.Expr.is_Number : check if the object is strictly
|
150 |
+
subclass of ``Number`` class.
|
151 |
+
|
152 |
+
sympy.core.expr.Expr.is_number : check if the object is number
|
153 |
+
without any free symbol.
|
154 |
+
|
155 |
+
"""
|
156 |
+
def __new__(cls):
|
157 |
+
return super().__new__(cls)
|
158 |
+
|
159 |
+
def __repr__(self):
|
160 |
+
return "NumberKind"
|
161 |
+
|
162 |
+
NumberKind = _NumberKind()
|
163 |
+
|
164 |
+
|
165 |
+
class _BooleanKind(Kind):
|
166 |
+
"""
|
167 |
+
Kind for boolean objects.
|
168 |
+
|
169 |
+
SymPy's ``S.true``, ``S.false``, and built-in ``True`` and ``False``
|
170 |
+
have this kind. Boolean number ``1`` and ``0`` are not relevant.
|
171 |
+
|
172 |
+
Examples
|
173 |
+
========
|
174 |
+
|
175 |
+
>>> from sympy import S, Q
|
176 |
+
>>> S.true.kind
|
177 |
+
BooleanKind
|
178 |
+
>>> Q.even(3).kind
|
179 |
+
BooleanKind
|
180 |
+
"""
|
181 |
+
def __new__(cls):
|
182 |
+
return super().__new__(cls)
|
183 |
+
|
184 |
+
def __repr__(self):
|
185 |
+
return "BooleanKind"
|
186 |
+
|
187 |
+
BooleanKind = _BooleanKind()
|
188 |
+
|
189 |
+
|
190 |
+
class KindDispatcher:
|
191 |
+
"""
|
192 |
+
Dispatcher to select a kind from multiple kinds by binary dispatching.
|
193 |
+
|
194 |
+
.. notes::
|
195 |
+
This approach is experimental, and can be replaced or deleted in
|
196 |
+
the future.
|
197 |
+
|
198 |
+
Explanation
|
199 |
+
===========
|
200 |
+
|
201 |
+
SymPy object's :obj:`sympy.core.kind.Kind()` vaguely represents the
|
202 |
+
algebraic structure where the object belongs to. Therefore, with
|
203 |
+
given operation, we can always find a dominating kind among the
|
204 |
+
different kinds. This class selects the kind by recursive binary
|
205 |
+
dispatching. If the result cannot be determined, ``UndefinedKind``
|
206 |
+
is returned.
|
207 |
+
|
208 |
+
Examples
|
209 |
+
========
|
210 |
+
|
211 |
+
Multiplication between numbers return number.
|
212 |
+
|
213 |
+
>>> from sympy import NumberKind, Mul
|
214 |
+
>>> Mul._kind_dispatcher(NumberKind, NumberKind)
|
215 |
+
NumberKind
|
216 |
+
|
217 |
+
Multiplication between number and unknown-kind object returns unknown kind.
|
218 |
+
|
219 |
+
>>> from sympy import UndefinedKind
|
220 |
+
>>> Mul._kind_dispatcher(NumberKind, UndefinedKind)
|
221 |
+
UndefinedKind
|
222 |
+
|
223 |
+
Any number and order of kinds is allowed.
|
224 |
+
|
225 |
+
>>> Mul._kind_dispatcher(UndefinedKind, NumberKind)
|
226 |
+
UndefinedKind
|
227 |
+
>>> Mul._kind_dispatcher(NumberKind, UndefinedKind, NumberKind)
|
228 |
+
UndefinedKind
|
229 |
+
|
230 |
+
Since matrix forms a vector space over scalar field, multiplication
|
231 |
+
between matrix with numeric element and number returns matrix with
|
232 |
+
numeric element.
|
233 |
+
|
234 |
+
>>> from sympy.matrices import MatrixKind
|
235 |
+
>>> Mul._kind_dispatcher(MatrixKind(NumberKind), NumberKind)
|
236 |
+
MatrixKind(NumberKind)
|
237 |
+
|
238 |
+
If a matrix with number element and another matrix with unknown-kind
|
239 |
+
element are multiplied, we know that the result is matrix but the
|
240 |
+
kind of its elements is unknown.
|
241 |
+
|
242 |
+
>>> Mul._kind_dispatcher(MatrixKind(NumberKind), MatrixKind(UndefinedKind))
|
243 |
+
MatrixKind(UndefinedKind)
|
244 |
+
|
245 |
+
Parameters
|
246 |
+
==========
|
247 |
+
|
248 |
+
name : str
|
249 |
+
|
250 |
+
commutative : bool, optional
|
251 |
+
If True, binary dispatch will be automatically registered in
|
252 |
+
reversed order as well.
|
253 |
+
|
254 |
+
doc : str, optional
|
255 |
+
|
256 |
+
"""
|
257 |
+
def __init__(self, name, commutative=False, doc=None):
|
258 |
+
self.name = name
|
259 |
+
self.doc = doc
|
260 |
+
self.commutative = commutative
|
261 |
+
self._dispatcher = Dispatcher(name)
|
262 |
+
|
263 |
+
def __repr__(self):
|
264 |
+
return "<dispatched %s>" % self.name
|
265 |
+
|
266 |
+
def register(self, *types, **kwargs):
|
267 |
+
"""
|
268 |
+
Register the binary dispatcher for two kind classes.
|
269 |
+
|
270 |
+
If *self.commutative* is ``True``, signature in reversed order is
|
271 |
+
automatically registered as well.
|
272 |
+
"""
|
273 |
+
on_ambiguity = kwargs.pop("on_ambiguity", None)
|
274 |
+
if not on_ambiguity:
|
275 |
+
if self.commutative:
|
276 |
+
on_ambiguity = ambiguity_register_error_ignore_dup
|
277 |
+
else:
|
278 |
+
on_ambiguity = ambiguity_warn
|
279 |
+
kwargs.update(on_ambiguity=on_ambiguity)
|
280 |
+
|
281 |
+
if not len(types) == 2:
|
282 |
+
raise RuntimeError(
|
283 |
+
"Only binary dispatch is supported, but got %s types: <%s>." % (
|
284 |
+
len(types), str_signature(types)
|
285 |
+
))
|
286 |
+
|
287 |
+
def _(func):
|
288 |
+
self._dispatcher.add(types, func, **kwargs)
|
289 |
+
if self.commutative:
|
290 |
+
self._dispatcher.add(tuple(reversed(types)), func, **kwargs)
|
291 |
+
return _
|
292 |
+
|
293 |
+
def __call__(self, *args, **kwargs):
|
294 |
+
if self.commutative:
|
295 |
+
kinds = frozenset(args)
|
296 |
+
else:
|
297 |
+
kinds = []
|
298 |
+
prev = None
|
299 |
+
for a in args:
|
300 |
+
if prev is not a:
|
301 |
+
kinds.append(a)
|
302 |
+
prev = a
|
303 |
+
return self.dispatch_kinds(kinds, **kwargs)
|
304 |
+
|
305 |
+
@cacheit
|
306 |
+
def dispatch_kinds(self, kinds, **kwargs):
|
307 |
+
# Quick exit for the case where all kinds are same
|
308 |
+
if len(kinds) == 1:
|
309 |
+
result, = kinds
|
310 |
+
if not isinstance(result, Kind):
|
311 |
+
raise RuntimeError("%s is not a kind." % result)
|
312 |
+
return result
|
313 |
+
|
314 |
+
for i,kind in enumerate(kinds):
|
315 |
+
if not isinstance(kind, Kind):
|
316 |
+
raise RuntimeError("%s is not a kind." % kind)
|
317 |
+
|
318 |
+
if i == 0:
|
319 |
+
result = kind
|
320 |
+
else:
|
321 |
+
prev_kind = result
|
322 |
+
|
323 |
+
t1, t2 = type(prev_kind), type(kind)
|
324 |
+
k1, k2 = prev_kind, kind
|
325 |
+
func = self._dispatcher.dispatch(t1, t2)
|
326 |
+
if func is None and self.commutative:
|
327 |
+
# try reversed order
|
328 |
+
func = self._dispatcher.dispatch(t2, t1)
|
329 |
+
k1, k2 = k2, k1
|
330 |
+
if func is None:
|
331 |
+
# unregistered kind relation
|
332 |
+
result = UndefinedKind
|
333 |
+
else:
|
334 |
+
result = func(k1, k2)
|
335 |
+
if not isinstance(result, Kind):
|
336 |
+
raise RuntimeError(
|
337 |
+
"Dispatcher for {!r} and {!r} must return a Kind, but got {!r}".format(
|
338 |
+
prev_kind, kind, result
|
339 |
+
))
|
340 |
+
|
341 |
+
return result
|
342 |
+
|
343 |
+
@property
|
344 |
+
def __doc__(self):
|
345 |
+
docs = [
|
346 |
+
"Kind dispatcher : %s" % self.name,
|
347 |
+
"Note that support for this is experimental. See the docs for :class:`KindDispatcher` for details"
|
348 |
+
]
|
349 |
+
|
350 |
+
if self.doc:
|
351 |
+
docs.append(self.doc)
|
352 |
+
|
353 |
+
s = "Registered kind classes\n"
|
354 |
+
s += '=' * len(s)
|
355 |
+
docs.append(s)
|
356 |
+
|
357 |
+
amb_sigs = []
|
358 |
+
|
359 |
+
typ_sigs = defaultdict(list)
|
360 |
+
for sigs in self._dispatcher.ordering[::-1]:
|
361 |
+
key = self._dispatcher.funcs[sigs]
|
362 |
+
typ_sigs[key].append(sigs)
|
363 |
+
|
364 |
+
for func, sigs in typ_sigs.items():
|
365 |
+
|
366 |
+
sigs_str = ', '.join('<%s>' % str_signature(sig) for sig in sigs)
|
367 |
+
|
368 |
+
if isinstance(func, RaiseNotImplementedError):
|
369 |
+
amb_sigs.append(sigs_str)
|
370 |
+
continue
|
371 |
+
|
372 |
+
s = 'Inputs: %s\n' % sigs_str
|
373 |
+
s += '-' * len(s) + '\n'
|
374 |
+
if func.__doc__:
|
375 |
+
s += func.__doc__.strip()
|
376 |
+
else:
|
377 |
+
s += func.__name__
|
378 |
+
docs.append(s)
|
379 |
+
|
380 |
+
if amb_sigs:
|
381 |
+
s = "Ambiguous kind classes\n"
|
382 |
+
s += '=' * len(s)
|
383 |
+
docs.append(s)
|
384 |
+
|
385 |
+
s = '\n'.join(amb_sigs)
|
386 |
+
docs.append(s)
|
387 |
+
|
388 |
+
return '\n\n'.join(docs)
|
llmeval-env/lib/python3.10/site-packages/sympy/core/mul.py
ADDED
@@ -0,0 +1,2195 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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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 itertools import product
|
5 |
+
import operator
|
6 |
+
|
7 |
+
from .sympify import sympify
|
8 |
+
from .basic import Basic
|
9 |
+
from .singleton import S
|
10 |
+
from .operations import AssocOp, AssocOpDispatcher
|
11 |
+
from .cache import cacheit
|
12 |
+
from .logic import fuzzy_not, _fuzzy_group
|
13 |
+
from .expr import Expr
|
14 |
+
from .parameters import global_parameters
|
15 |
+
from .kind import KindDispatcher
|
16 |
+
from .traversal import bottom_up
|
17 |
+
|
18 |
+
from sympy.utilities.iterables import sift
|
19 |
+
|
20 |
+
# internal marker to indicate:
|
21 |
+
# "there are still non-commutative objects -- don't forget to process them"
|
22 |
+
class NC_Marker:
|
23 |
+
is_Order = False
|
24 |
+
is_Mul = False
|
25 |
+
is_Number = False
|
26 |
+
is_Poly = False
|
27 |
+
|
28 |
+
is_commutative = False
|
29 |
+
|
30 |
+
|
31 |
+
# Key for sorting commutative args in canonical order
|
32 |
+
_args_sortkey = cmp_to_key(Basic.compare)
|
33 |
+
def _mulsort(args):
|
34 |
+
# in-place sorting of args
|
35 |
+
args.sort(key=_args_sortkey)
|
36 |
+
|
37 |
+
|
38 |
+
def _unevaluated_Mul(*args):
|
39 |
+
"""Return a well-formed unevaluated Mul: Numbers are collected and
|
40 |
+
put in slot 0, any arguments that are Muls will be flattened, and args
|
41 |
+
are sorted. Use this when args have changed but you still want to return
|
42 |
+
an unevaluated Mul.
|
43 |
+
|
44 |
+
Examples
|
45 |
+
========
|
46 |
+
|
47 |
+
>>> from sympy.core.mul import _unevaluated_Mul as uMul
|
48 |
+
>>> from sympy import S, sqrt, Mul
|
49 |
+
>>> from sympy.abc import x
|
50 |
+
>>> a = uMul(*[S(3.0), x, S(2)])
|
51 |
+
>>> a.args[0]
|
52 |
+
6.00000000000000
|
53 |
+
>>> a.args[1]
|
54 |
+
x
|
55 |
+
|
56 |
+
Two unevaluated Muls with the same arguments will
|
57 |
+
always compare as equal during testing:
|
58 |
+
|
59 |
+
>>> m = uMul(sqrt(2), sqrt(3))
|
60 |
+
>>> m == uMul(sqrt(3), sqrt(2))
|
61 |
+
True
|
62 |
+
>>> u = Mul(sqrt(3), sqrt(2), evaluate=False)
|
63 |
+
>>> m == uMul(u)
|
64 |
+
True
|
65 |
+
>>> m == Mul(*m.args)
|
66 |
+
False
|
67 |
+
|
68 |
+
"""
|
69 |
+
args = list(args)
|
70 |
+
newargs = []
|
71 |
+
ncargs = []
|
72 |
+
co = S.One
|
73 |
+
while args:
|
74 |
+
a = args.pop()
|
75 |
+
if a.is_Mul:
|
76 |
+
c, nc = a.args_cnc()
|
77 |
+
args.extend(c)
|
78 |
+
if nc:
|
79 |
+
ncargs.append(Mul._from_args(nc))
|
80 |
+
elif a.is_Number:
|
81 |
+
co *= a
|
82 |
+
else:
|
83 |
+
newargs.append(a)
|
84 |
+
_mulsort(newargs)
|
85 |
+
if co is not S.One:
|
86 |
+
newargs.insert(0, co)
|
87 |
+
if ncargs:
|
88 |
+
newargs.append(Mul._from_args(ncargs))
|
89 |
+
return Mul._from_args(newargs)
|
90 |
+
|
91 |
+
|
92 |
+
class Mul(Expr, AssocOp):
|
93 |
+
"""
|
94 |
+
Expression representing multiplication operation for algebraic field.
|
95 |
+
|
96 |
+
.. deprecated:: 1.7
|
97 |
+
|
98 |
+
Using arguments that aren't subclasses of :class:`~.Expr` in core
|
99 |
+
operators (:class:`~.Mul`, :class:`~.Add`, and :class:`~.Pow`) is
|
100 |
+
deprecated. See :ref:`non-expr-args-deprecated` for details.
|
101 |
+
|
102 |
+
Every argument of ``Mul()`` must be ``Expr``. Infix operator ``*``
|
103 |
+
on most scalar objects in SymPy calls this class.
|
104 |
+
|
105 |
+
Another use of ``Mul()`` is to represent the structure of abstract
|
106 |
+
multiplication so that its arguments can be substituted to return
|
107 |
+
different class. Refer to examples section for this.
|
108 |
+
|
109 |
+
``Mul()`` evaluates the argument unless ``evaluate=False`` is passed.
|
110 |
+
The evaluation logic includes:
|
111 |
+
|
112 |
+
1. Flattening
|
113 |
+
``Mul(x, Mul(y, z))`` -> ``Mul(x, y, z)``
|
114 |
+
|
115 |
+
2. Identity removing
|
116 |
+
``Mul(x, 1, y)`` -> ``Mul(x, y)``
|
117 |
+
|
118 |
+
3. Exponent collecting by ``.as_base_exp()``
|
119 |
+
``Mul(x, x**2)`` -> ``Pow(x, 3)``
|
120 |
+
|
121 |
+
4. Term sorting
|
122 |
+
``Mul(y, x, 2)`` -> ``Mul(2, x, y)``
|
123 |
+
|
124 |
+
Since multiplication can be vector space operation, arguments may
|
125 |
+
have the different :obj:`sympy.core.kind.Kind()`. Kind of the
|
126 |
+
resulting object is automatically inferred.
|
127 |
+
|
128 |
+
Examples
|
129 |
+
========
|
130 |
+
|
131 |
+
>>> from sympy import Mul
|
132 |
+
>>> from sympy.abc import x, y
|
133 |
+
>>> Mul(x, 1)
|
134 |
+
x
|
135 |
+
>>> Mul(x, x)
|
136 |
+
x**2
|
137 |
+
|
138 |
+
If ``evaluate=False`` is passed, result is not evaluated.
|
139 |
+
|
140 |
+
>>> Mul(1, 2, evaluate=False)
|
141 |
+
1*2
|
142 |
+
>>> Mul(x, x, evaluate=False)
|
143 |
+
x*x
|
144 |
+
|
145 |
+
``Mul()`` also represents the general structure of multiplication
|
146 |
+
operation.
|
147 |
+
|
148 |
+
>>> from sympy import MatrixSymbol
|
149 |
+
>>> A = MatrixSymbol('A', 2,2)
|
150 |
+
>>> expr = Mul(x,y).subs({y:A})
|
151 |
+
>>> expr
|
152 |
+
x*A
|
153 |
+
>>> type(expr)
|
154 |
+
<class 'sympy.matrices.expressions.matmul.MatMul'>
|
155 |
+
|
156 |
+
See Also
|
157 |
+
========
|
158 |
+
|
159 |
+
MatMul
|
160 |
+
|
161 |
+
"""
|
162 |
+
__slots__ = ()
|
163 |
+
|
164 |
+
args: tTuple[Expr]
|
165 |
+
|
166 |
+
is_Mul = True
|
167 |
+
|
168 |
+
_args_type = Expr
|
169 |
+
_kind_dispatcher = KindDispatcher("Mul_kind_dispatcher", commutative=True)
|
170 |
+
|
171 |
+
@property
|
172 |
+
def kind(self):
|
173 |
+
arg_kinds = (a.kind for a in self.args)
|
174 |
+
return self._kind_dispatcher(*arg_kinds)
|
175 |
+
|
176 |
+
def could_extract_minus_sign(self):
|
177 |
+
if self == (-self):
|
178 |
+
return False # e.g. zoo*x == -zoo*x
|
179 |
+
c = self.args[0]
|
180 |
+
return c.is_Number and c.is_extended_negative
|
181 |
+
|
182 |
+
def __neg__(self):
|
183 |
+
c, args = self.as_coeff_mul()
|
184 |
+
if args[0] is not S.ComplexInfinity:
|
185 |
+
c = -c
|
186 |
+
if c is not S.One:
|
187 |
+
if args[0].is_Number:
|
188 |
+
args = list(args)
|
189 |
+
if c is S.NegativeOne:
|
190 |
+
args[0] = -args[0]
|
191 |
+
else:
|
192 |
+
args[0] *= c
|
193 |
+
else:
|
194 |
+
args = (c,) + args
|
195 |
+
return self._from_args(args, self.is_commutative)
|
196 |
+
|
197 |
+
@classmethod
|
198 |
+
def flatten(cls, seq):
|
199 |
+
"""Return commutative, noncommutative and order arguments by
|
200 |
+
combining related terms.
|
201 |
+
|
202 |
+
Notes
|
203 |
+
=====
|
204 |
+
* In an expression like ``a*b*c``, Python process this through SymPy
|
205 |
+
as ``Mul(Mul(a, b), c)``. This can have undesirable consequences.
|
206 |
+
|
207 |
+
- Sometimes terms are not combined as one would like:
|
208 |
+
{c.f. https://github.com/sympy/sympy/issues/4596}
|
209 |
+
|
210 |
+
>>> from sympy import Mul, sqrt
|
211 |
+
>>> from sympy.abc import x, y, z
|
212 |
+
>>> 2*(x + 1) # this is the 2-arg Mul behavior
|
213 |
+
2*x + 2
|
214 |
+
>>> y*(x + 1)*2
|
215 |
+
2*y*(x + 1)
|
216 |
+
>>> 2*(x + 1)*y # 2-arg result will be obtained first
|
217 |
+
y*(2*x + 2)
|
218 |
+
>>> Mul(2, x + 1, y) # all 3 args simultaneously processed
|
219 |
+
2*y*(x + 1)
|
220 |
+
>>> 2*((x + 1)*y) # parentheses can control this behavior
|
221 |
+
2*y*(x + 1)
|
222 |
+
|
223 |
+
Powers with compound bases may not find a single base to
|
224 |
+
combine with unless all arguments are processed at once.
|
225 |
+
Post-processing may be necessary in such cases.
|
226 |
+
{c.f. https://github.com/sympy/sympy/issues/5728}
|
227 |
+
|
228 |
+
>>> a = sqrt(x*sqrt(y))
|
229 |
+
>>> a**3
|
230 |
+
(x*sqrt(y))**(3/2)
|
231 |
+
>>> Mul(a,a,a)
|
232 |
+
(x*sqrt(y))**(3/2)
|
233 |
+
>>> a*a*a
|
234 |
+
x*sqrt(y)*sqrt(x*sqrt(y))
|
235 |
+
>>> _.subs(a.base, z).subs(z, a.base)
|
236 |
+
(x*sqrt(y))**(3/2)
|
237 |
+
|
238 |
+
- If more than two terms are being multiplied then all the
|
239 |
+
previous terms will be re-processed for each new argument.
|
240 |
+
So if each of ``a``, ``b`` and ``c`` were :class:`Mul`
|
241 |
+
expression, then ``a*b*c`` (or building up the product
|
242 |
+
with ``*=``) will process all the arguments of ``a`` and
|
243 |
+
``b`` twice: once when ``a*b`` is computed and again when
|
244 |
+
``c`` is multiplied.
|
245 |
+
|
246 |
+
Using ``Mul(a, b, c)`` will process all arguments once.
|
247 |
+
|
248 |
+
* The results of Mul are cached according to arguments, so flatten
|
249 |
+
will only be called once for ``Mul(a, b, c)``. If you can
|
250 |
+
structure a calculation so the arguments are most likely to be
|
251 |
+
repeats then this can save time in computing the answer. For
|
252 |
+
example, say you had a Mul, M, that you wished to divide by ``d[i]``
|
253 |
+
and multiply by ``n[i]`` and you suspect there are many repeats
|
254 |
+
in ``n``. It would be better to compute ``M*n[i]/d[i]`` rather
|
255 |
+
than ``M/d[i]*n[i]`` since every time n[i] is a repeat, the
|
256 |
+
product, ``M*n[i]`` will be returned without flattening -- the
|
257 |
+
cached value will be returned. If you divide by the ``d[i]``
|
258 |
+
first (and those are more unique than the ``n[i]``) then that will
|
259 |
+
create a new Mul, ``M/d[i]`` the args of which will be traversed
|
260 |
+
again when it is multiplied by ``n[i]``.
|
261 |
+
|
262 |
+
{c.f. https://github.com/sympy/sympy/issues/5706}
|
263 |
+
|
264 |
+
This consideration is moot if the cache is turned off.
|
265 |
+
|
266 |
+
NB
|
267 |
+
--
|
268 |
+
The validity of the above notes depends on the implementation
|
269 |
+
details of Mul and flatten which may change at any time. Therefore,
|
270 |
+
you should only consider them when your code is highly performance
|
271 |
+
sensitive.
|
272 |
+
|
273 |
+
Removal of 1 from the sequence is already handled by AssocOp.__new__.
|
274 |
+
"""
|
275 |
+
|
276 |
+
from sympy.calculus.accumulationbounds import AccumBounds
|
277 |
+
from sympy.matrices.expressions import MatrixExpr
|
278 |
+
rv = None
|
279 |
+
if len(seq) == 2:
|
280 |
+
a, b = seq
|
281 |
+
if b.is_Rational:
|
282 |
+
a, b = b, a
|
283 |
+
seq = [a, b]
|
284 |
+
assert a is not S.One
|
285 |
+
if not a.is_zero and a.is_Rational:
|
286 |
+
r, b = b.as_coeff_Mul()
|
287 |
+
if b.is_Add:
|
288 |
+
if r is not S.One: # 2-arg hack
|
289 |
+
# leave the Mul as a Mul?
|
290 |
+
ar = a*r
|
291 |
+
if ar is S.One:
|
292 |
+
arb = b
|
293 |
+
else:
|
294 |
+
arb = cls(a*r, b, evaluate=False)
|
295 |
+
rv = [arb], [], None
|
296 |
+
elif global_parameters.distribute and b.is_commutative:
|
297 |
+
newb = Add(*[_keep_coeff(a, bi) for bi in b.args])
|
298 |
+
rv = [newb], [], None
|
299 |
+
if rv:
|
300 |
+
return rv
|
301 |
+
|
302 |
+
# apply associativity, separate commutative part of seq
|
303 |
+
c_part = [] # out: commutative factors
|
304 |
+
nc_part = [] # out: non-commutative factors
|
305 |
+
|
306 |
+
nc_seq = []
|
307 |
+
|
308 |
+
coeff = S.One # standalone term
|
309 |
+
# e.g. 3 * ...
|
310 |
+
|
311 |
+
c_powers = [] # (base,exp) n
|
312 |
+
# e.g. (x,n) for x
|
313 |
+
|
314 |
+
num_exp = [] # (num-base, exp) y
|
315 |
+
# e.g. (3, y) for ... * 3 * ...
|
316 |
+
|
317 |
+
neg1e = S.Zero # exponent on -1 extracted from Number-based Pow and I
|
318 |
+
|
319 |
+
pnum_rat = {} # (num-base, Rat-exp) 1/2
|
320 |
+
# e.g. (3, 1/2) for ... * 3 * ...
|
321 |
+
|
322 |
+
order_symbols = None
|
323 |
+
|
324 |
+
# --- PART 1 ---
|
325 |
+
#
|
326 |
+
# "collect powers and coeff":
|
327 |
+
#
|
328 |
+
# o coeff
|
329 |
+
# o c_powers
|
330 |
+
# o num_exp
|
331 |
+
# o neg1e
|
332 |
+
# o pnum_rat
|
333 |
+
#
|
334 |
+
# NOTE: this is optimized for all-objects-are-commutative case
|
335 |
+
for o in seq:
|
336 |
+
# O(x)
|
337 |
+
if o.is_Order:
|
338 |
+
o, order_symbols = o.as_expr_variables(order_symbols)
|
339 |
+
|
340 |
+
# Mul([...])
|
341 |
+
if o.is_Mul:
|
342 |
+
if o.is_commutative:
|
343 |
+
seq.extend(o.args) # XXX zerocopy?
|
344 |
+
|
345 |
+
else:
|
346 |
+
# NCMul can have commutative parts as well
|
347 |
+
for q in o.args:
|
348 |
+
if q.is_commutative:
|
349 |
+
seq.append(q)
|
350 |
+
else:
|
351 |
+
nc_seq.append(q)
|
352 |
+
|
353 |
+
# append non-commutative marker, so we don't forget to
|
354 |
+
# process scheduled non-commutative objects
|
355 |
+
seq.append(NC_Marker)
|
356 |
+
|
357 |
+
continue
|
358 |
+
|
359 |
+
# 3
|
360 |
+
elif o.is_Number:
|
361 |
+
if o is S.NaN or coeff is S.ComplexInfinity and o.is_zero:
|
362 |
+
# we know for sure the result will be nan
|
363 |
+
return [S.NaN], [], None
|
364 |
+
elif coeff.is_Number or isinstance(coeff, AccumBounds): # it could be zoo
|
365 |
+
coeff *= o
|
366 |
+
if coeff is S.NaN:
|
367 |
+
# we know for sure the result will be nan
|
368 |
+
return [S.NaN], [], None
|
369 |
+
continue
|
370 |
+
|
371 |
+
elif isinstance(o, AccumBounds):
|
372 |
+
coeff = o.__mul__(coeff)
|
373 |
+
continue
|
374 |
+
|
375 |
+
elif o is S.ComplexInfinity:
|
376 |
+
if not coeff:
|
377 |
+
# 0 * zoo = NaN
|
378 |
+
return [S.NaN], [], None
|
379 |
+
coeff = S.ComplexInfinity
|
380 |
+
continue
|
381 |
+
|
382 |
+
elif o is S.ImaginaryUnit:
|
383 |
+
neg1e += S.Half
|
384 |
+
continue
|
385 |
+
|
386 |
+
elif o.is_commutative:
|
387 |
+
# e
|
388 |
+
# o = b
|
389 |
+
b, e = o.as_base_exp()
|
390 |
+
|
391 |
+
# y
|
392 |
+
# 3
|
393 |
+
if o.is_Pow:
|
394 |
+
if b.is_Number:
|
395 |
+
|
396 |
+
# get all the factors with numeric base so they can be
|
397 |
+
# combined below, but don't combine negatives unless
|
398 |
+
# the exponent is an integer
|
399 |
+
if e.is_Rational:
|
400 |
+
if e.is_Integer:
|
401 |
+
coeff *= Pow(b, e) # it is an unevaluated power
|
402 |
+
continue
|
403 |
+
elif e.is_negative: # also a sign of an unevaluated power
|
404 |
+
seq.append(Pow(b, e))
|
405 |
+
continue
|
406 |
+
elif b.is_negative:
|
407 |
+
neg1e += e
|
408 |
+
b = -b
|
409 |
+
if b is not S.One:
|
410 |
+
pnum_rat.setdefault(b, []).append(e)
|
411 |
+
continue
|
412 |
+
elif b.is_positive or e.is_integer:
|
413 |
+
num_exp.append((b, e))
|
414 |
+
continue
|
415 |
+
|
416 |
+
c_powers.append((b, e))
|
417 |
+
|
418 |
+
# NON-COMMUTATIVE
|
419 |
+
# TODO: Make non-commutative exponents not combine automatically
|
420 |
+
else:
|
421 |
+
if o is not NC_Marker:
|
422 |
+
nc_seq.append(o)
|
423 |
+
|
424 |
+
# process nc_seq (if any)
|
425 |
+
while nc_seq:
|
426 |
+
o = nc_seq.pop(0)
|
427 |
+
if not nc_part:
|
428 |
+
nc_part.append(o)
|
429 |
+
continue
|
430 |
+
|
431 |
+
# b c b+c
|
432 |
+
# try to combine last terms: a * a -> a
|
433 |
+
o1 = nc_part.pop()
|
434 |
+
b1, e1 = o1.as_base_exp()
|
435 |
+
b2, e2 = o.as_base_exp()
|
436 |
+
new_exp = e1 + e2
|
437 |
+
# Only allow powers to combine if the new exponent is
|
438 |
+
# not an Add. This allow things like a**2*b**3 == a**5
|
439 |
+
# if a.is_commutative == False, but prohibits
|
440 |
+
# a**x*a**y and x**a*x**b from combining (x,y commute).
|
441 |
+
if b1 == b2 and (not new_exp.is_Add):
|
442 |
+
o12 = b1 ** new_exp
|
443 |
+
|
444 |
+
# now o12 could be a commutative object
|
445 |
+
if o12.is_commutative:
|
446 |
+
seq.append(o12)
|
447 |
+
continue
|
448 |
+
else:
|
449 |
+
nc_seq.insert(0, o12)
|
450 |
+
|
451 |
+
else:
|
452 |
+
nc_part.extend([o1, o])
|
453 |
+
|
454 |
+
# We do want a combined exponent if it would not be an Add, such as
|
455 |
+
# y 2y 3y
|
456 |
+
# x * x -> x
|
457 |
+
# We determine if two exponents have the same term by using
|
458 |
+
# as_coeff_Mul.
|
459 |
+
#
|
460 |
+
# Unfortunately, this isn't smart enough to consider combining into
|
461 |
+
# exponents that might already be adds, so things like:
|
462 |
+
# z - y y
|
463 |
+
# x * x will be left alone. This is because checking every possible
|
464 |
+
# combination can slow things down.
|
465 |
+
|
466 |
+
# gather exponents of common bases...
|
467 |
+
def _gather(c_powers):
|
468 |
+
common_b = {} # b:e
|
469 |
+
for b, e in c_powers:
|
470 |
+
co = e.as_coeff_Mul()
|
471 |
+
common_b.setdefault(b, {}).setdefault(
|
472 |
+
co[1], []).append(co[0])
|
473 |
+
for b, d in common_b.items():
|
474 |
+
for di, li in d.items():
|
475 |
+
d[di] = Add(*li)
|
476 |
+
new_c_powers = []
|
477 |
+
for b, e in common_b.items():
|
478 |
+
new_c_powers.extend([(b, c*t) for t, c in e.items()])
|
479 |
+
return new_c_powers
|
480 |
+
|
481 |
+
# in c_powers
|
482 |
+
c_powers = _gather(c_powers)
|
483 |
+
|
484 |
+
# and in num_exp
|
485 |
+
num_exp = _gather(num_exp)
|
486 |
+
|
487 |
+
# --- PART 2 ---
|
488 |
+
#
|
489 |
+
# o process collected powers (x**0 -> 1; x**1 -> x; otherwise Pow)
|
490 |
+
# o combine collected powers (2**x * 3**x -> 6**x)
|
491 |
+
# with numeric base
|
492 |
+
|
493 |
+
# ................................
|
494 |
+
# now we have:
|
495 |
+
# - coeff:
|
496 |
+
# - c_powers: (b, e)
|
497 |
+
# - num_exp: (2, e)
|
498 |
+
# - pnum_rat: {(1/3, [1/3, 2/3, 1/4])}
|
499 |
+
|
500 |
+
# 0 1
|
501 |
+
# x -> 1 x -> x
|
502 |
+
|
503 |
+
# this should only need to run twice; if it fails because
|
504 |
+
# it needs to be run more times, perhaps this should be
|
505 |
+
# changed to a "while True" loop -- the only reason it
|
506 |
+
# isn't such now is to allow a less-than-perfect result to
|
507 |
+
# be obtained rather than raising an error or entering an
|
508 |
+
# infinite loop
|
509 |
+
for i in range(2):
|
510 |
+
new_c_powers = []
|
511 |
+
changed = False
|
512 |
+
for b, e in c_powers:
|
513 |
+
if e.is_zero:
|
514 |
+
# canceling out infinities yields NaN
|
515 |
+
if (b.is_Add or b.is_Mul) and any(infty in b.args
|
516 |
+
for infty in (S.ComplexInfinity, S.Infinity,
|
517 |
+
S.NegativeInfinity)):
|
518 |
+
return [S.NaN], [], None
|
519 |
+
continue
|
520 |
+
if e is S.One:
|
521 |
+
if b.is_Number:
|
522 |
+
coeff *= b
|
523 |
+
continue
|
524 |
+
p = b
|
525 |
+
if e is not S.One:
|
526 |
+
p = Pow(b, e)
|
527 |
+
# check to make sure that the base doesn't change
|
528 |
+
# after exponentiation; to allow for unevaluated
|
529 |
+
# Pow, we only do so if b is not already a Pow
|
530 |
+
if p.is_Pow and not b.is_Pow:
|
531 |
+
bi = b
|
532 |
+
b, e = p.as_base_exp()
|
533 |
+
if b != bi:
|
534 |
+
changed = True
|
535 |
+
c_part.append(p)
|
536 |
+
new_c_powers.append((b, e))
|
537 |
+
# there might have been a change, but unless the base
|
538 |
+
# matches some other base, there is nothing to do
|
539 |
+
if changed and len({
|
540 |
+
b for b, e in new_c_powers}) != len(new_c_powers):
|
541 |
+
# start over again
|
542 |
+
c_part = []
|
543 |
+
c_powers = _gather(new_c_powers)
|
544 |
+
else:
|
545 |
+
break
|
546 |
+
|
547 |
+
# x x x
|
548 |
+
# 2 * 3 -> 6
|
549 |
+
inv_exp_dict = {} # exp:Mul(num-bases) x x
|
550 |
+
# e.g. x:6 for ... * 2 * 3 * ...
|
551 |
+
for b, e in num_exp:
|
552 |
+
inv_exp_dict.setdefault(e, []).append(b)
|
553 |
+
for e, b in inv_exp_dict.items():
|
554 |
+
inv_exp_dict[e] = cls(*b)
|
555 |
+
c_part.extend([Pow(b, e) for e, b in inv_exp_dict.items() if e])
|
556 |
+
|
557 |
+
# b, e -> e' = sum(e), b
|
558 |
+
# {(1/5, [1/3]), (1/2, [1/12, 1/4]} -> {(1/3, [1/5, 1/2])}
|
559 |
+
comb_e = {}
|
560 |
+
for b, e in pnum_rat.items():
|
561 |
+
comb_e.setdefault(Add(*e), []).append(b)
|
562 |
+
del pnum_rat
|
563 |
+
# process them, reducing exponents to values less than 1
|
564 |
+
# and updating coeff if necessary else adding them to
|
565 |
+
# num_rat for further processing
|
566 |
+
num_rat = []
|
567 |
+
for e, b in comb_e.items():
|
568 |
+
b = cls(*b)
|
569 |
+
if e.q == 1:
|
570 |
+
coeff *= Pow(b, e)
|
571 |
+
continue
|
572 |
+
if e.p > e.q:
|
573 |
+
e_i, ep = divmod(e.p, e.q)
|
574 |
+
coeff *= Pow(b, e_i)
|
575 |
+
e = Rational(ep, e.q)
|
576 |
+
num_rat.append((b, e))
|
577 |
+
del comb_e
|
578 |
+
|
579 |
+
# extract gcd of bases in num_rat
|
580 |
+
# 2**(1/3)*6**(1/4) -> 2**(1/3+1/4)*3**(1/4)
|
581 |
+
pnew = defaultdict(list)
|
582 |
+
i = 0 # steps through num_rat which may grow
|
583 |
+
while i < len(num_rat):
|
584 |
+
bi, ei = num_rat[i]
|
585 |
+
grow = []
|
586 |
+
for j in range(i + 1, len(num_rat)):
|
587 |
+
bj, ej = num_rat[j]
|
588 |
+
g = bi.gcd(bj)
|
589 |
+
if g is not S.One:
|
590 |
+
# 4**r1*6**r2 -> 2**(r1+r2) * 2**r1 * 3**r2
|
591 |
+
# this might have a gcd with something else
|
592 |
+
e = ei + ej
|
593 |
+
if e.q == 1:
|
594 |
+
coeff *= Pow(g, e)
|
595 |
+
else:
|
596 |
+
if e.p > e.q:
|
597 |
+
e_i, ep = divmod(e.p, e.q) # change e in place
|
598 |
+
coeff *= Pow(g, e_i)
|
599 |
+
e = Rational(ep, e.q)
|
600 |
+
grow.append((g, e))
|
601 |
+
# update the jth item
|
602 |
+
num_rat[j] = (bj/g, ej)
|
603 |
+
# update bi that we are checking with
|
604 |
+
bi = bi/g
|
605 |
+
if bi is S.One:
|
606 |
+
break
|
607 |
+
if bi is not S.One:
|
608 |
+
obj = Pow(bi, ei)
|
609 |
+
if obj.is_Number:
|
610 |
+
coeff *= obj
|
611 |
+
else:
|
612 |
+
# changes like sqrt(12) -> 2*sqrt(3)
|
613 |
+
for obj in Mul.make_args(obj):
|
614 |
+
if obj.is_Number:
|
615 |
+
coeff *= obj
|
616 |
+
else:
|
617 |
+
assert obj.is_Pow
|
618 |
+
bi, ei = obj.args
|
619 |
+
pnew[ei].append(bi)
|
620 |
+
|
621 |
+
num_rat.extend(grow)
|
622 |
+
i += 1
|
623 |
+
|
624 |
+
# combine bases of the new powers
|
625 |
+
for e, b in pnew.items():
|
626 |
+
pnew[e] = cls(*b)
|
627 |
+
|
628 |
+
# handle -1 and I
|
629 |
+
if neg1e:
|
630 |
+
# treat I as (-1)**(1/2) and compute -1's total exponent
|
631 |
+
p, q = neg1e.as_numer_denom()
|
632 |
+
# if the integer part is odd, extract -1
|
633 |
+
n, p = divmod(p, q)
|
634 |
+
if n % 2:
|
635 |
+
coeff = -coeff
|
636 |
+
# if it's a multiple of 1/2 extract I
|
637 |
+
if q == 2:
|
638 |
+
c_part.append(S.ImaginaryUnit)
|
639 |
+
elif p:
|
640 |
+
# see if there is any positive base this power of
|
641 |
+
# -1 can join
|
642 |
+
neg1e = Rational(p, q)
|
643 |
+
for e, b in pnew.items():
|
644 |
+
if e == neg1e and b.is_positive:
|
645 |
+
pnew[e] = -b
|
646 |
+
break
|
647 |
+
else:
|
648 |
+
# keep it separate; we've already evaluated it as
|
649 |
+
# much as possible so evaluate=False
|
650 |
+
c_part.append(Pow(S.NegativeOne, neg1e, evaluate=False))
|
651 |
+
|
652 |
+
# add all the pnew powers
|
653 |
+
c_part.extend([Pow(b, e) for e, b in pnew.items()])
|
654 |
+
|
655 |
+
# oo, -oo
|
656 |
+
if coeff in (S.Infinity, S.NegativeInfinity):
|
657 |
+
def _handle_for_oo(c_part, coeff_sign):
|
658 |
+
new_c_part = []
|
659 |
+
for t in c_part:
|
660 |
+
if t.is_extended_positive:
|
661 |
+
continue
|
662 |
+
if t.is_extended_negative:
|
663 |
+
coeff_sign *= -1
|
664 |
+
continue
|
665 |
+
new_c_part.append(t)
|
666 |
+
return new_c_part, coeff_sign
|
667 |
+
c_part, coeff_sign = _handle_for_oo(c_part, 1)
|
668 |
+
nc_part, coeff_sign = _handle_for_oo(nc_part, coeff_sign)
|
669 |
+
coeff *= coeff_sign
|
670 |
+
|
671 |
+
# zoo
|
672 |
+
if coeff is S.ComplexInfinity:
|
673 |
+
# zoo might be
|
674 |
+
# infinite_real + bounded_im
|
675 |
+
# bounded_real + infinite_im
|
676 |
+
# infinite_real + infinite_im
|
677 |
+
# and non-zero real or imaginary will not change that status.
|
678 |
+
c_part = [c for c in c_part if not (fuzzy_not(c.is_zero) and
|
679 |
+
c.is_extended_real is not None)]
|
680 |
+
nc_part = [c for c in nc_part if not (fuzzy_not(c.is_zero) and
|
681 |
+
c.is_extended_real is not None)]
|
682 |
+
|
683 |
+
# 0
|
684 |
+
elif coeff.is_zero:
|
685 |
+
# we know for sure the result will be 0 except the multiplicand
|
686 |
+
# is infinity or a matrix
|
687 |
+
if any(isinstance(c, MatrixExpr) for c in nc_part):
|
688 |
+
return [coeff], nc_part, order_symbols
|
689 |
+
if any(c.is_finite == False for c in c_part):
|
690 |
+
return [S.NaN], [], order_symbols
|
691 |
+
return [coeff], [], order_symbols
|
692 |
+
|
693 |
+
# check for straggling Numbers that were produced
|
694 |
+
_new = []
|
695 |
+
for i in c_part:
|
696 |
+
if i.is_Number:
|
697 |
+
coeff *= i
|
698 |
+
else:
|
699 |
+
_new.append(i)
|
700 |
+
c_part = _new
|
701 |
+
|
702 |
+
# order commutative part canonically
|
703 |
+
_mulsort(c_part)
|
704 |
+
|
705 |
+
# current code expects coeff to be always in slot-0
|
706 |
+
if coeff is not S.One:
|
707 |
+
c_part.insert(0, coeff)
|
708 |
+
|
709 |
+
# we are done
|
710 |
+
if (global_parameters.distribute and not nc_part and len(c_part) == 2 and
|
711 |
+
c_part[0].is_Number and c_part[0].is_finite and c_part[1].is_Add):
|
712 |
+
# 2*(1+a) -> 2 + 2 * a
|
713 |
+
coeff = c_part[0]
|
714 |
+
c_part = [Add(*[coeff*f for f in c_part[1].args])]
|
715 |
+
|
716 |
+
return c_part, nc_part, order_symbols
|
717 |
+
|
718 |
+
def _eval_power(self, e):
|
719 |
+
|
720 |
+
# don't break up NC terms: (A*B)**3 != A**3*B**3, it is A*B*A*B*A*B
|
721 |
+
cargs, nc = self.args_cnc(split_1=False)
|
722 |
+
|
723 |
+
if e.is_Integer:
|
724 |
+
return Mul(*[Pow(b, e, evaluate=False) for b in cargs]) * \
|
725 |
+
Pow(Mul._from_args(nc), e, evaluate=False)
|
726 |
+
if e.is_Rational and e.q == 2:
|
727 |
+
if self.is_imaginary:
|
728 |
+
a = self.as_real_imag()[1]
|
729 |
+
if a.is_Rational:
|
730 |
+
from .power import integer_nthroot
|
731 |
+
n, d = abs(a/2).as_numer_denom()
|
732 |
+
n, t = integer_nthroot(n, 2)
|
733 |
+
if t:
|
734 |
+
d, t = integer_nthroot(d, 2)
|
735 |
+
if t:
|
736 |
+
from sympy.functions.elementary.complexes import sign
|
737 |
+
r = sympify(n)/d
|
738 |
+
return _unevaluated_Mul(r**e.p, (1 + sign(a)*S.ImaginaryUnit)**e.p)
|
739 |
+
|
740 |
+
p = Pow(self, e, evaluate=False)
|
741 |
+
|
742 |
+
if e.is_Rational or e.is_Float:
|
743 |
+
return p._eval_expand_power_base()
|
744 |
+
|
745 |
+
return p
|
746 |
+
|
747 |
+
@classmethod
|
748 |
+
def class_key(cls):
|
749 |
+
return 3, 0, cls.__name__
|
750 |
+
|
751 |
+
def _eval_evalf(self, prec):
|
752 |
+
c, m = self.as_coeff_Mul()
|
753 |
+
if c is S.NegativeOne:
|
754 |
+
if m.is_Mul:
|
755 |
+
rv = -AssocOp._eval_evalf(m, prec)
|
756 |
+
else:
|
757 |
+
mnew = m._eval_evalf(prec)
|
758 |
+
if mnew is not None:
|
759 |
+
m = mnew
|
760 |
+
rv = -m
|
761 |
+
else:
|
762 |
+
rv = AssocOp._eval_evalf(self, prec)
|
763 |
+
if rv.is_number:
|
764 |
+
return rv.expand()
|
765 |
+
return rv
|
766 |
+
|
767 |
+
@property
|
768 |
+
def _mpc_(self):
|
769 |
+
"""
|
770 |
+
Convert self to an mpmath mpc if possible
|
771 |
+
"""
|
772 |
+
from .numbers import Float
|
773 |
+
im_part, imag_unit = self.as_coeff_Mul()
|
774 |
+
if imag_unit is not S.ImaginaryUnit:
|
775 |
+
# ValueError may seem more reasonable but since it's a @property,
|
776 |
+
# we need to use AttributeError to keep from confusing things like
|
777 |
+
# hasattr.
|
778 |
+
raise AttributeError("Cannot convert Mul to mpc. Must be of the form Number*I")
|
779 |
+
|
780 |
+
return (Float(0)._mpf_, Float(im_part)._mpf_)
|
781 |
+
|
782 |
+
@cacheit
|
783 |
+
def as_two_terms(self):
|
784 |
+
"""Return head and tail of self.
|
785 |
+
|
786 |
+
This is the most efficient way to get the head and tail of an
|
787 |
+
expression.
|
788 |
+
|
789 |
+
- if you want only the head, use self.args[0];
|
790 |
+
- if you want to process the arguments of the tail then use
|
791 |
+
self.as_coef_mul() which gives the head and a tuple containing
|
792 |
+
the arguments of the tail when treated as a Mul.
|
793 |
+
- if you want the coefficient when self is treated as an Add
|
794 |
+
then use self.as_coeff_add()[0]
|
795 |
+
|
796 |
+
Examples
|
797 |
+
========
|
798 |
+
|
799 |
+
>>> from sympy.abc import x, y
|
800 |
+
>>> (3*x*y).as_two_terms()
|
801 |
+
(3, x*y)
|
802 |
+
"""
|
803 |
+
args = self.args
|
804 |
+
|
805 |
+
if len(args) == 1:
|
806 |
+
return S.One, self
|
807 |
+
elif len(args) == 2:
|
808 |
+
return args
|
809 |
+
|
810 |
+
else:
|
811 |
+
return args[0], self._new_rawargs(*args[1:])
|
812 |
+
|
813 |
+
@cacheit
|
814 |
+
def as_coeff_mul(self, *deps, rational=True, **kwargs):
|
815 |
+
if deps:
|
816 |
+
l1, l2 = sift(self.args, lambda x: x.has(*deps), binary=True)
|
817 |
+
return self._new_rawargs(*l2), tuple(l1)
|
818 |
+
args = self.args
|
819 |
+
if args[0].is_Number:
|
820 |
+
if not rational or args[0].is_Rational:
|
821 |
+
return args[0], args[1:]
|
822 |
+
elif args[0].is_extended_negative:
|
823 |
+
return S.NegativeOne, (-args[0],) + args[1:]
|
824 |
+
return S.One, args
|
825 |
+
|
826 |
+
def as_coeff_Mul(self, rational=False):
|
827 |
+
"""
|
828 |
+
Efficiently extract the coefficient of a product.
|
829 |
+
"""
|
830 |
+
coeff, args = self.args[0], self.args[1:]
|
831 |
+
|
832 |
+
if coeff.is_Number:
|
833 |
+
if not rational or coeff.is_Rational:
|
834 |
+
if len(args) == 1:
|
835 |
+
return coeff, args[0]
|
836 |
+
else:
|
837 |
+
return coeff, self._new_rawargs(*args)
|
838 |
+
elif coeff.is_extended_negative:
|
839 |
+
return S.NegativeOne, self._new_rawargs(*((-coeff,) + args))
|
840 |
+
return S.One, self
|
841 |
+
|
842 |
+
def as_real_imag(self, deep=True, **hints):
|
843 |
+
from sympy.functions.elementary.complexes import Abs, im, re
|
844 |
+
other = []
|
845 |
+
coeffr = []
|
846 |
+
coeffi = []
|
847 |
+
addterms = S.One
|
848 |
+
for a in self.args:
|
849 |
+
r, i = a.as_real_imag()
|
850 |
+
if i.is_zero:
|
851 |
+
coeffr.append(r)
|
852 |
+
elif r.is_zero:
|
853 |
+
coeffi.append(i*S.ImaginaryUnit)
|
854 |
+
elif a.is_commutative:
|
855 |
+
aconj = a.conjugate() if other else None
|
856 |
+
# search for complex conjugate pairs:
|
857 |
+
for i, x in enumerate(other):
|
858 |
+
if x == aconj:
|
859 |
+
coeffr.append(Abs(x)**2)
|
860 |
+
del other[i]
|
861 |
+
break
|
862 |
+
else:
|
863 |
+
if a.is_Add:
|
864 |
+
addterms *= a
|
865 |
+
else:
|
866 |
+
other.append(a)
|
867 |
+
else:
|
868 |
+
other.append(a)
|
869 |
+
m = self.func(*other)
|
870 |
+
if hints.get('ignore') == m:
|
871 |
+
return
|
872 |
+
if len(coeffi) % 2:
|
873 |
+
imco = im(coeffi.pop(0))
|
874 |
+
# all other pairs make a real factor; they will be
|
875 |
+
# put into reco below
|
876 |
+
else:
|
877 |
+
imco = S.Zero
|
878 |
+
reco = self.func(*(coeffr + coeffi))
|
879 |
+
r, i = (reco*re(m), reco*im(m))
|
880 |
+
if addterms == 1:
|
881 |
+
if m == 1:
|
882 |
+
if imco.is_zero:
|
883 |
+
return (reco, S.Zero)
|
884 |
+
else:
|
885 |
+
return (S.Zero, reco*imco)
|
886 |
+
if imco is S.Zero:
|
887 |
+
return (r, i)
|
888 |
+
return (-imco*i, imco*r)
|
889 |
+
from .function import expand_mul
|
890 |
+
addre, addim = expand_mul(addterms, deep=False).as_real_imag()
|
891 |
+
if imco is S.Zero:
|
892 |
+
return (r*addre - i*addim, i*addre + r*addim)
|
893 |
+
else:
|
894 |
+
r, i = -imco*i, imco*r
|
895 |
+
return (r*addre - i*addim, r*addim + i*addre)
|
896 |
+
|
897 |
+
@staticmethod
|
898 |
+
def _expandsums(sums):
|
899 |
+
"""
|
900 |
+
Helper function for _eval_expand_mul.
|
901 |
+
|
902 |
+
sums must be a list of instances of Basic.
|
903 |
+
"""
|
904 |
+
|
905 |
+
L = len(sums)
|
906 |
+
if L == 1:
|
907 |
+
return sums[0].args
|
908 |
+
terms = []
|
909 |
+
left = Mul._expandsums(sums[:L//2])
|
910 |
+
right = Mul._expandsums(sums[L//2:])
|
911 |
+
|
912 |
+
terms = [Mul(a, b) for a in left for b in right]
|
913 |
+
added = Add(*terms)
|
914 |
+
return Add.make_args(added) # it may have collapsed down to one term
|
915 |
+
|
916 |
+
def _eval_expand_mul(self, **hints):
|
917 |
+
from sympy.simplify.radsimp import fraction
|
918 |
+
|
919 |
+
# Handle things like 1/(x*(x + 1)), which are automatically converted
|
920 |
+
# to 1/x*1/(x + 1)
|
921 |
+
expr = self
|
922 |
+
n, d = fraction(expr)
|
923 |
+
if d.is_Mul:
|
924 |
+
n, d = [i._eval_expand_mul(**hints) if i.is_Mul else i
|
925 |
+
for i in (n, d)]
|
926 |
+
expr = n/d
|
927 |
+
if not expr.is_Mul:
|
928 |
+
return expr
|
929 |
+
|
930 |
+
plain, sums, rewrite = [], [], False
|
931 |
+
for factor in expr.args:
|
932 |
+
if factor.is_Add:
|
933 |
+
sums.append(factor)
|
934 |
+
rewrite = True
|
935 |
+
else:
|
936 |
+
if factor.is_commutative:
|
937 |
+
plain.append(factor)
|
938 |
+
else:
|
939 |
+
sums.append(Basic(factor)) # Wrapper
|
940 |
+
|
941 |
+
if not rewrite:
|
942 |
+
return expr
|
943 |
+
else:
|
944 |
+
plain = self.func(*plain)
|
945 |
+
if sums:
|
946 |
+
deep = hints.get("deep", False)
|
947 |
+
terms = self.func._expandsums(sums)
|
948 |
+
args = []
|
949 |
+
for term in terms:
|
950 |
+
t = self.func(plain, term)
|
951 |
+
if t.is_Mul and any(a.is_Add for a in t.args) and deep:
|
952 |
+
t = t._eval_expand_mul()
|
953 |
+
args.append(t)
|
954 |
+
return Add(*args)
|
955 |
+
else:
|
956 |
+
return plain
|
957 |
+
|
958 |
+
@cacheit
|
959 |
+
def _eval_derivative(self, s):
|
960 |
+
args = list(self.args)
|
961 |
+
terms = []
|
962 |
+
for i in range(len(args)):
|
963 |
+
d = args[i].diff(s)
|
964 |
+
if d:
|
965 |
+
# Note: reduce is used in step of Mul as Mul is unable to
|
966 |
+
# handle subtypes and operation priority:
|
967 |
+
terms.append(reduce(lambda x, y: x*y, (args[:i] + [d] + args[i + 1:]), S.One))
|
968 |
+
return Add.fromiter(terms)
|
969 |
+
|
970 |
+
@cacheit
|
971 |
+
def _eval_derivative_n_times(self, s, n):
|
972 |
+
from .function import AppliedUndef
|
973 |
+
from .symbol import Symbol, symbols, Dummy
|
974 |
+
if not isinstance(s, (AppliedUndef, Symbol)):
|
975 |
+
# other types of s may not be well behaved, e.g.
|
976 |
+
# (cos(x)*sin(y)).diff([[x, y, z]])
|
977 |
+
return super()._eval_derivative_n_times(s, n)
|
978 |
+
from .numbers import Integer
|
979 |
+
args = self.args
|
980 |
+
m = len(args)
|
981 |
+
if isinstance(n, (int, Integer)):
|
982 |
+
# https://en.wikipedia.org/wiki/General_Leibniz_rule#More_than_two_factors
|
983 |
+
terms = []
|
984 |
+
from sympy.ntheory.multinomial import multinomial_coefficients_iterator
|
985 |
+
for kvals, c in multinomial_coefficients_iterator(m, n):
|
986 |
+
p = Mul(*[arg.diff((s, k)) for k, arg in zip(kvals, args)])
|
987 |
+
terms.append(c * p)
|
988 |
+
return Add(*terms)
|
989 |
+
from sympy.concrete.summations import Sum
|
990 |
+
from sympy.functions.combinatorial.factorials import factorial
|
991 |
+
from sympy.functions.elementary.miscellaneous import Max
|
992 |
+
kvals = symbols("k1:%i" % m, cls=Dummy)
|
993 |
+
klast = n - sum(kvals)
|
994 |
+
nfact = factorial(n)
|
995 |
+
e, l = (# better to use the multinomial?
|
996 |
+
nfact/prod(map(factorial, kvals))/factorial(klast)*\
|
997 |
+
Mul(*[args[t].diff((s, kvals[t])) for t in range(m-1)])*\
|
998 |
+
args[-1].diff((s, Max(0, klast))),
|
999 |
+
[(k, 0, n) for k in kvals])
|
1000 |
+
return Sum(e, *l)
|
1001 |
+
|
1002 |
+
def _eval_difference_delta(self, n, step):
|
1003 |
+
from sympy.series.limitseq import difference_delta as dd
|
1004 |
+
arg0 = self.args[0]
|
1005 |
+
rest = Mul(*self.args[1:])
|
1006 |
+
return (arg0.subs(n, n + step) * dd(rest, n, step) + dd(arg0, n, step) *
|
1007 |
+
rest)
|
1008 |
+
|
1009 |
+
def _matches_simple(self, expr, repl_dict):
|
1010 |
+
# handle (w*3).matches('x*5') -> {w: x*5/3}
|
1011 |
+
coeff, terms = self.as_coeff_Mul()
|
1012 |
+
terms = Mul.make_args(terms)
|
1013 |
+
if len(terms) == 1:
|
1014 |
+
newexpr = self.__class__._combine_inverse(expr, coeff)
|
1015 |
+
return terms[0].matches(newexpr, repl_dict)
|
1016 |
+
return
|
1017 |
+
|
1018 |
+
def matches(self, expr, repl_dict=None, old=False):
|
1019 |
+
expr = sympify(expr)
|
1020 |
+
if self.is_commutative and expr.is_commutative:
|
1021 |
+
return self._matches_commutative(expr, repl_dict, old)
|
1022 |
+
elif self.is_commutative is not expr.is_commutative:
|
1023 |
+
return None
|
1024 |
+
|
1025 |
+
# Proceed only if both both expressions are non-commutative
|
1026 |
+
c1, nc1 = self.args_cnc()
|
1027 |
+
c2, nc2 = expr.args_cnc()
|
1028 |
+
c1, c2 = [c or [1] for c in [c1, c2]]
|
1029 |
+
|
1030 |
+
# TODO: Should these be self.func?
|
1031 |
+
comm_mul_self = Mul(*c1)
|
1032 |
+
comm_mul_expr = Mul(*c2)
|
1033 |
+
|
1034 |
+
repl_dict = comm_mul_self.matches(comm_mul_expr, repl_dict, old)
|
1035 |
+
|
1036 |
+
# If the commutative arguments didn't match and aren't equal, then
|
1037 |
+
# then the expression as a whole doesn't match
|
1038 |
+
if not repl_dict and c1 != c2:
|
1039 |
+
return None
|
1040 |
+
|
1041 |
+
# Now match the non-commutative arguments, expanding powers to
|
1042 |
+
# multiplications
|
1043 |
+
nc1 = Mul._matches_expand_pows(nc1)
|
1044 |
+
nc2 = Mul._matches_expand_pows(nc2)
|
1045 |
+
|
1046 |
+
repl_dict = Mul._matches_noncomm(nc1, nc2, repl_dict)
|
1047 |
+
|
1048 |
+
return repl_dict or None
|
1049 |
+
|
1050 |
+
@staticmethod
|
1051 |
+
def _matches_expand_pows(arg_list):
|
1052 |
+
new_args = []
|
1053 |
+
for arg in arg_list:
|
1054 |
+
if arg.is_Pow and arg.exp > 0:
|
1055 |
+
new_args.extend([arg.base] * arg.exp)
|
1056 |
+
else:
|
1057 |
+
new_args.append(arg)
|
1058 |
+
return new_args
|
1059 |
+
|
1060 |
+
@staticmethod
|
1061 |
+
def _matches_noncomm(nodes, targets, repl_dict=None):
|
1062 |
+
"""Non-commutative multiplication matcher.
|
1063 |
+
|
1064 |
+
`nodes` is a list of symbols within the matcher multiplication
|
1065 |
+
expression, while `targets` is a list of arguments in the
|
1066 |
+
multiplication expression being matched against.
|
1067 |
+
"""
|
1068 |
+
if repl_dict is None:
|
1069 |
+
repl_dict = {}
|
1070 |
+
else:
|
1071 |
+
repl_dict = repl_dict.copy()
|
1072 |
+
|
1073 |
+
# List of possible future states to be considered
|
1074 |
+
agenda = []
|
1075 |
+
# The current matching state, storing index in nodes and targets
|
1076 |
+
state = (0, 0)
|
1077 |
+
node_ind, target_ind = state
|
1078 |
+
# Mapping between wildcard indices and the index ranges they match
|
1079 |
+
wildcard_dict = {}
|
1080 |
+
|
1081 |
+
while target_ind < len(targets) and node_ind < len(nodes):
|
1082 |
+
node = nodes[node_ind]
|
1083 |
+
|
1084 |
+
if node.is_Wild:
|
1085 |
+
Mul._matches_add_wildcard(wildcard_dict, state)
|
1086 |
+
|
1087 |
+
states_matches = Mul._matches_new_states(wildcard_dict, state,
|
1088 |
+
nodes, targets)
|
1089 |
+
if states_matches:
|
1090 |
+
new_states, new_matches = states_matches
|
1091 |
+
agenda.extend(new_states)
|
1092 |
+
if new_matches:
|
1093 |
+
for match in new_matches:
|
1094 |
+
repl_dict[match] = new_matches[match]
|
1095 |
+
if not agenda:
|
1096 |
+
return None
|
1097 |
+
else:
|
1098 |
+
state = agenda.pop()
|
1099 |
+
node_ind, target_ind = state
|
1100 |
+
|
1101 |
+
return repl_dict
|
1102 |
+
|
1103 |
+
@staticmethod
|
1104 |
+
def _matches_add_wildcard(dictionary, state):
|
1105 |
+
node_ind, target_ind = state
|
1106 |
+
if node_ind in dictionary:
|
1107 |
+
begin, end = dictionary[node_ind]
|
1108 |
+
dictionary[node_ind] = (begin, target_ind)
|
1109 |
+
else:
|
1110 |
+
dictionary[node_ind] = (target_ind, target_ind)
|
1111 |
+
|
1112 |
+
@staticmethod
|
1113 |
+
def _matches_new_states(dictionary, state, nodes, targets):
|
1114 |
+
node_ind, target_ind = state
|
1115 |
+
node = nodes[node_ind]
|
1116 |
+
target = targets[target_ind]
|
1117 |
+
|
1118 |
+
# Don't advance at all if we've exhausted the targets but not the nodes
|
1119 |
+
if target_ind >= len(targets) - 1 and node_ind < len(nodes) - 1:
|
1120 |
+
return None
|
1121 |
+
|
1122 |
+
if node.is_Wild:
|
1123 |
+
match_attempt = Mul._matches_match_wilds(dictionary, node_ind,
|
1124 |
+
nodes, targets)
|
1125 |
+
if match_attempt:
|
1126 |
+
# If the same node has been matched before, don't return
|
1127 |
+
# anything if the current match is diverging from the previous
|
1128 |
+
# match
|
1129 |
+
other_node_inds = Mul._matches_get_other_nodes(dictionary,
|
1130 |
+
nodes, node_ind)
|
1131 |
+
for ind in other_node_inds:
|
1132 |
+
other_begin, other_end = dictionary[ind]
|
1133 |
+
curr_begin, curr_end = dictionary[node_ind]
|
1134 |
+
|
1135 |
+
other_targets = targets[other_begin:other_end + 1]
|
1136 |
+
current_targets = targets[curr_begin:curr_end + 1]
|
1137 |
+
|
1138 |
+
for curr, other in zip(current_targets, other_targets):
|
1139 |
+
if curr != other:
|
1140 |
+
return None
|
1141 |
+
|
1142 |
+
# A wildcard node can match more than one target, so only the
|
1143 |
+
# target index is advanced
|
1144 |
+
new_state = [(node_ind, target_ind + 1)]
|
1145 |
+
# Only move on to the next node if there is one
|
1146 |
+
if node_ind < len(nodes) - 1:
|
1147 |
+
new_state.append((node_ind + 1, target_ind + 1))
|
1148 |
+
return new_state, match_attempt
|
1149 |
+
else:
|
1150 |
+
# If we're not at a wildcard, then make sure we haven't exhausted
|
1151 |
+
# nodes but not targets, since in this case one node can only match
|
1152 |
+
# one target
|
1153 |
+
if node_ind >= len(nodes) - 1 and target_ind < len(targets) - 1:
|
1154 |
+
return None
|
1155 |
+
|
1156 |
+
match_attempt = node.matches(target)
|
1157 |
+
|
1158 |
+
if match_attempt:
|
1159 |
+
return [(node_ind + 1, target_ind + 1)], match_attempt
|
1160 |
+
elif node == target:
|
1161 |
+
return [(node_ind + 1, target_ind + 1)], None
|
1162 |
+
else:
|
1163 |
+
return None
|
1164 |
+
|
1165 |
+
@staticmethod
|
1166 |
+
def _matches_match_wilds(dictionary, wildcard_ind, nodes, targets):
|
1167 |
+
"""Determine matches of a wildcard with sub-expression in `target`."""
|
1168 |
+
wildcard = nodes[wildcard_ind]
|
1169 |
+
begin, end = dictionary[wildcard_ind]
|
1170 |
+
terms = targets[begin:end + 1]
|
1171 |
+
# TODO: Should this be self.func?
|
1172 |
+
mult = Mul(*terms) if len(terms) > 1 else terms[0]
|
1173 |
+
return wildcard.matches(mult)
|
1174 |
+
|
1175 |
+
@staticmethod
|
1176 |
+
def _matches_get_other_nodes(dictionary, nodes, node_ind):
|
1177 |
+
"""Find other wildcards that may have already been matched."""
|
1178 |
+
ind_node = nodes[node_ind]
|
1179 |
+
return [ind for ind in dictionary if nodes[ind] == ind_node]
|
1180 |
+
|
1181 |
+
@staticmethod
|
1182 |
+
def _combine_inverse(lhs, rhs):
|
1183 |
+
"""
|
1184 |
+
Returns lhs/rhs, but treats arguments like symbols, so things
|
1185 |
+
like oo/oo return 1 (instead of a nan) and ``I`` behaves like
|
1186 |
+
a symbol instead of sqrt(-1).
|
1187 |
+
"""
|
1188 |
+
from sympy.simplify.simplify import signsimp
|
1189 |
+
from .symbol import Dummy
|
1190 |
+
if lhs == rhs:
|
1191 |
+
return S.One
|
1192 |
+
|
1193 |
+
def check(l, r):
|
1194 |
+
if l.is_Float and r.is_comparable:
|
1195 |
+
# if both objects are added to 0 they will share the same "normalization"
|
1196 |
+
# and are more likely to compare the same. Since Add(foo, 0) will not allow
|
1197 |
+
# the 0 to pass, we use __add__ directly.
|
1198 |
+
return l.__add__(0) == r.evalf().__add__(0)
|
1199 |
+
return False
|
1200 |
+
if check(lhs, rhs) or check(rhs, lhs):
|
1201 |
+
return S.One
|
1202 |
+
if any(i.is_Pow or i.is_Mul for i in (lhs, rhs)):
|
1203 |
+
# gruntz and limit wants a literal I to not combine
|
1204 |
+
# with a power of -1
|
1205 |
+
d = Dummy('I')
|
1206 |
+
_i = {S.ImaginaryUnit: d}
|
1207 |
+
i_ = {d: S.ImaginaryUnit}
|
1208 |
+
a = lhs.xreplace(_i).as_powers_dict()
|
1209 |
+
b = rhs.xreplace(_i).as_powers_dict()
|
1210 |
+
blen = len(b)
|
1211 |
+
for bi in tuple(b.keys()):
|
1212 |
+
if bi in a:
|
1213 |
+
a[bi] -= b.pop(bi)
|
1214 |
+
if not a[bi]:
|
1215 |
+
a.pop(bi)
|
1216 |
+
if len(b) != blen:
|
1217 |
+
lhs = Mul(*[k**v for k, v in a.items()]).xreplace(i_)
|
1218 |
+
rhs = Mul(*[k**v for k, v in b.items()]).xreplace(i_)
|
1219 |
+
rv = lhs/rhs
|
1220 |
+
srv = signsimp(rv)
|
1221 |
+
return srv if srv.is_Number else rv
|
1222 |
+
|
1223 |
+
def as_powers_dict(self):
|
1224 |
+
d = defaultdict(int)
|
1225 |
+
for term in self.args:
|
1226 |
+
for b, e in term.as_powers_dict().items():
|
1227 |
+
d[b] += e
|
1228 |
+
return d
|
1229 |
+
|
1230 |
+
def as_numer_denom(self):
|
1231 |
+
# don't use _from_args to rebuild the numerators and denominators
|
1232 |
+
# as the order is not guaranteed to be the same once they have
|
1233 |
+
# been separated from each other
|
1234 |
+
numers, denoms = list(zip(*[f.as_numer_denom() for f in self.args]))
|
1235 |
+
return self.func(*numers), self.func(*denoms)
|
1236 |
+
|
1237 |
+
def as_base_exp(self):
|
1238 |
+
e1 = None
|
1239 |
+
bases = []
|
1240 |
+
nc = 0
|
1241 |
+
for m in self.args:
|
1242 |
+
b, e = m.as_base_exp()
|
1243 |
+
if not b.is_commutative:
|
1244 |
+
nc += 1
|
1245 |
+
if e1 is None:
|
1246 |
+
e1 = e
|
1247 |
+
elif e != e1 or nc > 1:
|
1248 |
+
return self, S.One
|
1249 |
+
bases.append(b)
|
1250 |
+
return self.func(*bases), e1
|
1251 |
+
|
1252 |
+
def _eval_is_polynomial(self, syms):
|
1253 |
+
return all(term._eval_is_polynomial(syms) for term in self.args)
|
1254 |
+
|
1255 |
+
def _eval_is_rational_function(self, syms):
|
1256 |
+
return all(term._eval_is_rational_function(syms) for term in self.args)
|
1257 |
+
|
1258 |
+
def _eval_is_meromorphic(self, x, a):
|
1259 |
+
return _fuzzy_group((arg.is_meromorphic(x, a) for arg in self.args),
|
1260 |
+
quick_exit=True)
|
1261 |
+
|
1262 |
+
def _eval_is_algebraic_expr(self, syms):
|
1263 |
+
return all(term._eval_is_algebraic_expr(syms) for term in self.args)
|
1264 |
+
|
1265 |
+
_eval_is_commutative = lambda self: _fuzzy_group(
|
1266 |
+
a.is_commutative for a in self.args)
|
1267 |
+
|
1268 |
+
def _eval_is_complex(self):
|
1269 |
+
comp = _fuzzy_group(a.is_complex for a in self.args)
|
1270 |
+
if comp is False:
|
1271 |
+
if any(a.is_infinite for a in self.args):
|
1272 |
+
if any(a.is_zero is not False for a in self.args):
|
1273 |
+
return None
|
1274 |
+
return False
|
1275 |
+
return comp
|
1276 |
+
|
1277 |
+
def _eval_is_zero_infinite_helper(self):
|
1278 |
+
#
|
1279 |
+
# Helper used by _eval_is_zero and _eval_is_infinite.
|
1280 |
+
#
|
1281 |
+
# Three-valued logic is tricky so let us reason this carefully. It
|
1282 |
+
# would be nice to say that we just check is_zero/is_infinite in all
|
1283 |
+
# args but we need to be careful about the case that one arg is zero
|
1284 |
+
# and another is infinite like Mul(0, oo) or more importantly a case
|
1285 |
+
# where it is not known if the arguments are zero or infinite like
|
1286 |
+
# Mul(y, 1/x). If either y or x could be zero then there is a
|
1287 |
+
# *possibility* that we have Mul(0, oo) which should give None for both
|
1288 |
+
# is_zero and is_infinite.
|
1289 |
+
#
|
1290 |
+
# We keep track of whether we have seen a zero or infinity but we also
|
1291 |
+
# need to keep track of whether we have *possibly* seen one which
|
1292 |
+
# would be indicated by None.
|
1293 |
+
#
|
1294 |
+
# For each argument there is the possibility that is_zero might give
|
1295 |
+
# True, False or None and likewise that is_infinite might give True,
|
1296 |
+
# False or None, giving 9 combinations. The True cases for is_zero and
|
1297 |
+
# is_infinite are mutually exclusive though so there are 3 main cases:
|
1298 |
+
#
|
1299 |
+
# - is_zero = True
|
1300 |
+
# - is_infinite = True
|
1301 |
+
# - is_zero and is_infinite are both either False or None
|
1302 |
+
#
|
1303 |
+
# At the end seen_zero and seen_infinite can be any of 9 combinations
|
1304 |
+
# of True/False/None. Unless one is False though we cannot return
|
1305 |
+
# anything except None:
|
1306 |
+
#
|
1307 |
+
# - is_zero=True needs seen_zero=True and seen_infinite=False
|
1308 |
+
# - is_zero=False needs seen_zero=False
|
1309 |
+
# - is_infinite=True needs seen_infinite=True and seen_zero=False
|
1310 |
+
# - is_infinite=False needs seen_infinite=False
|
1311 |
+
# - anything else gives both is_zero=None and is_infinite=None
|
1312 |
+
#
|
1313 |
+
# The loop only sets the flags to True or None and never back to False.
|
1314 |
+
# Hence as soon as neither flag is False we exit early returning None.
|
1315 |
+
# In particular as soon as we encounter a single arg that has
|
1316 |
+
# is_zero=is_infinite=None we exit. This is a common case since it is
|
1317 |
+
# the default assumptions for a Symbol and also the case for most
|
1318 |
+
# expressions containing such a symbol. The early exit gives a big
|
1319 |
+
# speedup for something like Mul(*symbols('x:1000')).is_zero.
|
1320 |
+
#
|
1321 |
+
seen_zero = seen_infinite = False
|
1322 |
+
|
1323 |
+
for a in self.args:
|
1324 |
+
if a.is_zero:
|
1325 |
+
if seen_infinite is not False:
|
1326 |
+
return None, None
|
1327 |
+
seen_zero = True
|
1328 |
+
elif a.is_infinite:
|
1329 |
+
if seen_zero is not False:
|
1330 |
+
return None, None
|
1331 |
+
seen_infinite = True
|
1332 |
+
else:
|
1333 |
+
if seen_zero is False and a.is_zero is None:
|
1334 |
+
if seen_infinite is not False:
|
1335 |
+
return None, None
|
1336 |
+
seen_zero = None
|
1337 |
+
if seen_infinite is False and a.is_infinite is None:
|
1338 |
+
if seen_zero is not False:
|
1339 |
+
return None, None
|
1340 |
+
seen_infinite = None
|
1341 |
+
|
1342 |
+
return seen_zero, seen_infinite
|
1343 |
+
|
1344 |
+
def _eval_is_zero(self):
|
1345 |
+
# True iff any arg is zero and no arg is infinite but need to handle
|
1346 |
+
# three valued logic carefully.
|
1347 |
+
seen_zero, seen_infinite = self._eval_is_zero_infinite_helper()
|
1348 |
+
|
1349 |
+
if seen_zero is False:
|
1350 |
+
return False
|
1351 |
+
elif seen_zero is True and seen_infinite is False:
|
1352 |
+
return True
|
1353 |
+
else:
|
1354 |
+
return None
|
1355 |
+
|
1356 |
+
def _eval_is_infinite(self):
|
1357 |
+
# True iff any arg is infinite and no arg is zero but need to handle
|
1358 |
+
# three valued logic carefully.
|
1359 |
+
seen_zero, seen_infinite = self._eval_is_zero_infinite_helper()
|
1360 |
+
|
1361 |
+
if seen_infinite is True and seen_zero is False:
|
1362 |
+
return True
|
1363 |
+
elif seen_infinite is False:
|
1364 |
+
return False
|
1365 |
+
else:
|
1366 |
+
return None
|
1367 |
+
|
1368 |
+
# We do not need to implement _eval_is_finite because the assumptions
|
1369 |
+
# system can infer it from finite = not infinite.
|
1370 |
+
|
1371 |
+
def _eval_is_rational(self):
|
1372 |
+
r = _fuzzy_group((a.is_rational for a in self.args), quick_exit=True)
|
1373 |
+
if r:
|
1374 |
+
return r
|
1375 |
+
elif r is False:
|
1376 |
+
# All args except one are rational
|
1377 |
+
if all(a.is_zero is False for a in self.args):
|
1378 |
+
return False
|
1379 |
+
|
1380 |
+
def _eval_is_algebraic(self):
|
1381 |
+
r = _fuzzy_group((a.is_algebraic for a in self.args), quick_exit=True)
|
1382 |
+
if r:
|
1383 |
+
return r
|
1384 |
+
elif r is False:
|
1385 |
+
# All args except one are algebraic
|
1386 |
+
if all(a.is_zero is False for a in self.args):
|
1387 |
+
return False
|
1388 |
+
|
1389 |
+
# without involving odd/even checks this code would suffice:
|
1390 |
+
#_eval_is_integer = lambda self: _fuzzy_group(
|
1391 |
+
# (a.is_integer for a in self.args), quick_exit=True)
|
1392 |
+
def _eval_is_integer(self):
|
1393 |
+
from sympy.ntheory.factor_ import trailing
|
1394 |
+
is_rational = self._eval_is_rational()
|
1395 |
+
if is_rational is False:
|
1396 |
+
return False
|
1397 |
+
|
1398 |
+
numerators = []
|
1399 |
+
denominators = []
|
1400 |
+
unknown = False
|
1401 |
+
for a in self.args:
|
1402 |
+
hit = False
|
1403 |
+
if a.is_integer:
|
1404 |
+
if abs(a) is not S.One:
|
1405 |
+
numerators.append(a)
|
1406 |
+
elif a.is_Rational:
|
1407 |
+
n, d = a.as_numer_denom()
|
1408 |
+
if abs(n) is not S.One:
|
1409 |
+
numerators.append(n)
|
1410 |
+
if d is not S.One:
|
1411 |
+
denominators.append(d)
|
1412 |
+
elif a.is_Pow:
|
1413 |
+
b, e = a.as_base_exp()
|
1414 |
+
if not b.is_integer or not e.is_integer:
|
1415 |
+
hit = unknown = True
|
1416 |
+
if e.is_negative:
|
1417 |
+
denominators.append(2 if a is S.Half else
|
1418 |
+
Pow(a, S.NegativeOne))
|
1419 |
+
elif not hit:
|
1420 |
+
# int b and pos int e: a = b**e is integer
|
1421 |
+
assert not e.is_positive
|
1422 |
+
# for rational self and e equal to zero: a = b**e is 1
|
1423 |
+
assert not e.is_zero
|
1424 |
+
return # sign of e unknown -> self.is_integer unknown
|
1425 |
+
else:
|
1426 |
+
# x**2, 2**x, or x**y with x and y int-unknown -> unknown
|
1427 |
+
return
|
1428 |
+
else:
|
1429 |
+
return
|
1430 |
+
|
1431 |
+
if not denominators and not unknown:
|
1432 |
+
return True
|
1433 |
+
|
1434 |
+
allodd = lambda x: all(i.is_odd for i in x)
|
1435 |
+
alleven = lambda x: all(i.is_even for i in x)
|
1436 |
+
anyeven = lambda x: any(i.is_even for i in x)
|
1437 |
+
|
1438 |
+
from .relational import is_gt
|
1439 |
+
if not numerators and denominators and all(
|
1440 |
+
is_gt(_, S.One) for _ in denominators):
|
1441 |
+
return False
|
1442 |
+
elif unknown:
|
1443 |
+
return
|
1444 |
+
elif allodd(numerators) and anyeven(denominators):
|
1445 |
+
return False
|
1446 |
+
elif anyeven(numerators) and denominators == [2]:
|
1447 |
+
return True
|
1448 |
+
elif alleven(numerators) and allodd(denominators
|
1449 |
+
) and (Mul(*denominators, evaluate=False) - 1
|
1450 |
+
).is_positive:
|
1451 |
+
return False
|
1452 |
+
if len(denominators) == 1:
|
1453 |
+
d = denominators[0]
|
1454 |
+
if d.is_Integer and d.is_even:
|
1455 |
+
# if minimal power of 2 in num vs den is not
|
1456 |
+
# negative then we have an integer
|
1457 |
+
if (Add(*[i.as_base_exp()[1] for i in
|
1458 |
+
numerators if i.is_even]) - trailing(d.p)
|
1459 |
+
).is_nonnegative:
|
1460 |
+
return True
|
1461 |
+
if len(numerators) == 1:
|
1462 |
+
n = numerators[0]
|
1463 |
+
if n.is_Integer and n.is_even:
|
1464 |
+
# if minimal power of 2 in den vs num is positive
|
1465 |
+
# then we have have a non-integer
|
1466 |
+
if (Add(*[i.as_base_exp()[1] for i in
|
1467 |
+
denominators if i.is_even]) - trailing(n.p)
|
1468 |
+
).is_positive:
|
1469 |
+
return False
|
1470 |
+
|
1471 |
+
def _eval_is_polar(self):
|
1472 |
+
has_polar = any(arg.is_polar for arg in self.args)
|
1473 |
+
return has_polar and \
|
1474 |
+
all(arg.is_polar or arg.is_positive for arg in self.args)
|
1475 |
+
|
1476 |
+
def _eval_is_extended_real(self):
|
1477 |
+
return self._eval_real_imag(True)
|
1478 |
+
|
1479 |
+
def _eval_real_imag(self, real):
|
1480 |
+
zero = False
|
1481 |
+
t_not_re_im = None
|
1482 |
+
|
1483 |
+
for t in self.args:
|
1484 |
+
if (t.is_complex or t.is_infinite) is False and t.is_extended_real is False:
|
1485 |
+
return False
|
1486 |
+
elif t.is_imaginary: # I
|
1487 |
+
real = not real
|
1488 |
+
elif t.is_extended_real: # 2
|
1489 |
+
if not zero:
|
1490 |
+
z = t.is_zero
|
1491 |
+
if not z and zero is False:
|
1492 |
+
zero = z
|
1493 |
+
elif z:
|
1494 |
+
if all(a.is_finite for a in self.args):
|
1495 |
+
return True
|
1496 |
+
return
|
1497 |
+
elif t.is_extended_real is False:
|
1498 |
+
# symbolic or literal like `2 + I` or symbolic imaginary
|
1499 |
+
if t_not_re_im:
|
1500 |
+
return # complex terms might cancel
|
1501 |
+
t_not_re_im = t
|
1502 |
+
elif t.is_imaginary is False: # symbolic like `2` or `2 + I`
|
1503 |
+
if t_not_re_im:
|
1504 |
+
return # complex terms might cancel
|
1505 |
+
t_not_re_im = t
|
1506 |
+
else:
|
1507 |
+
return
|
1508 |
+
|
1509 |
+
if t_not_re_im:
|
1510 |
+
if t_not_re_im.is_extended_real is False:
|
1511 |
+
if real: # like 3
|
1512 |
+
return zero # 3*(smthng like 2 + I or i) is not real
|
1513 |
+
if t_not_re_im.is_imaginary is False: # symbolic 2 or 2 + I
|
1514 |
+
if not real: # like I
|
1515 |
+
return zero # I*(smthng like 2 or 2 + I) is not real
|
1516 |
+
elif zero is False:
|
1517 |
+
return real # can't be trumped by 0
|
1518 |
+
elif real:
|
1519 |
+
return real # doesn't matter what zero is
|
1520 |
+
|
1521 |
+
def _eval_is_imaginary(self):
|
1522 |
+
if all(a.is_zero is False and a.is_finite for a in self.args):
|
1523 |
+
return self._eval_real_imag(False)
|
1524 |
+
|
1525 |
+
def _eval_is_hermitian(self):
|
1526 |
+
return self._eval_herm_antiherm(True)
|
1527 |
+
|
1528 |
+
def _eval_is_antihermitian(self):
|
1529 |
+
return self._eval_herm_antiherm(False)
|
1530 |
+
|
1531 |
+
def _eval_herm_antiherm(self, herm):
|
1532 |
+
for t in self.args:
|
1533 |
+
if t.is_hermitian is None or t.is_antihermitian is None:
|
1534 |
+
return
|
1535 |
+
if t.is_hermitian:
|
1536 |
+
continue
|
1537 |
+
elif t.is_antihermitian:
|
1538 |
+
herm = not herm
|
1539 |
+
else:
|
1540 |
+
return
|
1541 |
+
|
1542 |
+
if herm is not False:
|
1543 |
+
return herm
|
1544 |
+
|
1545 |
+
is_zero = self._eval_is_zero()
|
1546 |
+
if is_zero:
|
1547 |
+
return True
|
1548 |
+
elif is_zero is False:
|
1549 |
+
return herm
|
1550 |
+
|
1551 |
+
def _eval_is_irrational(self):
|
1552 |
+
for t in self.args:
|
1553 |
+
a = t.is_irrational
|
1554 |
+
if a:
|
1555 |
+
others = list(self.args)
|
1556 |
+
others.remove(t)
|
1557 |
+
if all((x.is_rational and fuzzy_not(x.is_zero)) is True for x in others):
|
1558 |
+
return True
|
1559 |
+
return
|
1560 |
+
if a is None:
|
1561 |
+
return
|
1562 |
+
if all(x.is_real for x in self.args):
|
1563 |
+
return False
|
1564 |
+
|
1565 |
+
def _eval_is_extended_positive(self):
|
1566 |
+
"""Return True if self is positive, False if not, and None if it
|
1567 |
+
cannot be determined.
|
1568 |
+
|
1569 |
+
Explanation
|
1570 |
+
===========
|
1571 |
+
|
1572 |
+
This algorithm is non-recursive and works by keeping track of the
|
1573 |
+
sign which changes when a negative or nonpositive is encountered.
|
1574 |
+
Whether a nonpositive or nonnegative is seen is also tracked since
|
1575 |
+
the presence of these makes it impossible to return True, but
|
1576 |
+
possible to return False if the end result is nonpositive. e.g.
|
1577 |
+
|
1578 |
+
pos * neg * nonpositive -> pos or zero -> None is returned
|
1579 |
+
pos * neg * nonnegative -> neg or zero -> False is returned
|
1580 |
+
"""
|
1581 |
+
return self._eval_pos_neg(1)
|
1582 |
+
|
1583 |
+
def _eval_pos_neg(self, sign):
|
1584 |
+
saw_NON = saw_NOT = False
|
1585 |
+
for t in self.args:
|
1586 |
+
if t.is_extended_positive:
|
1587 |
+
continue
|
1588 |
+
elif t.is_extended_negative:
|
1589 |
+
sign = -sign
|
1590 |
+
elif t.is_zero:
|
1591 |
+
if all(a.is_finite for a in self.args):
|
1592 |
+
return False
|
1593 |
+
return
|
1594 |
+
elif t.is_extended_nonpositive:
|
1595 |
+
sign = -sign
|
1596 |
+
saw_NON = True
|
1597 |
+
elif t.is_extended_nonnegative:
|
1598 |
+
saw_NON = True
|
1599 |
+
# FIXME: is_positive/is_negative is False doesn't take account of
|
1600 |
+
# Symbol('x', infinite=True, extended_real=True) which has
|
1601 |
+
# e.g. is_positive is False but has uncertain sign.
|
1602 |
+
elif t.is_positive is False:
|
1603 |
+
sign = -sign
|
1604 |
+
if saw_NOT:
|
1605 |
+
return
|
1606 |
+
saw_NOT = True
|
1607 |
+
elif t.is_negative is False:
|
1608 |
+
if saw_NOT:
|
1609 |
+
return
|
1610 |
+
saw_NOT = True
|
1611 |
+
else:
|
1612 |
+
return
|
1613 |
+
if sign == 1 and saw_NON is False and saw_NOT is False:
|
1614 |
+
return True
|
1615 |
+
if sign < 0:
|
1616 |
+
return False
|
1617 |
+
|
1618 |
+
def _eval_is_extended_negative(self):
|
1619 |
+
return self._eval_pos_neg(-1)
|
1620 |
+
|
1621 |
+
def _eval_is_odd(self):
|
1622 |
+
is_integer = self._eval_is_integer()
|
1623 |
+
if is_integer is not True:
|
1624 |
+
return is_integer
|
1625 |
+
|
1626 |
+
from sympy.simplify.radsimp import fraction
|
1627 |
+
n, d = fraction(self)
|
1628 |
+
if d.is_Integer and d.is_even:
|
1629 |
+
from sympy.ntheory.factor_ import trailing
|
1630 |
+
# if minimal power of 2 in num vs den is
|
1631 |
+
# positive then we have an even number
|
1632 |
+
if (Add(*[i.as_base_exp()[1] for i in
|
1633 |
+
Mul.make_args(n) if i.is_even]) - trailing(d.p)
|
1634 |
+
).is_positive:
|
1635 |
+
return False
|
1636 |
+
return
|
1637 |
+
r, acc = True, 1
|
1638 |
+
for t in self.args:
|
1639 |
+
if abs(t) is S.One:
|
1640 |
+
continue
|
1641 |
+
if t.is_even:
|
1642 |
+
return False
|
1643 |
+
if r is False:
|
1644 |
+
pass
|
1645 |
+
elif acc != 1 and (acc + t).is_odd:
|
1646 |
+
r = False
|
1647 |
+
elif t.is_even is None:
|
1648 |
+
r = None
|
1649 |
+
acc = t
|
1650 |
+
return r
|
1651 |
+
|
1652 |
+
def _eval_is_even(self):
|
1653 |
+
from sympy.simplify.radsimp import fraction
|
1654 |
+
n, d = fraction(self)
|
1655 |
+
if n.is_Integer and n.is_even:
|
1656 |
+
# if minimal power of 2 in den vs num is not
|
1657 |
+
# negative then this is not an integer and
|
1658 |
+
# can't be even
|
1659 |
+
from sympy.ntheory.factor_ import trailing
|
1660 |
+
if (Add(*[i.as_base_exp()[1] for i in
|
1661 |
+
Mul.make_args(d) if i.is_even]) - trailing(n.p)
|
1662 |
+
).is_nonnegative:
|
1663 |
+
return False
|
1664 |
+
|
1665 |
+
def _eval_is_composite(self):
|
1666 |
+
"""
|
1667 |
+
Here we count the number of arguments that have a minimum value
|
1668 |
+
greater than two.
|
1669 |
+
If there are more than one of such a symbol then the result is composite.
|
1670 |
+
Else, the result cannot be determined.
|
1671 |
+
"""
|
1672 |
+
number_of_args = 0 # count of symbols with minimum value greater than one
|
1673 |
+
for arg in self.args:
|
1674 |
+
if not (arg.is_integer and arg.is_positive):
|
1675 |
+
return None
|
1676 |
+
if (arg-1).is_positive:
|
1677 |
+
number_of_args += 1
|
1678 |
+
|
1679 |
+
if number_of_args > 1:
|
1680 |
+
return True
|
1681 |
+
|
1682 |
+
def _eval_subs(self, old, new):
|
1683 |
+
from sympy.functions.elementary.complexes import sign
|
1684 |
+
from sympy.ntheory.factor_ import multiplicity
|
1685 |
+
from sympy.simplify.powsimp import powdenest
|
1686 |
+
from sympy.simplify.radsimp import fraction
|
1687 |
+
|
1688 |
+
if not old.is_Mul:
|
1689 |
+
return None
|
1690 |
+
|
1691 |
+
# try keep replacement literal so -2*x doesn't replace 4*x
|
1692 |
+
if old.args[0].is_Number and old.args[0] < 0:
|
1693 |
+
if self.args[0].is_Number:
|
1694 |
+
if self.args[0] < 0:
|
1695 |
+
return self._subs(-old, -new)
|
1696 |
+
return None
|
1697 |
+
|
1698 |
+
def base_exp(a):
|
1699 |
+
# if I and -1 are in a Mul, they get both end up with
|
1700 |
+
# a -1 base (see issue 6421); all we want here are the
|
1701 |
+
# true Pow or exp separated into base and exponent
|
1702 |
+
from sympy.functions.elementary.exponential import exp
|
1703 |
+
if a.is_Pow or isinstance(a, exp):
|
1704 |
+
return a.as_base_exp()
|
1705 |
+
return a, S.One
|
1706 |
+
|
1707 |
+
def breakup(eq):
|
1708 |
+
"""break up powers of eq when treated as a Mul:
|
1709 |
+
b**(Rational*e) -> b**e, Rational
|
1710 |
+
commutatives come back as a dictionary {b**e: Rational}
|
1711 |
+
noncommutatives come back as a list [(b**e, Rational)]
|
1712 |
+
"""
|
1713 |
+
|
1714 |
+
(c, nc) = (defaultdict(int), [])
|
1715 |
+
for a in Mul.make_args(eq):
|
1716 |
+
a = powdenest(a)
|
1717 |
+
(b, e) = base_exp(a)
|
1718 |
+
if e is not S.One:
|
1719 |
+
(co, _) = e.as_coeff_mul()
|
1720 |
+
b = Pow(b, e/co)
|
1721 |
+
e = co
|
1722 |
+
if a.is_commutative:
|
1723 |
+
c[b] += e
|
1724 |
+
else:
|
1725 |
+
nc.append([b, e])
|
1726 |
+
return (c, nc)
|
1727 |
+
|
1728 |
+
def rejoin(b, co):
|
1729 |
+
"""
|
1730 |
+
Put rational back with exponent; in general this is not ok, but
|
1731 |
+
since we took it from the exponent for analysis, it's ok to put
|
1732 |
+
it back.
|
1733 |
+
"""
|
1734 |
+
|
1735 |
+
(b, e) = base_exp(b)
|
1736 |
+
return Pow(b, e*co)
|
1737 |
+
|
1738 |
+
def ndiv(a, b):
|
1739 |
+
"""if b divides a in an extractive way (like 1/4 divides 1/2
|
1740 |
+
but not vice versa, and 2/5 does not divide 1/3) then return
|
1741 |
+
the integer number of times it divides, else return 0.
|
1742 |
+
"""
|
1743 |
+
if not b.q % a.q or not a.q % b.q:
|
1744 |
+
return int(a/b)
|
1745 |
+
return 0
|
1746 |
+
|
1747 |
+
# give Muls in the denominator a chance to be changed (see issue 5651)
|
1748 |
+
# rv will be the default return value
|
1749 |
+
rv = None
|
1750 |
+
n, d = fraction(self)
|
1751 |
+
self2 = self
|
1752 |
+
if d is not S.One:
|
1753 |
+
self2 = n._subs(old, new)/d._subs(old, new)
|
1754 |
+
if not self2.is_Mul:
|
1755 |
+
return self2._subs(old, new)
|
1756 |
+
if self2 != self:
|
1757 |
+
rv = self2
|
1758 |
+
|
1759 |
+
# Now continue with regular substitution.
|
1760 |
+
|
1761 |
+
# handle the leading coefficient and use it to decide if anything
|
1762 |
+
# should even be started; we always know where to find the Rational
|
1763 |
+
# so it's a quick test
|
1764 |
+
|
1765 |
+
co_self = self2.args[0]
|
1766 |
+
co_old = old.args[0]
|
1767 |
+
co_xmul = None
|
1768 |
+
if co_old.is_Rational and co_self.is_Rational:
|
1769 |
+
# if coeffs are the same there will be no updating to do
|
1770 |
+
# below after breakup() step; so skip (and keep co_xmul=None)
|
1771 |
+
if co_old != co_self:
|
1772 |
+
co_xmul = co_self.extract_multiplicatively(co_old)
|
1773 |
+
elif co_old.is_Rational:
|
1774 |
+
return rv
|
1775 |
+
|
1776 |
+
# break self and old into factors
|
1777 |
+
|
1778 |
+
(c, nc) = breakup(self2)
|
1779 |
+
(old_c, old_nc) = breakup(old)
|
1780 |
+
|
1781 |
+
# update the coefficients if we had an extraction
|
1782 |
+
# e.g. if co_self were 2*(3/35*x)**2 and co_old = 3/5
|
1783 |
+
# then co_self in c is replaced by (3/5)**2 and co_residual
|
1784 |
+
# is 2*(1/7)**2
|
1785 |
+
|
1786 |
+
if co_xmul and co_xmul.is_Rational and abs(co_old) != 1:
|
1787 |
+
mult = S(multiplicity(abs(co_old), co_self))
|
1788 |
+
c.pop(co_self)
|
1789 |
+
if co_old in c:
|
1790 |
+
c[co_old] += mult
|
1791 |
+
else:
|
1792 |
+
c[co_old] = mult
|
1793 |
+
co_residual = co_self/co_old**mult
|
1794 |
+
else:
|
1795 |
+
co_residual = 1
|
1796 |
+
|
1797 |
+
# do quick tests to see if we can't succeed
|
1798 |
+
|
1799 |
+
ok = True
|
1800 |
+
if len(old_nc) > len(nc):
|
1801 |
+
# more non-commutative terms
|
1802 |
+
ok = False
|
1803 |
+
elif len(old_c) > len(c):
|
1804 |
+
# more commutative terms
|
1805 |
+
ok = False
|
1806 |
+
elif {i[0] for i in old_nc}.difference({i[0] for i in nc}):
|
1807 |
+
# unmatched non-commutative bases
|
1808 |
+
ok = False
|
1809 |
+
elif set(old_c).difference(set(c)):
|
1810 |
+
# unmatched commutative terms
|
1811 |
+
ok = False
|
1812 |
+
elif any(sign(c[b]) != sign(old_c[b]) for b in old_c):
|
1813 |
+
# differences in sign
|
1814 |
+
ok = False
|
1815 |
+
if not ok:
|
1816 |
+
return rv
|
1817 |
+
|
1818 |
+
if not old_c:
|
1819 |
+
cdid = None
|
1820 |
+
else:
|
1821 |
+
rat = []
|
1822 |
+
for (b, old_e) in old_c.items():
|
1823 |
+
c_e = c[b]
|
1824 |
+
rat.append(ndiv(c_e, old_e))
|
1825 |
+
if not rat[-1]:
|
1826 |
+
return rv
|
1827 |
+
cdid = min(rat)
|
1828 |
+
|
1829 |
+
if not old_nc:
|
1830 |
+
ncdid = None
|
1831 |
+
for i in range(len(nc)):
|
1832 |
+
nc[i] = rejoin(*nc[i])
|
1833 |
+
else:
|
1834 |
+
ncdid = 0 # number of nc replacements we did
|
1835 |
+
take = len(old_nc) # how much to look at each time
|
1836 |
+
limit = cdid or S.Infinity # max number that we can take
|
1837 |
+
failed = [] # failed terms will need subs if other terms pass
|
1838 |
+
i = 0
|
1839 |
+
while limit and i + take <= len(nc):
|
1840 |
+
hit = False
|
1841 |
+
|
1842 |
+
# the bases must be equivalent in succession, and
|
1843 |
+
# the powers must be extractively compatible on the
|
1844 |
+
# first and last factor but equal in between.
|
1845 |
+
|
1846 |
+
rat = []
|
1847 |
+
for j in range(take):
|
1848 |
+
if nc[i + j][0] != old_nc[j][0]:
|
1849 |
+
break
|
1850 |
+
elif j == 0:
|
1851 |
+
rat.append(ndiv(nc[i + j][1], old_nc[j][1]))
|
1852 |
+
elif j == take - 1:
|
1853 |
+
rat.append(ndiv(nc[i + j][1], old_nc[j][1]))
|
1854 |
+
elif nc[i + j][1] != old_nc[j][1]:
|
1855 |
+
break
|
1856 |
+
else:
|
1857 |
+
rat.append(1)
|
1858 |
+
j += 1
|
1859 |
+
else:
|
1860 |
+
ndo = min(rat)
|
1861 |
+
if ndo:
|
1862 |
+
if take == 1:
|
1863 |
+
if cdid:
|
1864 |
+
ndo = min(cdid, ndo)
|
1865 |
+
nc[i] = Pow(new, ndo)*rejoin(nc[i][0],
|
1866 |
+
nc[i][1] - ndo*old_nc[0][1])
|
1867 |
+
else:
|
1868 |
+
ndo = 1
|
1869 |
+
|
1870 |
+
# the left residual
|
1871 |
+
|
1872 |
+
l = rejoin(nc[i][0], nc[i][1] - ndo*
|
1873 |
+
old_nc[0][1])
|
1874 |
+
|
1875 |
+
# eliminate all middle terms
|
1876 |
+
|
1877 |
+
mid = new
|
1878 |
+
|
1879 |
+
# the right residual (which may be the same as the middle if take == 2)
|
1880 |
+
|
1881 |
+
ir = i + take - 1
|
1882 |
+
r = (nc[ir][0], nc[ir][1] - ndo*
|
1883 |
+
old_nc[-1][1])
|
1884 |
+
if r[1]:
|
1885 |
+
if i + take < len(nc):
|
1886 |
+
nc[i:i + take] = [l*mid, r]
|
1887 |
+
else:
|
1888 |
+
r = rejoin(*r)
|
1889 |
+
nc[i:i + take] = [l*mid*r]
|
1890 |
+
else:
|
1891 |
+
|
1892 |
+
# there was nothing left on the right
|
1893 |
+
|
1894 |
+
nc[i:i + take] = [l*mid]
|
1895 |
+
|
1896 |
+
limit -= ndo
|
1897 |
+
ncdid += ndo
|
1898 |
+
hit = True
|
1899 |
+
if not hit:
|
1900 |
+
|
1901 |
+
# do the subs on this failing factor
|
1902 |
+
|
1903 |
+
failed.append(i)
|
1904 |
+
i += 1
|
1905 |
+
else:
|
1906 |
+
|
1907 |
+
if not ncdid:
|
1908 |
+
return rv
|
1909 |
+
|
1910 |
+
# although we didn't fail, certain nc terms may have
|
1911 |
+
# failed so we rebuild them after attempting a partial
|
1912 |
+
# subs on them
|
1913 |
+
|
1914 |
+
failed.extend(range(i, len(nc)))
|
1915 |
+
for i in failed:
|
1916 |
+
nc[i] = rejoin(*nc[i]).subs(old, new)
|
1917 |
+
|
1918 |
+
# rebuild the expression
|
1919 |
+
|
1920 |
+
if cdid is None:
|
1921 |
+
do = ncdid
|
1922 |
+
elif ncdid is None:
|
1923 |
+
do = cdid
|
1924 |
+
else:
|
1925 |
+
do = min(ncdid, cdid)
|
1926 |
+
|
1927 |
+
margs = []
|
1928 |
+
for b in c:
|
1929 |
+
if b in old_c:
|
1930 |
+
|
1931 |
+
# calculate the new exponent
|
1932 |
+
|
1933 |
+
e = c[b] - old_c[b]*do
|
1934 |
+
margs.append(rejoin(b, e))
|
1935 |
+
else:
|
1936 |
+
margs.append(rejoin(b.subs(old, new), c[b]))
|
1937 |
+
if cdid and not ncdid:
|
1938 |
+
|
1939 |
+
# in case we are replacing commutative with non-commutative,
|
1940 |
+
# we want the new term to come at the front just like the
|
1941 |
+
# rest of this routine
|
1942 |
+
|
1943 |
+
margs = [Pow(new, cdid)] + margs
|
1944 |
+
return co_residual*self2.func(*margs)*self2.func(*nc)
|
1945 |
+
|
1946 |
+
def _eval_nseries(self, x, n, logx, cdir=0):
|
1947 |
+
from .function import PoleError
|
1948 |
+
from sympy.functions.elementary.integers import ceiling
|
1949 |
+
from sympy.series.order import Order
|
1950 |
+
|
1951 |
+
def coeff_exp(term, x):
|
1952 |
+
lt = term.as_coeff_exponent(x)
|
1953 |
+
if lt[0].has(x):
|
1954 |
+
try:
|
1955 |
+
lt = term.leadterm(x)
|
1956 |
+
except ValueError:
|
1957 |
+
return term, S.Zero
|
1958 |
+
return lt
|
1959 |
+
|
1960 |
+
ords = []
|
1961 |
+
|
1962 |
+
try:
|
1963 |
+
for t in self.args:
|
1964 |
+
coeff, exp = t.leadterm(x)
|
1965 |
+
if not coeff.has(x):
|
1966 |
+
ords.append((t, exp))
|
1967 |
+
else:
|
1968 |
+
raise ValueError
|
1969 |
+
|
1970 |
+
n0 = sum(t[1] for t in ords if t[1].is_number)
|
1971 |
+
facs = []
|
1972 |
+
for t, m in ords:
|
1973 |
+
n1 = ceiling(n - n0 + (m if m.is_number else 0))
|
1974 |
+
s = t.nseries(x, n=n1, logx=logx, cdir=cdir)
|
1975 |
+
ns = s.getn()
|
1976 |
+
if ns is not None:
|
1977 |
+
if ns < n1: # less than expected
|
1978 |
+
n -= n1 - ns # reduce n
|
1979 |
+
facs.append(s)
|
1980 |
+
|
1981 |
+
except (ValueError, NotImplementedError, TypeError, AttributeError, PoleError):
|
1982 |
+
n0 = sympify(sum(t[1] for t in ords if t[1].is_number))
|
1983 |
+
if n0.is_nonnegative:
|
1984 |
+
n0 = S.Zero
|
1985 |
+
facs = [t.nseries(x, n=ceiling(n-n0), logx=logx, cdir=cdir) for t in self.args]
|
1986 |
+
from sympy.simplify.powsimp import powsimp
|
1987 |
+
res = powsimp(self.func(*facs).expand(), combine='exp', deep=True)
|
1988 |
+
if res.has(Order):
|
1989 |
+
res += Order(x**n, x)
|
1990 |
+
return res
|
1991 |
+
|
1992 |
+
res = S.Zero
|
1993 |
+
ords2 = [Add.make_args(factor) for factor in facs]
|
1994 |
+
|
1995 |
+
for fac in product(*ords2):
|
1996 |
+
ords3 = [coeff_exp(term, x) for term in fac]
|
1997 |
+
coeffs, powers = zip(*ords3)
|
1998 |
+
power = sum(powers)
|
1999 |
+
if (power - n).is_negative:
|
2000 |
+
res += Mul(*coeffs)*(x**power)
|
2001 |
+
|
2002 |
+
def max_degree(e, x):
|
2003 |
+
if e is x:
|
2004 |
+
return S.One
|
2005 |
+
if e.is_Atom:
|
2006 |
+
return S.Zero
|
2007 |
+
if e.is_Add:
|
2008 |
+
return max(max_degree(a, x) for a in e.args)
|
2009 |
+
if e.is_Mul:
|
2010 |
+
return Add(*[max_degree(a, x) for a in e.args])
|
2011 |
+
if e.is_Pow:
|
2012 |
+
return max_degree(e.base, x)*e.exp
|
2013 |
+
return S.Zero
|
2014 |
+
|
2015 |
+
if self.is_polynomial(x):
|
2016 |
+
from sympy.polys.polyerrors import PolynomialError
|
2017 |
+
from sympy.polys.polytools import degree
|
2018 |
+
try:
|
2019 |
+
if max_degree(self, x) >= n or degree(self, x) != degree(res, x):
|
2020 |
+
res += Order(x**n, x)
|
2021 |
+
except PolynomialError:
|
2022 |
+
pass
|
2023 |
+
else:
|
2024 |
+
return res
|
2025 |
+
|
2026 |
+
if res != self:
|
2027 |
+
if (self - res).subs(x, 0) == S.Zero and n > 0:
|
2028 |
+
lt = self._eval_as_leading_term(x, logx=logx, cdir=cdir)
|
2029 |
+
if lt == S.Zero:
|
2030 |
+
return res
|
2031 |
+
res += Order(x**n, x)
|
2032 |
+
return res
|
2033 |
+
|
2034 |
+
def _eval_as_leading_term(self, x, logx=None, cdir=0):
|
2035 |
+
return self.func(*[t.as_leading_term(x, logx=logx, cdir=cdir) for t in self.args])
|
2036 |
+
|
2037 |
+
def _eval_conjugate(self):
|
2038 |
+
return self.func(*[t.conjugate() for t in self.args])
|
2039 |
+
|
2040 |
+
def _eval_transpose(self):
|
2041 |
+
return self.func(*[t.transpose() for t in self.args[::-1]])
|
2042 |
+
|
2043 |
+
def _eval_adjoint(self):
|
2044 |
+
return self.func(*[t.adjoint() for t in self.args[::-1]])
|
2045 |
+
|
2046 |
+
def as_content_primitive(self, radical=False, clear=True):
|
2047 |
+
"""Return the tuple (R, self/R) where R is the positive Rational
|
2048 |
+
extracted from self.
|
2049 |
+
|
2050 |
+
Examples
|
2051 |
+
========
|
2052 |
+
|
2053 |
+
>>> from sympy import sqrt
|
2054 |
+
>>> (-3*sqrt(2)*(2 - 2*sqrt(2))).as_content_primitive()
|
2055 |
+
(6, -sqrt(2)*(1 - sqrt(2)))
|
2056 |
+
|
2057 |
+
See docstring of Expr.as_content_primitive for more examples.
|
2058 |
+
"""
|
2059 |
+
|
2060 |
+
coef = S.One
|
2061 |
+
args = []
|
2062 |
+
for a in self.args:
|
2063 |
+
c, p = a.as_content_primitive(radical=radical, clear=clear)
|
2064 |
+
coef *= c
|
2065 |
+
if p is not S.One:
|
2066 |
+
args.append(p)
|
2067 |
+
# don't use self._from_args here to reconstruct args
|
2068 |
+
# since there may be identical args now that should be combined
|
2069 |
+
# e.g. (2+2*x)*(3+3*x) should be (6, (1 + x)**2) not (6, (1+x)*(1+x))
|
2070 |
+
return coef, self.func(*args)
|
2071 |
+
|
2072 |
+
def as_ordered_factors(self, order=None):
|
2073 |
+
"""Transform an expression into an ordered list of factors.
|
2074 |
+
|
2075 |
+
Examples
|
2076 |
+
========
|
2077 |
+
|
2078 |
+
>>> from sympy import sin, cos
|
2079 |
+
>>> from sympy.abc import x, y
|
2080 |
+
|
2081 |
+
>>> (2*x*y*sin(x)*cos(x)).as_ordered_factors()
|
2082 |
+
[2, x, y, sin(x), cos(x)]
|
2083 |
+
|
2084 |
+
"""
|
2085 |
+
cpart, ncpart = self.args_cnc()
|
2086 |
+
cpart.sort(key=lambda expr: expr.sort_key(order=order))
|
2087 |
+
return cpart + ncpart
|
2088 |
+
|
2089 |
+
@property
|
2090 |
+
def _sorted_args(self):
|
2091 |
+
return tuple(self.as_ordered_factors())
|
2092 |
+
|
2093 |
+
mul = AssocOpDispatcher('mul')
|
2094 |
+
|
2095 |
+
|
2096 |
+
def prod(a, start=1):
|
2097 |
+
"""Return product of elements of a. Start with int 1 so if only
|
2098 |
+
ints are included then an int result is returned.
|
2099 |
+
|
2100 |
+
Examples
|
2101 |
+
========
|
2102 |
+
|
2103 |
+
>>> from sympy import prod, S
|
2104 |
+
>>> prod(range(3))
|
2105 |
+
0
|
2106 |
+
>>> type(_) is int
|
2107 |
+
True
|
2108 |
+
>>> prod([S(2), 3])
|
2109 |
+
6
|
2110 |
+
>>> _.is_Integer
|
2111 |
+
True
|
2112 |
+
|
2113 |
+
You can start the product at something other than 1:
|
2114 |
+
|
2115 |
+
>>> prod([1, 2], 3)
|
2116 |
+
6
|
2117 |
+
|
2118 |
+
"""
|
2119 |
+
return reduce(operator.mul, a, start)
|
2120 |
+
|
2121 |
+
|
2122 |
+
def _keep_coeff(coeff, factors, clear=True, sign=False):
|
2123 |
+
"""Return ``coeff*factors`` unevaluated if necessary.
|
2124 |
+
|
2125 |
+
If ``clear`` is False, do not keep the coefficient as a factor
|
2126 |
+
if it can be distributed on a single factor such that one or
|
2127 |
+
more terms will still have integer coefficients.
|
2128 |
+
|
2129 |
+
If ``sign`` is True, allow a coefficient of -1 to remain factored out.
|
2130 |
+
|
2131 |
+
Examples
|
2132 |
+
========
|
2133 |
+
|
2134 |
+
>>> from sympy.core.mul import _keep_coeff
|
2135 |
+
>>> from sympy.abc import x, y
|
2136 |
+
>>> from sympy import S
|
2137 |
+
|
2138 |
+
>>> _keep_coeff(S.Half, x + 2)
|
2139 |
+
(x + 2)/2
|
2140 |
+
>>> _keep_coeff(S.Half, x + 2, clear=False)
|
2141 |
+
x/2 + 1
|
2142 |
+
>>> _keep_coeff(S.Half, (x + 2)*y, clear=False)
|
2143 |
+
y*(x + 2)/2
|
2144 |
+
>>> _keep_coeff(S(-1), x + y)
|
2145 |
+
-x - y
|
2146 |
+
>>> _keep_coeff(S(-1), x + y, sign=True)
|
2147 |
+
-(x + y)
|
2148 |
+
"""
|
2149 |
+
if not coeff.is_Number:
|
2150 |
+
if factors.is_Number:
|
2151 |
+
factors, coeff = coeff, factors
|
2152 |
+
else:
|
2153 |
+
return coeff*factors
|
2154 |
+
if factors is S.One:
|
2155 |
+
return coeff
|
2156 |
+
if coeff is S.One:
|
2157 |
+
return factors
|
2158 |
+
elif coeff is S.NegativeOne and not sign:
|
2159 |
+
return -factors
|
2160 |
+
elif factors.is_Add:
|
2161 |
+
if not clear and coeff.is_Rational and coeff.q != 1:
|
2162 |
+
args = [i.as_coeff_Mul() for i in factors.args]
|
2163 |
+
args = [(_keep_coeff(c, coeff), m) for c, m in args]
|
2164 |
+
if any(c.is_Integer for c, _ in args):
|
2165 |
+
return Add._from_args([Mul._from_args(
|
2166 |
+
i[1:] if i[0] == 1 else i) for i in args])
|
2167 |
+
return Mul(coeff, factors, evaluate=False)
|
2168 |
+
elif factors.is_Mul:
|
2169 |
+
margs = list(factors.args)
|
2170 |
+
if margs[0].is_Number:
|
2171 |
+
margs[0] *= coeff
|
2172 |
+
if margs[0] == 1:
|
2173 |
+
margs.pop(0)
|
2174 |
+
else:
|
2175 |
+
margs.insert(0, coeff)
|
2176 |
+
return Mul._from_args(margs)
|
2177 |
+
else:
|
2178 |
+
m = coeff*factors
|
2179 |
+
if m.is_Number and not factors.is_Number:
|
2180 |
+
m = Mul._from_args((coeff, factors))
|
2181 |
+
return m
|
2182 |
+
|
2183 |
+
def expand_2arg(e):
|
2184 |
+
def do(e):
|
2185 |
+
if e.is_Mul:
|
2186 |
+
c, r = e.as_coeff_Mul()
|
2187 |
+
if c.is_Number and r.is_Add:
|
2188 |
+
return _unevaluated_Add(*[c*ri for ri in r.args])
|
2189 |
+
return e
|
2190 |
+
return bottom_up(e, do)
|
2191 |
+
|
2192 |
+
|
2193 |
+
from .numbers import Rational
|
2194 |
+
from .power import Pow
|
2195 |
+
from .add import Add, _unevaluated_Add
|
llmeval-env/lib/python3.10/site-packages/sympy/core/parameters.py
ADDED
@@ -0,0 +1,161 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Thread-safe global parameters"""
|
2 |
+
|
3 |
+
from .cache import clear_cache
|
4 |
+
from contextlib import contextmanager
|
5 |
+
from threading import local
|
6 |
+
|
7 |
+
class _global_parameters(local):
|
8 |
+
"""
|
9 |
+
Thread-local global parameters.
|
10 |
+
|
11 |
+
Explanation
|
12 |
+
===========
|
13 |
+
|
14 |
+
This class generates thread-local container for SymPy's global parameters.
|
15 |
+
Every global parameters must be passed as keyword argument when generating
|
16 |
+
its instance.
|
17 |
+
A variable, `global_parameters` is provided as default instance for this class.
|
18 |
+
|
19 |
+
WARNING! Although the global parameters are thread-local, SymPy's cache is not
|
20 |
+
by now.
|
21 |
+
This may lead to undesired result in multi-threading operations.
|
22 |
+
|
23 |
+
Examples
|
24 |
+
========
|
25 |
+
|
26 |
+
>>> from sympy.abc import x
|
27 |
+
>>> from sympy.core.cache import clear_cache
|
28 |
+
>>> from sympy.core.parameters import global_parameters as gp
|
29 |
+
|
30 |
+
>>> gp.evaluate
|
31 |
+
True
|
32 |
+
>>> x+x
|
33 |
+
2*x
|
34 |
+
|
35 |
+
>>> log = []
|
36 |
+
>>> def f():
|
37 |
+
... clear_cache()
|
38 |
+
... gp.evaluate = False
|
39 |
+
... log.append(x+x)
|
40 |
+
... clear_cache()
|
41 |
+
>>> import threading
|
42 |
+
>>> thread = threading.Thread(target=f)
|
43 |
+
>>> thread.start()
|
44 |
+
>>> thread.join()
|
45 |
+
|
46 |
+
>>> print(log)
|
47 |
+
[x + x]
|
48 |
+
|
49 |
+
>>> gp.evaluate
|
50 |
+
True
|
51 |
+
>>> x+x
|
52 |
+
2*x
|
53 |
+
|
54 |
+
References
|
55 |
+
==========
|
56 |
+
|
57 |
+
.. [1] https://docs.python.org/3/library/threading.html
|
58 |
+
|
59 |
+
"""
|
60 |
+
def __init__(self, **kwargs):
|
61 |
+
self.__dict__.update(kwargs)
|
62 |
+
|
63 |
+
def __setattr__(self, name, value):
|
64 |
+
if getattr(self, name) != value:
|
65 |
+
clear_cache()
|
66 |
+
return super().__setattr__(name, value)
|
67 |
+
|
68 |
+
global_parameters = _global_parameters(evaluate=True, distribute=True, exp_is_pow=False)
|
69 |
+
|
70 |
+
@contextmanager
|
71 |
+
def evaluate(x):
|
72 |
+
""" Control automatic evaluation
|
73 |
+
|
74 |
+
Explanation
|
75 |
+
===========
|
76 |
+
|
77 |
+
This context manager controls whether or not all SymPy functions evaluate
|
78 |
+
by default.
|
79 |
+
|
80 |
+
Note that much of SymPy expects evaluated expressions. This functionality
|
81 |
+
is experimental and is unlikely to function as intended on large
|
82 |
+
expressions.
|
83 |
+
|
84 |
+
Examples
|
85 |
+
========
|
86 |
+
|
87 |
+
>>> from sympy import evaluate
|
88 |
+
>>> from sympy.abc import x
|
89 |
+
>>> print(x + x)
|
90 |
+
2*x
|
91 |
+
>>> with evaluate(False):
|
92 |
+
... print(x + x)
|
93 |
+
x + x
|
94 |
+
"""
|
95 |
+
|
96 |
+
old = global_parameters.evaluate
|
97 |
+
|
98 |
+
try:
|
99 |
+
global_parameters.evaluate = x
|
100 |
+
yield
|
101 |
+
finally:
|
102 |
+
global_parameters.evaluate = old
|
103 |
+
|
104 |
+
|
105 |
+
@contextmanager
|
106 |
+
def distribute(x):
|
107 |
+
""" Control automatic distribution of Number over Add
|
108 |
+
|
109 |
+
Explanation
|
110 |
+
===========
|
111 |
+
|
112 |
+
This context manager controls whether or not Mul distribute Number over
|
113 |
+
Add. Plan is to avoid distributing Number over Add in all of sympy. Once
|
114 |
+
that is done, this contextmanager will be removed.
|
115 |
+
|
116 |
+
Examples
|
117 |
+
========
|
118 |
+
|
119 |
+
>>> from sympy.abc import x
|
120 |
+
>>> from sympy.core.parameters import distribute
|
121 |
+
>>> print(2*(x + 1))
|
122 |
+
2*x + 2
|
123 |
+
>>> with distribute(False):
|
124 |
+
... print(2*(x + 1))
|
125 |
+
2*(x + 1)
|
126 |
+
"""
|
127 |
+
|
128 |
+
old = global_parameters.distribute
|
129 |
+
|
130 |
+
try:
|
131 |
+
global_parameters.distribute = x
|
132 |
+
yield
|
133 |
+
finally:
|
134 |
+
global_parameters.distribute = old
|
135 |
+
|
136 |
+
|
137 |
+
@contextmanager
|
138 |
+
def _exp_is_pow(x):
|
139 |
+
"""
|
140 |
+
Control whether `e^x` should be represented as ``exp(x)`` or a ``Pow(E, x)``.
|
141 |
+
|
142 |
+
Examples
|
143 |
+
========
|
144 |
+
|
145 |
+
>>> from sympy import exp
|
146 |
+
>>> from sympy.abc import x
|
147 |
+
>>> from sympy.core.parameters import _exp_is_pow
|
148 |
+
>>> with _exp_is_pow(True): print(type(exp(x)))
|
149 |
+
<class 'sympy.core.power.Pow'>
|
150 |
+
>>> with _exp_is_pow(False): print(type(exp(x)))
|
151 |
+
exp
|
152 |
+
"""
|
153 |
+
old = global_parameters.exp_is_pow
|
154 |
+
|
155 |
+
clear_cache()
|
156 |
+
try:
|
157 |
+
global_parameters.exp_is_pow = x
|
158 |
+
yield
|
159 |
+
finally:
|
160 |
+
clear_cache()
|
161 |
+
global_parameters.exp_is_pow = old
|
llmeval-env/lib/python3.10/site-packages/sympy/discrete/__init__.py
ADDED
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""This module contains functions which operate on discrete sequences.
|
2 |
+
|
3 |
+
Transforms - ``fft``, ``ifft``, ``ntt``, ``intt``, ``fwht``, ``ifwht``,
|
4 |
+
``mobius_transform``, ``inverse_mobius_transform``
|
5 |
+
|
6 |
+
Convolutions - ``convolution``, ``convolution_fft``, ``convolution_ntt``,
|
7 |
+
``convolution_fwht``, ``convolution_subset``,
|
8 |
+
``covering_product``, ``intersecting_product``
|
9 |
+
"""
|
10 |
+
|
11 |
+
from .transforms import (fft, ifft, ntt, intt, fwht, ifwht,
|
12 |
+
mobius_transform, inverse_mobius_transform)
|
13 |
+
from .convolutions import convolution, covering_product, intersecting_product
|
14 |
+
|
15 |
+
__all__ = [
|
16 |
+
'fft', 'ifft', 'ntt', 'intt', 'fwht', 'ifwht', 'mobius_transform',
|
17 |
+
'inverse_mobius_transform',
|
18 |
+
|
19 |
+
'convolution', 'covering_product', 'intersecting_product',
|
20 |
+
]
|
llmeval-env/lib/python3.10/site-packages/sympy/discrete/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (960 Bytes). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/discrete/__pycache__/convolutions.cpython-310.pyc
ADDED
Binary file (12.9 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/discrete/__pycache__/recurrences.cpython-310.pyc
ADDED
Binary file (5.1 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/discrete/__pycache__/transforms.cpython-310.pyc
ADDED
Binary file (11.1 kB). View file
|
|
llmeval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HT**), Subset Convolution,
|
3 |
+
Covering Product, Intersecting Product
|
4 |
+
"""
|
5 |
+
|
6 |
+
from sympy.core import S, sympify
|
7 |
+
from sympy.core.function import expand_mul
|
8 |
+
from sympy.discrete.transforms import (
|
9 |
+
fft, ifft, ntt, intt, fwht, ifwht,
|
10 |
+
mobius_transform, inverse_mobius_transform)
|
11 |
+
from sympy.utilities.iterables import iterable
|
12 |
+
from sympy.utilities.misc import as_int
|
13 |
+
|
14 |
+
|
15 |
+
def convolution(a, b, cycle=0, dps=None, prime=None, dyadic=None, subset=None):
|
16 |
+
"""
|
17 |
+
Performs convolution by determining the type of desired
|
18 |
+
convolution using hints.
|
19 |
+
|
20 |
+
Exactly one of ``dps``, ``prime``, ``dyadic``, ``subset`` arguments
|
21 |
+
should be specified explicitly for identifying the type of convolution,
|
22 |
+
and the argument ``cycle`` can be specified optionally.
|
23 |
+
|
24 |
+
For the default arguments, linear convolution is performed using **FFT**.
|
25 |
+
|
26 |
+
Parameters
|
27 |
+
==========
|
28 |
+
|
29 |
+
a, b : iterables
|
30 |
+
The sequences for which convolution is performed.
|
31 |
+
cycle : Integer
|
32 |
+
Specifies the length for doing cyclic convolution.
|
33 |
+
dps : Integer
|
34 |
+
Specifies the number of decimal digits for precision for
|
35 |
+
performing **FFT** on the sequence.
|
36 |
+
prime : Integer
|
37 |
+
Prime modulus of the form `(m 2^k + 1)` to be used for
|
38 |
+
performing **NTT** on the sequence.
|
39 |
+
dyadic : bool
|
40 |
+
Identifies the convolution type as dyadic (*bitwise-XOR*)
|
41 |
+
convolution, which is performed using **FWHT**.
|
42 |
+
subset : bool
|
43 |
+
Identifies the convolution type as subset convolution.
|
44 |
+
|
45 |
+
Examples
|
46 |
+
========
|
47 |
+
|
48 |
+
>>> from sympy import convolution, symbols, S, I
|
49 |
+
>>> u, v, w, x, y, z = symbols('u v w x y z')
|
50 |
+
|
51 |
+
>>> convolution([1 + 2*I, 4 + 3*I], [S(5)/4, 6], dps=3)
|
52 |
+
[1.25 + 2.5*I, 11.0 + 15.8*I, 24.0 + 18.0*I]
|
53 |
+
>>> convolution([1, 2, 3], [4, 5, 6], cycle=3)
|
54 |
+
[31, 31, 28]
|
55 |
+
|
56 |
+
>>> convolution([111, 777], [888, 444], prime=19*2**10 + 1)
|
57 |
+
[1283, 19351, 14219]
|
58 |
+
>>> convolution([111, 777], [888, 444], prime=19*2**10 + 1, cycle=2)
|
59 |
+
[15502, 19351]
|
60 |
+
|
61 |
+
>>> convolution([u, v], [x, y, z], dyadic=True)
|
62 |
+
[u*x + v*y, u*y + v*x, u*z, v*z]
|
63 |
+
>>> convolution([u, v], [x, y, z], dyadic=True, cycle=2)
|
64 |
+
[u*x + u*z + v*y, u*y + v*x + v*z]
|
65 |
+
|
66 |
+
>>> convolution([u, v, w], [x, y, z], subset=True)
|
67 |
+
[u*x, u*y + v*x, u*z + w*x, v*z + w*y]
|
68 |
+
>>> convolution([u, v, w], [x, y, z], subset=True, cycle=3)
|
69 |
+
[u*x + v*z + w*y, u*y + v*x, u*z + w*x]
|
70 |
+
|
71 |
+
"""
|
72 |
+
|
73 |
+
c = as_int(cycle)
|
74 |
+
if c < 0:
|
75 |
+
raise ValueError("The length for cyclic convolution "
|
76 |
+
"must be non-negative")
|
77 |
+
|
78 |
+
dyadic = True if dyadic else None
|
79 |
+
subset = True if subset else None
|
80 |
+
if sum(x is not None for x in (prime, dps, dyadic, subset)) > 1:
|
81 |
+
raise TypeError("Ambiguity in determining the type of convolution")
|
82 |
+
|
83 |
+
if prime is not None:
|
84 |
+
ls = convolution_ntt(a, b, prime=prime)
|
85 |
+
return ls if not c else [sum(ls[i::c]) % prime for i in range(c)]
|
86 |
+
|
87 |
+
if dyadic:
|
88 |
+
ls = convolution_fwht(a, b)
|
89 |
+
elif subset:
|
90 |
+
ls = convolution_subset(a, b)
|
91 |
+
else:
|
92 |
+
ls = convolution_fft(a, b, dps=dps)
|
93 |
+
|
94 |
+
return ls if not c else [sum(ls[i::c]) for i in range(c)]
|
95 |
+
|
96 |
+
|
97 |
+
#----------------------------------------------------------------------------#
|
98 |
+
# #
|
99 |
+
# Convolution for Complex domain #
|
100 |
+
# #
|
101 |
+
#----------------------------------------------------------------------------#
|
102 |
+
|
103 |
+
def convolution_fft(a, b, dps=None):
|
104 |
+
"""
|
105 |
+
Performs linear convolution using Fast Fourier Transform.
|
106 |
+
|
107 |
+
Parameters
|
108 |
+
==========
|
109 |
+
|
110 |
+
a, b : iterables
|
111 |
+
The sequences for which convolution is performed.
|
112 |
+
dps : Integer
|
113 |
+
Specifies the number of decimal digits for precision.
|
114 |
+
|
115 |
+
Examples
|
116 |
+
========
|
117 |
+
|
118 |
+
>>> from sympy import S, I
|
119 |
+
>>> from sympy.discrete.convolutions import convolution_fft
|
120 |
+
|
121 |
+
>>> convolution_fft([2, 3], [4, 5])
|
122 |
+
[8, 22, 15]
|
123 |
+
>>> convolution_fft([2, 5], [6, 7, 3])
|
124 |
+
[12, 44, 41, 15]
|
125 |
+
>>> convolution_fft([1 + 2*I, 4 + 3*I], [S(5)/4, 6])
|
126 |
+
[5/4 + 5*I/2, 11 + 63*I/4, 24 + 18*I]
|
127 |
+
|
128 |
+
References
|
129 |
+
==========
|
130 |
+
|
131 |
+
.. [1] https://en.wikipedia.org/wiki/Convolution_theorem
|
132 |
+
.. [2] https://en.wikipedia.org/wiki/Discrete_Fourier_transform_(general%29
|
133 |
+
|
134 |
+
"""
|
135 |
+
|
136 |
+
a, b = a[:], b[:]
|
137 |
+
n = m = len(a) + len(b) - 1 # convolution size
|
138 |
+
|
139 |
+
if n > 0 and n&(n - 1): # not a power of 2
|
140 |
+
n = 2**n.bit_length()
|
141 |
+
|
142 |
+
# padding with zeros
|
143 |
+
a += [S.Zero]*(n - len(a))
|
144 |
+
b += [S.Zero]*(n - len(b))
|
145 |
+
|
146 |
+
a, b = fft(a, dps), fft(b, dps)
|
147 |
+
a = [expand_mul(x*y) for x, y in zip(a, b)]
|
148 |
+
a = ifft(a, dps)[:m]
|
149 |
+
|
150 |
+
return a
|
151 |
+
|
152 |
+
|
153 |
+
#----------------------------------------------------------------------------#
|
154 |
+
# #
|
155 |
+
# Convolution for GF(p) #
|
156 |
+
# #
|
157 |
+
#----------------------------------------------------------------------------#
|
158 |
+
|
159 |
+
def convolution_ntt(a, b, prime):
|
160 |
+
"""
|
161 |
+
Performs linear convolution using Number Theoretic Transform.
|
162 |
+
|
163 |
+
Parameters
|
164 |
+
==========
|
165 |
+
|
166 |
+
a, b : iterables
|
167 |
+
The sequences for which convolution is performed.
|
168 |
+
prime : Integer
|
169 |
+
Prime modulus of the form `(m 2^k + 1)` to be used for performing
|
170 |
+
**NTT** on the sequence.
|
171 |
+
|
172 |
+
Examples
|
173 |
+
========
|
174 |
+
|
175 |
+
>>> from sympy.discrete.convolutions import convolution_ntt
|
176 |
+
>>> convolution_ntt([2, 3], [4, 5], prime=19*2**10 + 1)
|
177 |
+
[8, 22, 15]
|
178 |
+
>>> convolution_ntt([2, 5], [6, 7, 3], prime=19*2**10 + 1)
|
179 |
+
[12, 44, 41, 15]
|
180 |
+
>>> convolution_ntt([333, 555], [222, 666], prime=19*2**10 + 1)
|
181 |
+
[15555, 14219, 19404]
|
182 |
+
|
183 |
+
References
|
184 |
+
==========
|
185 |
+
|
186 |
+
.. [1] https://en.wikipedia.org/wiki/Convolution_theorem
|
187 |
+
.. [2] https://en.wikipedia.org/wiki/Discrete_Fourier_transform_(general%29
|
188 |
+
|
189 |
+
"""
|
190 |
+
|
191 |
+
a, b, p = a[:], b[:], as_int(prime)
|
192 |
+
n = m = len(a) + len(b) - 1 # convolution size
|
193 |
+
|
194 |
+
if n > 0 and n&(n - 1): # not a power of 2
|
195 |
+
n = 2**n.bit_length()
|
196 |
+
|
197 |
+
# padding with zeros
|
198 |
+
a += [0]*(n - len(a))
|
199 |
+
b += [0]*(n - len(b))
|
200 |
+
|
201 |
+
a, b = ntt(a, p), ntt(b, p)
|
202 |
+
a = [x*y % p for x, y in zip(a, b)]
|
203 |
+
a = intt(a, p)[:m]
|
204 |
+
|
205 |
+
return a
|
206 |
+
|
207 |
+
|
208 |
+
#----------------------------------------------------------------------------#
|
209 |
+
# #
|
210 |
+
# Convolution for 2**n-group #
|
211 |
+
# #
|
212 |
+
#----------------------------------------------------------------------------#
|
213 |
+
|
214 |
+
def convolution_fwht(a, b):
|
215 |
+
"""
|
216 |
+
Performs dyadic (*bitwise-XOR*) convolution using Fast Walsh Hadamard
|
217 |
+
Transform.
|
218 |
+
|
219 |
+
The convolution is automatically padded to the right with zeros, as the
|
220 |
+
*radix-2 FWHT* requires the number of sample points to be a power of 2.
|
221 |
+
|
222 |
+
Parameters
|
223 |
+
==========
|
224 |
+
|
225 |
+
a, b : iterables
|
226 |
+
The sequences for which convolution is performed.
|
227 |
+
|
228 |
+
Examples
|
229 |
+
========
|
230 |
+
|
231 |
+
>>> from sympy import symbols, S, I
|
232 |
+
>>> from sympy.discrete.convolutions import convolution_fwht
|
233 |
+
|
234 |
+
>>> u, v, x, y = symbols('u v x y')
|
235 |
+
>>> convolution_fwht([u, v], [x, y])
|
236 |
+
[u*x + v*y, u*y + v*x]
|
237 |
+
|
238 |
+
>>> convolution_fwht([2, 3], [4, 5])
|
239 |
+
[23, 22]
|
240 |
+
>>> convolution_fwht([2, 5 + 4*I, 7], [6*I, 7, 3 + 4*I])
|
241 |
+
[56 + 68*I, -10 + 30*I, 6 + 50*I, 48 + 32*I]
|
242 |
+
|
243 |
+
>>> convolution_fwht([S(33)/7, S(55)/6, S(7)/4], [S(2)/3, 5])
|
244 |
+
[2057/42, 1870/63, 7/6, 35/4]
|
245 |
+
|
246 |
+
References
|
247 |
+
==========
|
248 |
+
|
249 |
+
.. [1] https://www.radioeng.cz/fulltexts/2002/02_03_40_42.pdf
|
250 |
+
.. [2] https://en.wikipedia.org/wiki/Hadamard_transform
|
251 |
+
|
252 |
+
"""
|
253 |
+
|
254 |
+
if not a or not b:
|
255 |
+
return []
|
256 |
+
|
257 |
+
a, b = a[:], b[:]
|
258 |
+
n = max(len(a), len(b))
|
259 |
+
|
260 |
+
if n&(n - 1): # not a power of 2
|
261 |
+
n = 2**n.bit_length()
|
262 |
+
|
263 |
+
# padding with zeros
|
264 |
+
a += [S.Zero]*(n - len(a))
|
265 |
+
b += [S.Zero]*(n - len(b))
|
266 |
+
|
267 |
+
a, b = fwht(a), fwht(b)
|
268 |
+
a = [expand_mul(x*y) for x, y in zip(a, b)]
|
269 |
+
a = ifwht(a)
|
270 |
+
|
271 |
+
return a
|
272 |
+
|
273 |
+
|
274 |
+
#----------------------------------------------------------------------------#
|
275 |
+
# #
|
276 |
+
# Subset Convolution #
|
277 |
+
# #
|
278 |
+
#----------------------------------------------------------------------------#
|
279 |
+
|
280 |
+
def convolution_subset(a, b):
|
281 |
+
"""
|
282 |
+
Performs Subset Convolution of given sequences.
|
283 |
+
|
284 |
+
The indices of each argument, considered as bit strings, correspond to
|
285 |
+
subsets of a finite set.
|
286 |
+
|
287 |
+
The sequence is automatically padded to the right with zeros, as the
|
288 |
+
definition of subset based on bitmasks (indices) requires the size of
|
289 |
+
sequence to be a power of 2.
|
290 |
+
|
291 |
+
Parameters
|
292 |
+
==========
|
293 |
+
|
294 |
+
a, b : iterables
|
295 |
+
The sequences for which convolution is performed.
|
296 |
+
|
297 |
+
Examples
|
298 |
+
========
|
299 |
+
|
300 |
+
>>> from sympy import symbols, S
|
301 |
+
>>> from sympy.discrete.convolutions import convolution_subset
|
302 |
+
>>> u, v, x, y, z = symbols('u v x y z')
|
303 |
+
|
304 |
+
>>> convolution_subset([u, v], [x, y])
|
305 |
+
[u*x, u*y + v*x]
|
306 |
+
>>> convolution_subset([u, v, x], [y, z])
|
307 |
+
[u*y, u*z + v*y, x*y, x*z]
|
308 |
+
|
309 |
+
>>> convolution_subset([1, S(2)/3], [3, 4])
|
310 |
+
[3, 6]
|
311 |
+
>>> convolution_subset([1, 3, S(5)/7], [7])
|
312 |
+
[7, 21, 5, 0]
|
313 |
+
|
314 |
+
References
|
315 |
+
==========
|
316 |
+
|
317 |
+
.. [1] https://people.csail.mit.edu/rrw/presentations/subset-conv.pdf
|
318 |
+
|
319 |
+
"""
|
320 |
+
|
321 |
+
if not a or not b:
|
322 |
+
return []
|
323 |
+
|
324 |
+
if not iterable(a) or not iterable(b):
|
325 |
+
raise TypeError("Expected a sequence of coefficients for convolution")
|
326 |
+
|
327 |
+
a = [sympify(arg) for arg in a]
|
328 |
+
b = [sympify(arg) for arg in b]
|
329 |
+
n = max(len(a), len(b))
|
330 |
+
|
331 |
+
if n&(n - 1): # not a power of 2
|
332 |
+
n = 2**n.bit_length()
|
333 |
+
|
334 |
+
# padding with zeros
|
335 |
+
a += [S.Zero]*(n - len(a))
|
336 |
+
b += [S.Zero]*(n - len(b))
|
337 |
+
|
338 |
+
c = [S.Zero]*n
|
339 |
+
|
340 |
+
for mask in range(n):
|
341 |
+
smask = mask
|
342 |
+
while smask > 0:
|
343 |
+
c[mask] += expand_mul(a[smask] * b[mask^smask])
|
344 |
+
smask = (smask - 1)&mask
|
345 |
+
|
346 |
+
c[mask] += expand_mul(a[smask] * b[mask^smask])
|
347 |
+
|
348 |
+
return c
|
349 |
+
|
350 |
+
|
351 |
+
#----------------------------------------------------------------------------#
|
352 |
+
# #
|
353 |
+
# Covering Product #
|
354 |
+
# #
|
355 |
+
#----------------------------------------------------------------------------#
|
356 |
+
|
357 |
+
def covering_product(a, b):
|
358 |
+
"""
|
359 |
+
Returns the covering product of given sequences.
|
360 |
+
|
361 |
+
The indices of each argument, considered as bit strings, correspond to
|
362 |
+
subsets of a finite set.
|
363 |
+
|
364 |
+
The covering product of given sequences is a sequence which contains
|
365 |
+
the sum of products of the elements of the given sequences grouped by
|
366 |
+
the *bitwise-OR* of the corresponding indices.
|
367 |
+
|
368 |
+
The sequence is automatically padded to the right with zeros, as the
|
369 |
+
definition of subset based on bitmasks (indices) requires the size of
|
370 |
+
sequence to be a power of 2.
|
371 |
+
|
372 |
+
Parameters
|
373 |
+
==========
|
374 |
+
|
375 |
+
a, b : iterables
|
376 |
+
The sequences for which covering product is to be obtained.
|
377 |
+
|
378 |
+
Examples
|
379 |
+
========
|
380 |
+
|
381 |
+
>>> from sympy import symbols, S, I, covering_product
|
382 |
+
>>> u, v, x, y, z = symbols('u v x y z')
|
383 |
+
|
384 |
+
>>> covering_product([u, v], [x, y])
|
385 |
+
[u*x, u*y + v*x + v*y]
|
386 |
+
>>> covering_product([u, v, x], [y, z])
|
387 |
+
[u*y, u*z + v*y + v*z, x*y, x*z]
|
388 |
+
|
389 |
+
>>> covering_product([1, S(2)/3], [3, 4 + 5*I])
|
390 |
+
[3, 26/3 + 25*I/3]
|
391 |
+
>>> covering_product([1, 3, S(5)/7], [7, 8])
|
392 |
+
[7, 53, 5, 40/7]
|
393 |
+
|
394 |
+
References
|
395 |
+
==========
|
396 |
+
|
397 |
+
.. [1] https://people.csail.mit.edu/rrw/presentations/subset-conv.pdf
|
398 |
+
|
399 |
+
"""
|
400 |
+
|
401 |
+
if not a or not b:
|
402 |
+
return []
|
403 |
+
|
404 |
+
a, b = a[:], b[:]
|
405 |
+
n = max(len(a), len(b))
|
406 |
+
|
407 |
+
if n&(n - 1): # not a power of 2
|
408 |
+
n = 2**n.bit_length()
|
409 |
+
|
410 |
+
# padding with zeros
|
411 |
+
a += [S.Zero]*(n - len(a))
|
412 |
+
b += [S.Zero]*(n - len(b))
|
413 |
+
|
414 |
+
a, b = mobius_transform(a), mobius_transform(b)
|
415 |
+
a = [expand_mul(x*y) for x, y in zip(a, b)]
|
416 |
+
a = inverse_mobius_transform(a)
|
417 |
+
|
418 |
+
return a
|
419 |
+
|
420 |
+
|
421 |
+
#----------------------------------------------------------------------------#
|
422 |
+
# #
|
423 |
+
# Intersecting Product #
|
424 |
+
# #
|
425 |
+
#----------------------------------------------------------------------------#
|
426 |
+
|
427 |
+
def intersecting_product(a, b):
|
428 |
+
"""
|
429 |
+
Returns the intersecting product of given sequences.
|
430 |
+
|
431 |
+
The indices of each argument, considered as bit strings, correspond to
|
432 |
+
subsets of a finite set.
|
433 |
+
|
434 |
+
The intersecting product of given sequences is the sequence which
|
435 |
+
contains the sum of products of the elements of the given sequences
|
436 |
+
grouped by the *bitwise-AND* of the corresponding indices.
|
437 |
+
|
438 |
+
The sequence is automatically padded to the right with zeros, as the
|
439 |
+
definition of subset based on bitmasks (indices) requires the size of
|
440 |
+
sequence to be a power of 2.
|
441 |
+
|
442 |
+
Parameters
|
443 |
+
==========
|
444 |
+
|
445 |
+
a, b : iterables
|
446 |
+
The sequences for which intersecting product is to be obtained.
|
447 |
+
|
448 |
+
Examples
|
449 |
+
========
|
450 |
+
|
451 |
+
>>> from sympy import symbols, S, I, intersecting_product
|
452 |
+
>>> u, v, x, y, z = symbols('u v x y z')
|
453 |
+
|
454 |
+
>>> intersecting_product([u, v], [x, y])
|
455 |
+
[u*x + u*y + v*x, v*y]
|
456 |
+
>>> intersecting_product([u, v, x], [y, z])
|
457 |
+
[u*y + u*z + v*y + x*y + x*z, v*z, 0, 0]
|
458 |
+
|
459 |
+
>>> intersecting_product([1, S(2)/3], [3, 4 + 5*I])
|
460 |
+
[9 + 5*I, 8/3 + 10*I/3]
|
461 |
+
>>> intersecting_product([1, 3, S(5)/7], [7, 8])
|
462 |
+
[327/7, 24, 0, 0]
|
463 |
+
|
464 |
+
References
|
465 |
+
==========
|
466 |
+
|
467 |
+
.. [1] https://people.csail.mit.edu/rrw/presentations/subset-conv.pdf
|
468 |
+
|
469 |
+
"""
|
470 |
+
|
471 |
+
if not a or not b:
|
472 |
+
return []
|
473 |
+
|
474 |
+
a, b = a[:], b[:]
|
475 |
+
n = max(len(a), len(b))
|
476 |
+
|
477 |
+
if n&(n - 1): # not a power of 2
|
478 |
+
n = 2**n.bit_length()
|
479 |
+
|
480 |
+
# padding with zeros
|
481 |
+
a += [S.Zero]*(n - len(a))
|
482 |
+
b += [S.Zero]*(n - len(b))
|
483 |
+
|
484 |
+
a, b = mobius_transform(a, subset=False), mobius_transform(b, subset=False)
|
485 |
+
a = [expand_mul(x*y) for x, y in zip(a, b)]
|
486 |
+
a = inverse_mobius_transform(a, subset=False)
|
487 |
+
|
488 |
+
return a
|
llmeval-env/lib/python3.10/site-packages/sympy/discrete/recurrences.py
ADDED
@@ -0,0 +1,166 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Recurrences
|
3 |
+
"""
|
4 |
+
|
5 |
+
from sympy.core import S, sympify
|
6 |
+
from sympy.utilities.iterables import iterable
|
7 |
+
from sympy.utilities.misc import as_int
|
8 |
+
|
9 |
+
|
10 |
+
def linrec(coeffs, init, n):
|
11 |
+
r"""
|
12 |
+
Evaluation of univariate linear recurrences of homogeneous type
|
13 |
+
having coefficients independent of the recurrence variable.
|
14 |
+
|
15 |
+
Parameters
|
16 |
+
==========
|
17 |
+
|
18 |
+
coeffs : iterable
|
19 |
+
Coefficients of the recurrence
|
20 |
+
init : iterable
|
21 |
+
Initial values of the recurrence
|
22 |
+
n : Integer
|
23 |
+
Point of evaluation for the recurrence
|
24 |
+
|
25 |
+
Notes
|
26 |
+
=====
|
27 |
+
|
28 |
+
Let `y(n)` be the recurrence of given type, ``c`` be the sequence
|
29 |
+
of coefficients, ``b`` be the sequence of initial/base values of the
|
30 |
+
recurrence and ``k`` (equal to ``len(c)``) be the order of recurrence.
|
31 |
+
Then,
|
32 |
+
|
33 |
+
.. math :: y(n) = \begin{cases} b_n & 0 \le n < k \\
|
34 |
+
c_0 y(n-1) + c_1 y(n-2) + \cdots + c_{k-1} y(n-k) & n \ge k
|
35 |
+
\end{cases}
|
36 |
+
|
37 |
+
Let `x_0, x_1, \ldots, x_n` be a sequence and consider the transformation
|
38 |
+
that maps each polynomial `f(x)` to `T(f(x))` where each power `x^i` is
|
39 |
+
replaced by the corresponding value `x_i`. The sequence is then a solution
|
40 |
+
of the recurrence if and only if `T(x^i p(x)) = 0` for each `i \ge 0` where
|
41 |
+
`p(x) = x^k - c_0 x^(k-1) - \cdots - c_{k-1}` is the characteristic
|
42 |
+
polynomial.
|
43 |
+
|
44 |
+
Then `T(f(x)p(x)) = 0` for each polynomial `f(x)` (as it is a linear
|
45 |
+
combination of powers `x^i`). Now, if `x^n` is congruent to
|
46 |
+
`g(x) = a_0 x^0 + a_1 x^1 + \cdots + a_{k-1} x^{k-1}` modulo `p(x)`, then
|
47 |
+
`T(x^n) = x_n` is equal to
|
48 |
+
`T(g(x)) = a_0 x_0 + a_1 x_1 + \cdots + a_{k-1} x_{k-1}`.
|
49 |
+
|
50 |
+
Computation of `x^n`,
|
51 |
+
given `x^k = c_0 x^{k-1} + c_1 x^{k-2} + \cdots + c_{k-1}`
|
52 |
+
is performed using exponentiation by squaring (refer to [1_]) with
|
53 |
+
an additional reduction step performed to retain only first `k` powers
|
54 |
+
of `x` in the representation of `x^n`.
|
55 |
+
|
56 |
+
Examples
|
57 |
+
========
|
58 |
+
|
59 |
+
>>> from sympy.discrete.recurrences import linrec
|
60 |
+
>>> from sympy.abc import x, y, z
|
61 |
+
|
62 |
+
>>> linrec(coeffs=[1, 1], init=[0, 1], n=10)
|
63 |
+
55
|
64 |
+
|
65 |
+
>>> linrec(coeffs=[1, 1], init=[x, y], n=10)
|
66 |
+
34*x + 55*y
|
67 |
+
|
68 |
+
>>> linrec(coeffs=[x, y], init=[0, 1], n=5)
|
69 |
+
x**2*y + x*(x**3 + 2*x*y) + y**2
|
70 |
+
|
71 |
+
>>> linrec(coeffs=[1, 2, 3, 0, 0, 4], init=[x, y, z], n=16)
|
72 |
+
13576*x + 5676*y + 2356*z
|
73 |
+
|
74 |
+
References
|
75 |
+
==========
|
76 |
+
|
77 |
+
.. [1] https://en.wikipedia.org/wiki/Exponentiation_by_squaring
|
78 |
+
.. [2] https://en.wikipedia.org/w/index.php?title=Modular_exponentiation§ion=6#Matrices
|
79 |
+
|
80 |
+
See Also
|
81 |
+
========
|
82 |
+
|
83 |
+
sympy.polys.agca.extensions.ExtensionElement.__pow__
|
84 |
+
|
85 |
+
"""
|
86 |
+
|
87 |
+
if not coeffs:
|
88 |
+
return S.Zero
|
89 |
+
|
90 |
+
if not iterable(coeffs):
|
91 |
+
raise TypeError("Expected a sequence of coefficients for"
|
92 |
+
" the recurrence")
|
93 |
+
|
94 |
+
if not iterable(init):
|
95 |
+
raise TypeError("Expected a sequence of values for the initialization"
|
96 |
+
" of the recurrence")
|
97 |
+
|
98 |
+
n = as_int(n)
|
99 |
+
if n < 0:
|
100 |
+
raise ValueError("Point of evaluation of recurrence must be a "
|
101 |
+
"non-negative integer")
|
102 |
+
|
103 |
+
c = [sympify(arg) for arg in coeffs]
|
104 |
+
b = [sympify(arg) for arg in init]
|
105 |
+
k = len(c)
|
106 |
+
|
107 |
+
if len(b) > k:
|
108 |
+
raise TypeError("Count of initial values should not exceed the "
|
109 |
+
"order of the recurrence")
|
110 |
+
else:
|
111 |
+
b += [S.Zero]*(k - len(b)) # remaining initial values default to zero
|
112 |
+
|
113 |
+
if n < k:
|
114 |
+
return b[n]
|
115 |
+
terms = [u*v for u, v in zip(linrec_coeffs(c, n), b)]
|
116 |
+
return sum(terms[:-1], terms[-1])
|
117 |
+
|
118 |
+
|
119 |
+
def linrec_coeffs(c, n):
|
120 |
+
r"""
|
121 |
+
Compute the coefficients of n'th term in linear recursion
|
122 |
+
sequence defined by c.
|
123 |
+
|
124 |
+
`x^k = c_0 x^{k-1} + c_1 x^{k-2} + \cdots + c_{k-1}`.
|
125 |
+
|
126 |
+
It computes the coefficients by using binary exponentiation.
|
127 |
+
This function is used by `linrec` and `_eval_pow_by_cayley`.
|
128 |
+
|
129 |
+
Parameters
|
130 |
+
==========
|
131 |
+
|
132 |
+
c = coefficients of the divisor polynomial
|
133 |
+
n = exponent of x, so dividend is x^n
|
134 |
+
|
135 |
+
"""
|
136 |
+
|
137 |
+
k = len(c)
|
138 |
+
|
139 |
+
def _square_and_reduce(u, offset):
|
140 |
+
# squares `(u_0 + u_1 x + u_2 x^2 + \cdots + u_{k-1} x^k)` (and
|
141 |
+
# multiplies by `x` if offset is 1) and reduces the above result of
|
142 |
+
# length upto `2k` to `k` using the characteristic equation of the
|
143 |
+
# recurrence given by, `x^k = c_0 x^{k-1} + c_1 x^{k-2} + \cdots + c_{k-1}`
|
144 |
+
|
145 |
+
w = [S.Zero]*(2*len(u) - 1 + offset)
|
146 |
+
for i, p in enumerate(u):
|
147 |
+
for j, q in enumerate(u):
|
148 |
+
w[offset + i + j] += p*q
|
149 |
+
|
150 |
+
for j in range(len(w) - 1, k - 1, -1):
|
151 |
+
for i in range(k):
|
152 |
+
w[j - i - 1] += w[j]*c[i]
|
153 |
+
|
154 |
+
return w[:k]
|
155 |
+
|
156 |
+
def _final_coeffs(n):
|
157 |
+
# computes the final coefficient list - `cf` corresponding to the
|
158 |
+
# point at which recurrence is to be evalauted - `n`, such that,
|
159 |
+
# `y(n) = cf_0 y(k-1) + cf_1 y(k-2) + \cdots + cf_{k-1} y(0)`
|
160 |
+
|
161 |
+
if n < k:
|
162 |
+
return [S.Zero]*n + [S.One] + [S.Zero]*(k - n - 1)
|
163 |
+
else:
|
164 |
+
return _square_and_reduce(_final_coeffs(n // 2), n % 2)
|
165 |
+
|
166 |
+
return _final_coeffs(n)
|
llmeval-env/lib/python3.10/site-packages/sympy/discrete/tests/__init__.py
ADDED
File without changes
|
llmeval-env/lib/python3.10/site-packages/sympy/discrete/tests/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (193 Bytes). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/discrete/tests/__pycache__/test_convolutions.cpython-310.pyc
ADDED
Binary file (15.3 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/discrete/tests/__pycache__/test_recurrences.cpython-310.pyc
ADDED
Binary file (3.45 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/discrete/tests/__pycache__/test_transforms.cpython-310.pyc
ADDED
Binary file (6.74 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/discrete/tests/test_convolutions.py
ADDED
@@ -0,0 +1,365 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.core.numbers import (E, Rational, pi)
|
2 |
+
from sympy.functions.elementary.exponential import exp
|
3 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
4 |
+
from sympy.core import S, symbols, I
|
5 |
+
from sympy.discrete.convolutions import (
|
6 |
+
convolution, convolution_fft, convolution_ntt, convolution_fwht,
|
7 |
+
convolution_subset, covering_product, intersecting_product)
|
8 |
+
from sympy.testing.pytest import raises
|
9 |
+
from sympy.abc import x, y
|
10 |
+
|
11 |
+
def test_convolution():
|
12 |
+
# fft
|
13 |
+
a = [1, Rational(5, 3), sqrt(3), Rational(7, 5)]
|
14 |
+
b = [9, 5, 5, 4, 3, 2]
|
15 |
+
c = [3, 5, 3, 7, 8]
|
16 |
+
d = [1422, 6572, 3213, 5552]
|
17 |
+
|
18 |
+
assert convolution(a, b) == convolution_fft(a, b)
|
19 |
+
assert convolution(a, b, dps=9) == convolution_fft(a, b, dps=9)
|
20 |
+
assert convolution(a, d, dps=7) == convolution_fft(d, a, dps=7)
|
21 |
+
assert convolution(a, d[1:], dps=3) == convolution_fft(d[1:], a, dps=3)
|
22 |
+
|
23 |
+
# prime moduli of the form (m*2**k + 1), sequence length
|
24 |
+
# should be a divisor of 2**k
|
25 |
+
p = 7*17*2**23 + 1
|
26 |
+
q = 19*2**10 + 1
|
27 |
+
|
28 |
+
# ntt
|
29 |
+
assert convolution(d, b, prime=q) == convolution_ntt(b, d, prime=q)
|
30 |
+
assert convolution(c, b, prime=p) == convolution_ntt(b, c, prime=p)
|
31 |
+
assert convolution(d, c, prime=p) == convolution_ntt(c, d, prime=p)
|
32 |
+
raises(TypeError, lambda: convolution(b, d, dps=5, prime=q))
|
33 |
+
raises(TypeError, lambda: convolution(b, d, dps=6, prime=q))
|
34 |
+
|
35 |
+
# fwht
|
36 |
+
assert convolution(a, b, dyadic=True) == convolution_fwht(a, b)
|
37 |
+
assert convolution(a, b, dyadic=False) == convolution(a, b)
|
38 |
+
raises(TypeError, lambda: convolution(b, d, dps=2, dyadic=True))
|
39 |
+
raises(TypeError, lambda: convolution(b, d, prime=p, dyadic=True))
|
40 |
+
raises(TypeError, lambda: convolution(a, b, dps=2, dyadic=True))
|
41 |
+
raises(TypeError, lambda: convolution(b, c, prime=p, dyadic=True))
|
42 |
+
|
43 |
+
# subset
|
44 |
+
assert convolution(a, b, subset=True) == convolution_subset(a, b) == \
|
45 |
+
convolution(a, b, subset=True, dyadic=False) == \
|
46 |
+
convolution(a, b, subset=True)
|
47 |
+
assert convolution(a, b, subset=False) == convolution(a, b)
|
48 |
+
raises(TypeError, lambda: convolution(a, b, subset=True, dyadic=True))
|
49 |
+
raises(TypeError, lambda: convolution(c, d, subset=True, dps=6))
|
50 |
+
raises(TypeError, lambda: convolution(a, c, subset=True, prime=q))
|
51 |
+
|
52 |
+
|
53 |
+
def test_cyclic_convolution():
|
54 |
+
# fft
|
55 |
+
a = [1, Rational(5, 3), sqrt(3), Rational(7, 5)]
|
56 |
+
b = [9, 5, 5, 4, 3, 2]
|
57 |
+
|
58 |
+
assert convolution([1, 2, 3], [4, 5, 6], cycle=0) == \
|
59 |
+
convolution([1, 2, 3], [4, 5, 6], cycle=5) == \
|
60 |
+
convolution([1, 2, 3], [4, 5, 6])
|
61 |
+
|
62 |
+
assert convolution([1, 2, 3], [4, 5, 6], cycle=3) == [31, 31, 28]
|
63 |
+
|
64 |
+
a = [Rational(1, 3), Rational(7, 3), Rational(5, 9), Rational(2, 7), Rational(5, 8)]
|
65 |
+
b = [Rational(3, 5), Rational(4, 7), Rational(7, 8), Rational(8, 9)]
|
66 |
+
|
67 |
+
assert convolution(a, b, cycle=0) == \
|
68 |
+
convolution(a, b, cycle=len(a) + len(b) - 1)
|
69 |
+
|
70 |
+
assert convolution(a, b, cycle=4) == [Rational(87277, 26460), Rational(30521, 11340),
|
71 |
+
Rational(11125, 4032), Rational(3653, 1080)]
|
72 |
+
|
73 |
+
assert convolution(a, b, cycle=6) == [Rational(20177, 20160), Rational(676, 315), Rational(47, 24),
|
74 |
+
Rational(3053, 1080), Rational(16397, 5292), Rational(2497, 2268)]
|
75 |
+
|
76 |
+
assert convolution(a, b, cycle=9) == \
|
77 |
+
convolution(a, b, cycle=0) + [S.Zero]
|
78 |
+
|
79 |
+
# ntt
|
80 |
+
a = [2313, 5323532, S(3232), 42142, 42242421]
|
81 |
+
b = [S(33456), 56757, 45754, 432423]
|
82 |
+
|
83 |
+
assert convolution(a, b, prime=19*2**10 + 1, cycle=0) == \
|
84 |
+
convolution(a, b, prime=19*2**10 + 1, cycle=8) == \
|
85 |
+
convolution(a, b, prime=19*2**10 + 1)
|
86 |
+
|
87 |
+
assert convolution(a, b, prime=19*2**10 + 1, cycle=5) == [96, 17146, 2664,
|
88 |
+
15534, 3517]
|
89 |
+
|
90 |
+
assert convolution(a, b, prime=19*2**10 + 1, cycle=7) == [4643, 3458, 1260,
|
91 |
+
15534, 3517, 16314, 13688]
|
92 |
+
|
93 |
+
assert convolution(a, b, prime=19*2**10 + 1, cycle=9) == \
|
94 |
+
convolution(a, b, prime=19*2**10 + 1) + [0]
|
95 |
+
|
96 |
+
# fwht
|
97 |
+
u, v, w, x, y = symbols('u v w x y')
|
98 |
+
p, q, r, s, t = symbols('p q r s t')
|
99 |
+
c = [u, v, w, x, y]
|
100 |
+
d = [p, q, r, s, t]
|
101 |
+
|
102 |
+
assert convolution(a, b, dyadic=True, cycle=3) == \
|
103 |
+
[2499522285783, 19861417974796, 4702176579021]
|
104 |
+
|
105 |
+
assert convolution(a, b, dyadic=True, cycle=5) == [2718149225143,
|
106 |
+
2114320852171, 20571217906407, 246166418903, 1413262436976]
|
107 |
+
|
108 |
+
assert convolution(c, d, dyadic=True, cycle=4) == \
|
109 |
+
[p*u + p*y + q*v + r*w + s*x + t*u + t*y,
|
110 |
+
p*v + q*u + q*y + r*x + s*w + t*v,
|
111 |
+
p*w + q*x + r*u + r*y + s*v + t*w,
|
112 |
+
p*x + q*w + r*v + s*u + s*y + t*x]
|
113 |
+
|
114 |
+
assert convolution(c, d, dyadic=True, cycle=6) == \
|
115 |
+
[p*u + q*v + r*w + r*y + s*x + t*w + t*y,
|
116 |
+
p*v + q*u + r*x + s*w + s*y + t*x,
|
117 |
+
p*w + q*x + r*u + s*v,
|
118 |
+
p*x + q*w + r*v + s*u,
|
119 |
+
p*y + t*u,
|
120 |
+
q*y + t*v]
|
121 |
+
|
122 |
+
# subset
|
123 |
+
assert convolution(a, b, subset=True, cycle=7) == [18266671799811,
|
124 |
+
178235365533, 213958794, 246166418903, 1413262436976,
|
125 |
+
2397553088697, 1932759730434]
|
126 |
+
|
127 |
+
assert convolution(a[1:], b, subset=True, cycle=4) == \
|
128 |
+
[178104086592, 302255835516, 244982785880, 3717819845434]
|
129 |
+
|
130 |
+
assert convolution(a, b[:-1], subset=True, cycle=6) == [1932837114162,
|
131 |
+
178235365533, 213958794, 245166224504, 1413262436976, 2397553088697]
|
132 |
+
|
133 |
+
assert convolution(c, d, subset=True, cycle=3) == \
|
134 |
+
[p*u + p*x + q*w + r*v + r*y + s*u + t*w,
|
135 |
+
p*v + p*y + q*u + s*y + t*u + t*x,
|
136 |
+
p*w + q*y + r*u + t*v]
|
137 |
+
|
138 |
+
assert convolution(c, d, subset=True, cycle=5) == \
|
139 |
+
[p*u + q*y + t*v,
|
140 |
+
p*v + q*u + r*y + t*w,
|
141 |
+
p*w + r*u + s*y + t*x,
|
142 |
+
p*x + q*w + r*v + s*u,
|
143 |
+
p*y + t*u]
|
144 |
+
|
145 |
+
raises(ValueError, lambda: convolution([1, 2, 3], [4, 5, 6], cycle=-1))
|
146 |
+
|
147 |
+
|
148 |
+
def test_convolution_fft():
|
149 |
+
assert all(convolution_fft([], x, dps=y) == [] for x in ([], [1]) for y in (None, 3))
|
150 |
+
assert convolution_fft([1, 2, 3], [4, 5, 6]) == [4, 13, 28, 27, 18]
|
151 |
+
assert convolution_fft([1], [5, 6, 7]) == [5, 6, 7]
|
152 |
+
assert convolution_fft([1, 3], [5, 6, 7]) == [5, 21, 25, 21]
|
153 |
+
|
154 |
+
assert convolution_fft([1 + 2*I], [2 + 3*I]) == [-4 + 7*I]
|
155 |
+
assert convolution_fft([1 + 2*I, 3 + 4*I, 5 + 3*I/5], [Rational(2, 5) + 4*I/7]) == \
|
156 |
+
[Rational(-26, 35) + I*48/35, Rational(-38, 35) + I*116/35, Rational(58, 35) + I*542/175]
|
157 |
+
|
158 |
+
assert convolution_fft([Rational(3, 4), Rational(5, 6)], [Rational(7, 8), Rational(1, 3), Rational(2, 5)]) == \
|
159 |
+
[Rational(21, 32), Rational(47, 48), Rational(26, 45), Rational(1, 3)]
|
160 |
+
|
161 |
+
assert convolution_fft([Rational(1, 9), Rational(2, 3), Rational(3, 5)], [Rational(2, 5), Rational(3, 7), Rational(4, 9)]) == \
|
162 |
+
[Rational(2, 45), Rational(11, 35), Rational(8152, 14175), Rational(523, 945), Rational(4, 15)]
|
163 |
+
|
164 |
+
assert convolution_fft([pi, E, sqrt(2)], [sqrt(3), 1/pi, 1/E]) == \
|
165 |
+
[sqrt(3)*pi, 1 + sqrt(3)*E, E/pi + pi*exp(-1) + sqrt(6),
|
166 |
+
sqrt(2)/pi + 1, sqrt(2)*exp(-1)]
|
167 |
+
|
168 |
+
assert convolution_fft([2321, 33123], [5321, 6321, 71323]) == \
|
169 |
+
[12350041, 190918524, 374911166, 2362431729]
|
170 |
+
|
171 |
+
assert convolution_fft([312313, 31278232], [32139631, 319631]) == \
|
172 |
+
[10037624576503, 1005370659728895, 9997492572392]
|
173 |
+
|
174 |
+
raises(TypeError, lambda: convolution_fft(x, y))
|
175 |
+
raises(ValueError, lambda: convolution_fft([x, y], [y, x]))
|
176 |
+
|
177 |
+
|
178 |
+
def test_convolution_ntt():
|
179 |
+
# prime moduli of the form (m*2**k + 1), sequence length
|
180 |
+
# should be a divisor of 2**k
|
181 |
+
p = 7*17*2**23 + 1
|
182 |
+
q = 19*2**10 + 1
|
183 |
+
r = 2*500000003 + 1 # only for sequences of length 1 or 2
|
184 |
+
# s = 2*3*5*7 # composite modulus
|
185 |
+
|
186 |
+
assert all(convolution_ntt([], x, prime=y) == [] for x in ([], [1]) for y in (p, q, r))
|
187 |
+
assert convolution_ntt([2], [3], r) == [6]
|
188 |
+
assert convolution_ntt([2, 3], [4], r) == [8, 12]
|
189 |
+
|
190 |
+
assert convolution_ntt([32121, 42144, 4214, 4241], [32132, 3232, 87242], p) == [33867619,
|
191 |
+
459741727, 79180879, 831885249, 381344700, 369993322]
|
192 |
+
assert convolution_ntt([121913, 3171831, 31888131, 12], [17882, 21292, 29921, 312], q) == \
|
193 |
+
[8158, 3065, 3682, 7090, 1239, 2232, 3744]
|
194 |
+
|
195 |
+
assert convolution_ntt([12, 19, 21, 98, 67], [2, 6, 7, 8, 9], p) == \
|
196 |
+
convolution_ntt([12, 19, 21, 98, 67], [2, 6, 7, 8, 9], q)
|
197 |
+
assert convolution_ntt([12, 19, 21, 98, 67], [21, 76, 17, 78, 69], p) == \
|
198 |
+
convolution_ntt([12, 19, 21, 98, 67], [21, 76, 17, 78, 69], q)
|
199 |
+
|
200 |
+
raises(ValueError, lambda: convolution_ntt([2, 3], [4, 5], r))
|
201 |
+
raises(ValueError, lambda: convolution_ntt([x, y], [y, x], q))
|
202 |
+
raises(TypeError, lambda: convolution_ntt(x, y, p))
|
203 |
+
|
204 |
+
|
205 |
+
def test_convolution_fwht():
|
206 |
+
assert convolution_fwht([], []) == []
|
207 |
+
assert convolution_fwht([], [1]) == []
|
208 |
+
assert convolution_fwht([1, 2, 3], [4, 5, 6]) == [32, 13, 18, 27]
|
209 |
+
|
210 |
+
assert convolution_fwht([Rational(5, 7), Rational(6, 8), Rational(7, 3)], [2, 4, Rational(6, 7)]) == \
|
211 |
+
[Rational(45, 7), Rational(61, 14), Rational(776, 147), Rational(419, 42)]
|
212 |
+
|
213 |
+
a = [1, Rational(5, 3), sqrt(3), Rational(7, 5), 4 + 5*I]
|
214 |
+
b = [94, 51, 53, 45, 31, 27, 13]
|
215 |
+
c = [3 + 4*I, 5 + 7*I, 3, Rational(7, 6), 8]
|
216 |
+
|
217 |
+
assert convolution_fwht(a, b) == [53*sqrt(3) + 366 + 155*I,
|
218 |
+
45*sqrt(3) + Rational(5848, 15) + 135*I,
|
219 |
+
94*sqrt(3) + Rational(1257, 5) + 65*I,
|
220 |
+
51*sqrt(3) + Rational(3974, 15),
|
221 |
+
13*sqrt(3) + 452 + 470*I,
|
222 |
+
Rational(4513, 15) + 255*I,
|
223 |
+
31*sqrt(3) + Rational(1314, 5) + 265*I,
|
224 |
+
27*sqrt(3) + Rational(3676, 15) + 225*I]
|
225 |
+
|
226 |
+
assert convolution_fwht(b, c) == [Rational(1993, 2) + 733*I, Rational(6215, 6) + 862*I,
|
227 |
+
Rational(1659, 2) + 527*I, Rational(1988, 3) + 551*I, 1019 + 313*I, Rational(3955, 6) + 325*I,
|
228 |
+
Rational(1175, 2) + 52*I, Rational(3253, 6) + 91*I]
|
229 |
+
|
230 |
+
assert convolution_fwht(a[3:], c) == [Rational(-54, 5) + I*293/5, -1 + I*204/5,
|
231 |
+
Rational(133, 15) + I*35/6, Rational(409, 30) + 15*I, Rational(56, 5), 32 + 40*I, 0, 0]
|
232 |
+
|
233 |
+
u, v, w, x, y, z = symbols('u v w x y z')
|
234 |
+
|
235 |
+
assert convolution_fwht([u, v], [x, y]) == [u*x + v*y, u*y + v*x]
|
236 |
+
|
237 |
+
assert convolution_fwht([u, v, w], [x, y]) == \
|
238 |
+
[u*x + v*y, u*y + v*x, w*x, w*y]
|
239 |
+
|
240 |
+
assert convolution_fwht([u, v, w], [x, y, z]) == \
|
241 |
+
[u*x + v*y + w*z, u*y + v*x, u*z + w*x, v*z + w*y]
|
242 |
+
|
243 |
+
raises(TypeError, lambda: convolution_fwht(x, y))
|
244 |
+
raises(TypeError, lambda: convolution_fwht(x*y, u + v))
|
245 |
+
|
246 |
+
|
247 |
+
def test_convolution_subset():
|
248 |
+
assert convolution_subset([], []) == []
|
249 |
+
assert convolution_subset([], [Rational(1, 3)]) == []
|
250 |
+
assert convolution_subset([6 + I*3/7], [Rational(2, 3)]) == [4 + I*2/7]
|
251 |
+
|
252 |
+
a = [1, Rational(5, 3), sqrt(3), 4 + 5*I]
|
253 |
+
b = [64, 71, 55, 47, 33, 29, 15]
|
254 |
+
c = [3 + I*2/3, 5 + 7*I, 7, Rational(7, 5), 9]
|
255 |
+
|
256 |
+
assert convolution_subset(a, b) == [64, Rational(533, 3), 55 + 64*sqrt(3),
|
257 |
+
71*sqrt(3) + Rational(1184, 3) + 320*I, 33, 84,
|
258 |
+
15 + 33*sqrt(3), 29*sqrt(3) + 157 + 165*I]
|
259 |
+
|
260 |
+
assert convolution_subset(b, c) == [192 + I*128/3, 533 + I*1486/3,
|
261 |
+
613 + I*110/3, Rational(5013, 5) + I*1249/3,
|
262 |
+
675 + 22*I, 891 + I*751/3,
|
263 |
+
771 + 10*I, Rational(3736, 5) + 105*I]
|
264 |
+
|
265 |
+
assert convolution_subset(a, c) == convolution_subset(c, a)
|
266 |
+
assert convolution_subset(a[:2], b) == \
|
267 |
+
[64, Rational(533, 3), 55, Rational(416, 3), 33, 84, 15, 25]
|
268 |
+
|
269 |
+
assert convolution_subset(a[:2], c) == \
|
270 |
+
[3 + I*2/3, 10 + I*73/9, 7, Rational(196, 15), 9, 15, 0, 0]
|
271 |
+
|
272 |
+
u, v, w, x, y, z = symbols('u v w x y z')
|
273 |
+
|
274 |
+
assert convolution_subset([u, v, w], [x, y]) == [u*x, u*y + v*x, w*x, w*y]
|
275 |
+
assert convolution_subset([u, v, w, x], [y, z]) == \
|
276 |
+
[u*y, u*z + v*y, w*y, w*z + x*y]
|
277 |
+
|
278 |
+
assert convolution_subset([u, v], [x, y, z]) == \
|
279 |
+
convolution_subset([x, y, z], [u, v])
|
280 |
+
|
281 |
+
raises(TypeError, lambda: convolution_subset(x, z))
|
282 |
+
raises(TypeError, lambda: convolution_subset(Rational(7, 3), u))
|
283 |
+
|
284 |
+
|
285 |
+
def test_covering_product():
|
286 |
+
assert covering_product([], []) == []
|
287 |
+
assert covering_product([], [Rational(1, 3)]) == []
|
288 |
+
assert covering_product([6 + I*3/7], [Rational(2, 3)]) == [4 + I*2/7]
|
289 |
+
|
290 |
+
a = [1, Rational(5, 8), sqrt(7), 4 + 9*I]
|
291 |
+
b = [66, 81, 95, 49, 37, 89, 17]
|
292 |
+
c = [3 + I*2/3, 51 + 72*I, 7, Rational(7, 15), 91]
|
293 |
+
|
294 |
+
assert covering_product(a, b) == [66, Rational(1383, 8), 95 + 161*sqrt(7),
|
295 |
+
130*sqrt(7) + 1303 + 2619*I, 37,
|
296 |
+
Rational(671, 4), 17 + 54*sqrt(7),
|
297 |
+
89*sqrt(7) + Rational(4661, 8) + 1287*I]
|
298 |
+
|
299 |
+
assert covering_product(b, c) == [198 + 44*I, 7740 + 10638*I,
|
300 |
+
1412 + I*190/3, Rational(42684, 5) + I*31202/3,
|
301 |
+
9484 + I*74/3, 22163 + I*27394/3,
|
302 |
+
10621 + I*34/3, Rational(90236, 15) + 1224*I]
|
303 |
+
|
304 |
+
assert covering_product(a, c) == covering_product(c, a)
|
305 |
+
assert covering_product(b, c[:-1]) == [198 + 44*I, 7740 + 10638*I,
|
306 |
+
1412 + I*190/3, Rational(42684, 5) + I*31202/3,
|
307 |
+
111 + I*74/3, 6693 + I*27394/3,
|
308 |
+
429 + I*34/3, Rational(23351, 15) + 1224*I]
|
309 |
+
|
310 |
+
assert covering_product(a, c[:-1]) == [3 + I*2/3,
|
311 |
+
Rational(339, 4) + I*1409/12, 7 + 10*sqrt(7) + 2*sqrt(7)*I/3,
|
312 |
+
-403 + 772*sqrt(7)/15 + 72*sqrt(7)*I + I*12658/15]
|
313 |
+
|
314 |
+
u, v, w, x, y, z = symbols('u v w x y z')
|
315 |
+
|
316 |
+
assert covering_product([u, v, w], [x, y]) == \
|
317 |
+
[u*x, u*y + v*x + v*y, w*x, w*y]
|
318 |
+
|
319 |
+
assert covering_product([u, v, w, x], [y, z]) == \
|
320 |
+
[u*y, u*z + v*y + v*z, w*y, w*z + x*y + x*z]
|
321 |
+
|
322 |
+
assert covering_product([u, v], [x, y, z]) == \
|
323 |
+
covering_product([x, y, z], [u, v])
|
324 |
+
|
325 |
+
raises(TypeError, lambda: covering_product(x, z))
|
326 |
+
raises(TypeError, lambda: covering_product(Rational(7, 3), u))
|
327 |
+
|
328 |
+
|
329 |
+
def test_intersecting_product():
|
330 |
+
assert intersecting_product([], []) == []
|
331 |
+
assert intersecting_product([], [Rational(1, 3)]) == []
|
332 |
+
assert intersecting_product([6 + I*3/7], [Rational(2, 3)]) == [4 + I*2/7]
|
333 |
+
|
334 |
+
a = [1, sqrt(5), Rational(3, 8) + 5*I, 4 + 7*I]
|
335 |
+
b = [67, 51, 65, 48, 36, 79, 27]
|
336 |
+
c = [3 + I*2/5, 5 + 9*I, 7, Rational(7, 19), 13]
|
337 |
+
|
338 |
+
assert intersecting_product(a, b) == [195*sqrt(5) + Rational(6979, 8) + 1886*I,
|
339 |
+
178*sqrt(5) + 520 + 910*I, Rational(841, 2) + 1344*I,
|
340 |
+
192 + 336*I, 0, 0, 0, 0]
|
341 |
+
|
342 |
+
assert intersecting_product(b, c) == [Rational(128553, 19) + I*9521/5,
|
343 |
+
Rational(17820, 19) + 1602*I, Rational(19264, 19), Rational(336, 19), 1846, 0, 0, 0]
|
344 |
+
|
345 |
+
assert intersecting_product(a, c) == intersecting_product(c, a)
|
346 |
+
assert intersecting_product(b[1:], c[:-1]) == [Rational(64788, 19) + I*8622/5,
|
347 |
+
Rational(12804, 19) + 1152*I, Rational(11508, 19), Rational(252, 19), 0, 0, 0, 0]
|
348 |
+
|
349 |
+
assert intersecting_product(a, c[:-2]) == \
|
350 |
+
[Rational(-99, 5) + 10*sqrt(5) + 2*sqrt(5)*I/5 + I*3021/40,
|
351 |
+
-43 + 5*sqrt(5) + 9*sqrt(5)*I + 71*I, Rational(245, 8) + 84*I, 0]
|
352 |
+
|
353 |
+
u, v, w, x, y, z = symbols('u v w x y z')
|
354 |
+
|
355 |
+
assert intersecting_product([u, v, w], [x, y]) == \
|
356 |
+
[u*x + u*y + v*x + w*x + w*y, v*y, 0, 0]
|
357 |
+
|
358 |
+
assert intersecting_product([u, v, w, x], [y, z]) == \
|
359 |
+
[u*y + u*z + v*y + w*y + w*z + x*y, v*z + x*z, 0, 0]
|
360 |
+
|
361 |
+
assert intersecting_product([u, v], [x, y, z]) == \
|
362 |
+
intersecting_product([x, y, z], [u, v])
|
363 |
+
|
364 |
+
raises(TypeError, lambda: intersecting_product(x, z))
|
365 |
+
raises(TypeError, lambda: intersecting_product(u, Rational(8, 3)))
|
llmeval-env/lib/python3.10/site-packages/sympy/discrete/tests/test_recurrences.py
ADDED
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.core.numbers import Rational
|
2 |
+
from sympy.functions.combinatorial.numbers import fibonacci
|
3 |
+
from sympy.core import S, symbols
|
4 |
+
from sympy.testing.pytest import raises
|
5 |
+
from sympy.discrete.recurrences import linrec
|
6 |
+
|
7 |
+
def test_linrec():
|
8 |
+
assert linrec(coeffs=[1, 1], init=[1, 1], n=20) == 10946
|
9 |
+
assert linrec(coeffs=[1, 2, 3, 4, 5], init=[1, 1, 0, 2], n=10) == 1040
|
10 |
+
assert linrec(coeffs=[0, 0, 11, 13], init=[23, 27], n=25) == 59628567384
|
11 |
+
assert linrec(coeffs=[0, 0, 1, 1, 2], init=[1, 5, 3], n=15) == 165
|
12 |
+
assert linrec(coeffs=[11, 13, 15, 17], init=[1, 2, 3, 4], n=70) == \
|
13 |
+
56889923441670659718376223533331214868804815612050381493741233489928913241
|
14 |
+
assert linrec(coeffs=[0]*55 + [1, 1, 2, 3], init=[0]*50 + [1, 2, 3], n=4000) == \
|
15 |
+
702633573874937994980598979769135096432444135301118916539
|
16 |
+
|
17 |
+
assert linrec(coeffs=[11, 13, 15, 17], init=[1, 2, 3, 4], n=10**4)
|
18 |
+
assert linrec(coeffs=[11, 13, 15, 17], init=[1, 2, 3, 4], n=10**5)
|
19 |
+
|
20 |
+
assert all(linrec(coeffs=[1, 1], init=[0, 1], n=n) == fibonacci(n)
|
21 |
+
for n in range(95, 115))
|
22 |
+
|
23 |
+
assert all(linrec(coeffs=[1, 1], init=[1, 1], n=n) == fibonacci(n + 1)
|
24 |
+
for n in range(595, 615))
|
25 |
+
|
26 |
+
a = [S.Half, Rational(3, 4), Rational(5, 6), 7, Rational(8, 9), Rational(3, 5)]
|
27 |
+
b = [1, 2, 8, Rational(5, 7), Rational(3, 7), Rational(2, 9), 6]
|
28 |
+
x, y, z = symbols('x y z')
|
29 |
+
|
30 |
+
assert linrec(coeffs=a[:5], init=b[:4], n=80) == \
|
31 |
+
Rational(1726244235456268979436592226626304376013002142588105090705187189,
|
32 |
+
1960143456748895967474334873705475211264)
|
33 |
+
|
34 |
+
assert linrec(coeffs=a[:4], init=b[:4], n=50) == \
|
35 |
+
Rational(368949940033050147080268092104304441, 504857282956046106624)
|
36 |
+
|
37 |
+
assert linrec(coeffs=a[3:], init=b[:3], n=35) == \
|
38 |
+
Rational(97409272177295731943657945116791049305244422833125109,
|
39 |
+
814315512679031689453125)
|
40 |
+
|
41 |
+
assert linrec(coeffs=[0]*60 + [Rational(2, 3), Rational(4, 5)], init=b, n=3000) == \
|
42 |
+
Rational(26777668739896791448594650497024, 48084516708184142230517578125)
|
43 |
+
|
44 |
+
raises(TypeError, lambda: linrec(coeffs=[11, 13, 15, 17], init=[1, 2, 3, 4, 5], n=1))
|
45 |
+
raises(TypeError, lambda: linrec(coeffs=a[:4], init=b[:5], n=10000))
|
46 |
+
raises(ValueError, lambda: linrec(coeffs=a[:4], init=b[:4], n=-10000))
|
47 |
+
raises(TypeError, lambda: linrec(x, b, n=10000))
|
48 |
+
raises(TypeError, lambda: linrec(a, y, n=10000))
|
49 |
+
|
50 |
+
assert linrec(coeffs=[x, y, z], init=[1, 1, 1], n=4) == \
|
51 |
+
x**2 + x*y + x*z + y + z
|
52 |
+
assert linrec(coeffs=[1, 2, 1], init=[x, y, z], n=20) == \
|
53 |
+
269542*x + 664575*y + 578949*z
|
54 |
+
assert linrec(coeffs=[0, 3, 1, 2], init=[x, y], n=30) == \
|
55 |
+
58516436*x + 56372788*y
|
56 |
+
assert linrec(coeffs=[0]*50 + [1, 2, 3], init=[x, y, z], n=1000) == \
|
57 |
+
11477135884896*x + 25999077948732*y + 41975630244216*z
|
58 |
+
assert linrec(coeffs=[], init=[1, 1], n=20) == 0
|
59 |
+
assert linrec(coeffs=[x, y, z], init=[1, 2, 3], n=2) == 3
|
llmeval-env/lib/python3.10/site-packages/sympy/discrete/tests/test_transforms.py
ADDED
@@ -0,0 +1,154 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
2 |
+
from sympy.core import S, Symbol, symbols, I, Rational
|
3 |
+
from sympy.discrete import (fft, ifft, ntt, intt, fwht, ifwht,
|
4 |
+
mobius_transform, inverse_mobius_transform)
|
5 |
+
from sympy.testing.pytest import raises
|
6 |
+
|
7 |
+
|
8 |
+
def test_fft_ifft():
|
9 |
+
assert all(tf(ls) == ls for tf in (fft, ifft)
|
10 |
+
for ls in ([], [Rational(5, 3)]))
|
11 |
+
|
12 |
+
ls = list(range(6))
|
13 |
+
fls = [15, -7*sqrt(2)/2 - 4 - sqrt(2)*I/2 + 2*I, 2 + 3*I,
|
14 |
+
-4 + 7*sqrt(2)/2 - 2*I - sqrt(2)*I/2, -3,
|
15 |
+
-4 + 7*sqrt(2)/2 + sqrt(2)*I/2 + 2*I,
|
16 |
+
2 - 3*I, -7*sqrt(2)/2 - 4 - 2*I + sqrt(2)*I/2]
|
17 |
+
|
18 |
+
assert fft(ls) == fls
|
19 |
+
assert ifft(fls) == ls + [S.Zero]*2
|
20 |
+
|
21 |
+
ls = [1 + 2*I, 3 + 4*I, 5 + 6*I]
|
22 |
+
ifls = [Rational(9, 4) + 3*I, I*Rational(-7, 4), Rational(3, 4) + I, -2 - I/4]
|
23 |
+
|
24 |
+
assert ifft(ls) == ifls
|
25 |
+
assert fft(ifls) == ls + [S.Zero]
|
26 |
+
|
27 |
+
x = Symbol('x', real=True)
|
28 |
+
raises(TypeError, lambda: fft(x))
|
29 |
+
raises(ValueError, lambda: ifft([x, 2*x, 3*x**2, 4*x**3]))
|
30 |
+
|
31 |
+
|
32 |
+
def test_ntt_intt():
|
33 |
+
# prime moduli of the form (m*2**k + 1), sequence length
|
34 |
+
# should be a divisor of 2**k
|
35 |
+
p = 7*17*2**23 + 1
|
36 |
+
q = 2*500000003 + 1 # only for sequences of length 1 or 2
|
37 |
+
r = 2*3*5*7 # composite modulus
|
38 |
+
|
39 |
+
assert all(tf(ls, p) == ls for tf in (ntt, intt)
|
40 |
+
for ls in ([], [5]))
|
41 |
+
|
42 |
+
ls = list(range(6))
|
43 |
+
nls = [15, 801133602, 738493201, 334102277, 998244350, 849020224,
|
44 |
+
259751156, 12232587]
|
45 |
+
|
46 |
+
assert ntt(ls, p) == nls
|
47 |
+
assert intt(nls, p) == ls + [0]*2
|
48 |
+
|
49 |
+
ls = [1 + 2*I, 3 + 4*I, 5 + 6*I]
|
50 |
+
x = Symbol('x', integer=True)
|
51 |
+
|
52 |
+
raises(TypeError, lambda: ntt(x, p))
|
53 |
+
raises(ValueError, lambda: intt([x, 2*x, 3*x**2, 4*x**3], p))
|
54 |
+
raises(ValueError, lambda: intt(ls, p))
|
55 |
+
raises(ValueError, lambda: ntt([1.2, 2.1, 3.5], p))
|
56 |
+
raises(ValueError, lambda: ntt([3, 5, 6], q))
|
57 |
+
raises(ValueError, lambda: ntt([4, 5, 7], r))
|
58 |
+
raises(ValueError, lambda: ntt([1.0, 2.0, 3.0], p))
|
59 |
+
|
60 |
+
|
61 |
+
def test_fwht_ifwht():
|
62 |
+
assert all(tf(ls) == ls for tf in (fwht, ifwht) \
|
63 |
+
for ls in ([], [Rational(7, 4)]))
|
64 |
+
|
65 |
+
ls = [213, 321, 43235, 5325, 312, 53]
|
66 |
+
fls = [49459, 38061, -47661, -37759, 48729, 37543, -48391, -38277]
|
67 |
+
|
68 |
+
assert fwht(ls) == fls
|
69 |
+
assert ifwht(fls) == ls + [S.Zero]*2
|
70 |
+
|
71 |
+
ls = [S.Half + 2*I, Rational(3, 7) + 4*I, Rational(5, 6) + 6*I, Rational(7, 3), Rational(9, 4)]
|
72 |
+
ifls = [Rational(533, 672) + I*3/2, Rational(23, 224) + I/2, Rational(1, 672), Rational(107, 224) - I,
|
73 |
+
Rational(155, 672) + I*3/2, Rational(-103, 224) + I/2, Rational(-377, 672), Rational(-19, 224) - I]
|
74 |
+
|
75 |
+
assert ifwht(ls) == ifls
|
76 |
+
assert fwht(ifls) == ls + [S.Zero]*3
|
77 |
+
|
78 |
+
x, y = symbols('x y')
|
79 |
+
|
80 |
+
raises(TypeError, lambda: fwht(x))
|
81 |
+
|
82 |
+
ls = [x, 2*x, 3*x**2, 4*x**3]
|
83 |
+
ifls = [x**3 + 3*x**2/4 + x*Rational(3, 4),
|
84 |
+
-x**3 + 3*x**2/4 - x/4,
|
85 |
+
-x**3 - 3*x**2/4 + x*Rational(3, 4),
|
86 |
+
x**3 - 3*x**2/4 - x/4]
|
87 |
+
|
88 |
+
assert ifwht(ls) == ifls
|
89 |
+
assert fwht(ifls) == ls
|
90 |
+
|
91 |
+
ls = [x, y, x**2, y**2, x*y]
|
92 |
+
fls = [x**2 + x*y + x + y**2 + y,
|
93 |
+
x**2 + x*y + x - y**2 - y,
|
94 |
+
-x**2 + x*y + x - y**2 + y,
|
95 |
+
-x**2 + x*y + x + y**2 - y,
|
96 |
+
x**2 - x*y + x + y**2 + y,
|
97 |
+
x**2 - x*y + x - y**2 - y,
|
98 |
+
-x**2 - x*y + x - y**2 + y,
|
99 |
+
-x**2 - x*y + x + y**2 - y]
|
100 |
+
|
101 |
+
assert fwht(ls) == fls
|
102 |
+
assert ifwht(fls) == ls + [S.Zero]*3
|
103 |
+
|
104 |
+
ls = list(range(6))
|
105 |
+
|
106 |
+
assert fwht(ls) == [x*8 for x in ifwht(ls)]
|
107 |
+
|
108 |
+
|
109 |
+
def test_mobius_transform():
|
110 |
+
assert all(tf(ls, subset=subset) == ls
|
111 |
+
for ls in ([], [Rational(7, 4)]) for subset in (True, False)
|
112 |
+
for tf in (mobius_transform, inverse_mobius_transform))
|
113 |
+
|
114 |
+
w, x, y, z = symbols('w x y z')
|
115 |
+
|
116 |
+
assert mobius_transform([x, y]) == [x, x + y]
|
117 |
+
assert inverse_mobius_transform([x, x + y]) == [x, y]
|
118 |
+
assert mobius_transform([x, y], subset=False) == [x + y, y]
|
119 |
+
assert inverse_mobius_transform([x + y, y], subset=False) == [x, y]
|
120 |
+
|
121 |
+
assert mobius_transform([w, x, y, z]) == [w, w + x, w + y, w + x + y + z]
|
122 |
+
assert inverse_mobius_transform([w, w + x, w + y, w + x + y + z]) == \
|
123 |
+
[w, x, y, z]
|
124 |
+
assert mobius_transform([w, x, y, z], subset=False) == \
|
125 |
+
[w + x + y + z, x + z, y + z, z]
|
126 |
+
assert inverse_mobius_transform([w + x + y + z, x + z, y + z, z], subset=False) == \
|
127 |
+
[w, x, y, z]
|
128 |
+
|
129 |
+
ls = [Rational(2, 3), Rational(6, 7), Rational(5, 8), 9, Rational(5, 3) + 7*I]
|
130 |
+
mls = [Rational(2, 3), Rational(32, 21), Rational(31, 24), Rational(1873, 168),
|
131 |
+
Rational(7, 3) + 7*I, Rational(67, 21) + 7*I, Rational(71, 24) + 7*I,
|
132 |
+
Rational(2153, 168) + 7*I]
|
133 |
+
|
134 |
+
assert mobius_transform(ls) == mls
|
135 |
+
assert inverse_mobius_transform(mls) == ls + [S.Zero]*3
|
136 |
+
|
137 |
+
mls = [Rational(2153, 168) + 7*I, Rational(69, 7), Rational(77, 8), 9, Rational(5, 3) + 7*I, 0, 0, 0]
|
138 |
+
|
139 |
+
assert mobius_transform(ls, subset=False) == mls
|
140 |
+
assert inverse_mobius_transform(mls, subset=False) == ls + [S.Zero]*3
|
141 |
+
|
142 |
+
ls = ls[:-1]
|
143 |
+
mls = [Rational(2, 3), Rational(32, 21), Rational(31, 24), Rational(1873, 168)]
|
144 |
+
|
145 |
+
assert mobius_transform(ls) == mls
|
146 |
+
assert inverse_mobius_transform(mls) == ls
|
147 |
+
|
148 |
+
mls = [Rational(1873, 168), Rational(69, 7), Rational(77, 8), 9]
|
149 |
+
|
150 |
+
assert mobius_transform(ls, subset=False) == mls
|
151 |
+
assert inverse_mobius_transform(mls, subset=False) == ls
|
152 |
+
|
153 |
+
raises(TypeError, lambda: mobius_transform(x, subset=True))
|
154 |
+
raises(TypeError, lambda: inverse_mobius_transform(y, subset=False))
|
llmeval-env/lib/python3.10/site-packages/sympy/discrete/transforms.py
ADDED
@@ -0,0 +1,425 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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+
from sympy.core.function import expand_mul
|
8 |
+
from sympy.core.numbers import pi, I
|
9 |
+
from sympy.functions.elementary.trigonometric import sin, cos
|
10 |
+
from sympy.ntheory import isprime, primitive_root
|
11 |
+
from sympy.utilities.iterables import ibin, iterable
|
12 |
+
from sympy.utilities.misc import as_int
|
13 |
+
|
14 |
+
|
15 |
+
#----------------------------------------------------------------------------#
|
16 |
+
# #
|
17 |
+
# Discrete Fourier Transform #
|
18 |
+
# #
|
19 |
+
#----------------------------------------------------------------------------#
|
20 |
+
|
21 |
+
def _fourier_transform(seq, dps, inverse=False):
|
22 |
+
"""Utility function for the Discrete Fourier Transform"""
|
23 |
+
|
24 |
+
if not iterable(seq):
|
25 |
+
raise TypeError("Expected a sequence of numeric coefficients "
|
26 |
+
"for Fourier Transform")
|
27 |
+
|
28 |
+
a = [sympify(arg) for arg in seq]
|
29 |
+
if any(x.has(Symbol) for x in a):
|
30 |
+
raise ValueError("Expected non-symbolic coefficients")
|
31 |
+
|
32 |
+
n = len(a)
|
33 |
+
if n < 2:
|
34 |
+
return a
|
35 |
+
|
36 |
+
b = n.bit_length() - 1
|
37 |
+
if n&(n - 1): # not a power of 2
|
38 |
+
b += 1
|
39 |
+
n = 2**b
|
40 |
+
|
41 |
+
a += [S.Zero]*(n - len(a))
|
42 |
+
for i in range(1, n):
|
43 |
+
j = int(ibin(i, b, str=True)[::-1], 2)
|
44 |
+
if i < j:
|
45 |
+
a[i], a[j] = a[j], a[i]
|
46 |
+
|
47 |
+
ang = -2*pi/n if inverse else 2*pi/n
|
48 |
+
|
49 |
+
if dps is not None:
|
50 |
+
ang = ang.evalf(dps + 2)
|
51 |
+
|
52 |
+
w = [cos(ang*i) + I*sin(ang*i) for i in range(n // 2)]
|
53 |
+
|
54 |
+
h = 2
|
55 |
+
while h <= n:
|
56 |
+
hf, ut = h // 2, n // h
|
57 |
+
for i in range(0, n, h):
|
58 |
+
for j in range(hf):
|
59 |
+
u, v = a[i + j], expand_mul(a[i + j + hf]*w[ut * j])
|
60 |
+
a[i + j], a[i + j + hf] = u + v, u - v
|
61 |
+
h *= 2
|
62 |
+
|
63 |
+
if inverse:
|
64 |
+
a = [(x/n).evalf(dps) for x in a] if dps is not None \
|
65 |
+
else [x/n for x in a]
|
66 |
+
|
67 |
+
return a
|
68 |
+
|
69 |
+
|
70 |
+
def fft(seq, dps=None):
|
71 |
+
r"""
|
72 |
+
Performs the Discrete Fourier Transform (**DFT**) in the complex domain.
|
73 |
+
|
74 |
+
The sequence is automatically padded to the right with zeros, as the
|
75 |
+
*radix-2 FFT* requires the number of sample points to be a power of 2.
|
76 |
+
|
77 |
+
This method should be used with default arguments only for short sequences
|
78 |
+
as the complexity of expressions increases with the size of the sequence.
|
79 |
+
|
80 |
+
Parameters
|
81 |
+
==========
|
82 |
+
|
83 |
+
seq : iterable
|
84 |
+
The sequence on which **DFT** is to be applied.
|
85 |
+
dps : Integer
|
86 |
+
Specifies the number of decimal digits for precision.
|
87 |
+
|
88 |
+
Examples
|
89 |
+
========
|
90 |
+
|
91 |
+
>>> from sympy import fft, ifft
|
92 |
+
|
93 |
+
>>> fft([1, 2, 3, 4])
|
94 |
+
[10, -2 - 2*I, -2, -2 + 2*I]
|
95 |
+
>>> ifft(_)
|
96 |
+
[1, 2, 3, 4]
|
97 |
+
|
98 |
+
>>> ifft([1, 2, 3, 4])
|
99 |
+
[5/2, -1/2 + I/2, -1/2, -1/2 - I/2]
|
100 |
+
>>> fft(_)
|
101 |
+
[1, 2, 3, 4]
|
102 |
+
|
103 |
+
>>> ifft([1, 7, 3, 4], dps=15)
|
104 |
+
[3.75, -0.5 - 0.75*I, -1.75, -0.5 + 0.75*I]
|
105 |
+
>>> fft(_)
|
106 |
+
[1.0, 7.0, 3.0, 4.0]
|
107 |
+
|
108 |
+
References
|
109 |
+
==========
|
110 |
+
|
111 |
+
.. [1] https://en.wikipedia.org/wiki/Cooley%E2%80%93Tukey_FFT_algorithm
|
112 |
+
.. [2] https://mathworld.wolfram.com/FastFourierTransform.html
|
113 |
+
|
114 |
+
"""
|
115 |
+
|
116 |
+
return _fourier_transform(seq, dps=dps)
|
117 |
+
|
118 |
+
|
119 |
+
def ifft(seq, dps=None):
|
120 |
+
return _fourier_transform(seq, dps=dps, inverse=True)
|
121 |
+
|
122 |
+
ifft.__doc__ = fft.__doc__
|
123 |
+
|
124 |
+
|
125 |
+
#----------------------------------------------------------------------------#
|
126 |
+
# #
|
127 |
+
# Number Theoretic Transform #
|
128 |
+
# #
|
129 |
+
#----------------------------------------------------------------------------#
|
130 |
+
|
131 |
+
def _number_theoretic_transform(seq, prime, inverse=False):
|
132 |
+
"""Utility function for the Number Theoretic Transform"""
|
133 |
+
|
134 |
+
if not iterable(seq):
|
135 |
+
raise TypeError("Expected a sequence of integer coefficients "
|
136 |
+
"for Number Theoretic Transform")
|
137 |
+
|
138 |
+
p = as_int(prime)
|
139 |
+
if not isprime(p):
|
140 |
+
raise ValueError("Expected prime modulus for "
|
141 |
+
"Number Theoretic Transform")
|
142 |
+
|
143 |
+
a = [as_int(x) % p for x in seq]
|
144 |
+
|
145 |
+
n = len(a)
|
146 |
+
if n < 1:
|
147 |
+
return a
|
148 |
+
|
149 |
+
b = n.bit_length() - 1
|
150 |
+
if n&(n - 1):
|
151 |
+
b += 1
|
152 |
+
n = 2**b
|
153 |
+
|
154 |
+
if (p - 1) % n:
|
155 |
+
raise ValueError("Expected prime modulus of the form (m*2**k + 1)")
|
156 |
+
|
157 |
+
a += [0]*(n - len(a))
|
158 |
+
for i in range(1, n):
|
159 |
+
j = int(ibin(i, b, str=True)[::-1], 2)
|
160 |
+
if i < j:
|
161 |
+
a[i], a[j] = a[j], a[i]
|
162 |
+
|
163 |
+
pr = primitive_root(p)
|
164 |
+
|
165 |
+
rt = pow(pr, (p - 1) // n, p)
|
166 |
+
if inverse:
|
167 |
+
rt = pow(rt, p - 2, p)
|
168 |
+
|
169 |
+
w = [1]*(n // 2)
|
170 |
+
for i in range(1, n // 2):
|
171 |
+
w[i] = w[i - 1]*rt % p
|
172 |
+
|
173 |
+
h = 2
|
174 |
+
while h <= n:
|
175 |
+
hf, ut = h // 2, n // h
|
176 |
+
for i in range(0, n, h):
|
177 |
+
for j in range(hf):
|
178 |
+
u, v = a[i + j], a[i + j + hf]*w[ut * j]
|
179 |
+
a[i + j], a[i + j + hf] = (u + v) % p, (u - v) % p
|
180 |
+
h *= 2
|
181 |
+
|
182 |
+
if inverse:
|
183 |
+
rv = pow(n, p - 2, p)
|
184 |
+
a = [x*rv % p for x in a]
|
185 |
+
|
186 |
+
return a
|
187 |
+
|
188 |
+
|
189 |
+
def ntt(seq, prime):
|
190 |
+
r"""
|
191 |
+
Performs the Number Theoretic Transform (**NTT**), which specializes the
|
192 |
+
Discrete Fourier Transform (**DFT**) over quotient ring `Z/pZ` for prime
|
193 |
+
`p` instead of complex numbers `C`.
|
194 |
+
|
195 |
+
The sequence is automatically padded to the right with zeros, as the
|
196 |
+
*radix-2 NTT* requires the number of sample points to be a power of 2.
|
197 |
+
|
198 |
+
Parameters
|
199 |
+
==========
|
200 |
+
|
201 |
+
seq : iterable
|
202 |
+
The sequence on which **DFT** is to be applied.
|
203 |
+
prime : Integer
|
204 |
+
Prime modulus of the form `(m 2^k + 1)` to be used for performing
|
205 |
+
**NTT** on the sequence.
|
206 |
+
|
207 |
+
Examples
|
208 |
+
========
|
209 |
+
|
210 |
+
>>> from sympy import ntt, intt
|
211 |
+
>>> ntt([1, 2, 3, 4], prime=3*2**8 + 1)
|
212 |
+
[10, 643, 767, 122]
|
213 |
+
>>> intt(_, 3*2**8 + 1)
|
214 |
+
[1, 2, 3, 4]
|
215 |
+
>>> intt([1, 2, 3, 4], prime=3*2**8 + 1)
|
216 |
+
[387, 415, 384, 353]
|
217 |
+
>>> ntt(_, prime=3*2**8 + 1)
|
218 |
+
[1, 2, 3, 4]
|
219 |
+
|
220 |
+
References
|
221 |
+
==========
|
222 |
+
|
223 |
+
.. [1] http://www.apfloat.org/ntt.html
|
224 |
+
.. [2] https://mathworld.wolfram.com/NumberTheoreticTransform.html
|
225 |
+
.. [3] https://en.wikipedia.org/wiki/Discrete_Fourier_transform_(general%29
|
226 |
+
|
227 |
+
"""
|
228 |
+
|
229 |
+
return _number_theoretic_transform(seq, prime=prime)
|
230 |
+
|
231 |
+
|
232 |
+
def intt(seq, prime):
|
233 |
+
return _number_theoretic_transform(seq, prime=prime, inverse=True)
|
234 |
+
|
235 |
+
intt.__doc__ = ntt.__doc__
|
236 |
+
|
237 |
+
|
238 |
+
#----------------------------------------------------------------------------#
|
239 |
+
# #
|
240 |
+
# Walsh Hadamard Transform #
|
241 |
+
# #
|
242 |
+
#----------------------------------------------------------------------------#
|
243 |
+
|
244 |
+
def _walsh_hadamard_transform(seq, inverse=False):
|
245 |
+
"""Utility function for the Walsh Hadamard Transform"""
|
246 |
+
|
247 |
+
if not iterable(seq):
|
248 |
+
raise TypeError("Expected a sequence of coefficients "
|
249 |
+
"for Walsh Hadamard Transform")
|
250 |
+
|
251 |
+
a = [sympify(arg) for arg in seq]
|
252 |
+
n = len(a)
|
253 |
+
if n < 2:
|
254 |
+
return a
|
255 |
+
|
256 |
+
if n&(n - 1):
|
257 |
+
n = 2**n.bit_length()
|
258 |
+
|
259 |
+
a += [S.Zero]*(n - len(a))
|
260 |
+
h = 2
|
261 |
+
while h <= n:
|
262 |
+
hf = h // 2
|
263 |
+
for i in range(0, n, h):
|
264 |
+
for j in range(hf):
|
265 |
+
u, v = a[i + j], a[i + j + hf]
|
266 |
+
a[i + j], a[i + j + hf] = u + v, u - v
|
267 |
+
h *= 2
|
268 |
+
|
269 |
+
if inverse:
|
270 |
+
a = [x/n for x in a]
|
271 |
+
|
272 |
+
return a
|
273 |
+
|
274 |
+
|
275 |
+
def fwht(seq):
|
276 |
+
r"""
|
277 |
+
Performs the Walsh Hadamard Transform (**WHT**), and uses Hadamard
|
278 |
+
ordering for the sequence.
|
279 |
+
|
280 |
+
The sequence is automatically padded to the right with zeros, as the
|
281 |
+
*radix-2 FWHT* requires the number of sample points to be a power of 2.
|
282 |
+
|
283 |
+
Parameters
|
284 |
+
==========
|
285 |
+
|
286 |
+
seq : iterable
|
287 |
+
The sequence on which WHT is to be applied.
|
288 |
+
|
289 |
+
Examples
|
290 |
+
========
|
291 |
+
|
292 |
+
>>> from sympy import fwht, ifwht
|
293 |
+
>>> fwht([4, 2, 2, 0, 0, 2, -2, 0])
|
294 |
+
[8, 0, 8, 0, 8, 8, 0, 0]
|
295 |
+
>>> ifwht(_)
|
296 |
+
[4, 2, 2, 0, 0, 2, -2, 0]
|
297 |
+
|
298 |
+
>>> ifwht([19, -1, 11, -9, -7, 13, -15, 5])
|
299 |
+
[2, 0, 4, 0, 3, 10, 0, 0]
|
300 |
+
>>> fwht(_)
|
301 |
+
[19, -1, 11, -9, -7, 13, -15, 5]
|
302 |
+
|
303 |
+
References
|
304 |
+
==========
|
305 |
+
|
306 |
+
.. [1] https://en.wikipedia.org/wiki/Hadamard_transform
|
307 |
+
.. [2] https://en.wikipedia.org/wiki/Fast_Walsh%E2%80%93Hadamard_transform
|
308 |
+
|
309 |
+
"""
|
310 |
+
|
311 |
+
return _walsh_hadamard_transform(seq)
|
312 |
+
|
313 |
+
|
314 |
+
def ifwht(seq):
|
315 |
+
return _walsh_hadamard_transform(seq, inverse=True)
|
316 |
+
|
317 |
+
ifwht.__doc__ = fwht.__doc__
|
318 |
+
|
319 |
+
|
320 |
+
#----------------------------------------------------------------------------#
|
321 |
+
# #
|
322 |
+
# Mobius Transform for Subset Lattice #
|
323 |
+
# #
|
324 |
+
#----------------------------------------------------------------------------#
|
325 |
+
|
326 |
+
def _mobius_transform(seq, sgn, subset):
|
327 |
+
r"""Utility function for performing Mobius Transform using
|
328 |
+
Yate's Dynamic Programming method"""
|
329 |
+
|
330 |
+
if not iterable(seq):
|
331 |
+
raise TypeError("Expected a sequence of coefficients")
|
332 |
+
|
333 |
+
a = [sympify(arg) for arg in seq]
|
334 |
+
|
335 |
+
n = len(a)
|
336 |
+
if n < 2:
|
337 |
+
return a
|
338 |
+
|
339 |
+
if n&(n - 1):
|
340 |
+
n = 2**n.bit_length()
|
341 |
+
|
342 |
+
a += [S.Zero]*(n - len(a))
|
343 |
+
|
344 |
+
if subset:
|
345 |
+
i = 1
|
346 |
+
while i < n:
|
347 |
+
for j in range(n):
|
348 |
+
if j & i:
|
349 |
+
a[j] += sgn*a[j ^ i]
|
350 |
+
i *= 2
|
351 |
+
|
352 |
+
else:
|
353 |
+
i = 1
|
354 |
+
while i < n:
|
355 |
+
for j in range(n):
|
356 |
+
if j & i:
|
357 |
+
continue
|
358 |
+
a[j] += sgn*a[j ^ i]
|
359 |
+
i *= 2
|
360 |
+
|
361 |
+
return a
|
362 |
+
|
363 |
+
|
364 |
+
def mobius_transform(seq, subset=True):
|
365 |
+
r"""
|
366 |
+
Performs the Mobius Transform for subset lattice with indices of
|
367 |
+
sequence as bitmasks.
|
368 |
+
|
369 |
+
The indices of each argument, considered as bit strings, correspond
|
370 |
+
to subsets of a finite set.
|
371 |
+
|
372 |
+
The sequence is automatically padded to the right with zeros, as the
|
373 |
+
definition of subset/superset based on bitmasks (indices) requires
|
374 |
+
the size of sequence to be a power of 2.
|
375 |
+
|
376 |
+
Parameters
|
377 |
+
==========
|
378 |
+
|
379 |
+
seq : iterable
|
380 |
+
The sequence on which Mobius Transform is to be applied.
|
381 |
+
subset : bool
|
382 |
+
Specifies if Mobius Transform is applied by enumerating subsets
|
383 |
+
or supersets of the given set.
|
384 |
+
|
385 |
+
Examples
|
386 |
+
========
|
387 |
+
|
388 |
+
>>> from sympy import symbols
|
389 |
+
>>> from sympy import mobius_transform, inverse_mobius_transform
|
390 |
+
>>> x, y, z = symbols('x y z')
|
391 |
+
|
392 |
+
>>> mobius_transform([x, y, z])
|
393 |
+
[x, x + y, x + z, x + y + z]
|
394 |
+
>>> inverse_mobius_transform(_)
|
395 |
+
[x, y, z, 0]
|
396 |
+
|
397 |
+
>>> mobius_transform([x, y, z], subset=False)
|
398 |
+
[x + y + z, y, z, 0]
|
399 |
+
>>> inverse_mobius_transform(_, subset=False)
|
400 |
+
[x, y, z, 0]
|
401 |
+
|
402 |
+
>>> mobius_transform([1, 2, 3, 4])
|
403 |
+
[1, 3, 4, 10]
|
404 |
+
>>> inverse_mobius_transform(_)
|
405 |
+
[1, 2, 3, 4]
|
406 |
+
>>> mobius_transform([1, 2, 3, 4], subset=False)
|
407 |
+
[10, 6, 7, 4]
|
408 |
+
>>> inverse_mobius_transform(_, subset=False)
|
409 |
+
[1, 2, 3, 4]
|
410 |
+
|
411 |
+
References
|
412 |
+
==========
|
413 |
+
|
414 |
+
.. [1] https://en.wikipedia.org/wiki/M%C3%B6bius_inversion_formula
|
415 |
+
.. [2] https://people.csail.mit.edu/rrw/presentations/subset-conv.pdf
|
416 |
+
.. [3] https://arxiv.org/pdf/1211.0189.pdf
|
417 |
+
|
418 |
+
"""
|
419 |
+
|
420 |
+
return _mobius_transform(seq, sgn=+1, subset=subset)
|
421 |
+
|
422 |
+
def inverse_mobius_transform(seq, subset=True):
|
423 |
+
return _mobius_transform(seq, sgn=-1, subset=subset)
|
424 |
+
|
425 |
+
inverse_mobius_transform.__doc__ = mobius_transform.__doc__
|
llmeval-env/lib/python3.10/site-packages/sympy/solvers/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (1.95 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/solvers/__pycache__/bivariate.cpython-310.pyc
ADDED
Binary file (13.9 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/solvers/__pycache__/decompogen.cpython-310.pyc
ADDED
Binary file (3.51 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/solvers/__pycache__/deutils.cpython-310.pyc
ADDED
Binary file (8.06 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/solvers/__pycache__/inequalities.cpython-310.pyc
ADDED
Binary file (23.9 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/solvers/__pycache__/pde.cpython-310.pyc
ADDED
Binary file (29.8 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/solvers/__pycache__/polysys.cpython-310.pyc
ADDED
Binary file (12.8 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/solvers/__pycache__/recurr.cpython-310.pyc
ADDED
Binary file (22.9 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/solvers/__pycache__/solvers.cpython-310.pyc
ADDED
Binary file (98.6 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/solvers/__pycache__/solveset.cpython-310.pyc
ADDED
Binary file (105 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/solvers/diophantine/__init__.py
ADDED
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from .diophantine import diophantine, classify_diop, diop_solve
|
2 |
+
|
3 |
+
__all__ = [
|
4 |
+
'diophantine', 'classify_diop', 'diop_solve'
|
5 |
+
]
|
llmeval-env/lib/python3.10/site-packages/sympy/solvers/diophantine/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (296 Bytes). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/solvers/diophantine/__pycache__/diophantine.cpython-310.pyc
ADDED
Binary file (103 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/solvers/diophantine/diophantine.py
ADDED
The diff for this file is too large to render.
See raw diff
|
|
llmeval-env/lib/python3.10/site-packages/sympy/solvers/diophantine/tests/__init__.py
ADDED
File without changes
|
llmeval-env/lib/python3.10/site-packages/sympy/solvers/diophantine/tests/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (204 Bytes). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/solvers/diophantine/tests/__pycache__/test_diophantine.cpython-310.pyc
ADDED
Binary file (46 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/solvers/diophantine/tests/test_diophantine.py
ADDED
@@ -0,0 +1,1037 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.core.add import Add
|
2 |
+
from sympy.core.mul import Mul
|
3 |
+
from sympy.core.numbers import (Rational, oo, pi)
|
4 |
+
from sympy.core.relational import Eq
|
5 |
+
from sympy.core.singleton import S
|
6 |
+
from sympy.core.symbol import symbols
|
7 |
+
from sympy.matrices.dense import Matrix
|
8 |
+
from sympy.ntheory.factor_ import factorint
|
9 |
+
from sympy.simplify.powsimp import powsimp
|
10 |
+
from sympy.core.function import _mexpand
|
11 |
+
from sympy.core.sorting import default_sort_key, ordered
|
12 |
+
from sympy.functions.elementary.trigonometric import sin
|
13 |
+
from sympy.solvers.diophantine import diophantine
|
14 |
+
from sympy.solvers.diophantine.diophantine import (diop_DN,
|
15 |
+
diop_solve, diop_ternary_quadratic_normal,
|
16 |
+
diop_general_pythagorean, diop_ternary_quadratic, diop_linear,
|
17 |
+
diop_quadratic, diop_general_sum_of_squares, diop_general_sum_of_even_powers,
|
18 |
+
descent, diop_bf_DN, divisible, equivalent, find_DN, ldescent, length,
|
19 |
+
reconstruct, partition, power_representation,
|
20 |
+
prime_as_sum_of_two_squares, square_factor, sum_of_four_squares,
|
21 |
+
sum_of_three_squares, transformation_to_DN, transformation_to_normal,
|
22 |
+
classify_diop, base_solution_linear, cornacchia, sqf_normal, gaussian_reduce, holzer,
|
23 |
+
check_param, parametrize_ternary_quadratic, sum_of_powers, sum_of_squares,
|
24 |
+
_diop_ternary_quadratic_normal, _nint_or_floor,
|
25 |
+
_odd, _even, _remove_gcd, _can_do_sum_of_squares, DiophantineSolutionSet, GeneralPythagorean,
|
26 |
+
BinaryQuadratic)
|
27 |
+
|
28 |
+
from sympy.testing.pytest import slow, raises, XFAIL
|
29 |
+
from sympy.utilities.iterables import (
|
30 |
+
signed_permutations)
|
31 |
+
|
32 |
+
a, b, c, d, p, q, x, y, z, w, t, u, v, X, Y, Z = symbols(
|
33 |
+
"a, b, c, d, p, q, x, y, z, w, t, u, v, X, Y, Z", integer=True)
|
34 |
+
t_0, t_1, t_2, t_3, t_4, t_5, t_6 = symbols("t_:7", integer=True)
|
35 |
+
m1, m2, m3 = symbols('m1:4', integer=True)
|
36 |
+
n1 = symbols('n1', integer=True)
|
37 |
+
|
38 |
+
|
39 |
+
def diop_simplify(eq):
|
40 |
+
return _mexpand(powsimp(_mexpand(eq)))
|
41 |
+
|
42 |
+
|
43 |
+
def test_input_format():
|
44 |
+
raises(TypeError, lambda: diophantine(sin(x)))
|
45 |
+
raises(TypeError, lambda: diophantine(x/pi - 3))
|
46 |
+
|
47 |
+
|
48 |
+
def test_nosols():
|
49 |
+
# diophantine should sympify eq so that these are equivalent
|
50 |
+
assert diophantine(3) == set()
|
51 |
+
assert diophantine(S(3)) == set()
|
52 |
+
|
53 |
+
|
54 |
+
def test_univariate():
|
55 |
+
assert diop_solve((x - 1)*(x - 2)**2) == {(1,), (2,)}
|
56 |
+
assert diop_solve((x - 1)*(x - 2)) == {(1,), (2,)}
|
57 |
+
|
58 |
+
|
59 |
+
def test_classify_diop():
|
60 |
+
raises(TypeError, lambda: classify_diop(x**2/3 - 1))
|
61 |
+
raises(ValueError, lambda: classify_diop(1))
|
62 |
+
raises(NotImplementedError, lambda: classify_diop(w*x*y*z - 1))
|
63 |
+
raises(NotImplementedError, lambda: classify_diop(x**3 + y**3 + z**4 - 90))
|
64 |
+
assert classify_diop(14*x**2 + 15*x - 42) == (
|
65 |
+
[x], {1: -42, x: 15, x**2: 14}, 'univariate')
|
66 |
+
assert classify_diop(x*y + z) == (
|
67 |
+
[x, y, z], {x*y: 1, z: 1}, 'inhomogeneous_ternary_quadratic')
|
68 |
+
assert classify_diop(x*y + z + w + x**2) == (
|
69 |
+
[w, x, y, z], {x*y: 1, w: 1, x**2: 1, z: 1}, 'inhomogeneous_general_quadratic')
|
70 |
+
assert classify_diop(x*y + x*z + x**2 + 1) == (
|
71 |
+
[x, y, z], {x*y: 1, x*z: 1, x**2: 1, 1: 1}, 'inhomogeneous_general_quadratic')
|
72 |
+
assert classify_diop(x*y + z + w + 42) == (
|
73 |
+
[w, x, y, z], {x*y: 1, w: 1, 1: 42, z: 1}, 'inhomogeneous_general_quadratic')
|
74 |
+
assert classify_diop(x*y + z*w) == (
|
75 |
+
[w, x, y, z], {x*y: 1, w*z: 1}, 'homogeneous_general_quadratic')
|
76 |
+
assert classify_diop(x*y**2 + 1) == (
|
77 |
+
[x, y], {x*y**2: 1, 1: 1}, 'cubic_thue')
|
78 |
+
assert classify_diop(x**4 + y**4 + z**4 - (1 + 16 + 81)) == (
|
79 |
+
[x, y, z], {1: -98, x**4: 1, z**4: 1, y**4: 1}, 'general_sum_of_even_powers')
|
80 |
+
assert classify_diop(x**2 + y**2 + z**2) == (
|
81 |
+
[x, y, z], {x**2: 1, y**2: 1, z**2: 1}, 'homogeneous_ternary_quadratic_normal')
|
82 |
+
|
83 |
+
|
84 |
+
def test_linear():
|
85 |
+
assert diop_solve(x) == (0,)
|
86 |
+
assert diop_solve(1*x) == (0,)
|
87 |
+
assert diop_solve(3*x) == (0,)
|
88 |
+
assert diop_solve(x + 1) == (-1,)
|
89 |
+
assert diop_solve(2*x + 1) == (None,)
|
90 |
+
assert diop_solve(2*x + 4) == (-2,)
|
91 |
+
assert diop_solve(y + x) == (t_0, -t_0)
|
92 |
+
assert diop_solve(y + x + 0) == (t_0, -t_0)
|
93 |
+
assert diop_solve(y + x - 0) == (t_0, -t_0)
|
94 |
+
assert diop_solve(0*x - y - 5) == (-5,)
|
95 |
+
assert diop_solve(3*y + 2*x - 5) == (3*t_0 - 5, -2*t_0 + 5)
|
96 |
+
assert diop_solve(2*x - 3*y - 5) == (3*t_0 - 5, 2*t_0 - 5)
|
97 |
+
assert diop_solve(-2*x - 3*y - 5) == (3*t_0 + 5, -2*t_0 - 5)
|
98 |
+
assert diop_solve(7*x + 5*y) == (5*t_0, -7*t_0)
|
99 |
+
assert diop_solve(2*x + 4*y) == (2*t_0, -t_0)
|
100 |
+
assert diop_solve(4*x + 6*y - 4) == (3*t_0 - 2, -2*t_0 + 2)
|
101 |
+
assert diop_solve(4*x + 6*y - 3) == (None, None)
|
102 |
+
assert diop_solve(0*x + 3*y - 4*z + 5) == (4*t_0 + 5, 3*t_0 + 5)
|
103 |
+
assert diop_solve(4*x + 3*y - 4*z + 5) == (t_0, 8*t_0 + 4*t_1 + 5, 7*t_0 + 3*t_1 + 5)
|
104 |
+
assert diop_solve(4*x + 3*y - 4*z + 5, None) == (0, 5, 5)
|
105 |
+
assert diop_solve(4*x + 2*y + 8*z - 5) == (None, None, None)
|
106 |
+
assert diop_solve(5*x + 7*y - 2*z - 6) == (t_0, -3*t_0 + 2*t_1 + 6, -8*t_0 + 7*t_1 + 18)
|
107 |
+
assert diop_solve(3*x - 6*y + 12*z - 9) == (2*t_0 + 3, t_0 + 2*t_1, t_1)
|
108 |
+
assert diop_solve(6*w + 9*x + 20*y - z) == (t_0, t_1, t_1 + t_2, 6*t_0 + 29*t_1 + 20*t_2)
|
109 |
+
|
110 |
+
# to ignore constant factors, use diophantine
|
111 |
+
raises(TypeError, lambda: diop_solve(x/2))
|
112 |
+
|
113 |
+
|
114 |
+
def test_quadratic_simple_hyperbolic_case():
|
115 |
+
# Simple Hyperbolic case: A = C = 0 and B != 0
|
116 |
+
assert diop_solve(3*x*y + 34*x - 12*y + 1) == \
|
117 |
+
{(-133, -11), (5, -57)}
|
118 |
+
assert diop_solve(6*x*y + 2*x + 3*y + 1) == set()
|
119 |
+
assert diop_solve(-13*x*y + 2*x - 4*y - 54) == {(27, 0)}
|
120 |
+
assert diop_solve(-27*x*y - 30*x - 12*y - 54) == {(-14, -1)}
|
121 |
+
assert diop_solve(2*x*y + 5*x + 56*y + 7) == {(-161, -3), (-47, -6), (-35, -12),
|
122 |
+
(-29, -69), (-27, 64), (-21, 7),
|
123 |
+
(-9, 1), (105, -2)}
|
124 |
+
assert diop_solve(6*x*y + 9*x + 2*y + 3) == set()
|
125 |
+
assert diop_solve(x*y + x + y + 1) == {(-1, t), (t, -1)}
|
126 |
+
assert diophantine(48*x*y)
|
127 |
+
|
128 |
+
|
129 |
+
def test_quadratic_elliptical_case():
|
130 |
+
# Elliptical case: B**2 - 4AC < 0
|
131 |
+
|
132 |
+
assert diop_solve(42*x**2 + 8*x*y + 15*y**2 + 23*x + 17*y - 4915) == {(-11, -1)}
|
133 |
+
assert diop_solve(4*x**2 + 3*y**2 + 5*x - 11*y + 12) == set()
|
134 |
+
assert diop_solve(x**2 + y**2 + 2*x + 2*y + 2) == {(-1, -1)}
|
135 |
+
assert diop_solve(15*x**2 - 9*x*y + 14*y**2 - 23*x - 14*y - 4950) == {(-15, 6)}
|
136 |
+
assert diop_solve(10*x**2 + 12*x*y + 12*y**2 - 34) == \
|
137 |
+
{(-1, -1), (-1, 2), (1, -2), (1, 1)}
|
138 |
+
|
139 |
+
|
140 |
+
def test_quadratic_parabolic_case():
|
141 |
+
# Parabolic case: B**2 - 4AC = 0
|
142 |
+
assert check_solutions(8*x**2 - 24*x*y + 18*y**2 + 5*x + 7*y + 16)
|
143 |
+
assert check_solutions(8*x**2 - 24*x*y + 18*y**2 + 6*x + 12*y - 6)
|
144 |
+
assert check_solutions(8*x**2 + 24*x*y + 18*y**2 + 4*x + 6*y - 7)
|
145 |
+
assert check_solutions(-4*x**2 + 4*x*y - y**2 + 2*x - 3)
|
146 |
+
assert check_solutions(x**2 + 2*x*y + y**2 + 2*x + 2*y + 1)
|
147 |
+
assert check_solutions(x**2 - 2*x*y + y**2 + 2*x + 2*y + 1)
|
148 |
+
assert check_solutions(y**2 - 41*x + 40)
|
149 |
+
|
150 |
+
|
151 |
+
def test_quadratic_perfect_square():
|
152 |
+
# B**2 - 4*A*C > 0
|
153 |
+
# B**2 - 4*A*C is a perfect square
|
154 |
+
assert check_solutions(48*x*y)
|
155 |
+
assert check_solutions(4*x**2 - 5*x*y + y**2 + 2)
|
156 |
+
assert check_solutions(-2*x**2 - 3*x*y + 2*y**2 -2*x - 17*y + 25)
|
157 |
+
assert check_solutions(12*x**2 + 13*x*y + 3*y**2 - 2*x + 3*y - 12)
|
158 |
+
assert check_solutions(8*x**2 + 10*x*y + 2*y**2 - 32*x - 13*y - 23)
|
159 |
+
assert check_solutions(4*x**2 - 4*x*y - 3*y- 8*x - 3)
|
160 |
+
assert check_solutions(- 4*x*y - 4*y**2 - 3*y- 5*x - 10)
|
161 |
+
assert check_solutions(x**2 - y**2 - 2*x - 2*y)
|
162 |
+
assert check_solutions(x**2 - 9*y**2 - 2*x - 6*y)
|
163 |
+
assert check_solutions(4*x**2 - 9*y**2 - 4*x - 12*y - 3)
|
164 |
+
|
165 |
+
|
166 |
+
def test_quadratic_non_perfect_square():
|
167 |
+
# B**2 - 4*A*C is not a perfect square
|
168 |
+
# Used check_solutions() since the solutions are complex expressions involving
|
169 |
+
# square roots and exponents
|
170 |
+
assert check_solutions(x**2 - 2*x - 5*y**2)
|
171 |
+
assert check_solutions(3*x**2 - 2*y**2 - 2*x - 2*y)
|
172 |
+
assert check_solutions(x**2 - x*y - y**2 - 3*y)
|
173 |
+
assert check_solutions(x**2 - 9*y**2 - 2*x - 6*y)
|
174 |
+
assert BinaryQuadratic(x**2 + y**2 + 2*x + 2*y + 2).solve() == {(-1, -1)}
|
175 |
+
|
176 |
+
|
177 |
+
def test_issue_9106():
|
178 |
+
eq = -48 - 2*x*(3*x - 1) + y*(3*y - 1)
|
179 |
+
v = (x, y)
|
180 |
+
for sol in diophantine(eq):
|
181 |
+
assert not diop_simplify(eq.xreplace(dict(zip(v, sol))))
|
182 |
+
|
183 |
+
|
184 |
+
def test_issue_18138():
|
185 |
+
eq = x**2 - x - y**2
|
186 |
+
v = (x, y)
|
187 |
+
for sol in diophantine(eq):
|
188 |
+
assert not diop_simplify(eq.xreplace(dict(zip(v, sol))))
|
189 |
+
|
190 |
+
|
191 |
+
@slow
|
192 |
+
def test_quadratic_non_perfect_slow():
|
193 |
+
assert check_solutions(8*x**2 + 10*x*y - 2*y**2 - 32*x - 13*y - 23)
|
194 |
+
# This leads to very large numbers.
|
195 |
+
# assert check_solutions(5*x**2 - 13*x*y + y**2 - 4*x - 4*y - 15)
|
196 |
+
assert check_solutions(-3*x**2 - 2*x*y + 7*y**2 - 5*x - 7)
|
197 |
+
assert check_solutions(-4 - x + 4*x**2 - y - 3*x*y - 4*y**2)
|
198 |
+
assert check_solutions(1 + 2*x + 2*x**2 + 2*y + x*y - 2*y**2)
|
199 |
+
|
200 |
+
|
201 |
+
def test_DN():
|
202 |
+
# Most of the test cases were adapted from,
|
203 |
+
# Solving the generalized Pell equation x**2 - D*y**2 = N, John P. Robertson, July 31, 2004.
|
204 |
+
# https://web.archive.org/web/20160323033128/http://www.jpr2718.org/pell.pdf
|
205 |
+
# others are verified using Wolfram Alpha.
|
206 |
+
|
207 |
+
# Covers cases where D <= 0 or D > 0 and D is a square or N = 0
|
208 |
+
# Solutions are straightforward in these cases.
|
209 |
+
assert diop_DN(3, 0) == [(0, 0)]
|
210 |
+
assert diop_DN(-17, -5) == []
|
211 |
+
assert diop_DN(-19, 23) == [(2, 1)]
|
212 |
+
assert diop_DN(-13, 17) == [(2, 1)]
|
213 |
+
assert diop_DN(-15, 13) == []
|
214 |
+
assert diop_DN(0, 5) == []
|
215 |
+
assert diop_DN(0, 9) == [(3, t)]
|
216 |
+
assert diop_DN(9, 0) == [(3*t, t)]
|
217 |
+
assert diop_DN(16, 24) == []
|
218 |
+
assert diop_DN(9, 180) == [(18, 4)]
|
219 |
+
assert diop_DN(9, -180) == [(12, 6)]
|
220 |
+
assert diop_DN(7, 0) == [(0, 0)]
|
221 |
+
|
222 |
+
# When equation is x**2 + y**2 = N
|
223 |
+
# Solutions are interchangeable
|
224 |
+
assert diop_DN(-1, 5) == [(2, 1), (1, 2)]
|
225 |
+
assert diop_DN(-1, 169) == [(12, 5), (5, 12), (13, 0), (0, 13)]
|
226 |
+
|
227 |
+
# D > 0 and D is not a square
|
228 |
+
|
229 |
+
# N = 1
|
230 |
+
assert diop_DN(13, 1) == [(649, 180)]
|
231 |
+
assert diop_DN(980, 1) == [(51841, 1656)]
|
232 |
+
assert diop_DN(981, 1) == [(158070671986249, 5046808151700)]
|
233 |
+
assert diop_DN(986, 1) == [(49299, 1570)]
|
234 |
+
assert diop_DN(991, 1) == [(379516400906811930638014896080, 12055735790331359447442538767)]
|
235 |
+
assert diop_DN(17, 1) == [(33, 8)]
|
236 |
+
assert diop_DN(19, 1) == [(170, 39)]
|
237 |
+
|
238 |
+
# N = -1
|
239 |
+
assert diop_DN(13, -1) == [(18, 5)]
|
240 |
+
assert diop_DN(991, -1) == []
|
241 |
+
assert diop_DN(41, -1) == [(32, 5)]
|
242 |
+
assert diop_DN(290, -1) == [(17, 1)]
|
243 |
+
assert diop_DN(21257, -1) == [(13913102721304, 95427381109)]
|
244 |
+
assert diop_DN(32, -1) == []
|
245 |
+
|
246 |
+
# |N| > 1
|
247 |
+
# Some tests were created using calculator at
|
248 |
+
# http://www.numbertheory.org/php/patz.html
|
249 |
+
|
250 |
+
assert diop_DN(13, -4) == [(3, 1), (393, 109), (36, 10)]
|
251 |
+
# Source I referred returned (3, 1), (393, 109) and (-3, 1) as fundamental solutions
|
252 |
+
# So (-3, 1) and (393, 109) should be in the same equivalent class
|
253 |
+
assert equivalent(-3, 1, 393, 109, 13, -4) == True
|
254 |
+
|
255 |
+
assert diop_DN(13, 27) == [(220, 61), (40, 11), (768, 213), (12, 3)]
|
256 |
+
assert set(diop_DN(157, 12)) == {(13, 1), (10663, 851), (579160, 46222),
|
257 |
+
(483790960, 38610722), (26277068347, 2097138361),
|
258 |
+
(21950079635497, 1751807067011)}
|
259 |
+
assert diop_DN(13, 25) == [(3245, 900)]
|
260 |
+
assert diop_DN(192, 18) == []
|
261 |
+
assert diop_DN(23, 13) == [(-6, 1), (6, 1)]
|
262 |
+
assert diop_DN(167, 2) == [(13, 1)]
|
263 |
+
assert diop_DN(167, -2) == []
|
264 |
+
|
265 |
+
assert diop_DN(123, -2) == [(11, 1)]
|
266 |
+
# One calculator returned [(11, 1), (-11, 1)] but both of these are in
|
267 |
+
# the same equivalence class
|
268 |
+
assert equivalent(11, 1, -11, 1, 123, -2)
|
269 |
+
|
270 |
+
assert diop_DN(123, -23) == [(-10, 1), (10, 1)]
|
271 |
+
|
272 |
+
assert diop_DN(0, 0, t) == [(0, t)]
|
273 |
+
assert diop_DN(0, -1, t) == []
|
274 |
+
|
275 |
+
|
276 |
+
def test_bf_pell():
|
277 |
+
assert diop_bf_DN(13, -4) == [(3, 1), (-3, 1), (36, 10)]
|
278 |
+
assert diop_bf_DN(13, 27) == [(12, 3), (-12, 3), (40, 11), (-40, 11)]
|
279 |
+
assert diop_bf_DN(167, -2) == []
|
280 |
+
assert diop_bf_DN(1729, 1) == [(44611924489705, 1072885712316)]
|
281 |
+
assert diop_bf_DN(89, -8) == [(9, 1), (-9, 1)]
|
282 |
+
assert diop_bf_DN(21257, -1) == [(13913102721304, 95427381109)]
|
283 |
+
assert diop_bf_DN(340, -4) == [(756, 41)]
|
284 |
+
assert diop_bf_DN(-1, 0, t) == [(0, 0)]
|
285 |
+
assert diop_bf_DN(0, 0, t) == [(0, t)]
|
286 |
+
assert diop_bf_DN(4, 0, t) == [(2*t, t), (-2*t, t)]
|
287 |
+
assert diop_bf_DN(3, 0, t) == [(0, 0)]
|
288 |
+
assert diop_bf_DN(1, -2, t) == []
|
289 |
+
|
290 |
+
|
291 |
+
def test_length():
|
292 |
+
assert length(2, 1, 0) == 1
|
293 |
+
assert length(-2, 4, 5) == 3
|
294 |
+
assert length(-5, 4, 17) == 4
|
295 |
+
assert length(0, 4, 13) == 6
|
296 |
+
assert length(7, 13, 11) == 23
|
297 |
+
assert length(1, 6, 4) == 2
|
298 |
+
|
299 |
+
|
300 |
+
def is_pell_transformation_ok(eq):
|
301 |
+
"""
|
302 |
+
Test whether X*Y, X, or Y terms are present in the equation
|
303 |
+
after transforming the equation using the transformation returned
|
304 |
+
by transformation_to_pell(). If they are not present we are good.
|
305 |
+
Moreover, coefficient of X**2 should be a divisor of coefficient of
|
306 |
+
Y**2 and the constant term.
|
307 |
+
"""
|
308 |
+
A, B = transformation_to_DN(eq)
|
309 |
+
u = (A*Matrix([X, Y]) + B)[0]
|
310 |
+
v = (A*Matrix([X, Y]) + B)[1]
|
311 |
+
simplified = diop_simplify(eq.subs(zip((x, y), (u, v))))
|
312 |
+
|
313 |
+
coeff = dict([reversed(t.as_independent(*[X, Y])) for t in simplified.args])
|
314 |
+
|
315 |
+
for term in [X*Y, X, Y]:
|
316 |
+
if term in coeff.keys():
|
317 |
+
return False
|
318 |
+
|
319 |
+
for term in [X**2, Y**2, 1]:
|
320 |
+
if term not in coeff.keys():
|
321 |
+
coeff[term] = 0
|
322 |
+
|
323 |
+
if coeff[X**2] != 0:
|
324 |
+
return divisible(coeff[Y**2], coeff[X**2]) and \
|
325 |
+
divisible(coeff[1], coeff[X**2])
|
326 |
+
|
327 |
+
return True
|
328 |
+
|
329 |
+
|
330 |
+
def test_transformation_to_pell():
|
331 |
+
assert is_pell_transformation_ok(-13*x**2 - 7*x*y + y**2 + 2*x - 2*y - 14)
|
332 |
+
assert is_pell_transformation_ok(-17*x**2 + 19*x*y - 7*y**2 - 5*x - 13*y - 23)
|
333 |
+
assert is_pell_transformation_ok(x**2 - y**2 + 17)
|
334 |
+
assert is_pell_transformation_ok(-x**2 + 7*y**2 - 23)
|
335 |
+
assert is_pell_transformation_ok(25*x**2 - 45*x*y + 5*y**2 - 5*x - 10*y + 5)
|
336 |
+
assert is_pell_transformation_ok(190*x**2 + 30*x*y + y**2 - 3*y - 170*x - 130)
|
337 |
+
assert is_pell_transformation_ok(x**2 - 2*x*y -190*y**2 - 7*y - 23*x - 89)
|
338 |
+
assert is_pell_transformation_ok(15*x**2 - 9*x*y + 14*y**2 - 23*x - 14*y - 4950)
|
339 |
+
|
340 |
+
|
341 |
+
def test_find_DN():
|
342 |
+
assert find_DN(x**2 - 2*x - y**2) == (1, 1)
|
343 |
+
assert find_DN(x**2 - 3*y**2 - 5) == (3, 5)
|
344 |
+
assert find_DN(x**2 - 2*x*y - 4*y**2 - 7) == (5, 7)
|
345 |
+
assert find_DN(4*x**2 - 8*x*y - y**2 - 9) == (20, 36)
|
346 |
+
assert find_DN(7*x**2 - 2*x*y - y**2 - 12) == (8, 84)
|
347 |
+
assert find_DN(-3*x**2 + 4*x*y -y**2) == (1, 0)
|
348 |
+
assert find_DN(-13*x**2 - 7*x*y + y**2 + 2*x - 2*y -14) == (101, -7825480)
|
349 |
+
|
350 |
+
|
351 |
+
def test_ldescent():
|
352 |
+
# Equations which have solutions
|
353 |
+
u = ([(13, 23), (3, -11), (41, -113), (4, -7), (-7, 4), (91, -3), (1, 1), (1, -1),
|
354 |
+
(4, 32), (17, 13), (123689, 1), (19, -570)])
|
355 |
+
for a, b in u:
|
356 |
+
w, x, y = ldescent(a, b)
|
357 |
+
assert a*x**2 + b*y**2 == w**2
|
358 |
+
assert ldescent(-1, -1) is None
|
359 |
+
|
360 |
+
|
361 |
+
def test_diop_ternary_quadratic_normal():
|
362 |
+
assert check_solutions(234*x**2 - 65601*y**2 - z**2)
|
363 |
+
assert check_solutions(23*x**2 + 616*y**2 - z**2)
|
364 |
+
assert check_solutions(5*x**2 + 4*y**2 - z**2)
|
365 |
+
assert check_solutions(3*x**2 + 6*y**2 - 3*z**2)
|
366 |
+
assert check_solutions(x**2 + 3*y**2 - z**2)
|
367 |
+
assert check_solutions(4*x**2 + 5*y**2 - z**2)
|
368 |
+
assert check_solutions(x**2 + y**2 - z**2)
|
369 |
+
assert check_solutions(16*x**2 + y**2 - 25*z**2)
|
370 |
+
assert check_solutions(6*x**2 - y**2 + 10*z**2)
|
371 |
+
assert check_solutions(213*x**2 + 12*y**2 - 9*z**2)
|
372 |
+
assert check_solutions(34*x**2 - 3*y**2 - 301*z**2)
|
373 |
+
assert check_solutions(124*x**2 - 30*y**2 - 7729*z**2)
|
374 |
+
|
375 |
+
|
376 |
+
def is_normal_transformation_ok(eq):
|
377 |
+
A = transformation_to_normal(eq)
|
378 |
+
X, Y, Z = A*Matrix([x, y, z])
|
379 |
+
simplified = diop_simplify(eq.subs(zip((x, y, z), (X, Y, Z))))
|
380 |
+
|
381 |
+
coeff = dict([reversed(t.as_independent(*[X, Y, Z])) for t in simplified.args])
|
382 |
+
for term in [X*Y, Y*Z, X*Z]:
|
383 |
+
if term in coeff.keys():
|
384 |
+
return False
|
385 |
+
|
386 |
+
return True
|
387 |
+
|
388 |
+
|
389 |
+
def test_transformation_to_normal():
|
390 |
+
assert is_normal_transformation_ok(x**2 + 3*y**2 + z**2 - 13*x*y - 16*y*z + 12*x*z)
|
391 |
+
assert is_normal_transformation_ok(x**2 + 3*y**2 - 100*z**2)
|
392 |
+
assert is_normal_transformation_ok(x**2 + 23*y*z)
|
393 |
+
assert is_normal_transformation_ok(3*y**2 - 100*z**2 - 12*x*y)
|
394 |
+
assert is_normal_transformation_ok(x**2 + 23*x*y - 34*y*z + 12*x*z)
|
395 |
+
assert is_normal_transformation_ok(z**2 + 34*x*y - 23*y*z + x*z)
|
396 |
+
assert is_normal_transformation_ok(x**2 + y**2 + z**2 - x*y - y*z - x*z)
|
397 |
+
assert is_normal_transformation_ok(x**2 + 2*y*z + 3*z**2)
|
398 |
+
assert is_normal_transformation_ok(x*y + 2*x*z + 3*y*z)
|
399 |
+
assert is_normal_transformation_ok(2*x*z + 3*y*z)
|
400 |
+
|
401 |
+
|
402 |
+
def test_diop_ternary_quadratic():
|
403 |
+
assert check_solutions(2*x**2 + z**2 + y**2 - 4*x*y)
|
404 |
+
assert check_solutions(x**2 - y**2 - z**2 - x*y - y*z)
|
405 |
+
assert check_solutions(3*x**2 - x*y - y*z - x*z)
|
406 |
+
assert check_solutions(x**2 - y*z - x*z)
|
407 |
+
assert check_solutions(5*x**2 - 3*x*y - x*z)
|
408 |
+
assert check_solutions(4*x**2 - 5*y**2 - x*z)
|
409 |
+
assert check_solutions(3*x**2 + 2*y**2 - z**2 - 2*x*y + 5*y*z - 7*y*z)
|
410 |
+
assert check_solutions(8*x**2 - 12*y*z)
|
411 |
+
assert check_solutions(45*x**2 - 7*y**2 - 8*x*y - z**2)
|
412 |
+
assert check_solutions(x**2 - 49*y**2 - z**2 + 13*z*y -8*x*y)
|
413 |
+
assert check_solutions(90*x**2 + 3*y**2 + 5*x*y + 2*z*y + 5*x*z)
|
414 |
+
assert check_solutions(x**2 + 3*y**2 + z**2 - x*y - 17*y*z)
|
415 |
+
assert check_solutions(x**2 + 3*y**2 + z**2 - x*y - 16*y*z + 12*x*z)
|
416 |
+
assert check_solutions(x**2 + 3*y**2 + z**2 - 13*x*y - 16*y*z + 12*x*z)
|
417 |
+
assert check_solutions(x*y - 7*y*z + 13*x*z)
|
418 |
+
|
419 |
+
assert diop_ternary_quadratic_normal(x**2 + y**2 + z**2) == (None, None, None)
|
420 |
+
assert diop_ternary_quadratic_normal(x**2 + y**2) is None
|
421 |
+
raises(ValueError, lambda:
|
422 |
+
_diop_ternary_quadratic_normal((x, y, z),
|
423 |
+
{x*y: 1, x**2: 2, y**2: 3, z**2: 0}))
|
424 |
+
eq = -2*x*y - 6*x*z + 7*y**2 - 3*y*z + 4*z**2
|
425 |
+
assert diop_ternary_quadratic(eq) == (7, 2, 0)
|
426 |
+
assert diop_ternary_quadratic_normal(4*x**2 + 5*y**2 - z**2) == \
|
427 |
+
(1, 0, 2)
|
428 |
+
assert diop_ternary_quadratic(x*y + 2*y*z) == \
|
429 |
+
(-2, 0, n1)
|
430 |
+
eq = -5*x*y - 8*x*z - 3*y*z + 8*z**2
|
431 |
+
assert parametrize_ternary_quadratic(eq) == \
|
432 |
+
(8*p**2 - 3*p*q, -8*p*q + 8*q**2, 5*p*q)
|
433 |
+
# this cannot be tested with diophantine because it will
|
434 |
+
# factor into a product
|
435 |
+
assert diop_solve(x*y + 2*y*z) == (-2*p*q, -n1*p**2 + p**2, p*q)
|
436 |
+
|
437 |
+
|
438 |
+
def test_square_factor():
|
439 |
+
assert square_factor(1) == square_factor(-1) == 1
|
440 |
+
assert square_factor(0) == 1
|
441 |
+
assert square_factor(5) == square_factor(-5) == 1
|
442 |
+
assert square_factor(4) == square_factor(-4) == 2
|
443 |
+
assert square_factor(12) == square_factor(-12) == 2
|
444 |
+
assert square_factor(6) == 1
|
445 |
+
assert square_factor(18) == 3
|
446 |
+
assert square_factor(52) == 2
|
447 |
+
assert square_factor(49) == 7
|
448 |
+
assert square_factor(392) == 14
|
449 |
+
assert square_factor(factorint(-12)) == 2
|
450 |
+
|
451 |
+
|
452 |
+
def test_parametrize_ternary_quadratic():
|
453 |
+
assert check_solutions(x**2 + y**2 - z**2)
|
454 |
+
assert check_solutions(x**2 + 2*x*y + z**2)
|
455 |
+
assert check_solutions(234*x**2 - 65601*y**2 - z**2)
|
456 |
+
assert check_solutions(3*x**2 + 2*y**2 - z**2 - 2*x*y + 5*y*z - 7*y*z)
|
457 |
+
assert check_solutions(x**2 - y**2 - z**2)
|
458 |
+
assert check_solutions(x**2 - 49*y**2 - z**2 + 13*z*y - 8*x*y)
|
459 |
+
assert check_solutions(8*x*y + z**2)
|
460 |
+
assert check_solutions(124*x**2 - 30*y**2 - 7729*z**2)
|
461 |
+
assert check_solutions(236*x**2 - 225*y**2 - 11*x*y - 13*y*z - 17*x*z)
|
462 |
+
assert check_solutions(90*x**2 + 3*y**2 + 5*x*y + 2*z*y + 5*x*z)
|
463 |
+
assert check_solutions(124*x**2 - 30*y**2 - 7729*z**2)
|
464 |
+
|
465 |
+
|
466 |
+
def test_no_square_ternary_quadratic():
|
467 |
+
assert check_solutions(2*x*y + y*z - 3*x*z)
|
468 |
+
assert check_solutions(189*x*y - 345*y*z - 12*x*z)
|
469 |
+
assert check_solutions(23*x*y + 34*y*z)
|
470 |
+
assert check_solutions(x*y + y*z + z*x)
|
471 |
+
assert check_solutions(23*x*y + 23*y*z + 23*x*z)
|
472 |
+
|
473 |
+
|
474 |
+
def test_descent():
|
475 |
+
|
476 |
+
u = ([(13, 23), (3, -11), (41, -113), (91, -3), (1, 1), (1, -1), (17, 13), (123689, 1), (19, -570)])
|
477 |
+
for a, b in u:
|
478 |
+
w, x, y = descent(a, b)
|
479 |
+
assert a*x**2 + b*y**2 == w**2
|
480 |
+
# the docstring warns against bad input, so these are expected results
|
481 |
+
# - can't both be negative
|
482 |
+
raises(TypeError, lambda: descent(-1, -3))
|
483 |
+
# A can't be zero unless B != 1
|
484 |
+
raises(ZeroDivisionError, lambda: descent(0, 3))
|
485 |
+
# supposed to be square-free
|
486 |
+
raises(TypeError, lambda: descent(4, 3))
|
487 |
+
|
488 |
+
|
489 |
+
def test_diophantine():
|
490 |
+
assert check_solutions((x - y)*(y - z)*(z - x))
|
491 |
+
assert check_solutions((x - y)*(x**2 + y**2 - z**2))
|
492 |
+
assert check_solutions((x - 3*y + 7*z)*(x**2 + y**2 - z**2))
|
493 |
+
assert check_solutions(x**2 - 3*y**2 - 1)
|
494 |
+
assert check_solutions(y**2 + 7*x*y)
|
495 |
+
assert check_solutions(x**2 - 3*x*y + y**2)
|
496 |
+
assert check_solutions(z*(x**2 - y**2 - 15))
|
497 |
+
assert check_solutions(x*(2*y - 2*z + 5))
|
498 |
+
assert check_solutions((x**2 - 3*y**2 - 1)*(x**2 - y**2 - 15))
|
499 |
+
assert check_solutions((x**2 - 3*y**2 - 1)*(y - 7*z))
|
500 |
+
assert check_solutions((x**2 + y**2 - z**2)*(x - 7*y - 3*z + 4*w))
|
501 |
+
# Following test case caused problems in parametric representation
|
502 |
+
# But this can be solved by factoring out y.
|
503 |
+
# No need to use methods for ternary quadratic equations.
|
504 |
+
assert check_solutions(y**2 - 7*x*y + 4*y*z)
|
505 |
+
assert check_solutions(x**2 - 2*x + 1)
|
506 |
+
|
507 |
+
assert diophantine(x - y) == diophantine(Eq(x, y))
|
508 |
+
# 18196
|
509 |
+
eq = x**4 + y**4 - 97
|
510 |
+
assert diophantine(eq, permute=True) == diophantine(-eq, permute=True)
|
511 |
+
assert diophantine(3*x*pi - 2*y*pi) == {(2*t_0, 3*t_0)}
|
512 |
+
eq = x**2 + y**2 + z**2 - 14
|
513 |
+
base_sol = {(1, 2, 3)}
|
514 |
+
assert diophantine(eq) == base_sol
|
515 |
+
complete_soln = set(signed_permutations(base_sol.pop()))
|
516 |
+
assert diophantine(eq, permute=True) == complete_soln
|
517 |
+
|
518 |
+
assert diophantine(x**2 + x*Rational(15, 14) - 3) == set()
|
519 |
+
# test issue 11049
|
520 |
+
eq = 92*x**2 - 99*y**2 - z**2
|
521 |
+
coeff = eq.as_coefficients_dict()
|
522 |
+
assert _diop_ternary_quadratic_normal((x, y, z), coeff) == \
|
523 |
+
{(9, 7, 51)}
|
524 |
+
assert diophantine(eq) == {(
|
525 |
+
891*p**2 + 9*q**2, -693*p**2 - 102*p*q + 7*q**2,
|
526 |
+
5049*p**2 - 1386*p*q - 51*q**2)}
|
527 |
+
eq = 2*x**2 + 2*y**2 - z**2
|
528 |
+
coeff = eq.as_coefficients_dict()
|
529 |
+
assert _diop_ternary_quadratic_normal((x, y, z), coeff) == \
|
530 |
+
{(1, 1, 2)}
|
531 |
+
assert diophantine(eq) == {(
|
532 |
+
2*p**2 - q**2, -2*p**2 + 4*p*q - q**2,
|
533 |
+
4*p**2 - 4*p*q + 2*q**2)}
|
534 |
+
eq = 411*x**2+57*y**2-221*z**2
|
535 |
+
coeff = eq.as_coefficients_dict()
|
536 |
+
assert _diop_ternary_quadratic_normal((x, y, z), coeff) == \
|
537 |
+
{(2021, 2645, 3066)}
|
538 |
+
assert diophantine(eq) == \
|
539 |
+
{(115197*p**2 - 446641*q**2, -150765*p**2 + 1355172*p*q -
|
540 |
+
584545*q**2, 174762*p**2 - 301530*p*q + 677586*q**2)}
|
541 |
+
eq = 573*x**2+267*y**2-984*z**2
|
542 |
+
coeff = eq.as_coefficients_dict()
|
543 |
+
assert _diop_ternary_quadratic_normal((x, y, z), coeff) == \
|
544 |
+
{(49, 233, 127)}
|
545 |
+
assert diophantine(eq) == \
|
546 |
+
{(4361*p**2 - 16072*q**2, -20737*p**2 + 83312*p*q - 76424*q**2,
|
547 |
+
11303*p**2 - 41474*p*q + 41656*q**2)}
|
548 |
+
# this produces factors during reconstruction
|
549 |
+
eq = x**2 + 3*y**2 - 12*z**2
|
550 |
+
coeff = eq.as_coefficients_dict()
|
551 |
+
assert _diop_ternary_quadratic_normal((x, y, z), coeff) == \
|
552 |
+
{(0, 2, 1)}
|
553 |
+
assert diophantine(eq) == \
|
554 |
+
{(24*p*q, 2*p**2 - 24*q**2, p**2 + 12*q**2)}
|
555 |
+
# solvers have not been written for every type
|
556 |
+
raises(NotImplementedError, lambda: diophantine(x*y**2 + 1))
|
557 |
+
|
558 |
+
# rational expressions
|
559 |
+
assert diophantine(1/x) == set()
|
560 |
+
assert diophantine(1/x + 1/y - S.Half) == {(6, 3), (-2, 1), (4, 4), (1, -2), (3, 6)}
|
561 |
+
assert diophantine(x**2 + y**2 +3*x- 5, permute=True) == \
|
562 |
+
{(-1, 1), (-4, -1), (1, -1), (1, 1), (-4, 1), (-1, -1), (4, 1), (4, -1)}
|
563 |
+
|
564 |
+
|
565 |
+
#test issue 18186
|
566 |
+
assert diophantine(y**4 + x**4 - 2**4 - 3**4, syms=(x, y), permute=True) == \
|
567 |
+
{(-3, -2), (-3, 2), (-2, -3), (-2, 3), (2, -3), (2, 3), (3, -2), (3, 2)}
|
568 |
+
assert diophantine(y**4 + x**4 - 2**4 - 3**4, syms=(y, x), permute=True) == \
|
569 |
+
{(-3, -2), (-3, 2), (-2, -3), (-2, 3), (2, -3), (2, 3), (3, -2), (3, 2)}
|
570 |
+
|
571 |
+
# issue 18122
|
572 |
+
assert check_solutions(x**2-y)
|
573 |
+
assert check_solutions(y**2-x)
|
574 |
+
assert diophantine((x**2-y), t) == {(t, t**2)}
|
575 |
+
assert diophantine((y**2-x), t) == {(t**2, -t)}
|
576 |
+
|
577 |
+
|
578 |
+
def test_general_pythagorean():
|
579 |
+
from sympy.abc import a, b, c, d, e
|
580 |
+
|
581 |
+
assert check_solutions(a**2 + b**2 + c**2 - d**2)
|
582 |
+
assert check_solutions(a**2 + 4*b**2 + 4*c**2 - d**2)
|
583 |
+
assert check_solutions(9*a**2 + 4*b**2 + 4*c**2 - d**2)
|
584 |
+
assert check_solutions(9*a**2 + 4*b**2 - 25*d**2 + 4*c**2 )
|
585 |
+
assert check_solutions(9*a**2 - 16*d**2 + 4*b**2 + 4*c**2)
|
586 |
+
assert check_solutions(-e**2 + 9*a**2 + 4*b**2 + 4*c**2 + 25*d**2)
|
587 |
+
assert check_solutions(16*a**2 - b**2 + 9*c**2 + d**2 + 25*e**2)
|
588 |
+
|
589 |
+
assert GeneralPythagorean(a**2 + b**2 + c**2 - d**2).solve(parameters=[x, y, z]) == \
|
590 |
+
{(x**2 + y**2 - z**2, 2*x*z, 2*y*z, x**2 + y**2 + z**2)}
|
591 |
+
|
592 |
+
|
593 |
+
def test_diop_general_sum_of_squares_quick():
|
594 |
+
for i in range(3, 10):
|
595 |
+
assert check_solutions(sum(i**2 for i in symbols(':%i' % i)) - i)
|
596 |
+
|
597 |
+
assert diop_general_sum_of_squares(x**2 + y**2 - 2) is None
|
598 |
+
assert diop_general_sum_of_squares(x**2 + y**2 + z**2 + 2) == set()
|
599 |
+
eq = x**2 + y**2 + z**2 - (1 + 4 + 9)
|
600 |
+
assert diop_general_sum_of_squares(eq) == \
|
601 |
+
{(1, 2, 3)}
|
602 |
+
eq = u**2 + v**2 + x**2 + y**2 + z**2 - 1313
|
603 |
+
assert len(diop_general_sum_of_squares(eq, 3)) == 3
|
604 |
+
# issue 11016
|
605 |
+
var = symbols(':5') + (symbols('6', negative=True),)
|
606 |
+
eq = Add(*[i**2 for i in var]) - 112
|
607 |
+
|
608 |
+
base_soln = {(0, 1, 1, 5, 6, -7), (1, 1, 1, 3, 6, -8), (2, 3, 3, 4, 5, -7), (0, 1, 1, 1, 3, -10),
|
609 |
+
(0, 0, 4, 4, 4, -8), (1, 2, 3, 3, 5, -8), (0, 1, 2, 3, 7, -7), (2, 2, 4, 4, 6, -6),
|
610 |
+
(1, 1, 3, 4, 6, -7), (0, 2, 3, 3, 3, -9), (0, 0, 2, 2, 2, -10), (1, 1, 2, 3, 4, -9),
|
611 |
+
(0, 1, 1, 2, 5, -9), (0, 0, 2, 6, 6, -6), (1, 3, 4, 5, 5, -6), (0, 2, 2, 2, 6, -8),
|
612 |
+
(0, 3, 3, 3, 6, -7), (0, 2, 3, 5, 5, -7), (0, 1, 5, 5, 5, -6)}
|
613 |
+
assert diophantine(eq) == base_soln
|
614 |
+
assert len(diophantine(eq, permute=True)) == 196800
|
615 |
+
|
616 |
+
# handle negated squares with signsimp
|
617 |
+
assert diophantine(12 - x**2 - y**2 - z**2) == {(2, 2, 2)}
|
618 |
+
# diophantine handles simplification, so classify_diop should
|
619 |
+
# not have to look for additional patterns that are removed
|
620 |
+
# by diophantine
|
621 |
+
eq = a**2 + b**2 + c**2 + d**2 - 4
|
622 |
+
raises(NotImplementedError, lambda: classify_diop(-eq))
|
623 |
+
|
624 |
+
|
625 |
+
def test_issue_23807():
|
626 |
+
# fixes recursion error
|
627 |
+
eq = x**2 + y**2 + z**2 - 1000000
|
628 |
+
base_soln = {(0, 0, 1000), (0, 352, 936), (480, 600, 640), (24, 640, 768), (192, 640, 744),
|
629 |
+
(192, 480, 856), (168, 224, 960), (0, 600, 800), (280, 576, 768), (152, 480, 864),
|
630 |
+
(0, 280, 960), (352, 360, 864), (424, 480, 768), (360, 480, 800), (224, 600, 768),
|
631 |
+
(96, 360, 928), (168, 576, 800), (96, 480, 872)}
|
632 |
+
|
633 |
+
assert diophantine(eq) == base_soln
|
634 |
+
|
635 |
+
|
636 |
+
def test_diop_partition():
|
637 |
+
for n in [8, 10]:
|
638 |
+
for k in range(1, 8):
|
639 |
+
for p in partition(n, k):
|
640 |
+
assert len(p) == k
|
641 |
+
assert list(partition(3, 5)) == []
|
642 |
+
assert [list(p) for p in partition(3, 5, 1)] == [
|
643 |
+
[0, 0, 0, 0, 3], [0, 0, 0, 1, 2], [0, 0, 1, 1, 1]]
|
644 |
+
assert list(partition(0)) == [()]
|
645 |
+
assert list(partition(1, 0)) == [()]
|
646 |
+
assert [list(i) for i in partition(3)] == [[1, 1, 1], [1, 2], [3]]
|
647 |
+
|
648 |
+
|
649 |
+
def test_prime_as_sum_of_two_squares():
|
650 |
+
for i in [5, 13, 17, 29, 37, 41, 2341, 3557, 34841, 64601]:
|
651 |
+
a, b = prime_as_sum_of_two_squares(i)
|
652 |
+
assert a**2 + b**2 == i
|
653 |
+
assert prime_as_sum_of_two_squares(7) is None
|
654 |
+
ans = prime_as_sum_of_two_squares(800029)
|
655 |
+
assert ans == (450, 773) and type(ans[0]) is int
|
656 |
+
|
657 |
+
|
658 |
+
def test_sum_of_three_squares():
|
659 |
+
for i in [0, 1, 2, 34, 123, 34304595905, 34304595905394941, 343045959052344,
|
660 |
+
800, 801, 802, 803, 804, 805, 806]:
|
661 |
+
a, b, c = sum_of_three_squares(i)
|
662 |
+
assert a**2 + b**2 + c**2 == i
|
663 |
+
|
664 |
+
assert sum_of_three_squares(7) is None
|
665 |
+
assert sum_of_three_squares((4**5)*15) is None
|
666 |
+
assert sum_of_three_squares(25) == (5, 0, 0)
|
667 |
+
assert sum_of_three_squares(4) == (0, 0, 2)
|
668 |
+
|
669 |
+
|
670 |
+
def test_sum_of_four_squares():
|
671 |
+
from sympy.core.random import randint
|
672 |
+
|
673 |
+
# this should never fail
|
674 |
+
n = randint(1, 100000000000000)
|
675 |
+
assert sum(i**2 for i in sum_of_four_squares(n)) == n
|
676 |
+
|
677 |
+
assert sum_of_four_squares(0) == (0, 0, 0, 0)
|
678 |
+
assert sum_of_four_squares(14) == (0, 1, 2, 3)
|
679 |
+
assert sum_of_four_squares(15) == (1, 1, 2, 3)
|
680 |
+
assert sum_of_four_squares(18) == (1, 2, 2, 3)
|
681 |
+
assert sum_of_four_squares(19) == (0, 1, 3, 3)
|
682 |
+
assert sum_of_four_squares(48) == (0, 4, 4, 4)
|
683 |
+
|
684 |
+
|
685 |
+
def test_power_representation():
|
686 |
+
tests = [(1729, 3, 2), (234, 2, 4), (2, 1, 2), (3, 1, 3), (5, 2, 2), (12352, 2, 4),
|
687 |
+
(32760, 2, 3)]
|
688 |
+
|
689 |
+
for test in tests:
|
690 |
+
n, p, k = test
|
691 |
+
f = power_representation(n, p, k)
|
692 |
+
|
693 |
+
while True:
|
694 |
+
try:
|
695 |
+
l = next(f)
|
696 |
+
assert len(l) == k
|
697 |
+
|
698 |
+
chk_sum = 0
|
699 |
+
for l_i in l:
|
700 |
+
chk_sum = chk_sum + l_i**p
|
701 |
+
assert chk_sum == n
|
702 |
+
|
703 |
+
except StopIteration:
|
704 |
+
break
|
705 |
+
|
706 |
+
assert list(power_representation(20, 2, 4, True)) == \
|
707 |
+
[(1, 1, 3, 3), (0, 0, 2, 4)]
|
708 |
+
raises(ValueError, lambda: list(power_representation(1.2, 2, 2)))
|
709 |
+
raises(ValueError, lambda: list(power_representation(2, 0, 2)))
|
710 |
+
raises(ValueError, lambda: list(power_representation(2, 2, 0)))
|
711 |
+
assert list(power_representation(-1, 2, 2)) == []
|
712 |
+
assert list(power_representation(1, 1, 1)) == [(1,)]
|
713 |
+
assert list(power_representation(3, 2, 1)) == []
|
714 |
+
assert list(power_representation(4, 2, 1)) == [(2,)]
|
715 |
+
assert list(power_representation(3**4, 4, 6, zeros=True)) == \
|
716 |
+
[(1, 2, 2, 2, 2, 2), (0, 0, 0, 0, 0, 3)]
|
717 |
+
assert list(power_representation(3**4, 4, 5, zeros=False)) == []
|
718 |
+
assert list(power_representation(-2, 3, 2)) == [(-1, -1)]
|
719 |
+
assert list(power_representation(-2, 4, 2)) == []
|
720 |
+
assert list(power_representation(0, 3, 2, True)) == [(0, 0)]
|
721 |
+
assert list(power_representation(0, 3, 2, False)) == []
|
722 |
+
# when we are dealing with squares, do feasibility checks
|
723 |
+
assert len(list(power_representation(4**10*(8*10 + 7), 2, 3))) == 0
|
724 |
+
# there will be a recursion error if these aren't recognized
|
725 |
+
big = 2**30
|
726 |
+
for i in [13, 10, 7, 5, 4, 2, 1]:
|
727 |
+
assert list(sum_of_powers(big, 2, big - i)) == []
|
728 |
+
|
729 |
+
|
730 |
+
def test_assumptions():
|
731 |
+
"""
|
732 |
+
Test whether diophantine respects the assumptions.
|
733 |
+
"""
|
734 |
+
#Test case taken from the below so question regarding assumptions in diophantine module
|
735 |
+
#https://stackoverflow.com/questions/23301941/how-can-i-declare-natural-symbols-with-sympy
|
736 |
+
m, n = symbols('m n', integer=True, positive=True)
|
737 |
+
diof = diophantine(n**2 + m*n - 500)
|
738 |
+
assert diof == {(5, 20), (40, 10), (95, 5), (121, 4), (248, 2), (499, 1)}
|
739 |
+
|
740 |
+
a, b = symbols('a b', integer=True, positive=False)
|
741 |
+
diof = diophantine(a*b + 2*a + 3*b - 6)
|
742 |
+
assert diof == {(-15, -3), (-9, -4), (-7, -5), (-6, -6), (-5, -8), (-4, -14)}
|
743 |
+
|
744 |
+
|
745 |
+
def check_solutions(eq):
|
746 |
+
"""
|
747 |
+
Determines whether solutions returned by diophantine() satisfy the original
|
748 |
+
equation. Hope to generalize this so we can remove functions like check_ternay_quadratic,
|
749 |
+
check_solutions_normal, check_solutions()
|
750 |
+
"""
|
751 |
+
s = diophantine(eq)
|
752 |
+
|
753 |
+
factors = Mul.make_args(eq)
|
754 |
+
|
755 |
+
var = list(eq.free_symbols)
|
756 |
+
var.sort(key=default_sort_key)
|
757 |
+
|
758 |
+
while s:
|
759 |
+
solution = s.pop()
|
760 |
+
for f in factors:
|
761 |
+
if diop_simplify(f.subs(zip(var, solution))) == 0:
|
762 |
+
break
|
763 |
+
else:
|
764 |
+
return False
|
765 |
+
return True
|
766 |
+
|
767 |
+
|
768 |
+
def test_diopcoverage():
|
769 |
+
eq = (2*x + y + 1)**2
|
770 |
+
assert diop_solve(eq) == {(t_0, -2*t_0 - 1)}
|
771 |
+
eq = 2*x**2 + 6*x*y + 12*x + 4*y**2 + 18*y + 18
|
772 |
+
assert diop_solve(eq) == {(t, -t - 3), (2*t - 3, -t)}
|
773 |
+
assert diop_quadratic(x + y**2 - 3) == {(-t**2 + 3, -t)}
|
774 |
+
|
775 |
+
assert diop_linear(x + y - 3) == (t_0, 3 - t_0)
|
776 |
+
|
777 |
+
assert base_solution_linear(0, 1, 2, t=None) == (0, 0)
|
778 |
+
ans = (3*t - 1, -2*t + 1)
|
779 |
+
assert base_solution_linear(4, 8, 12, t) == ans
|
780 |
+
assert base_solution_linear(4, 8, 12, t=None) == tuple(_.subs(t, 0) for _ in ans)
|
781 |
+
|
782 |
+
assert cornacchia(1, 1, 20) is None
|
783 |
+
assert cornacchia(1, 1, 5) == {(2, 1)}
|
784 |
+
assert cornacchia(1, 2, 17) == {(3, 2)}
|
785 |
+
|
786 |
+
raises(ValueError, lambda: reconstruct(4, 20, 1))
|
787 |
+
|
788 |
+
assert gaussian_reduce(4, 1, 3) == (1, 1)
|
789 |
+
eq = -w**2 - x**2 - y**2 + z**2
|
790 |
+
|
791 |
+
assert diop_general_pythagorean(eq) == \
|
792 |
+
diop_general_pythagorean(-eq) == \
|
793 |
+
(m1**2 + m2**2 - m3**2, 2*m1*m3,
|
794 |
+
2*m2*m3, m1**2 + m2**2 + m3**2)
|
795 |
+
|
796 |
+
assert len(check_param(S(3) + x/3, S(4) + x/2, S(2), [x])) == 0
|
797 |
+
assert len(check_param(Rational(3, 2), S(4) + x, S(2), [x])) == 0
|
798 |
+
assert len(check_param(S(4) + x, Rational(3, 2), S(2), [x])) == 0
|
799 |
+
|
800 |
+
assert _nint_or_floor(16, 10) == 2
|
801 |
+
assert _odd(1) == (not _even(1)) == True
|
802 |
+
assert _odd(0) == (not _even(0)) == False
|
803 |
+
assert _remove_gcd(2, 4, 6) == (1, 2, 3)
|
804 |
+
raises(TypeError, lambda: _remove_gcd((2, 4, 6)))
|
805 |
+
assert sqf_normal(2*3**2*5, 2*5*11, 2*7**2*11) == \
|
806 |
+
(11, 1, 5)
|
807 |
+
|
808 |
+
# it's ok if these pass some day when the solvers are implemented
|
809 |
+
raises(NotImplementedError, lambda: diophantine(x**2 + y**2 + x*y + 2*y*z - 12))
|
810 |
+
raises(NotImplementedError, lambda: diophantine(x**3 + y**2))
|
811 |
+
assert diop_quadratic(x**2 + y**2 - 1**2 - 3**4) == \
|
812 |
+
{(-9, -1), (-9, 1), (-1, -9), (-1, 9), (1, -9), (1, 9), (9, -1), (9, 1)}
|
813 |
+
|
814 |
+
|
815 |
+
def test_holzer():
|
816 |
+
# if the input is good, don't let it diverge in holzer()
|
817 |
+
# (but see test_fail_holzer below)
|
818 |
+
assert holzer(2, 7, 13, 4, 79, 23) == (2, 7, 13)
|
819 |
+
|
820 |
+
# None in uv condition met; solution is not Holzer reduced
|
821 |
+
# so this will hopefully change but is here for coverage
|
822 |
+
assert holzer(2, 6, 2, 1, 1, 10) == (2, 6, 2)
|
823 |
+
|
824 |
+
raises(ValueError, lambda: holzer(2, 7, 14, 4, 79, 23))
|
825 |
+
|
826 |
+
|
827 |
+
@XFAIL
|
828 |
+
def test_fail_holzer():
|
829 |
+
eq = lambda x, y, z: a*x**2 + b*y**2 - c*z**2
|
830 |
+
a, b, c = 4, 79, 23
|
831 |
+
x, y, z = xyz = 26, 1, 11
|
832 |
+
X, Y, Z = ans = 2, 7, 13
|
833 |
+
assert eq(*xyz) == 0
|
834 |
+
assert eq(*ans) == 0
|
835 |
+
assert max(a*x**2, b*y**2, c*z**2) <= a*b*c
|
836 |
+
assert max(a*X**2, b*Y**2, c*Z**2) <= a*b*c
|
837 |
+
h = holzer(x, y, z, a, b, c)
|
838 |
+
assert h == ans # it would be nice to get the smaller soln
|
839 |
+
|
840 |
+
|
841 |
+
def test_issue_9539():
|
842 |
+
assert diophantine(6*w + 9*y + 20*x - z) == \
|
843 |
+
{(t_0, t_1, t_1 + t_2, 6*t_0 + 29*t_1 + 9*t_2)}
|
844 |
+
|
845 |
+
|
846 |
+
def test_issue_8943():
|
847 |
+
assert diophantine(
|
848 |
+
3*(x**2 + y**2 + z**2) - 14*(x*y + y*z + z*x)) == \
|
849 |
+
{(0, 0, 0)}
|
850 |
+
|
851 |
+
|
852 |
+
def test_diop_sum_of_even_powers():
|
853 |
+
eq = x**4 + y**4 + z**4 - 2673
|
854 |
+
assert diop_solve(eq) == {(3, 6, 6), (2, 4, 7)}
|
855 |
+
assert diop_general_sum_of_even_powers(eq, 2) == {(3, 6, 6), (2, 4, 7)}
|
856 |
+
raises(NotImplementedError, lambda: diop_general_sum_of_even_powers(-eq, 2))
|
857 |
+
neg = symbols('neg', negative=True)
|
858 |
+
eq = x**4 + y**4 + neg**4 - 2673
|
859 |
+
assert diop_general_sum_of_even_powers(eq) == {(-3, 6, 6)}
|
860 |
+
assert diophantine(x**4 + y**4 + 2) == set()
|
861 |
+
assert diop_general_sum_of_even_powers(x**4 + y**4 - 2, limit=0) == set()
|
862 |
+
|
863 |
+
|
864 |
+
def test_sum_of_squares_powers():
|
865 |
+
tru = {(0, 0, 1, 1, 11), (0, 0, 5, 7, 7), (0, 1, 3, 7, 8), (0, 1, 4, 5, 9), (0, 3, 4, 7, 7), (0, 3, 5, 5, 8),
|
866 |
+
(1, 1, 2, 6, 9), (1, 1, 6, 6, 7), (1, 2, 3, 3, 10), (1, 3, 4, 4, 9), (1, 5, 5, 6, 6), (2, 2, 3, 5, 9),
|
867 |
+
(2, 3, 5, 6, 7), (3, 3, 4, 5, 8)}
|
868 |
+
eq = u**2 + v**2 + x**2 + y**2 + z**2 - 123
|
869 |
+
ans = diop_general_sum_of_squares(eq, oo) # allow oo to be used
|
870 |
+
assert len(ans) == 14
|
871 |
+
assert ans == tru
|
872 |
+
|
873 |
+
raises(ValueError, lambda: list(sum_of_squares(10, -1)))
|
874 |
+
assert list(sum_of_squares(-10, 2)) == []
|
875 |
+
assert list(sum_of_squares(2, 3)) == []
|
876 |
+
assert list(sum_of_squares(0, 3, True)) == [(0, 0, 0)]
|
877 |
+
assert list(sum_of_squares(0, 3)) == []
|
878 |
+
assert list(sum_of_squares(4, 1)) == [(2,)]
|
879 |
+
assert list(sum_of_squares(5, 1)) == []
|
880 |
+
assert list(sum_of_squares(50, 2)) == [(5, 5), (1, 7)]
|
881 |
+
assert list(sum_of_squares(11, 5, True)) == [
|
882 |
+
(1, 1, 1, 2, 2), (0, 0, 1, 1, 3)]
|
883 |
+
assert list(sum_of_squares(8, 8)) == [(1, 1, 1, 1, 1, 1, 1, 1)]
|
884 |
+
|
885 |
+
assert [len(list(sum_of_squares(i, 5, True))) for i in range(30)] == [
|
886 |
+
1, 1, 1, 1, 2,
|
887 |
+
2, 1, 1, 2, 2,
|
888 |
+
2, 2, 2, 3, 2,
|
889 |
+
1, 3, 3, 3, 3,
|
890 |
+
4, 3, 3, 2, 2,
|
891 |
+
4, 4, 4, 4, 5]
|
892 |
+
assert [len(list(sum_of_squares(i, 5))) for i in range(30)] == [
|
893 |
+
0, 0, 0, 0, 0,
|
894 |
+
1, 0, 0, 1, 0,
|
895 |
+
0, 1, 0, 1, 1,
|
896 |
+
0, 1, 1, 0, 1,
|
897 |
+
2, 1, 1, 1, 1,
|
898 |
+
1, 1, 1, 1, 3]
|
899 |
+
for i in range(30):
|
900 |
+
s1 = set(sum_of_squares(i, 5, True))
|
901 |
+
assert not s1 or all(sum(j**2 for j in t) == i for t in s1)
|
902 |
+
s2 = set(sum_of_squares(i, 5))
|
903 |
+
assert all(sum(j**2 for j in t) == i for t in s2)
|
904 |
+
|
905 |
+
raises(ValueError, lambda: list(sum_of_powers(2, -1, 1)))
|
906 |
+
raises(ValueError, lambda: list(sum_of_powers(2, 1, -1)))
|
907 |
+
assert list(sum_of_powers(-2, 3, 2)) == [(-1, -1)]
|
908 |
+
assert list(sum_of_powers(-2, 4, 2)) == []
|
909 |
+
assert list(sum_of_powers(2, 1, 1)) == [(2,)]
|
910 |
+
assert list(sum_of_powers(2, 1, 3, True)) == [(0, 0, 2), (0, 1, 1)]
|
911 |
+
assert list(sum_of_powers(5, 1, 2, True)) == [(0, 5), (1, 4), (2, 3)]
|
912 |
+
assert list(sum_of_powers(6, 2, 2)) == []
|
913 |
+
assert list(sum_of_powers(3**5, 3, 1)) == []
|
914 |
+
assert list(sum_of_powers(3**6, 3, 1)) == [(9,)] and (9**3 == 3**6)
|
915 |
+
assert list(sum_of_powers(2**1000, 5, 2)) == []
|
916 |
+
|
917 |
+
|
918 |
+
def test__can_do_sum_of_squares():
|
919 |
+
assert _can_do_sum_of_squares(3, -1) is False
|
920 |
+
assert _can_do_sum_of_squares(-3, 1) is False
|
921 |
+
assert _can_do_sum_of_squares(0, 1)
|
922 |
+
assert _can_do_sum_of_squares(4, 1)
|
923 |
+
assert _can_do_sum_of_squares(1, 2)
|
924 |
+
assert _can_do_sum_of_squares(2, 2)
|
925 |
+
assert _can_do_sum_of_squares(3, 2) is False
|
926 |
+
|
927 |
+
|
928 |
+
def test_diophantine_permute_sign():
|
929 |
+
from sympy.abc import a, b, c, d, e
|
930 |
+
eq = a**4 + b**4 - (2**4 + 3**4)
|
931 |
+
base_sol = {(2, 3)}
|
932 |
+
assert diophantine(eq) == base_sol
|
933 |
+
complete_soln = set(signed_permutations(base_sol.pop()))
|
934 |
+
assert diophantine(eq, permute=True) == complete_soln
|
935 |
+
|
936 |
+
eq = a**2 + b**2 + c**2 + d**2 + e**2 - 234
|
937 |
+
assert len(diophantine(eq)) == 35
|
938 |
+
assert len(diophantine(eq, permute=True)) == 62000
|
939 |
+
soln = {(-1, -1), (-1, 2), (1, -2), (1, 1)}
|
940 |
+
assert diophantine(10*x**2 + 12*x*y + 12*y**2 - 34, permute=True) == soln
|
941 |
+
|
942 |
+
|
943 |
+
@XFAIL
|
944 |
+
def test_not_implemented():
|
945 |
+
eq = x**2 + y**4 - 1**2 - 3**4
|
946 |
+
assert diophantine(eq, syms=[x, y]) == {(9, 1), (1, 3)}
|
947 |
+
|
948 |
+
|
949 |
+
def test_issue_9538():
|
950 |
+
eq = x - 3*y + 2
|
951 |
+
assert diophantine(eq, syms=[y,x]) == {(t_0, 3*t_0 - 2)}
|
952 |
+
raises(TypeError, lambda: diophantine(eq, syms={y, x}))
|
953 |
+
|
954 |
+
|
955 |
+
def test_ternary_quadratic():
|
956 |
+
# solution with 3 parameters
|
957 |
+
s = diophantine(2*x**2 + y**2 - 2*z**2)
|
958 |
+
p, q, r = ordered(S(s).free_symbols)
|
959 |
+
assert s == {(
|
960 |
+
p**2 - 2*q**2,
|
961 |
+
-2*p**2 + 4*p*q - 4*p*r - 4*q**2,
|
962 |
+
p**2 - 4*p*q + 2*q**2 - 4*q*r)}
|
963 |
+
# solution with Mul in solution
|
964 |
+
s = diophantine(x**2 + 2*y**2 - 2*z**2)
|
965 |
+
assert s == {(4*p*q, p**2 - 2*q**2, p**2 + 2*q**2)}
|
966 |
+
# solution with no Mul in solution
|
967 |
+
s = diophantine(2*x**2 + 2*y**2 - z**2)
|
968 |
+
assert s == {(2*p**2 - q**2, -2*p**2 + 4*p*q - q**2,
|
969 |
+
4*p**2 - 4*p*q + 2*q**2)}
|
970 |
+
# reduced form when parametrized
|
971 |
+
s = diophantine(3*x**2 + 72*y**2 - 27*z**2)
|
972 |
+
assert s == {(24*p**2 - 9*q**2, 6*p*q, 8*p**2 + 3*q**2)}
|
973 |
+
assert parametrize_ternary_quadratic(
|
974 |
+
3*x**2 + 2*y**2 - z**2 - 2*x*y + 5*y*z - 7*y*z) == (
|
975 |
+
2*p**2 - 2*p*q - q**2, 2*p**2 + 2*p*q - q**2, 2*p**2 -
|
976 |
+
2*p*q + 3*q**2)
|
977 |
+
assert parametrize_ternary_quadratic(
|
978 |
+
124*x**2 - 30*y**2 - 7729*z**2) == (
|
979 |
+
-1410*p**2 - 363263*q**2, 2700*p**2 + 30916*p*q -
|
980 |
+
695610*q**2, -60*p**2 + 5400*p*q + 15458*q**2)
|
981 |
+
|
982 |
+
|
983 |
+
def test_diophantine_solution_set():
|
984 |
+
s1 = DiophantineSolutionSet([], [])
|
985 |
+
assert set(s1) == set()
|
986 |
+
assert s1.symbols == ()
|
987 |
+
assert s1.parameters == ()
|
988 |
+
raises(ValueError, lambda: s1.add((x,)))
|
989 |
+
assert list(s1.dict_iterator()) == []
|
990 |
+
|
991 |
+
s2 = DiophantineSolutionSet([x, y], [t, u])
|
992 |
+
assert s2.symbols == (x, y)
|
993 |
+
assert s2.parameters == (t, u)
|
994 |
+
raises(ValueError, lambda: s2.add((1,)))
|
995 |
+
s2.add((3, 4))
|
996 |
+
assert set(s2) == {(3, 4)}
|
997 |
+
s2.update((3, 4), (-1, u))
|
998 |
+
assert set(s2) == {(3, 4), (-1, u)}
|
999 |
+
raises(ValueError, lambda: s1.update(s2))
|
1000 |
+
assert list(s2.dict_iterator()) == [{x: -1, y: u}, {x: 3, y: 4}]
|
1001 |
+
|
1002 |
+
s3 = DiophantineSolutionSet([x, y, z], [t, u])
|
1003 |
+
assert len(s3.parameters) == 2
|
1004 |
+
s3.add((t**2 + u, t - u, 1))
|
1005 |
+
assert set(s3) == {(t**2 + u, t - u, 1)}
|
1006 |
+
assert s3.subs(t, 2) == {(u + 4, 2 - u, 1)}
|
1007 |
+
assert s3(2) == {(u + 4, 2 - u, 1)}
|
1008 |
+
assert s3.subs({t: 7, u: 8}) == {(57, -1, 1)}
|
1009 |
+
assert s3(7, 8) == {(57, -1, 1)}
|
1010 |
+
assert s3.subs({t: 5}) == {(u + 25, 5 - u, 1)}
|
1011 |
+
assert s3(5) == {(u + 25, 5 - u, 1)}
|
1012 |
+
assert s3.subs(u, -3) == {(t**2 - 3, t + 3, 1)}
|
1013 |
+
assert s3(None, -3) == {(t**2 - 3, t + 3, 1)}
|
1014 |
+
assert s3.subs({t: 2, u: 8}) == {(12, -6, 1)}
|
1015 |
+
assert s3(2, 8) == {(12, -6, 1)}
|
1016 |
+
assert s3.subs({t: 5, u: -3}) == {(22, 8, 1)}
|
1017 |
+
assert s3(5, -3) == {(22, 8, 1)}
|
1018 |
+
raises(ValueError, lambda: s3.subs(x=1))
|
1019 |
+
raises(ValueError, lambda: s3.subs(1, 2, 3))
|
1020 |
+
raises(ValueError, lambda: s3.add(()))
|
1021 |
+
raises(ValueError, lambda: s3.add((1, 2, 3, 4)))
|
1022 |
+
raises(ValueError, lambda: s3.add((1, 2)))
|
1023 |
+
raises(ValueError, lambda: s3(1, 2, 3))
|
1024 |
+
raises(TypeError, lambda: s3(t=1))
|
1025 |
+
|
1026 |
+
s4 = DiophantineSolutionSet([x, y], [t, u])
|
1027 |
+
s4.add((t, 11*t))
|
1028 |
+
s4.add((-t, 22*t))
|
1029 |
+
assert s4(0, 0) == {(0, 0)}
|
1030 |
+
|
1031 |
+
|
1032 |
+
def test_quadratic_parameter_passing():
|
1033 |
+
eq = -33*x*y + 3*y**2
|
1034 |
+
solution = BinaryQuadratic(eq).solve(parameters=[t, u])
|
1035 |
+
# test that parameters are passed all the way to the final solution
|
1036 |
+
assert solution == {(t, 11*t), (-t, 22*t)}
|
1037 |
+
assert solution(0, 0) == {(0, 0)}
|
llmeval-env/lib/python3.10/site-packages/sympy/solvers/ode/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (607 Bytes). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/solvers/ode/__pycache__/hypergeometric.cpython-310.pyc
ADDED
Binary file (7.08 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/solvers/ode/__pycache__/lie_group.cpython-310.pyc
ADDED
Binary file (30.8 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/solvers/ode/__pycache__/nonhomogeneous.cpython-310.pyc
ADDED
Binary file (14.8 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/solvers/ode/__pycache__/ode.cpython-310.pyc
ADDED
Binary file (121 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/solvers/ode/__pycache__/riccati.cpython-310.pyc
ADDED
Binary file (24.4 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/solvers/ode/__pycache__/single.cpython-310.pyc
ADDED
Binary file (105 kB). View file
|
|