Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- ckpts/universal/global_step120/zero/11.mlp.dense_4h_to_h.weight/exp_avg.pt +3 -0
- ckpts/universal/global_step120/zero/19.input_layernorm.weight/exp_avg_sq.pt +3 -0
- ckpts/universal/global_step120/zero/19.input_layernorm.weight/fp32.pt +3 -0
- ckpts/universal/global_step120/zero/25.mlp.dense_h_to_4h_swiglu.weight/fp32.pt +3 -0
- venv/lib/python3.10/site-packages/sympy/core/__init__.py +100 -0
- venv/lib/python3.10/site-packages/sympy/core/_print_helpers.py +65 -0
- venv/lib/python3.10/site-packages/sympy/core/assumptions.py +692 -0
- venv/lib/python3.10/site-packages/sympy/core/assumptions_generated.py +1615 -0
- venv/lib/python3.10/site-packages/sympy/core/basic.py +2233 -0
- venv/lib/python3.10/site-packages/sympy/core/cache.py +210 -0
- venv/lib/python3.10/site-packages/sympy/core/compatibility.py +35 -0
- venv/lib/python3.10/site-packages/sympy/core/containers.py +410 -0
- venv/lib/python3.10/site-packages/sympy/core/coreerrors.py +9 -0
- venv/lib/python3.10/site-packages/sympy/core/expr.py +0 -0
- venv/lib/python3.10/site-packages/sympy/core/exprtools.py +1569 -0
- venv/lib/python3.10/site-packages/sympy/core/facts.py +634 -0
- venv/lib/python3.10/site-packages/sympy/core/function.py +0 -0
- venv/lib/python3.10/site-packages/sympy/core/kind.py +388 -0
- venv/lib/python3.10/site-packages/sympy/core/logic.py +427 -0
- venv/lib/python3.10/site-packages/sympy/core/mul.py +2195 -0
- venv/lib/python3.10/site-packages/sympy/core/multidimensional.py +131 -0
- venv/lib/python3.10/site-packages/sympy/core/numbers.py +0 -0
- venv/lib/python3.10/site-packages/sympy/core/operations.py +722 -0
- venv/lib/python3.10/site-packages/sympy/core/random.py +227 -0
- venv/lib/python3.10/site-packages/sympy/core/rules.py +66 -0
- venv/lib/python3.10/site-packages/sympy/core/singleton.py +174 -0
- venv/lib/python3.10/site-packages/sympy/core/symbol.py +945 -0
- venv/lib/python3.10/site-packages/sympy/core/sympify.py +634 -0
- venv/lib/python3.10/site-packages/sympy/core/tests/__init__.py +0 -0
- venv/lib/python3.10/site-packages/sympy/core/tests/__pycache__/test_args.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/core/tests/__pycache__/test_assumptions.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/core/tests/__pycache__/test_basic.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/core/tests/__pycache__/test_complex.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/core/tests/__pycache__/test_count_ops.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/core/tests/__pycache__/test_evalf.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/core/tests/__pycache__/test_expand.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/core/tests/__pycache__/test_multidimensional.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/core/tests/__pycache__/test_numbers.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/core/tests/__pycache__/test_operations.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/core/tests/__pycache__/test_relational.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/core/tests/__pycache__/test_singleton.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/core/tests/__pycache__/test_subs.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/core/tests/__pycache__/test_truediv.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/core/tests/__pycache__/test_var.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/core/tests/test_args.py +0 -0
- venv/lib/python3.10/site-packages/sympy/core/tests/test_cache.py +91 -0
- venv/lib/python3.10/site-packages/sympy/core/tests/test_compatibility.py +6 -0
- venv/lib/python3.10/site-packages/sympy/core/tests/test_complex.py +226 -0
- venv/lib/python3.10/site-packages/sympy/core/tests/test_constructor_postprocessor.py +87 -0
- venv/lib/python3.10/site-packages/sympy/core/tests/test_count_ops.py +155 -0
ckpts/universal/global_step120/zero/11.mlp.dense_4h_to_h.weight/exp_avg.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:22b4ca883fc01485997e70e63c100dcf3a1ed80c87ba3a89b43d6f52ec30748c
|
3 |
+
size 33555612
|
ckpts/universal/global_step120/zero/19.input_layernorm.weight/exp_avg_sq.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:cf837404b2838b6eed48c444a50dafcbc6ba5fd9f7c5d1e03915cc79107e51c4
|
3 |
+
size 9387
|
ckpts/universal/global_step120/zero/19.input_layernorm.weight/fp32.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:9978eb257c2a4067edc093ab6054e6db02c885e85ccbc3e6db9c0f09cb771c71
|
3 |
+
size 9293
|
ckpts/universal/global_step120/zero/25.mlp.dense_h_to_4h_swiglu.weight/fp32.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:5a2a43f32a28a814b4c2d3e0ef1e58eb6eae32e41ade877f8de35a8bea1ddb46
|
3 |
+
size 33555533
|
venv/lib/python3.10/site-packages/sympy/core/__init__.py
ADDED
@@ -0,0 +1,100 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Core module. Provides the basic operations needed in sympy.
|
2 |
+
"""
|
3 |
+
|
4 |
+
from .sympify import sympify, SympifyError
|
5 |
+
from .cache import cacheit
|
6 |
+
from .assumptions import assumptions, check_assumptions, failing_assumptions, common_assumptions
|
7 |
+
from .basic import Basic, Atom
|
8 |
+
from .singleton import S
|
9 |
+
from .expr import Expr, AtomicExpr, UnevaluatedExpr
|
10 |
+
from .symbol import Symbol, Wild, Dummy, symbols, var
|
11 |
+
from .numbers import Number, Float, Rational, Integer, NumberSymbol, \
|
12 |
+
RealNumber, igcd, ilcm, seterr, E, I, nan, oo, pi, zoo, \
|
13 |
+
AlgebraicNumber, comp, mod_inverse
|
14 |
+
from .power import Pow, integer_nthroot, integer_log
|
15 |
+
from .mul import Mul, prod
|
16 |
+
from .add import Add
|
17 |
+
from .mod import Mod
|
18 |
+
from .relational import ( Rel, Eq, Ne, Lt, Le, Gt, Ge,
|
19 |
+
Equality, GreaterThan, LessThan, Unequality, StrictGreaterThan,
|
20 |
+
StrictLessThan )
|
21 |
+
from .multidimensional import vectorize
|
22 |
+
from .function import Lambda, WildFunction, Derivative, diff, FunctionClass, \
|
23 |
+
Function, Subs, expand, PoleError, count_ops, \
|
24 |
+
expand_mul, expand_log, expand_func, \
|
25 |
+
expand_trig, expand_complex, expand_multinomial, nfloat, \
|
26 |
+
expand_power_base, expand_power_exp, arity
|
27 |
+
from .evalf import PrecisionExhausted, N
|
28 |
+
from .containers import Tuple, Dict
|
29 |
+
from .exprtools import gcd_terms, factor_terms, factor_nc
|
30 |
+
from .parameters import evaluate
|
31 |
+
from .kind import UndefinedKind, NumberKind, BooleanKind
|
32 |
+
from .traversal import preorder_traversal, bottom_up, use, postorder_traversal
|
33 |
+
from .sorting import default_sort_key, ordered
|
34 |
+
|
35 |
+
# expose singletons
|
36 |
+
Catalan = S.Catalan
|
37 |
+
EulerGamma = S.EulerGamma
|
38 |
+
GoldenRatio = S.GoldenRatio
|
39 |
+
TribonacciConstant = S.TribonacciConstant
|
40 |
+
|
41 |
+
__all__ = [
|
42 |
+
'sympify', 'SympifyError',
|
43 |
+
|
44 |
+
'cacheit',
|
45 |
+
|
46 |
+
'assumptions', 'check_assumptions', 'failing_assumptions',
|
47 |
+
'common_assumptions',
|
48 |
+
|
49 |
+
'Basic', 'Atom',
|
50 |
+
|
51 |
+
'S',
|
52 |
+
|
53 |
+
'Expr', 'AtomicExpr', 'UnevaluatedExpr',
|
54 |
+
|
55 |
+
'Symbol', 'Wild', 'Dummy', 'symbols', 'var',
|
56 |
+
|
57 |
+
'Number', 'Float', 'Rational', 'Integer', 'NumberSymbol', 'RealNumber',
|
58 |
+
'igcd', 'ilcm', 'seterr', 'E', 'I', 'nan', 'oo', 'pi', 'zoo',
|
59 |
+
'AlgebraicNumber', 'comp', 'mod_inverse',
|
60 |
+
|
61 |
+
'Pow', 'integer_nthroot', 'integer_log',
|
62 |
+
|
63 |
+
'Mul', 'prod',
|
64 |
+
|
65 |
+
'Add',
|
66 |
+
|
67 |
+
'Mod',
|
68 |
+
|
69 |
+
'Rel', 'Eq', 'Ne', 'Lt', 'Le', 'Gt', 'Ge', 'Equality', 'GreaterThan',
|
70 |
+
'LessThan', 'Unequality', 'StrictGreaterThan', 'StrictLessThan',
|
71 |
+
|
72 |
+
'vectorize',
|
73 |
+
|
74 |
+
'Lambda', 'WildFunction', 'Derivative', 'diff', 'FunctionClass',
|
75 |
+
'Function', 'Subs', 'expand', 'PoleError', 'count_ops', 'expand_mul',
|
76 |
+
'expand_log', 'expand_func', 'expand_trig', 'expand_complex',
|
77 |
+
'expand_multinomial', 'nfloat', 'expand_power_base', 'expand_power_exp',
|
78 |
+
'arity',
|
79 |
+
|
80 |
+
'PrecisionExhausted', 'N',
|
81 |
+
|
82 |
+
'evalf', # The module?
|
83 |
+
|
84 |
+
'Tuple', 'Dict',
|
85 |
+
|
86 |
+
'gcd_terms', 'factor_terms', 'factor_nc',
|
87 |
+
|
88 |
+
'evaluate',
|
89 |
+
|
90 |
+
'Catalan',
|
91 |
+
'EulerGamma',
|
92 |
+
'GoldenRatio',
|
93 |
+
'TribonacciConstant',
|
94 |
+
|
95 |
+
'UndefinedKind', 'NumberKind', 'BooleanKind',
|
96 |
+
|
97 |
+
'preorder_traversal', 'bottom_up', 'use', 'postorder_traversal',
|
98 |
+
|
99 |
+
'default_sort_key', 'ordered',
|
100 |
+
]
|
venv/lib/python3.10/site-packages/sympy/core/_print_helpers.py
ADDED
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Base class to provide str and repr hooks that `init_printing` can overwrite.
|
3 |
+
|
4 |
+
This is exposed publicly in the `printing.defaults` module,
|
5 |
+
but cannot be defined there without causing circular imports.
|
6 |
+
"""
|
7 |
+
|
8 |
+
class Printable:
|
9 |
+
"""
|
10 |
+
The default implementation of printing for SymPy classes.
|
11 |
+
|
12 |
+
This implements a hack that allows us to print elements of built-in
|
13 |
+
Python containers in a readable way. Natively Python uses ``repr()``
|
14 |
+
even if ``str()`` was explicitly requested. Mix in this trait into
|
15 |
+
a class to get proper default printing.
|
16 |
+
|
17 |
+
This also adds support for LaTeX printing in jupyter notebooks.
|
18 |
+
"""
|
19 |
+
|
20 |
+
# Since this class is used as a mixin we set empty slots. That means that
|
21 |
+
# instances of any subclasses that use slots will not need to have a
|
22 |
+
# __dict__.
|
23 |
+
__slots__ = ()
|
24 |
+
|
25 |
+
# Note, we always use the default ordering (lex) in __str__ and __repr__,
|
26 |
+
# regardless of the global setting. See issue 5487.
|
27 |
+
def __str__(self):
|
28 |
+
from sympy.printing.str import sstr
|
29 |
+
return sstr(self, order=None)
|
30 |
+
|
31 |
+
__repr__ = __str__
|
32 |
+
|
33 |
+
def _repr_disabled(self):
|
34 |
+
"""
|
35 |
+
No-op repr function used to disable jupyter display hooks.
|
36 |
+
|
37 |
+
When :func:`sympy.init_printing` is used to disable certain display
|
38 |
+
formats, this function is copied into the appropriate ``_repr_*_``
|
39 |
+
attributes.
|
40 |
+
|
41 |
+
While we could just set the attributes to `None``, doing it this way
|
42 |
+
allows derived classes to call `super()`.
|
43 |
+
"""
|
44 |
+
return None
|
45 |
+
|
46 |
+
# We don't implement _repr_png_ here because it would add a large amount of
|
47 |
+
# data to any notebook containing SymPy expressions, without adding
|
48 |
+
# anything useful to the notebook. It can still enabled manually, e.g.,
|
49 |
+
# for the qtconsole, with init_printing().
|
50 |
+
_repr_png_ = _repr_disabled
|
51 |
+
|
52 |
+
_repr_svg_ = _repr_disabled
|
53 |
+
|
54 |
+
def _repr_latex_(self):
|
55 |
+
"""
|
56 |
+
IPython/Jupyter LaTeX printing
|
57 |
+
|
58 |
+
To change the behavior of this (e.g., pass in some settings to LaTeX),
|
59 |
+
use init_printing(). init_printing() will also enable LaTeX printing
|
60 |
+
for built in numeric types like ints and container types that contain
|
61 |
+
SymPy objects, like lists and dictionaries of expressions.
|
62 |
+
"""
|
63 |
+
from sympy.printing.latex import latex
|
64 |
+
s = latex(self, mode='plain')
|
65 |
+
return "$\\displaystyle %s$" % s
|
venv/lib/python3.10/site-packages/sympy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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)
|
venv/lib/python3.10/site-packages/sympy/core/assumptions_generated.py
ADDED
@@ -0,0 +1,1615 @@
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Do NOT manually edit this file.
|
3 |
+
Instead, run ./bin/ask_update.py.
|
4 |
+
"""
|
5 |
+
|
6 |
+
defined_facts = [
|
7 |
+
'algebraic',
|
8 |
+
'antihermitian',
|
9 |
+
'commutative',
|
10 |
+
'complex',
|
11 |
+
'composite',
|
12 |
+
'even',
|
13 |
+
'extended_negative',
|
14 |
+
'extended_nonnegative',
|
15 |
+
'extended_nonpositive',
|
16 |
+
'extended_nonzero',
|
17 |
+
'extended_positive',
|
18 |
+
'extended_real',
|
19 |
+
'finite',
|
20 |
+
'hermitian',
|
21 |
+
'imaginary',
|
22 |
+
'infinite',
|
23 |
+
'integer',
|
24 |
+
'irrational',
|
25 |
+
'negative',
|
26 |
+
'noninteger',
|
27 |
+
'nonnegative',
|
28 |
+
'nonpositive',
|
29 |
+
'nonzero',
|
30 |
+
'odd',
|
31 |
+
'positive',
|
32 |
+
'prime',
|
33 |
+
'rational',
|
34 |
+
'real',
|
35 |
+
'transcendental',
|
36 |
+
'zero',
|
37 |
+
] # defined_facts
|
38 |
+
|
39 |
+
|
40 |
+
full_implications = dict( [
|
41 |
+
# Implications of algebraic = True:
|
42 |
+
(('algebraic', True), set( (
|
43 |
+
('commutative', True),
|
44 |
+
('complex', True),
|
45 |
+
('finite', True),
|
46 |
+
('infinite', False),
|
47 |
+
('transcendental', False),
|
48 |
+
) ),
|
49 |
+
),
|
50 |
+
# Implications of algebraic = False:
|
51 |
+
(('algebraic', False), set( (
|
52 |
+
('composite', False),
|
53 |
+
('even', False),
|
54 |
+
('integer', False),
|
55 |
+
('odd', False),
|
56 |
+
('prime', False),
|
57 |
+
('rational', False),
|
58 |
+
('zero', False),
|
59 |
+
) ),
|
60 |
+
),
|
61 |
+
# Implications of antihermitian = True:
|
62 |
+
(('antihermitian', True), set( (
|
63 |
+
) ),
|
64 |
+
),
|
65 |
+
# Implications of antihermitian = False:
|
66 |
+
(('antihermitian', False), set( (
|
67 |
+
('imaginary', False),
|
68 |
+
) ),
|
69 |
+
),
|
70 |
+
# Implications of commutative = True:
|
71 |
+
(('commutative', True), set( (
|
72 |
+
) ),
|
73 |
+
),
|
74 |
+
# Implications of commutative = False:
|
75 |
+
(('commutative', False), set( (
|
76 |
+
('algebraic', False),
|
77 |
+
('complex', False),
|
78 |
+
('composite', False),
|
79 |
+
('even', False),
|
80 |
+
('extended_negative', False),
|
81 |
+
('extended_nonnegative', False),
|
82 |
+
('extended_nonpositive', False),
|
83 |
+
('extended_nonzero', False),
|
84 |
+
('extended_positive', False),
|
85 |
+
('extended_real', False),
|
86 |
+
('imaginary', False),
|
87 |
+
('integer', False),
|
88 |
+
('irrational', False),
|
89 |
+
('negative', False),
|
90 |
+
('noninteger', False),
|
91 |
+
('nonnegative', False),
|
92 |
+
('nonpositive', False),
|
93 |
+
('nonzero', False),
|
94 |
+
('odd', False),
|
95 |
+
('positive', False),
|
96 |
+
('prime', False),
|
97 |
+
('rational', False),
|
98 |
+
('real', False),
|
99 |
+
('transcendental', False),
|
100 |
+
('zero', False),
|
101 |
+
) ),
|
102 |
+
),
|
103 |
+
# Implications of complex = True:
|
104 |
+
(('complex', True), set( (
|
105 |
+
('commutative', True),
|
106 |
+
('finite', True),
|
107 |
+
('infinite', False),
|
108 |
+
) ),
|
109 |
+
),
|
110 |
+
# Implications of complex = False:
|
111 |
+
(('complex', False), set( (
|
112 |
+
('algebraic', False),
|
113 |
+
('composite', False),
|
114 |
+
('even', False),
|
115 |
+
('imaginary', False),
|
116 |
+
('integer', False),
|
117 |
+
('irrational', False),
|
118 |
+
('negative', False),
|
119 |
+
('nonnegative', False),
|
120 |
+
('nonpositive', False),
|
121 |
+
('nonzero', False),
|
122 |
+
('odd', False),
|
123 |
+
('positive', False),
|
124 |
+
('prime', False),
|
125 |
+
('rational', False),
|
126 |
+
('real', False),
|
127 |
+
('transcendental', False),
|
128 |
+
('zero', False),
|
129 |
+
) ),
|
130 |
+
),
|
131 |
+
# Implications of composite = True:
|
132 |
+
(('composite', True), set( (
|
133 |
+
('algebraic', True),
|
134 |
+
('commutative', True),
|
135 |
+
('complex', True),
|
136 |
+
('extended_negative', False),
|
137 |
+
('extended_nonnegative', True),
|
138 |
+
('extended_nonpositive', False),
|
139 |
+
('extended_nonzero', True),
|
140 |
+
('extended_positive', True),
|
141 |
+
('extended_real', True),
|
142 |
+
('finite', True),
|
143 |
+
('hermitian', True),
|
144 |
+
('imaginary', False),
|
145 |
+
('infinite', False),
|
146 |
+
('integer', True),
|
147 |
+
('irrational', False),
|
148 |
+
('negative', False),
|
149 |
+
('noninteger', False),
|
150 |
+
('nonnegative', True),
|
151 |
+
('nonpositive', False),
|
152 |
+
('nonzero', True),
|
153 |
+
('positive', True),
|
154 |
+
('prime', False),
|
155 |
+
('rational', True),
|
156 |
+
('real', True),
|
157 |
+
('transcendental', False),
|
158 |
+
('zero', False),
|
159 |
+
) ),
|
160 |
+
),
|
161 |
+
# Implications of composite = False:
|
162 |
+
(('composite', False), set( (
|
163 |
+
) ),
|
164 |
+
),
|
165 |
+
# Implications of even = True:
|
166 |
+
(('even', True), set( (
|
167 |
+
('algebraic', True),
|
168 |
+
('commutative', True),
|
169 |
+
('complex', True),
|
170 |
+
('extended_real', True),
|
171 |
+
('finite', True),
|
172 |
+
('hermitian', True),
|
173 |
+
('imaginary', False),
|
174 |
+
('infinite', False),
|
175 |
+
('integer', True),
|
176 |
+
('irrational', False),
|
177 |
+
('noninteger', False),
|
178 |
+
('odd', False),
|
179 |
+
('rational', True),
|
180 |
+
('real', True),
|
181 |
+
('transcendental', False),
|
182 |
+
) ),
|
183 |
+
),
|
184 |
+
# Implications of even = False:
|
185 |
+
(('even', False), set( (
|
186 |
+
('zero', False),
|
187 |
+
) ),
|
188 |
+
),
|
189 |
+
# Implications of extended_negative = True:
|
190 |
+
(('extended_negative', True), set( (
|
191 |
+
('commutative', True),
|
192 |
+
('composite', False),
|
193 |
+
('extended_nonnegative', False),
|
194 |
+
('extended_nonpositive', True),
|
195 |
+
('extended_nonzero', True),
|
196 |
+
('extended_positive', False),
|
197 |
+
('extended_real', True),
|
198 |
+
('imaginary', False),
|
199 |
+
('nonnegative', False),
|
200 |
+
('positive', False),
|
201 |
+
('prime', False),
|
202 |
+
('zero', False),
|
203 |
+
) ),
|
204 |
+
),
|
205 |
+
# Implications of extended_negative = False:
|
206 |
+
(('extended_negative', False), set( (
|
207 |
+
('negative', False),
|
208 |
+
) ),
|
209 |
+
),
|
210 |
+
# Implications of extended_nonnegative = True:
|
211 |
+
(('extended_nonnegative', True), set( (
|
212 |
+
('commutative', True),
|
213 |
+
('extended_negative', False),
|
214 |
+
('extended_real', True),
|
215 |
+
('imaginary', False),
|
216 |
+
('negative', False),
|
217 |
+
) ),
|
218 |
+
),
|
219 |
+
# Implications of extended_nonnegative = False:
|
220 |
+
(('extended_nonnegative', False), set( (
|
221 |
+
('composite', False),
|
222 |
+
('extended_positive', False),
|
223 |
+
('nonnegative', False),
|
224 |
+
('positive', False),
|
225 |
+
('prime', False),
|
226 |
+
('zero', False),
|
227 |
+
) ),
|
228 |
+
),
|
229 |
+
# Implications of extended_nonpositive = True:
|
230 |
+
(('extended_nonpositive', True), set( (
|
231 |
+
('commutative', True),
|
232 |
+
('composite', False),
|
233 |
+
('extended_positive', False),
|
234 |
+
('extended_real', True),
|
235 |
+
('imaginary', False),
|
236 |
+
('positive', False),
|
237 |
+
('prime', False),
|
238 |
+
) ),
|
239 |
+
),
|
240 |
+
# Implications of extended_nonpositive = False:
|
241 |
+
(('extended_nonpositive', False), set( (
|
242 |
+
('extended_negative', False),
|
243 |
+
('negative', False),
|
244 |
+
('nonpositive', False),
|
245 |
+
('zero', False),
|
246 |
+
) ),
|
247 |
+
),
|
248 |
+
# Implications of extended_nonzero = True:
|
249 |
+
(('extended_nonzero', True), set( (
|
250 |
+
('commutative', True),
|
251 |
+
('extended_real', True),
|
252 |
+
('imaginary', False),
|
253 |
+
('zero', False),
|
254 |
+
) ),
|
255 |
+
),
|
256 |
+
# Implications of extended_nonzero = False:
|
257 |
+
(('extended_nonzero', False), set( (
|
258 |
+
('composite', False),
|
259 |
+
('extended_negative', False),
|
260 |
+
('extended_positive', False),
|
261 |
+
('negative', False),
|
262 |
+
('nonzero', False),
|
263 |
+
('positive', False),
|
264 |
+
('prime', False),
|
265 |
+
) ),
|
266 |
+
),
|
267 |
+
# Implications of extended_positive = True:
|
268 |
+
(('extended_positive', True), set( (
|
269 |
+
('commutative', True),
|
270 |
+
('extended_negative', False),
|
271 |
+
('extended_nonnegative', True),
|
272 |
+
('extended_nonpositive', False),
|
273 |
+
('extended_nonzero', True),
|
274 |
+
('extended_real', True),
|
275 |
+
('imaginary', False),
|
276 |
+
('negative', False),
|
277 |
+
('nonpositive', False),
|
278 |
+
('zero', False),
|
279 |
+
) ),
|
280 |
+
),
|
281 |
+
# Implications of extended_positive = False:
|
282 |
+
(('extended_positive', False), set( (
|
283 |
+
('composite', False),
|
284 |
+
('positive', False),
|
285 |
+
('prime', False),
|
286 |
+
) ),
|
287 |
+
),
|
288 |
+
# Implications of extended_real = True:
|
289 |
+
(('extended_real', True), set( (
|
290 |
+
('commutative', True),
|
291 |
+
('imaginary', False),
|
292 |
+
) ),
|
293 |
+
),
|
294 |
+
# Implications of extended_real = False:
|
295 |
+
(('extended_real', False), set( (
|
296 |
+
('composite', False),
|
297 |
+
('even', False),
|
298 |
+
('extended_negative', False),
|
299 |
+
('extended_nonnegative', False),
|
300 |
+
('extended_nonpositive', False),
|
301 |
+
('extended_nonzero', False),
|
302 |
+
('extended_positive', False),
|
303 |
+
('integer', False),
|
304 |
+
('irrational', False),
|
305 |
+
('negative', False),
|
306 |
+
('noninteger', False),
|
307 |
+
('nonnegative', False),
|
308 |
+
('nonpositive', False),
|
309 |
+
('nonzero', False),
|
310 |
+
('odd', False),
|
311 |
+
('positive', False),
|
312 |
+
('prime', False),
|
313 |
+
('rational', False),
|
314 |
+
('real', False),
|
315 |
+
('zero', False),
|
316 |
+
) ),
|
317 |
+
),
|
318 |
+
# Implications of finite = True:
|
319 |
+
(('finite', True), set( (
|
320 |
+
('infinite', False),
|
321 |
+
) ),
|
322 |
+
),
|
323 |
+
# Implications of finite = False:
|
324 |
+
(('finite', False), set( (
|
325 |
+
('algebraic', False),
|
326 |
+
('complex', False),
|
327 |
+
('composite', False),
|
328 |
+
('even', False),
|
329 |
+
('imaginary', False),
|
330 |
+
('infinite', True),
|
331 |
+
('integer', False),
|
332 |
+
('irrational', False),
|
333 |
+
('negative', False),
|
334 |
+
('nonnegative', False),
|
335 |
+
('nonpositive', False),
|
336 |
+
('nonzero', False),
|
337 |
+
('odd', False),
|
338 |
+
('positive', False),
|
339 |
+
('prime', False),
|
340 |
+
('rational', False),
|
341 |
+
('real', False),
|
342 |
+
('transcendental', False),
|
343 |
+
('zero', False),
|
344 |
+
) ),
|
345 |
+
),
|
346 |
+
# Implications of hermitian = True:
|
347 |
+
(('hermitian', True), set( (
|
348 |
+
) ),
|
349 |
+
),
|
350 |
+
# Implications of hermitian = False:
|
351 |
+
(('hermitian', False), set( (
|
352 |
+
('composite', False),
|
353 |
+
('even', False),
|
354 |
+
('integer', False),
|
355 |
+
('irrational', False),
|
356 |
+
('negative', False),
|
357 |
+
('nonnegative', False),
|
358 |
+
('nonpositive', False),
|
359 |
+
('nonzero', False),
|
360 |
+
('odd', False),
|
361 |
+
('positive', False),
|
362 |
+
('prime', False),
|
363 |
+
('rational', False),
|
364 |
+
('real', False),
|
365 |
+
('zero', False),
|
366 |
+
) ),
|
367 |
+
),
|
368 |
+
# Implications of imaginary = True:
|
369 |
+
(('imaginary', True), set( (
|
370 |
+
('antihermitian', True),
|
371 |
+
('commutative', True),
|
372 |
+
('complex', True),
|
373 |
+
('composite', False),
|
374 |
+
('even', False),
|
375 |
+
('extended_negative', False),
|
376 |
+
('extended_nonnegative', False),
|
377 |
+
('extended_nonpositive', False),
|
378 |
+
('extended_nonzero', False),
|
379 |
+
('extended_positive', False),
|
380 |
+
('extended_real', False),
|
381 |
+
('finite', True),
|
382 |
+
('infinite', False),
|
383 |
+
('integer', False),
|
384 |
+
('irrational', False),
|
385 |
+
('negative', False),
|
386 |
+
('noninteger', False),
|
387 |
+
('nonnegative', False),
|
388 |
+
('nonpositive', False),
|
389 |
+
('nonzero', False),
|
390 |
+
('odd', False),
|
391 |
+
('positive', False),
|
392 |
+
('prime', False),
|
393 |
+
('rational', False),
|
394 |
+
('real', False),
|
395 |
+
('zero', False),
|
396 |
+
) ),
|
397 |
+
),
|
398 |
+
# Implications of imaginary = False:
|
399 |
+
(('imaginary', False), set( (
|
400 |
+
) ),
|
401 |
+
),
|
402 |
+
# Implications of infinite = True:
|
403 |
+
(('infinite', True), set( (
|
404 |
+
('algebraic', False),
|
405 |
+
('complex', False),
|
406 |
+
('composite', False),
|
407 |
+
('even', False),
|
408 |
+
('finite', False),
|
409 |
+
('imaginary', False),
|
410 |
+
('integer', False),
|
411 |
+
('irrational', False),
|
412 |
+
('negative', False),
|
413 |
+
('nonnegative', False),
|
414 |
+
('nonpositive', False),
|
415 |
+
('nonzero', False),
|
416 |
+
('odd', False),
|
417 |
+
('positive', False),
|
418 |
+
('prime', False),
|
419 |
+
('rational', False),
|
420 |
+
('real', False),
|
421 |
+
('transcendental', False),
|
422 |
+
('zero', False),
|
423 |
+
) ),
|
424 |
+
),
|
425 |
+
# Implications of infinite = False:
|
426 |
+
(('infinite', False), set( (
|
427 |
+
('finite', True),
|
428 |
+
) ),
|
429 |
+
),
|
430 |
+
# Implications of integer = True:
|
431 |
+
(('integer', True), set( (
|
432 |
+
('algebraic', True),
|
433 |
+
('commutative', True),
|
434 |
+
('complex', True),
|
435 |
+
('extended_real', True),
|
436 |
+
('finite', True),
|
437 |
+
('hermitian', True),
|
438 |
+
('imaginary', False),
|
439 |
+
('infinite', False),
|
440 |
+
('irrational', False),
|
441 |
+
('noninteger', False),
|
442 |
+
('rational', True),
|
443 |
+
('real', True),
|
444 |
+
('transcendental', False),
|
445 |
+
) ),
|
446 |
+
),
|
447 |
+
# Implications of integer = False:
|
448 |
+
(('integer', False), set( (
|
449 |
+
('composite', False),
|
450 |
+
('even', False),
|
451 |
+
('odd', False),
|
452 |
+
('prime', False),
|
453 |
+
('zero', False),
|
454 |
+
) ),
|
455 |
+
),
|
456 |
+
# Implications of irrational = True:
|
457 |
+
(('irrational', True), set( (
|
458 |
+
('commutative', True),
|
459 |
+
('complex', True),
|
460 |
+
('composite', False),
|
461 |
+
('even', False),
|
462 |
+
('extended_nonzero', True),
|
463 |
+
('extended_real', True),
|
464 |
+
('finite', True),
|
465 |
+
('hermitian', True),
|
466 |
+
('imaginary', False),
|
467 |
+
('infinite', False),
|
468 |
+
('integer', False),
|
469 |
+
('noninteger', True),
|
470 |
+
('nonzero', True),
|
471 |
+
('odd', False),
|
472 |
+
('prime', False),
|
473 |
+
('rational', False),
|
474 |
+
('real', True),
|
475 |
+
('zero', False),
|
476 |
+
) ),
|
477 |
+
),
|
478 |
+
# Implications of irrational = False:
|
479 |
+
(('irrational', False), set( (
|
480 |
+
) ),
|
481 |
+
),
|
482 |
+
# Implications of negative = True:
|
483 |
+
(('negative', True), set( (
|
484 |
+
('commutative', True),
|
485 |
+
('complex', True),
|
486 |
+
('composite', False),
|
487 |
+
('extended_negative', True),
|
488 |
+
('extended_nonnegative', False),
|
489 |
+
('extended_nonpositive', True),
|
490 |
+
('extended_nonzero', True),
|
491 |
+
('extended_positive', False),
|
492 |
+
('extended_real', True),
|
493 |
+
('finite', True),
|
494 |
+
('hermitian', True),
|
495 |
+
('imaginary', False),
|
496 |
+
('infinite', False),
|
497 |
+
('nonnegative', False),
|
498 |
+
('nonpositive', True),
|
499 |
+
('nonzero', True),
|
500 |
+
('positive', False),
|
501 |
+
('prime', False),
|
502 |
+
('real', True),
|
503 |
+
('zero', False),
|
504 |
+
) ),
|
505 |
+
),
|
506 |
+
# Implications of negative = False:
|
507 |
+
(('negative', False), set( (
|
508 |
+
) ),
|
509 |
+
),
|
510 |
+
# Implications of noninteger = True:
|
511 |
+
(('noninteger', True), set( (
|
512 |
+
('commutative', True),
|
513 |
+
('composite', False),
|
514 |
+
('even', False),
|
515 |
+
('extended_nonzero', True),
|
516 |
+
('extended_real', True),
|
517 |
+
('imaginary', False),
|
518 |
+
('integer', False),
|
519 |
+
('odd', False),
|
520 |
+
('prime', False),
|
521 |
+
('zero', False),
|
522 |
+
) ),
|
523 |
+
),
|
524 |
+
# Implications of noninteger = False:
|
525 |
+
(('noninteger', False), set( (
|
526 |
+
) ),
|
527 |
+
),
|
528 |
+
# Implications of nonnegative = True:
|
529 |
+
(('nonnegative', True), set( (
|
530 |
+
('commutative', True),
|
531 |
+
('complex', True),
|
532 |
+
('extended_negative', False),
|
533 |
+
('extended_nonnegative', True),
|
534 |
+
('extended_real', True),
|
535 |
+
('finite', True),
|
536 |
+
('hermitian', True),
|
537 |
+
('imaginary', False),
|
538 |
+
('infinite', False),
|
539 |
+
('negative', False),
|
540 |
+
('real', True),
|
541 |
+
) ),
|
542 |
+
),
|
543 |
+
# Implications of nonnegative = False:
|
544 |
+
(('nonnegative', False), set( (
|
545 |
+
('composite', False),
|
546 |
+
('positive', False),
|
547 |
+
('prime', False),
|
548 |
+
('zero', False),
|
549 |
+
) ),
|
550 |
+
),
|
551 |
+
# Implications of nonpositive = True:
|
552 |
+
(('nonpositive', True), set( (
|
553 |
+
('commutative', True),
|
554 |
+
('complex', True),
|
555 |
+
('composite', False),
|
556 |
+
('extended_nonpositive', True),
|
557 |
+
('extended_positive', False),
|
558 |
+
('extended_real', True),
|
559 |
+
('finite', True),
|
560 |
+
('hermitian', True),
|
561 |
+
('imaginary', False),
|
562 |
+
('infinite', False),
|
563 |
+
('positive', False),
|
564 |
+
('prime', False),
|
565 |
+
('real', True),
|
566 |
+
) ),
|
567 |
+
),
|
568 |
+
# Implications of nonpositive = False:
|
569 |
+
(('nonpositive', False), set( (
|
570 |
+
('negative', False),
|
571 |
+
('zero', False),
|
572 |
+
) ),
|
573 |
+
),
|
574 |
+
# Implications of nonzero = True:
|
575 |
+
(('nonzero', True), set( (
|
576 |
+
('commutative', True),
|
577 |
+
('complex', True),
|
578 |
+
('extended_nonzero', True),
|
579 |
+
('extended_real', True),
|
580 |
+
('finite', True),
|
581 |
+
('hermitian', True),
|
582 |
+
('imaginary', False),
|
583 |
+
('infinite', False),
|
584 |
+
('real', True),
|
585 |
+
('zero', False),
|
586 |
+
) ),
|
587 |
+
),
|
588 |
+
# Implications of nonzero = False:
|
589 |
+
(('nonzero', False), set( (
|
590 |
+
('composite', False),
|
591 |
+
('negative', False),
|
592 |
+
('positive', False),
|
593 |
+
('prime', False),
|
594 |
+
) ),
|
595 |
+
),
|
596 |
+
# Implications of odd = True:
|
597 |
+
(('odd', True), set( (
|
598 |
+
('algebraic', True),
|
599 |
+
('commutative', True),
|
600 |
+
('complex', True),
|
601 |
+
('even', False),
|
602 |
+
('extended_nonzero', True),
|
603 |
+
('extended_real', True),
|
604 |
+
('finite', True),
|
605 |
+
('hermitian', True),
|
606 |
+
('imaginary', False),
|
607 |
+
('infinite', False),
|
608 |
+
('integer', True),
|
609 |
+
('irrational', False),
|
610 |
+
('noninteger', False),
|
611 |
+
('nonzero', True),
|
612 |
+
('rational', True),
|
613 |
+
('real', True),
|
614 |
+
('transcendental', False),
|
615 |
+
('zero', False),
|
616 |
+
) ),
|
617 |
+
),
|
618 |
+
# Implications of odd = False:
|
619 |
+
(('odd', False), set( (
|
620 |
+
) ),
|
621 |
+
),
|
622 |
+
# Implications of positive = True:
|
623 |
+
(('positive', True), set( (
|
624 |
+
('commutative', True),
|
625 |
+
('complex', True),
|
626 |
+
('extended_negative', False),
|
627 |
+
('extended_nonnegative', True),
|
628 |
+
('extended_nonpositive', False),
|
629 |
+
('extended_nonzero', True),
|
630 |
+
('extended_positive', True),
|
631 |
+
('extended_real', True),
|
632 |
+
('finite', True),
|
633 |
+
('hermitian', True),
|
634 |
+
('imaginary', False),
|
635 |
+
('infinite', False),
|
636 |
+
('negative', False),
|
637 |
+
('nonnegative', True),
|
638 |
+
('nonpositive', False),
|
639 |
+
('nonzero', True),
|
640 |
+
('real', True),
|
641 |
+
('zero', False),
|
642 |
+
) ),
|
643 |
+
),
|
644 |
+
# Implications of positive = False:
|
645 |
+
(('positive', False), set( (
|
646 |
+
('composite', False),
|
647 |
+
('prime', False),
|
648 |
+
) ),
|
649 |
+
),
|
650 |
+
# Implications of prime = True:
|
651 |
+
(('prime', True), set( (
|
652 |
+
('algebraic', True),
|
653 |
+
('commutative', True),
|
654 |
+
('complex', True),
|
655 |
+
('composite', False),
|
656 |
+
('extended_negative', False),
|
657 |
+
('extended_nonnegative', True),
|
658 |
+
('extended_nonpositive', False),
|
659 |
+
('extended_nonzero', True),
|
660 |
+
('extended_positive', True),
|
661 |
+
('extended_real', True),
|
662 |
+
('finite', True),
|
663 |
+
('hermitian', True),
|
664 |
+
('imaginary', False),
|
665 |
+
('infinite', False),
|
666 |
+
('integer', True),
|
667 |
+
('irrational', False),
|
668 |
+
('negative', False),
|
669 |
+
('noninteger', False),
|
670 |
+
('nonnegative', True),
|
671 |
+
('nonpositive', False),
|
672 |
+
('nonzero', True),
|
673 |
+
('positive', True),
|
674 |
+
('rational', True),
|
675 |
+
('real', True),
|
676 |
+
('transcendental', False),
|
677 |
+
('zero', False),
|
678 |
+
) ),
|
679 |
+
),
|
680 |
+
# Implications of prime = False:
|
681 |
+
(('prime', False), set( (
|
682 |
+
) ),
|
683 |
+
),
|
684 |
+
# Implications of rational = True:
|
685 |
+
(('rational', True), set( (
|
686 |
+
('algebraic', True),
|
687 |
+
('commutative', True),
|
688 |
+
('complex', True),
|
689 |
+
('extended_real', True),
|
690 |
+
('finite', True),
|
691 |
+
('hermitian', True),
|
692 |
+
('imaginary', False),
|
693 |
+
('infinite', False),
|
694 |
+
('irrational', False),
|
695 |
+
('real', True),
|
696 |
+
('transcendental', False),
|
697 |
+
) ),
|
698 |
+
),
|
699 |
+
# Implications of rational = False:
|
700 |
+
(('rational', False), set( (
|
701 |
+
('composite', False),
|
702 |
+
('even', False),
|
703 |
+
('integer', False),
|
704 |
+
('odd', False),
|
705 |
+
('prime', False),
|
706 |
+
('zero', False),
|
707 |
+
) ),
|
708 |
+
),
|
709 |
+
# Implications of real = True:
|
710 |
+
(('real', True), set( (
|
711 |
+
('commutative', True),
|
712 |
+
('complex', True),
|
713 |
+
('extended_real', True),
|
714 |
+
('finite', True),
|
715 |
+
('hermitian', True),
|
716 |
+
('imaginary', False),
|
717 |
+
('infinite', False),
|
718 |
+
) ),
|
719 |
+
),
|
720 |
+
# Implications of real = False:
|
721 |
+
(('real', False), set( (
|
722 |
+
('composite', False),
|
723 |
+
('even', False),
|
724 |
+
('integer', False),
|
725 |
+
('irrational', False),
|
726 |
+
('negative', False),
|
727 |
+
('nonnegative', False),
|
728 |
+
('nonpositive', False),
|
729 |
+
('nonzero', False),
|
730 |
+
('odd', False),
|
731 |
+
('positive', False),
|
732 |
+
('prime', False),
|
733 |
+
('rational', False),
|
734 |
+
('zero', False),
|
735 |
+
) ),
|
736 |
+
),
|
737 |
+
# Implications of transcendental = True:
|
738 |
+
(('transcendental', True), set( (
|
739 |
+
('algebraic', False),
|
740 |
+
('commutative', True),
|
741 |
+
('complex', True),
|
742 |
+
('composite', False),
|
743 |
+
('even', False),
|
744 |
+
('finite', True),
|
745 |
+
('infinite', False),
|
746 |
+
('integer', False),
|
747 |
+
('odd', False),
|
748 |
+
('prime', False),
|
749 |
+
('rational', False),
|
750 |
+
('zero', False),
|
751 |
+
) ),
|
752 |
+
),
|
753 |
+
# Implications of transcendental = False:
|
754 |
+
(('transcendental', False), set( (
|
755 |
+
) ),
|
756 |
+
),
|
757 |
+
# Implications of zero = True:
|
758 |
+
(('zero', True), set( (
|
759 |
+
('algebraic', True),
|
760 |
+
('commutative', True),
|
761 |
+
('complex', True),
|
762 |
+
('composite', False),
|
763 |
+
('even', True),
|
764 |
+
('extended_negative', False),
|
765 |
+
('extended_nonnegative', True),
|
766 |
+
('extended_nonpositive', True),
|
767 |
+
('extended_nonzero', False),
|
768 |
+
('extended_positive', False),
|
769 |
+
('extended_real', True),
|
770 |
+
('finite', True),
|
771 |
+
('hermitian', True),
|
772 |
+
('imaginary', False),
|
773 |
+
('infinite', False),
|
774 |
+
('integer', True),
|
775 |
+
('irrational', False),
|
776 |
+
('negative', False),
|
777 |
+
('noninteger', False),
|
778 |
+
('nonnegative', True),
|
779 |
+
('nonpositive', True),
|
780 |
+
('nonzero', False),
|
781 |
+
('odd', False),
|
782 |
+
('positive', False),
|
783 |
+
('prime', False),
|
784 |
+
('rational', True),
|
785 |
+
('real', True),
|
786 |
+
('transcendental', False),
|
787 |
+
) ),
|
788 |
+
),
|
789 |
+
# Implications of zero = False:
|
790 |
+
(('zero', False), set( (
|
791 |
+
) ),
|
792 |
+
),
|
793 |
+
] ) # full_implications
|
794 |
+
|
795 |
+
|
796 |
+
prereq = {
|
797 |
+
|
798 |
+
# facts that could determine the value of algebraic
|
799 |
+
'algebraic': {
|
800 |
+
'commutative',
|
801 |
+
'complex',
|
802 |
+
'composite',
|
803 |
+
'even',
|
804 |
+
'finite',
|
805 |
+
'infinite',
|
806 |
+
'integer',
|
807 |
+
'odd',
|
808 |
+
'prime',
|
809 |
+
'rational',
|
810 |
+
'transcendental',
|
811 |
+
'zero',
|
812 |
+
},
|
813 |
+
|
814 |
+
# facts that could determine the value of antihermitian
|
815 |
+
'antihermitian': {
|
816 |
+
'imaginary',
|
817 |
+
},
|
818 |
+
|
819 |
+
# facts that could determine the value of commutative
|
820 |
+
'commutative': {
|
821 |
+
'algebraic',
|
822 |
+
'complex',
|
823 |
+
'composite',
|
824 |
+
'even',
|
825 |
+
'extended_negative',
|
826 |
+
'extended_nonnegative',
|
827 |
+
'extended_nonpositive',
|
828 |
+
'extended_nonzero',
|
829 |
+
'extended_positive',
|
830 |
+
'extended_real',
|
831 |
+
'imaginary',
|
832 |
+
'integer',
|
833 |
+
'irrational',
|
834 |
+
'negative',
|
835 |
+
'noninteger',
|
836 |
+
'nonnegative',
|
837 |
+
'nonpositive',
|
838 |
+
'nonzero',
|
839 |
+
'odd',
|
840 |
+
'positive',
|
841 |
+
'prime',
|
842 |
+
'rational',
|
843 |
+
'real',
|
844 |
+
'transcendental',
|
845 |
+
'zero',
|
846 |
+
},
|
847 |
+
|
848 |
+
# facts that could determine the value of complex
|
849 |
+
'complex': {
|
850 |
+
'algebraic',
|
851 |
+
'commutative',
|
852 |
+
'composite',
|
853 |
+
'even',
|
854 |
+
'finite',
|
855 |
+
'imaginary',
|
856 |
+
'infinite',
|
857 |
+
'integer',
|
858 |
+
'irrational',
|
859 |
+
'negative',
|
860 |
+
'nonnegative',
|
861 |
+
'nonpositive',
|
862 |
+
'nonzero',
|
863 |
+
'odd',
|
864 |
+
'positive',
|
865 |
+
'prime',
|
866 |
+
'rational',
|
867 |
+
'real',
|
868 |
+
'transcendental',
|
869 |
+
'zero',
|
870 |
+
},
|
871 |
+
|
872 |
+
# facts that could determine the value of composite
|
873 |
+
'composite': {
|
874 |
+
'algebraic',
|
875 |
+
'commutative',
|
876 |
+
'complex',
|
877 |
+
'extended_negative',
|
878 |
+
'extended_nonnegative',
|
879 |
+
'extended_nonpositive',
|
880 |
+
'extended_nonzero',
|
881 |
+
'extended_positive',
|
882 |
+
'extended_real',
|
883 |
+
'finite',
|
884 |
+
'hermitian',
|
885 |
+
'imaginary',
|
886 |
+
'infinite',
|
887 |
+
'integer',
|
888 |
+
'irrational',
|
889 |
+
'negative',
|
890 |
+
'noninteger',
|
891 |
+
'nonnegative',
|
892 |
+
'nonpositive',
|
893 |
+
'nonzero',
|
894 |
+
'positive',
|
895 |
+
'prime',
|
896 |
+
'rational',
|
897 |
+
'real',
|
898 |
+
'transcendental',
|
899 |
+
'zero',
|
900 |
+
},
|
901 |
+
|
902 |
+
# facts that could determine the value of even
|
903 |
+
'even': {
|
904 |
+
'algebraic',
|
905 |
+
'commutative',
|
906 |
+
'complex',
|
907 |
+
'extended_real',
|
908 |
+
'finite',
|
909 |
+
'hermitian',
|
910 |
+
'imaginary',
|
911 |
+
'infinite',
|
912 |
+
'integer',
|
913 |
+
'irrational',
|
914 |
+
'noninteger',
|
915 |
+
'odd',
|
916 |
+
'rational',
|
917 |
+
'real',
|
918 |
+
'transcendental',
|
919 |
+
'zero',
|
920 |
+
},
|
921 |
+
|
922 |
+
# facts that could determine the value of extended_negative
|
923 |
+
'extended_negative': {
|
924 |
+
'commutative',
|
925 |
+
'composite',
|
926 |
+
'extended_nonnegative',
|
927 |
+
'extended_nonpositive',
|
928 |
+
'extended_nonzero',
|
929 |
+
'extended_positive',
|
930 |
+
'extended_real',
|
931 |
+
'imaginary',
|
932 |
+
'negative',
|
933 |
+
'nonnegative',
|
934 |
+
'positive',
|
935 |
+
'prime',
|
936 |
+
'zero',
|
937 |
+
},
|
938 |
+
|
939 |
+
# facts that could determine the value of extended_nonnegative
|
940 |
+
'extended_nonnegative': {
|
941 |
+
'commutative',
|
942 |
+
'composite',
|
943 |
+
'extended_negative',
|
944 |
+
'extended_positive',
|
945 |
+
'extended_real',
|
946 |
+
'imaginary',
|
947 |
+
'negative',
|
948 |
+
'nonnegative',
|
949 |
+
'positive',
|
950 |
+
'prime',
|
951 |
+
'zero',
|
952 |
+
},
|
953 |
+
|
954 |
+
# facts that could determine the value of extended_nonpositive
|
955 |
+
'extended_nonpositive': {
|
956 |
+
'commutative',
|
957 |
+
'composite',
|
958 |
+
'extended_negative',
|
959 |
+
'extended_positive',
|
960 |
+
'extended_real',
|
961 |
+
'imaginary',
|
962 |
+
'negative',
|
963 |
+
'nonpositive',
|
964 |
+
'positive',
|
965 |
+
'prime',
|
966 |
+
'zero',
|
967 |
+
},
|
968 |
+
|
969 |
+
# facts that could determine the value of extended_nonzero
|
970 |
+
'extended_nonzero': {
|
971 |
+
'commutative',
|
972 |
+
'composite',
|
973 |
+
'extended_negative',
|
974 |
+
'extended_positive',
|
975 |
+
'extended_real',
|
976 |
+
'imaginary',
|
977 |
+
'irrational',
|
978 |
+
'negative',
|
979 |
+
'noninteger',
|
980 |
+
'nonzero',
|
981 |
+
'odd',
|
982 |
+
'positive',
|
983 |
+
'prime',
|
984 |
+
'zero',
|
985 |
+
},
|
986 |
+
|
987 |
+
# facts that could determine the value of extended_positive
|
988 |
+
'extended_positive': {
|
989 |
+
'commutative',
|
990 |
+
'composite',
|
991 |
+
'extended_negative',
|
992 |
+
'extended_nonnegative',
|
993 |
+
'extended_nonpositive',
|
994 |
+
'extended_nonzero',
|
995 |
+
'extended_real',
|
996 |
+
'imaginary',
|
997 |
+
'negative',
|
998 |
+
'nonpositive',
|
999 |
+
'positive',
|
1000 |
+
'prime',
|
1001 |
+
'zero',
|
1002 |
+
},
|
1003 |
+
|
1004 |
+
# facts that could determine the value of extended_real
|
1005 |
+
'extended_real': {
|
1006 |
+
'commutative',
|
1007 |
+
'composite',
|
1008 |
+
'even',
|
1009 |
+
'extended_negative',
|
1010 |
+
'extended_nonnegative',
|
1011 |
+
'extended_nonpositive',
|
1012 |
+
'extended_nonzero',
|
1013 |
+
'extended_positive',
|
1014 |
+
'imaginary',
|
1015 |
+
'integer',
|
1016 |
+
'irrational',
|
1017 |
+
'negative',
|
1018 |
+
'noninteger',
|
1019 |
+
'nonnegative',
|
1020 |
+
'nonpositive',
|
1021 |
+
'nonzero',
|
1022 |
+
'odd',
|
1023 |
+
'positive',
|
1024 |
+
'prime',
|
1025 |
+
'rational',
|
1026 |
+
'real',
|
1027 |
+
'zero',
|
1028 |
+
},
|
1029 |
+
|
1030 |
+
# facts that could determine the value of finite
|
1031 |
+
'finite': {
|
1032 |
+
'algebraic',
|
1033 |
+
'complex',
|
1034 |
+
'composite',
|
1035 |
+
'even',
|
1036 |
+
'imaginary',
|
1037 |
+
'infinite',
|
1038 |
+
'integer',
|
1039 |
+
'irrational',
|
1040 |
+
'negative',
|
1041 |
+
'nonnegative',
|
1042 |
+
'nonpositive',
|
1043 |
+
'nonzero',
|
1044 |
+
'odd',
|
1045 |
+
'positive',
|
1046 |
+
'prime',
|
1047 |
+
'rational',
|
1048 |
+
'real',
|
1049 |
+
'transcendental',
|
1050 |
+
'zero',
|
1051 |
+
},
|
1052 |
+
|
1053 |
+
# facts that could determine the value of hermitian
|
1054 |
+
'hermitian': {
|
1055 |
+
'composite',
|
1056 |
+
'even',
|
1057 |
+
'integer',
|
1058 |
+
'irrational',
|
1059 |
+
'negative',
|
1060 |
+
'nonnegative',
|
1061 |
+
'nonpositive',
|
1062 |
+
'nonzero',
|
1063 |
+
'odd',
|
1064 |
+
'positive',
|
1065 |
+
'prime',
|
1066 |
+
'rational',
|
1067 |
+
'real',
|
1068 |
+
'zero',
|
1069 |
+
},
|
1070 |
+
|
1071 |
+
# facts that could determine the value of imaginary
|
1072 |
+
'imaginary': {
|
1073 |
+
'antihermitian',
|
1074 |
+
'commutative',
|
1075 |
+
'complex',
|
1076 |
+
'composite',
|
1077 |
+
'even',
|
1078 |
+
'extended_negative',
|
1079 |
+
'extended_nonnegative',
|
1080 |
+
'extended_nonpositive',
|
1081 |
+
'extended_nonzero',
|
1082 |
+
'extended_positive',
|
1083 |
+
'extended_real',
|
1084 |
+
'finite',
|
1085 |
+
'infinite',
|
1086 |
+
'integer',
|
1087 |
+
'irrational',
|
1088 |
+
'negative',
|
1089 |
+
'noninteger',
|
1090 |
+
'nonnegative',
|
1091 |
+
'nonpositive',
|
1092 |
+
'nonzero',
|
1093 |
+
'odd',
|
1094 |
+
'positive',
|
1095 |
+
'prime',
|
1096 |
+
'rational',
|
1097 |
+
'real',
|
1098 |
+
'zero',
|
1099 |
+
},
|
1100 |
+
|
1101 |
+
# facts that could determine the value of infinite
|
1102 |
+
'infinite': {
|
1103 |
+
'algebraic',
|
1104 |
+
'complex',
|
1105 |
+
'composite',
|
1106 |
+
'even',
|
1107 |
+
'finite',
|
1108 |
+
'imaginary',
|
1109 |
+
'integer',
|
1110 |
+
'irrational',
|
1111 |
+
'negative',
|
1112 |
+
'nonnegative',
|
1113 |
+
'nonpositive',
|
1114 |
+
'nonzero',
|
1115 |
+
'odd',
|
1116 |
+
'positive',
|
1117 |
+
'prime',
|
1118 |
+
'rational',
|
1119 |
+
'real',
|
1120 |
+
'transcendental',
|
1121 |
+
'zero',
|
1122 |
+
},
|
1123 |
+
|
1124 |
+
# facts that could determine the value of integer
|
1125 |
+
'integer': {
|
1126 |
+
'algebraic',
|
1127 |
+
'commutative',
|
1128 |
+
'complex',
|
1129 |
+
'composite',
|
1130 |
+
'even',
|
1131 |
+
'extended_real',
|
1132 |
+
'finite',
|
1133 |
+
'hermitian',
|
1134 |
+
'imaginary',
|
1135 |
+
'infinite',
|
1136 |
+
'irrational',
|
1137 |
+
'noninteger',
|
1138 |
+
'odd',
|
1139 |
+
'prime',
|
1140 |
+
'rational',
|
1141 |
+
'real',
|
1142 |
+
'transcendental',
|
1143 |
+
'zero',
|
1144 |
+
},
|
1145 |
+
|
1146 |
+
# facts that could determine the value of irrational
|
1147 |
+
'irrational': {
|
1148 |
+
'commutative',
|
1149 |
+
'complex',
|
1150 |
+
'composite',
|
1151 |
+
'even',
|
1152 |
+
'extended_real',
|
1153 |
+
'finite',
|
1154 |
+
'hermitian',
|
1155 |
+
'imaginary',
|
1156 |
+
'infinite',
|
1157 |
+
'integer',
|
1158 |
+
'odd',
|
1159 |
+
'prime',
|
1160 |
+
'rational',
|
1161 |
+
'real',
|
1162 |
+
'zero',
|
1163 |
+
},
|
1164 |
+
|
1165 |
+
# facts that could determine the value of negative
|
1166 |
+
'negative': {
|
1167 |
+
'commutative',
|
1168 |
+
'complex',
|
1169 |
+
'composite',
|
1170 |
+
'extended_negative',
|
1171 |
+
'extended_nonnegative',
|
1172 |
+
'extended_nonpositive',
|
1173 |
+
'extended_nonzero',
|
1174 |
+
'extended_positive',
|
1175 |
+
'extended_real',
|
1176 |
+
'finite',
|
1177 |
+
'hermitian',
|
1178 |
+
'imaginary',
|
1179 |
+
'infinite',
|
1180 |
+
'nonnegative',
|
1181 |
+
'nonpositive',
|
1182 |
+
'nonzero',
|
1183 |
+
'positive',
|
1184 |
+
'prime',
|
1185 |
+
'real',
|
1186 |
+
'zero',
|
1187 |
+
},
|
1188 |
+
|
1189 |
+
# facts that could determine the value of noninteger
|
1190 |
+
'noninteger': {
|
1191 |
+
'commutative',
|
1192 |
+
'composite',
|
1193 |
+
'even',
|
1194 |
+
'extended_real',
|
1195 |
+
'imaginary',
|
1196 |
+
'integer',
|
1197 |
+
'irrational',
|
1198 |
+
'odd',
|
1199 |
+
'prime',
|
1200 |
+
'zero',
|
1201 |
+
},
|
1202 |
+
|
1203 |
+
# facts that could determine the value of nonnegative
|
1204 |
+
'nonnegative': {
|
1205 |
+
'commutative',
|
1206 |
+
'complex',
|
1207 |
+
'composite',
|
1208 |
+
'extended_negative',
|
1209 |
+
'extended_nonnegative',
|
1210 |
+
'extended_real',
|
1211 |
+
'finite',
|
1212 |
+
'hermitian',
|
1213 |
+
'imaginary',
|
1214 |
+
'infinite',
|
1215 |
+
'negative',
|
1216 |
+
'positive',
|
1217 |
+
'prime',
|
1218 |
+
'real',
|
1219 |
+
'zero',
|
1220 |
+
},
|
1221 |
+
|
1222 |
+
# facts that could determine the value of nonpositive
|
1223 |
+
'nonpositive': {
|
1224 |
+
'commutative',
|
1225 |
+
'complex',
|
1226 |
+
'composite',
|
1227 |
+
'extended_nonpositive',
|
1228 |
+
'extended_positive',
|
1229 |
+
'extended_real',
|
1230 |
+
'finite',
|
1231 |
+
'hermitian',
|
1232 |
+
'imaginary',
|
1233 |
+
'infinite',
|
1234 |
+
'negative',
|
1235 |
+
'positive',
|
1236 |
+
'prime',
|
1237 |
+
'real',
|
1238 |
+
'zero',
|
1239 |
+
},
|
1240 |
+
|
1241 |
+
# facts that could determine the value of nonzero
|
1242 |
+
'nonzero': {
|
1243 |
+
'commutative',
|
1244 |
+
'complex',
|
1245 |
+
'composite',
|
1246 |
+
'extended_nonzero',
|
1247 |
+
'extended_real',
|
1248 |
+
'finite',
|
1249 |
+
'hermitian',
|
1250 |
+
'imaginary',
|
1251 |
+
'infinite',
|
1252 |
+
'irrational',
|
1253 |
+
'negative',
|
1254 |
+
'odd',
|
1255 |
+
'positive',
|
1256 |
+
'prime',
|
1257 |
+
'real',
|
1258 |
+
'zero',
|
1259 |
+
},
|
1260 |
+
|
1261 |
+
# facts that could determine the value of odd
|
1262 |
+
'odd': {
|
1263 |
+
'algebraic',
|
1264 |
+
'commutative',
|
1265 |
+
'complex',
|
1266 |
+
'even',
|
1267 |
+
'extended_real',
|
1268 |
+
'finite',
|
1269 |
+
'hermitian',
|
1270 |
+
'imaginary',
|
1271 |
+
'infinite',
|
1272 |
+
'integer',
|
1273 |
+
'irrational',
|
1274 |
+
'noninteger',
|
1275 |
+
'rational',
|
1276 |
+
'real',
|
1277 |
+
'transcendental',
|
1278 |
+
'zero',
|
1279 |
+
},
|
1280 |
+
|
1281 |
+
# facts that could determine the value of positive
|
1282 |
+
'positive': {
|
1283 |
+
'commutative',
|
1284 |
+
'complex',
|
1285 |
+
'composite',
|
1286 |
+
'extended_negative',
|
1287 |
+
'extended_nonnegative',
|
1288 |
+
'extended_nonpositive',
|
1289 |
+
'extended_nonzero',
|
1290 |
+
'extended_positive',
|
1291 |
+
'extended_real',
|
1292 |
+
'finite',
|
1293 |
+
'hermitian',
|
1294 |
+
'imaginary',
|
1295 |
+
'infinite',
|
1296 |
+
'negative',
|
1297 |
+
'nonnegative',
|
1298 |
+
'nonpositive',
|
1299 |
+
'nonzero',
|
1300 |
+
'prime',
|
1301 |
+
'real',
|
1302 |
+
'zero',
|
1303 |
+
},
|
1304 |
+
|
1305 |
+
# facts that could determine the value of prime
|
1306 |
+
'prime': {
|
1307 |
+
'algebraic',
|
1308 |
+
'commutative',
|
1309 |
+
'complex',
|
1310 |
+
'composite',
|
1311 |
+
'extended_negative',
|
1312 |
+
'extended_nonnegative',
|
1313 |
+
'extended_nonpositive',
|
1314 |
+
'extended_nonzero',
|
1315 |
+
'extended_positive',
|
1316 |
+
'extended_real',
|
1317 |
+
'finite',
|
1318 |
+
'hermitian',
|
1319 |
+
'imaginary',
|
1320 |
+
'infinite',
|
1321 |
+
'integer',
|
1322 |
+
'irrational',
|
1323 |
+
'negative',
|
1324 |
+
'noninteger',
|
1325 |
+
'nonnegative',
|
1326 |
+
'nonpositive',
|
1327 |
+
'nonzero',
|
1328 |
+
'positive',
|
1329 |
+
'rational',
|
1330 |
+
'real',
|
1331 |
+
'transcendental',
|
1332 |
+
'zero',
|
1333 |
+
},
|
1334 |
+
|
1335 |
+
# facts that could determine the value of rational
|
1336 |
+
'rational': {
|
1337 |
+
'algebraic',
|
1338 |
+
'commutative',
|
1339 |
+
'complex',
|
1340 |
+
'composite',
|
1341 |
+
'even',
|
1342 |
+
'extended_real',
|
1343 |
+
'finite',
|
1344 |
+
'hermitian',
|
1345 |
+
'imaginary',
|
1346 |
+
'infinite',
|
1347 |
+
'integer',
|
1348 |
+
'irrational',
|
1349 |
+
'odd',
|
1350 |
+
'prime',
|
1351 |
+
'real',
|
1352 |
+
'transcendental',
|
1353 |
+
'zero',
|
1354 |
+
},
|
1355 |
+
|
1356 |
+
# facts that could determine the value of real
|
1357 |
+
'real': {
|
1358 |
+
'commutative',
|
1359 |
+
'complex',
|
1360 |
+
'composite',
|
1361 |
+
'even',
|
1362 |
+
'extended_real',
|
1363 |
+
'finite',
|
1364 |
+
'hermitian',
|
1365 |
+
'imaginary',
|
1366 |
+
'infinite',
|
1367 |
+
'integer',
|
1368 |
+
'irrational',
|
1369 |
+
'negative',
|
1370 |
+
'nonnegative',
|
1371 |
+
'nonpositive',
|
1372 |
+
'nonzero',
|
1373 |
+
'odd',
|
1374 |
+
'positive',
|
1375 |
+
'prime',
|
1376 |
+
'rational',
|
1377 |
+
'zero',
|
1378 |
+
},
|
1379 |
+
|
1380 |
+
# facts that could determine the value of transcendental
|
1381 |
+
'transcendental': {
|
1382 |
+
'algebraic',
|
1383 |
+
'commutative',
|
1384 |
+
'complex',
|
1385 |
+
'composite',
|
1386 |
+
'even',
|
1387 |
+
'finite',
|
1388 |
+
'infinite',
|
1389 |
+
'integer',
|
1390 |
+
'odd',
|
1391 |
+
'prime',
|
1392 |
+
'rational',
|
1393 |
+
'zero',
|
1394 |
+
},
|
1395 |
+
|
1396 |
+
# facts that could determine the value of zero
|
1397 |
+
'zero': {
|
1398 |
+
'algebraic',
|
1399 |
+
'commutative',
|
1400 |
+
'complex',
|
1401 |
+
'composite',
|
1402 |
+
'even',
|
1403 |
+
'extended_negative',
|
1404 |
+
'extended_nonnegative',
|
1405 |
+
'extended_nonpositive',
|
1406 |
+
'extended_nonzero',
|
1407 |
+
'extended_positive',
|
1408 |
+
'extended_real',
|
1409 |
+
'finite',
|
1410 |
+
'hermitian',
|
1411 |
+
'imaginary',
|
1412 |
+
'infinite',
|
1413 |
+
'integer',
|
1414 |
+
'irrational',
|
1415 |
+
'negative',
|
1416 |
+
'noninteger',
|
1417 |
+
'nonnegative',
|
1418 |
+
'nonpositive',
|
1419 |
+
'nonzero',
|
1420 |
+
'odd',
|
1421 |
+
'positive',
|
1422 |
+
'prime',
|
1423 |
+
'rational',
|
1424 |
+
'real',
|
1425 |
+
'transcendental',
|
1426 |
+
},
|
1427 |
+
|
1428 |
+
} # prereq
|
1429 |
+
|
1430 |
+
|
1431 |
+
# Note: the order of the beta rules is used in the beta_triggers
|
1432 |
+
beta_rules = [
|
1433 |
+
|
1434 |
+
# Rules implying composite = True
|
1435 |
+
({('even', True), ('positive', True), ('prime', False)},
|
1436 |
+
('composite', True)),
|
1437 |
+
|
1438 |
+
# Rules implying even = False
|
1439 |
+
({('composite', False), ('positive', True), ('prime', False)},
|
1440 |
+
('even', False)),
|
1441 |
+
|
1442 |
+
# Rules implying even = True
|
1443 |
+
({('integer', True), ('odd', False)},
|
1444 |
+
('even', True)),
|
1445 |
+
|
1446 |
+
# Rules implying extended_negative = True
|
1447 |
+
({('extended_positive', False), ('extended_real', True), ('zero', False)},
|
1448 |
+
('extended_negative', True)),
|
1449 |
+
({('extended_nonpositive', True), ('extended_nonzero', True)},
|
1450 |
+
('extended_negative', True)),
|
1451 |
+
|
1452 |
+
# Rules implying extended_nonnegative = True
|
1453 |
+
({('extended_negative', False), ('extended_real', True)},
|
1454 |
+
('extended_nonnegative', True)),
|
1455 |
+
|
1456 |
+
# Rules implying extended_nonpositive = True
|
1457 |
+
({('extended_positive', False), ('extended_real', True)},
|
1458 |
+
('extended_nonpositive', True)),
|
1459 |
+
|
1460 |
+
# Rules implying extended_nonzero = True
|
1461 |
+
({('extended_real', True), ('zero', False)},
|
1462 |
+
('extended_nonzero', True)),
|
1463 |
+
|
1464 |
+
# Rules implying extended_positive = True
|
1465 |
+
({('extended_negative', False), ('extended_real', True), ('zero', False)},
|
1466 |
+
('extended_positive', True)),
|
1467 |
+
({('extended_nonnegative', True), ('extended_nonzero', True)},
|
1468 |
+
('extended_positive', True)),
|
1469 |
+
|
1470 |
+
# Rules implying extended_real = False
|
1471 |
+
({('infinite', False), ('real', False)},
|
1472 |
+
('extended_real', False)),
|
1473 |
+
({('extended_negative', False), ('extended_positive', False), ('zero', False)},
|
1474 |
+
('extended_real', False)),
|
1475 |
+
|
1476 |
+
# Rules implying infinite = True
|
1477 |
+
({('extended_real', True), ('real', False)},
|
1478 |
+
('infinite', True)),
|
1479 |
+
|
1480 |
+
# Rules implying irrational = True
|
1481 |
+
({('rational', False), ('real', True)},
|
1482 |
+
('irrational', True)),
|
1483 |
+
|
1484 |
+
# Rules implying negative = True
|
1485 |
+
({('positive', False), ('real', True), ('zero', False)},
|
1486 |
+
('negative', True)),
|
1487 |
+
({('nonpositive', True), ('nonzero', True)},
|
1488 |
+
('negative', True)),
|
1489 |
+
({('extended_negative', True), ('finite', True)},
|
1490 |
+
('negative', True)),
|
1491 |
+
|
1492 |
+
# Rules implying noninteger = True
|
1493 |
+
({('extended_real', True), ('integer', False)},
|
1494 |
+
('noninteger', True)),
|
1495 |
+
|
1496 |
+
# Rules implying nonnegative = True
|
1497 |
+
({('negative', False), ('real', True)},
|
1498 |
+
('nonnegative', True)),
|
1499 |
+
({('extended_nonnegative', True), ('finite', True)},
|
1500 |
+
('nonnegative', True)),
|
1501 |
+
|
1502 |
+
# Rules implying nonpositive = True
|
1503 |
+
({('positive', False), ('real', True)},
|
1504 |
+
('nonpositive', True)),
|
1505 |
+
({('extended_nonpositive', True), ('finite', True)},
|
1506 |
+
('nonpositive', True)),
|
1507 |
+
|
1508 |
+
# Rules implying nonzero = True
|
1509 |
+
({('extended_nonzero', True), ('finite', True)},
|
1510 |
+
('nonzero', True)),
|
1511 |
+
|
1512 |
+
# Rules implying odd = True
|
1513 |
+
({('even', False), ('integer', True)},
|
1514 |
+
('odd', True)),
|
1515 |
+
|
1516 |
+
# Rules implying positive = False
|
1517 |
+
({('composite', False), ('even', True), ('prime', False)},
|
1518 |
+
('positive', False)),
|
1519 |
+
|
1520 |
+
# Rules implying positive = True
|
1521 |
+
({('negative', False), ('real', True), ('zero', False)},
|
1522 |
+
('positive', True)),
|
1523 |
+
({('nonnegative', True), ('nonzero', True)},
|
1524 |
+
('positive', True)),
|
1525 |
+
({('extended_positive', True), ('finite', True)},
|
1526 |
+
('positive', True)),
|
1527 |
+
|
1528 |
+
# Rules implying prime = True
|
1529 |
+
({('composite', False), ('even', True), ('positive', True)},
|
1530 |
+
('prime', True)),
|
1531 |
+
|
1532 |
+
# Rules implying real = False
|
1533 |
+
({('negative', False), ('positive', False), ('zero', False)},
|
1534 |
+
('real', False)),
|
1535 |
+
|
1536 |
+
# Rules implying real = True
|
1537 |
+
({('extended_real', True), ('infinite', False)},
|
1538 |
+
('real', True)),
|
1539 |
+
({('extended_real', True), ('finite', True)},
|
1540 |
+
('real', True)),
|
1541 |
+
|
1542 |
+
# Rules implying transcendental = True
|
1543 |
+
({('algebraic', False), ('complex', True)},
|
1544 |
+
('transcendental', True)),
|
1545 |
+
|
1546 |
+
# Rules implying zero = True
|
1547 |
+
({('extended_negative', False), ('extended_positive', False), ('extended_real', True)},
|
1548 |
+
('zero', True)),
|
1549 |
+
({('negative', False), ('positive', False), ('real', True)},
|
1550 |
+
('zero', True)),
|
1551 |
+
({('extended_nonnegative', True), ('extended_nonpositive', True)},
|
1552 |
+
('zero', True)),
|
1553 |
+
({('nonnegative', True), ('nonpositive', True)},
|
1554 |
+
('zero', True)),
|
1555 |
+
|
1556 |
+
] # beta_rules
|
1557 |
+
beta_triggers = {
|
1558 |
+
('algebraic', False): [32, 11, 3, 8, 29, 14, 25, 13, 17, 7],
|
1559 |
+
('algebraic', True): [10, 30, 31, 27, 16, 21, 19, 22],
|
1560 |
+
('antihermitian', False): [],
|
1561 |
+
('commutative', False): [],
|
1562 |
+
('complex', False): [10, 12, 11, 3, 8, 17, 7],
|
1563 |
+
('complex', True): [32, 10, 30, 31, 27, 16, 21, 19, 22],
|
1564 |
+
('composite', False): [1, 28, 24],
|
1565 |
+
('composite', True): [23, 2],
|
1566 |
+
('even', False): [23, 11, 3, 8, 29, 14, 25, 7],
|
1567 |
+
('even', True): [3, 33, 8, 6, 5, 14, 34, 25, 20, 18, 27, 16, 21, 19, 22, 0, 28, 24, 7],
|
1568 |
+
('extended_negative', False): [11, 33, 8, 5, 29, 34, 25, 18],
|
1569 |
+
('extended_negative', True): [30, 12, 31, 29, 14, 20, 16, 21, 22, 17],
|
1570 |
+
('extended_nonnegative', False): [11, 3, 6, 29, 14, 20, 7],
|
1571 |
+
('extended_nonnegative', True): [30, 12, 31, 33, 8, 9, 6, 29, 34, 25, 18, 19, 35, 17, 7],
|
1572 |
+
('extended_nonpositive', False): [11, 8, 5, 29, 25, 18, 7],
|
1573 |
+
('extended_nonpositive', True): [30, 12, 31, 3, 33, 4, 5, 29, 14, 34, 20, 21, 35, 17, 7],
|
1574 |
+
('extended_nonzero', False): [11, 33, 6, 5, 29, 34, 20, 18],
|
1575 |
+
('extended_nonzero', True): [30, 12, 31, 3, 8, 4, 9, 6, 5, 29, 14, 25, 22, 17],
|
1576 |
+
('extended_positive', False): [11, 3, 33, 6, 29, 14, 34, 20],
|
1577 |
+
('extended_positive', True): [30, 12, 31, 29, 25, 18, 27, 19, 22, 17],
|
1578 |
+
('extended_real', False): [],
|
1579 |
+
('extended_real', True): [30, 12, 31, 3, 33, 8, 6, 5, 17, 7],
|
1580 |
+
('finite', False): [11, 3, 8, 17, 7],
|
1581 |
+
('finite', True): [10, 30, 31, 27, 16, 21, 19, 22],
|
1582 |
+
('hermitian', False): [10, 12, 11, 3, 8, 17, 7],
|
1583 |
+
('imaginary', True): [32],
|
1584 |
+
('infinite', False): [10, 30, 31, 27, 16, 21, 19, 22],
|
1585 |
+
('infinite', True): [11, 3, 8, 17, 7],
|
1586 |
+
('integer', False): [11, 3, 8, 29, 14, 25, 17, 7],
|
1587 |
+
('integer', True): [23, 2, 3, 33, 8, 6, 5, 14, 34, 25, 20, 18, 27, 16, 21, 19, 22, 7],
|
1588 |
+
('irrational', True): [32, 3, 8, 4, 9, 6, 5, 14, 25, 15, 26, 20, 18, 27, 16, 21, 19],
|
1589 |
+
('negative', False): [29, 34, 25, 18],
|
1590 |
+
('negative', True): [32, 13, 17],
|
1591 |
+
('noninteger', True): [30, 12, 31, 3, 8, 4, 9, 6, 5, 29, 14, 25, 22],
|
1592 |
+
('nonnegative', False): [11, 3, 8, 29, 14, 20, 7],
|
1593 |
+
('nonnegative', True): [32, 33, 8, 9, 6, 34, 25, 26, 20, 27, 21, 22, 35, 36, 13, 17, 7],
|
1594 |
+
('nonpositive', False): [11, 3, 8, 29, 25, 18, 7],
|
1595 |
+
('nonpositive', True): [32, 3, 33, 4, 5, 14, 34, 15, 18, 16, 19, 22, 35, 36, 13, 17, 7],
|
1596 |
+
('nonzero', False): [29, 34, 20, 18],
|
1597 |
+
('nonzero', True): [32, 3, 8, 4, 9, 6, 5, 14, 25, 15, 26, 20, 18, 27, 16, 21, 19, 13, 17],
|
1598 |
+
('odd', False): [2],
|
1599 |
+
('odd', True): [3, 8, 4, 9, 6, 5, 14, 25, 15, 26, 20, 18, 27, 16, 21, 19],
|
1600 |
+
('positive', False): [29, 14, 34, 20],
|
1601 |
+
('positive', True): [32, 0, 1, 28, 13, 17],
|
1602 |
+
('prime', False): [0, 1, 24],
|
1603 |
+
('prime', True): [23, 2],
|
1604 |
+
('rational', False): [11, 3, 8, 29, 14, 25, 13, 17, 7],
|
1605 |
+
('rational', True): [3, 33, 8, 6, 5, 14, 34, 25, 20, 18, 27, 16, 21, 19, 22, 17, 7],
|
1606 |
+
('real', False): [10, 12, 11, 3, 8, 17, 7],
|
1607 |
+
('real', True): [32, 3, 33, 8, 6, 5, 14, 34, 25, 20, 18, 27, 16, 21, 19, 22, 13, 17, 7],
|
1608 |
+
('transcendental', True): [10, 30, 31, 11, 3, 8, 29, 14, 25, 27, 16, 21, 19, 22, 13, 17, 7],
|
1609 |
+
('zero', False): [11, 3, 8, 29, 14, 25, 7],
|
1610 |
+
('zero', True): [],
|
1611 |
+
} # beta_triggers
|
1612 |
+
|
1613 |
+
|
1614 |
+
generated_assumptions = {'defined_facts': defined_facts, 'full_implications': full_implications,
|
1615 |
+
'prereq': prereq, 'beta_rules': beta_rules, 'beta_triggers': beta_triggers}
|
venv/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)
|
venv/lib/python3.10/site-packages/sympy/core/cache.py
ADDED
@@ -0,0 +1,210 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
""" Caching facility for SymPy """
|
2 |
+
from importlib import import_module
|
3 |
+
from typing import Callable
|
4 |
+
|
5 |
+
class _cache(list):
|
6 |
+
""" List of cached functions """
|
7 |
+
|
8 |
+
def print_cache(self):
|
9 |
+
"""print cache info"""
|
10 |
+
|
11 |
+
for item in self:
|
12 |
+
name = item.__name__
|
13 |
+
myfunc = item
|
14 |
+
while hasattr(myfunc, '__wrapped__'):
|
15 |
+
if hasattr(myfunc, 'cache_info'):
|
16 |
+
info = myfunc.cache_info()
|
17 |
+
break
|
18 |
+
else:
|
19 |
+
myfunc = myfunc.__wrapped__
|
20 |
+
else:
|
21 |
+
info = None
|
22 |
+
|
23 |
+
print(name, info)
|
24 |
+
|
25 |
+
def clear_cache(self):
|
26 |
+
"""clear cache content"""
|
27 |
+
for item in self:
|
28 |
+
myfunc = item
|
29 |
+
while hasattr(myfunc, '__wrapped__'):
|
30 |
+
if hasattr(myfunc, 'cache_clear'):
|
31 |
+
myfunc.cache_clear()
|
32 |
+
break
|
33 |
+
else:
|
34 |
+
myfunc = myfunc.__wrapped__
|
35 |
+
|
36 |
+
|
37 |
+
# global cache registry:
|
38 |
+
CACHE = _cache()
|
39 |
+
# make clear and print methods available
|
40 |
+
print_cache = CACHE.print_cache
|
41 |
+
clear_cache = CACHE.clear_cache
|
42 |
+
|
43 |
+
from functools import lru_cache, wraps
|
44 |
+
|
45 |
+
def __cacheit(maxsize):
|
46 |
+
"""caching decorator.
|
47 |
+
|
48 |
+
important: the result of cached function must be *immutable*
|
49 |
+
|
50 |
+
|
51 |
+
Examples
|
52 |
+
========
|
53 |
+
|
54 |
+
>>> from sympy import cacheit
|
55 |
+
>>> @cacheit
|
56 |
+
... def f(a, b):
|
57 |
+
... return a+b
|
58 |
+
|
59 |
+
>>> @cacheit
|
60 |
+
... def f(a, b): # noqa: F811
|
61 |
+
... return [a, b] # <-- WRONG, returns mutable object
|
62 |
+
|
63 |
+
to force cacheit to check returned results mutability and consistency,
|
64 |
+
set environment variable SYMPY_USE_CACHE to 'debug'
|
65 |
+
"""
|
66 |
+
def func_wrapper(func):
|
67 |
+
cfunc = lru_cache(maxsize, typed=True)(func)
|
68 |
+
|
69 |
+
@wraps(func)
|
70 |
+
def wrapper(*args, **kwargs):
|
71 |
+
try:
|
72 |
+
retval = cfunc(*args, **kwargs)
|
73 |
+
except TypeError as e:
|
74 |
+
if not e.args or not e.args[0].startswith('unhashable type:'):
|
75 |
+
raise
|
76 |
+
retval = func(*args, **kwargs)
|
77 |
+
return retval
|
78 |
+
|
79 |
+
wrapper.cache_info = cfunc.cache_info
|
80 |
+
wrapper.cache_clear = cfunc.cache_clear
|
81 |
+
|
82 |
+
CACHE.append(wrapper)
|
83 |
+
return wrapper
|
84 |
+
|
85 |
+
return func_wrapper
|
86 |
+
########################################
|
87 |
+
|
88 |
+
|
89 |
+
def __cacheit_nocache(func):
|
90 |
+
return func
|
91 |
+
|
92 |
+
|
93 |
+
def __cacheit_debug(maxsize):
|
94 |
+
"""cacheit + code to check cache consistency"""
|
95 |
+
def func_wrapper(func):
|
96 |
+
cfunc = __cacheit(maxsize)(func)
|
97 |
+
|
98 |
+
@wraps(func)
|
99 |
+
def wrapper(*args, **kw_args):
|
100 |
+
# always call function itself and compare it with cached version
|
101 |
+
r1 = func(*args, **kw_args)
|
102 |
+
r2 = cfunc(*args, **kw_args)
|
103 |
+
|
104 |
+
# try to see if the result is immutable
|
105 |
+
#
|
106 |
+
# this works because:
|
107 |
+
#
|
108 |
+
# hash([1,2,3]) -> raise TypeError
|
109 |
+
# hash({'a':1, 'b':2}) -> raise TypeError
|
110 |
+
# hash((1,[2,3])) -> raise TypeError
|
111 |
+
#
|
112 |
+
# hash((1,2,3)) -> just computes the hash
|
113 |
+
hash(r1), hash(r2)
|
114 |
+
|
115 |
+
# also see if returned values are the same
|
116 |
+
if r1 != r2:
|
117 |
+
raise RuntimeError("Returned values are not the same")
|
118 |
+
return r1
|
119 |
+
return wrapper
|
120 |
+
return func_wrapper
|
121 |
+
|
122 |
+
|
123 |
+
def _getenv(key, default=None):
|
124 |
+
from os import getenv
|
125 |
+
return getenv(key, default)
|
126 |
+
|
127 |
+
# SYMPY_USE_CACHE=yes/no/debug
|
128 |
+
USE_CACHE = _getenv('SYMPY_USE_CACHE', 'yes').lower()
|
129 |
+
# SYMPY_CACHE_SIZE=some_integer/None
|
130 |
+
# special cases :
|
131 |
+
# SYMPY_CACHE_SIZE=0 -> No caching
|
132 |
+
# SYMPY_CACHE_SIZE=None -> Unbounded caching
|
133 |
+
scs = _getenv('SYMPY_CACHE_SIZE', '1000')
|
134 |
+
if scs.lower() == 'none':
|
135 |
+
SYMPY_CACHE_SIZE = None
|
136 |
+
else:
|
137 |
+
try:
|
138 |
+
SYMPY_CACHE_SIZE = int(scs)
|
139 |
+
except ValueError:
|
140 |
+
raise RuntimeError(
|
141 |
+
'SYMPY_CACHE_SIZE must be a valid integer or None. ' + \
|
142 |
+
'Got: %s' % SYMPY_CACHE_SIZE)
|
143 |
+
|
144 |
+
if USE_CACHE == 'no':
|
145 |
+
cacheit = __cacheit_nocache
|
146 |
+
elif USE_CACHE == 'yes':
|
147 |
+
cacheit = __cacheit(SYMPY_CACHE_SIZE)
|
148 |
+
elif USE_CACHE == 'debug':
|
149 |
+
cacheit = __cacheit_debug(SYMPY_CACHE_SIZE) # a lot slower
|
150 |
+
else:
|
151 |
+
raise RuntimeError(
|
152 |
+
'unrecognized value for SYMPY_USE_CACHE: %s' % USE_CACHE)
|
153 |
+
|
154 |
+
|
155 |
+
def cached_property(func):
|
156 |
+
'''Decorator to cache property method'''
|
157 |
+
attrname = '__' + func.__name__
|
158 |
+
_cached_property_sentinel = object()
|
159 |
+
def propfunc(self):
|
160 |
+
val = getattr(self, attrname, _cached_property_sentinel)
|
161 |
+
if val is _cached_property_sentinel:
|
162 |
+
val = func(self)
|
163 |
+
setattr(self, attrname, val)
|
164 |
+
return val
|
165 |
+
return property(propfunc)
|
166 |
+
|
167 |
+
|
168 |
+
def lazy_function(module : str, name : str) -> Callable:
|
169 |
+
"""Create a lazy proxy for a function in a module.
|
170 |
+
|
171 |
+
The module containing the function is not imported until the function is used.
|
172 |
+
|
173 |
+
"""
|
174 |
+
func = None
|
175 |
+
|
176 |
+
def _get_function():
|
177 |
+
nonlocal func
|
178 |
+
if func is None:
|
179 |
+
func = getattr(import_module(module), name)
|
180 |
+
return func
|
181 |
+
|
182 |
+
# The metaclass is needed so that help() shows the docstring
|
183 |
+
class LazyFunctionMeta(type):
|
184 |
+
@property
|
185 |
+
def __doc__(self):
|
186 |
+
docstring = _get_function().__doc__
|
187 |
+
docstring += f"\n\nNote: this is a {self.__class__.__name__} wrapper of '{module}.{name}'"
|
188 |
+
return docstring
|
189 |
+
|
190 |
+
class LazyFunction(metaclass=LazyFunctionMeta):
|
191 |
+
def __call__(self, *args, **kwargs):
|
192 |
+
# inline get of function for performance gh-23832
|
193 |
+
nonlocal func
|
194 |
+
if func is None:
|
195 |
+
func = getattr(import_module(module), name)
|
196 |
+
return func(*args, **kwargs)
|
197 |
+
|
198 |
+
@property
|
199 |
+
def __doc__(self):
|
200 |
+
docstring = _get_function().__doc__
|
201 |
+
docstring += f"\n\nNote: this is a {self.__class__.__name__} wrapper of '{module}.{name}'"
|
202 |
+
return docstring
|
203 |
+
|
204 |
+
def __str__(self):
|
205 |
+
return _get_function().__str__()
|
206 |
+
|
207 |
+
def __repr__(self):
|
208 |
+
return f"<{__class__.__name__} object at 0x{id(self):x}>: wrapping '{module}.{name}'"
|
209 |
+
|
210 |
+
return LazyFunction()
|
venv/lib/python3.10/site-packages/sympy/core/compatibility.py
ADDED
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
.. deprecated:: 1.10
|
3 |
+
|
4 |
+
``sympy.core.compatibility`` is deprecated. See
|
5 |
+
:ref:`sympy-core-compatibility`.
|
6 |
+
|
7 |
+
Reimplementations of constructs introduced in later versions of Python than
|
8 |
+
we support. Also some functions that are needed SymPy-wide and are located
|
9 |
+
here for easy import.
|
10 |
+
|
11 |
+
"""
|
12 |
+
|
13 |
+
|
14 |
+
from sympy.utilities.exceptions import sympy_deprecation_warning
|
15 |
+
|
16 |
+
sympy_deprecation_warning("""
|
17 |
+
The sympy.core.compatibility submodule is deprecated.
|
18 |
+
|
19 |
+
This module was only ever intended for internal use. Some of the functions
|
20 |
+
that were in this module are available from the top-level SymPy namespace,
|
21 |
+
i.e.,
|
22 |
+
|
23 |
+
from sympy import ordered, default_sort_key
|
24 |
+
|
25 |
+
The remaining were only intended for internal SymPy use and should not be used
|
26 |
+
by user code.
|
27 |
+
""",
|
28 |
+
deprecated_since_version="1.10",
|
29 |
+
active_deprecations_target="deprecated-sympy-core-compatibility",
|
30 |
+
)
|
31 |
+
|
32 |
+
|
33 |
+
from .sorting import ordered, _nodes, default_sort_key # noqa:F401
|
34 |
+
from sympy.utilities.misc import as_int as _as_int # noqa:F401
|
35 |
+
from sympy.utilities.iterables import iterable, is_sequence, NotIterable # noqa:F401
|
venv/lib/python3.10/site-packages/sympy/core/containers.py
ADDED
@@ -0,0 +1,410 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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 |
+
|
5 |
+
The containers implemented in this module are subclassed to Basic.
|
6 |
+
They are supposed to work seamlessly within the SymPy framework.
|
7 |
+
"""
|
8 |
+
|
9 |
+
from collections import OrderedDict
|
10 |
+
from collections.abc import MutableSet
|
11 |
+
from typing import Any, Callable
|
12 |
+
|
13 |
+
from .basic import Basic
|
14 |
+
from .sorting import default_sort_key, ordered
|
15 |
+
from .sympify import _sympify, sympify, _sympy_converter, SympifyError
|
16 |
+
from sympy.core.kind import Kind
|
17 |
+
from sympy.utilities.iterables import iterable
|
18 |
+
from sympy.utilities.misc import as_int
|
19 |
+
|
20 |
+
|
21 |
+
class Tuple(Basic):
|
22 |
+
"""
|
23 |
+
Wrapper around the builtin tuple object.
|
24 |
+
|
25 |
+
Explanation
|
26 |
+
===========
|
27 |
+
|
28 |
+
The Tuple is a subclass of Basic, so that it works well in the
|
29 |
+
SymPy framework. The wrapped tuple is available as self.args, but
|
30 |
+
you can also access elements or slices with [:] syntax.
|
31 |
+
|
32 |
+
Parameters
|
33 |
+
==========
|
34 |
+
|
35 |
+
sympify : bool
|
36 |
+
If ``False``, ``sympify`` is not called on ``args``. This
|
37 |
+
can be used for speedups for very large tuples where the
|
38 |
+
elements are known to already be SymPy objects.
|
39 |
+
|
40 |
+
Examples
|
41 |
+
========
|
42 |
+
|
43 |
+
>>> from sympy import Tuple, symbols
|
44 |
+
>>> a, b, c, d = symbols('a b c d')
|
45 |
+
>>> Tuple(a, b, c)[1:]
|
46 |
+
(b, c)
|
47 |
+
>>> Tuple(a, b, c).subs(a, d)
|
48 |
+
(d, b, c)
|
49 |
+
|
50 |
+
"""
|
51 |
+
|
52 |
+
def __new__(cls, *args, **kwargs):
|
53 |
+
if kwargs.get('sympify', True):
|
54 |
+
args = (sympify(arg) for arg in args)
|
55 |
+
obj = Basic.__new__(cls, *args)
|
56 |
+
return obj
|
57 |
+
|
58 |
+
def __getitem__(self, i):
|
59 |
+
if isinstance(i, slice):
|
60 |
+
indices = i.indices(len(self))
|
61 |
+
return Tuple(*(self.args[j] for j in range(*indices)))
|
62 |
+
return self.args[i]
|
63 |
+
|
64 |
+
def __len__(self):
|
65 |
+
return len(self.args)
|
66 |
+
|
67 |
+
def __contains__(self, item):
|
68 |
+
return item in self.args
|
69 |
+
|
70 |
+
def __iter__(self):
|
71 |
+
return iter(self.args)
|
72 |
+
|
73 |
+
def __add__(self, other):
|
74 |
+
if isinstance(other, Tuple):
|
75 |
+
return Tuple(*(self.args + other.args))
|
76 |
+
elif isinstance(other, tuple):
|
77 |
+
return Tuple(*(self.args + other))
|
78 |
+
else:
|
79 |
+
return NotImplemented
|
80 |
+
|
81 |
+
def __radd__(self, other):
|
82 |
+
if isinstance(other, Tuple):
|
83 |
+
return Tuple(*(other.args + self.args))
|
84 |
+
elif isinstance(other, tuple):
|
85 |
+
return Tuple(*(other + self.args))
|
86 |
+
else:
|
87 |
+
return NotImplemented
|
88 |
+
|
89 |
+
def __mul__(self, other):
|
90 |
+
try:
|
91 |
+
n = as_int(other)
|
92 |
+
except ValueError:
|
93 |
+
raise TypeError("Can't multiply sequence by non-integer of type '%s'" % type(other))
|
94 |
+
return self.func(*(self.args*n))
|
95 |
+
|
96 |
+
__rmul__ = __mul__
|
97 |
+
|
98 |
+
def __eq__(self, other):
|
99 |
+
if isinstance(other, Basic):
|
100 |
+
return super().__eq__(other)
|
101 |
+
return self.args == other
|
102 |
+
|
103 |
+
def __ne__(self, other):
|
104 |
+
if isinstance(other, Basic):
|
105 |
+
return super().__ne__(other)
|
106 |
+
return self.args != other
|
107 |
+
|
108 |
+
def __hash__(self):
|
109 |
+
return hash(self.args)
|
110 |
+
|
111 |
+
def _to_mpmath(self, prec):
|
112 |
+
return tuple(a._to_mpmath(prec) for a in self.args)
|
113 |
+
|
114 |
+
def __lt__(self, other):
|
115 |
+
return _sympify(self.args < other.args)
|
116 |
+
|
117 |
+
def __le__(self, other):
|
118 |
+
return _sympify(self.args <= other.args)
|
119 |
+
|
120 |
+
# XXX: Basic defines count() as something different, so we can't
|
121 |
+
# redefine it here. Originally this lead to cse() test failure.
|
122 |
+
def tuple_count(self, value) -> int:
|
123 |
+
"""Return number of occurrences of value."""
|
124 |
+
return self.args.count(value)
|
125 |
+
|
126 |
+
def index(self, value, start=None, stop=None):
|
127 |
+
"""Searches and returns the first index of the value."""
|
128 |
+
# XXX: One would expect:
|
129 |
+
#
|
130 |
+
# return self.args.index(value, start, stop)
|
131 |
+
#
|
132 |
+
# here. Any trouble with that? Yes:
|
133 |
+
#
|
134 |
+
# >>> (1,).index(1, None, None)
|
135 |
+
# Traceback (most recent call last):
|
136 |
+
# File "<stdin>", line 1, in <module>
|
137 |
+
# TypeError: slice indices must be integers or None or have an __index__ method
|
138 |
+
#
|
139 |
+
# See: http://bugs.python.org/issue13340
|
140 |
+
|
141 |
+
if start is None and stop is None:
|
142 |
+
return self.args.index(value)
|
143 |
+
elif stop is None:
|
144 |
+
return self.args.index(value, start)
|
145 |
+
else:
|
146 |
+
return self.args.index(value, start, stop)
|
147 |
+
|
148 |
+
@property
|
149 |
+
def kind(self):
|
150 |
+
"""
|
151 |
+
The kind of a Tuple instance.
|
152 |
+
|
153 |
+
The kind of a Tuple is always of :class:`TupleKind` but
|
154 |
+
parametrised by the number of elements and the kind of each element.
|
155 |
+
|
156 |
+
Examples
|
157 |
+
========
|
158 |
+
|
159 |
+
>>> from sympy import Tuple, Matrix
|
160 |
+
>>> Tuple(1, 2).kind
|
161 |
+
TupleKind(NumberKind, NumberKind)
|
162 |
+
>>> Tuple(Matrix([1, 2]), 1).kind
|
163 |
+
TupleKind(MatrixKind(NumberKind), NumberKind)
|
164 |
+
>>> Tuple(1, 2).kind.element_kind
|
165 |
+
(NumberKind, NumberKind)
|
166 |
+
|
167 |
+
See Also
|
168 |
+
========
|
169 |
+
|
170 |
+
sympy.matrices.common.MatrixKind
|
171 |
+
sympy.core.kind.NumberKind
|
172 |
+
"""
|
173 |
+
return TupleKind(*(i.kind for i in self.args))
|
174 |
+
|
175 |
+
_sympy_converter[tuple] = lambda tup: Tuple(*tup)
|
176 |
+
|
177 |
+
|
178 |
+
|
179 |
+
|
180 |
+
|
181 |
+
def tuple_wrapper(method):
|
182 |
+
"""
|
183 |
+
Decorator that converts any tuple in the function arguments into a Tuple.
|
184 |
+
|
185 |
+
Explanation
|
186 |
+
===========
|
187 |
+
|
188 |
+
The motivation for this is to provide simple user interfaces. The user can
|
189 |
+
call a function with regular tuples in the argument, and the wrapper will
|
190 |
+
convert them to Tuples before handing them to the function.
|
191 |
+
|
192 |
+
Explanation
|
193 |
+
===========
|
194 |
+
|
195 |
+
>>> from sympy.core.containers import tuple_wrapper
|
196 |
+
>>> def f(*args):
|
197 |
+
... return args
|
198 |
+
>>> g = tuple_wrapper(f)
|
199 |
+
|
200 |
+
The decorated function g sees only the Tuple argument:
|
201 |
+
|
202 |
+
>>> g(0, (1, 2), 3)
|
203 |
+
(0, (1, 2), 3)
|
204 |
+
|
205 |
+
"""
|
206 |
+
def wrap_tuples(*args, **kw_args):
|
207 |
+
newargs = []
|
208 |
+
for arg in args:
|
209 |
+
if isinstance(arg, tuple):
|
210 |
+
newargs.append(Tuple(*arg))
|
211 |
+
else:
|
212 |
+
newargs.append(arg)
|
213 |
+
return method(*newargs, **kw_args)
|
214 |
+
return wrap_tuples
|
215 |
+
|
216 |
+
|
217 |
+
class Dict(Basic):
|
218 |
+
"""
|
219 |
+
Wrapper around the builtin dict object.
|
220 |
+
|
221 |
+
Explanation
|
222 |
+
===========
|
223 |
+
|
224 |
+
The Dict is a subclass of Basic, so that it works well in the
|
225 |
+
SymPy framework. Because it is immutable, it may be included
|
226 |
+
in sets, but its values must all be given at instantiation and
|
227 |
+
cannot be changed afterwards. Otherwise it behaves identically
|
228 |
+
to the Python dict.
|
229 |
+
|
230 |
+
Examples
|
231 |
+
========
|
232 |
+
|
233 |
+
>>> from sympy import Dict, Symbol
|
234 |
+
|
235 |
+
>>> D = Dict({1: 'one', 2: 'two'})
|
236 |
+
>>> for key in D:
|
237 |
+
... if key == 1:
|
238 |
+
... print('%s %s' % (key, D[key]))
|
239 |
+
1 one
|
240 |
+
|
241 |
+
The args are sympified so the 1 and 2 are Integers and the values
|
242 |
+
are Symbols. Queries automatically sympify args so the following work:
|
243 |
+
|
244 |
+
>>> 1 in D
|
245 |
+
True
|
246 |
+
>>> D.has(Symbol('one')) # searches keys and values
|
247 |
+
True
|
248 |
+
>>> 'one' in D # not in the keys
|
249 |
+
False
|
250 |
+
>>> D[1]
|
251 |
+
one
|
252 |
+
|
253 |
+
"""
|
254 |
+
|
255 |
+
def __new__(cls, *args):
|
256 |
+
if len(args) == 1 and isinstance(args[0], (dict, Dict)):
|
257 |
+
items = [Tuple(k, v) for k, v in args[0].items()]
|
258 |
+
elif iterable(args) and all(len(arg) == 2 for arg in args):
|
259 |
+
items = [Tuple(k, v) for k, v in args]
|
260 |
+
else:
|
261 |
+
raise TypeError('Pass Dict args as Dict((k1, v1), ...) or Dict({k1: v1, ...})')
|
262 |
+
elements = frozenset(items)
|
263 |
+
obj = Basic.__new__(cls, *ordered(items))
|
264 |
+
obj.elements = elements
|
265 |
+
obj._dict = dict(items) # In case Tuple decides it wants to sympify
|
266 |
+
return obj
|
267 |
+
|
268 |
+
def __getitem__(self, key):
|
269 |
+
"""x.__getitem__(y) <==> x[y]"""
|
270 |
+
try:
|
271 |
+
key = _sympify(key)
|
272 |
+
except SympifyError:
|
273 |
+
raise KeyError(key)
|
274 |
+
|
275 |
+
return self._dict[key]
|
276 |
+
|
277 |
+
def __setitem__(self, key, value):
|
278 |
+
raise NotImplementedError("SymPy Dicts are Immutable")
|
279 |
+
|
280 |
+
def items(self):
|
281 |
+
'''Returns a set-like object providing a view on dict's items.
|
282 |
+
'''
|
283 |
+
return self._dict.items()
|
284 |
+
|
285 |
+
def keys(self):
|
286 |
+
'''Returns the list of the dict's keys.'''
|
287 |
+
return self._dict.keys()
|
288 |
+
|
289 |
+
def values(self):
|
290 |
+
'''Returns the list of the dict's values.'''
|
291 |
+
return self._dict.values()
|
292 |
+
|
293 |
+
def __iter__(self):
|
294 |
+
'''x.__iter__() <==> iter(x)'''
|
295 |
+
return iter(self._dict)
|
296 |
+
|
297 |
+
def __len__(self):
|
298 |
+
'''x.__len__() <==> len(x)'''
|
299 |
+
return self._dict.__len__()
|
300 |
+
|
301 |
+
def get(self, key, default=None):
|
302 |
+
'''Returns the value for key if the key is in the dictionary.'''
|
303 |
+
try:
|
304 |
+
key = _sympify(key)
|
305 |
+
except SympifyError:
|
306 |
+
return default
|
307 |
+
return self._dict.get(key, default)
|
308 |
+
|
309 |
+
def __contains__(self, key):
|
310 |
+
'''D.__contains__(k) -> True if D has a key k, else False'''
|
311 |
+
try:
|
312 |
+
key = _sympify(key)
|
313 |
+
except SympifyError:
|
314 |
+
return False
|
315 |
+
return key in self._dict
|
316 |
+
|
317 |
+
def __lt__(self, other):
|
318 |
+
return _sympify(self.args < other.args)
|
319 |
+
|
320 |
+
@property
|
321 |
+
def _sorted_args(self):
|
322 |
+
return tuple(sorted(self.args, key=default_sort_key))
|
323 |
+
|
324 |
+
def __eq__(self, other):
|
325 |
+
if isinstance(other, dict):
|
326 |
+
return self == Dict(other)
|
327 |
+
return super().__eq__(other)
|
328 |
+
|
329 |
+
__hash__ : Callable[[Basic], Any] = Basic.__hash__
|
330 |
+
|
331 |
+
# this handles dict, defaultdict, OrderedDict
|
332 |
+
_sympy_converter[dict] = lambda d: Dict(*d.items())
|
333 |
+
|
334 |
+
class OrderedSet(MutableSet):
|
335 |
+
def __init__(self, iterable=None):
|
336 |
+
if iterable:
|
337 |
+
self.map = OrderedDict((item, None) for item in iterable)
|
338 |
+
else:
|
339 |
+
self.map = OrderedDict()
|
340 |
+
|
341 |
+
def __len__(self):
|
342 |
+
return len(self.map)
|
343 |
+
|
344 |
+
def __contains__(self, key):
|
345 |
+
return key in self.map
|
346 |
+
|
347 |
+
def add(self, key):
|
348 |
+
self.map[key] = None
|
349 |
+
|
350 |
+
def discard(self, key):
|
351 |
+
self.map.pop(key)
|
352 |
+
|
353 |
+
def pop(self, last=True):
|
354 |
+
return self.map.popitem(last=last)[0]
|
355 |
+
|
356 |
+
def __iter__(self):
|
357 |
+
yield from self.map.keys()
|
358 |
+
|
359 |
+
def __repr__(self):
|
360 |
+
if not self.map:
|
361 |
+
return '%s()' % (self.__class__.__name__,)
|
362 |
+
return '%s(%r)' % (self.__class__.__name__, list(self.map.keys()))
|
363 |
+
|
364 |
+
def intersection(self, other):
|
365 |
+
return self.__class__([val for val in self if val in other])
|
366 |
+
|
367 |
+
def difference(self, other):
|
368 |
+
return self.__class__([val for val in self if val not in other])
|
369 |
+
|
370 |
+
def update(self, iterable):
|
371 |
+
for val in iterable:
|
372 |
+
self.add(val)
|
373 |
+
|
374 |
+
class TupleKind(Kind):
|
375 |
+
"""
|
376 |
+
TupleKind is a subclass of Kind, which is used to define Kind of ``Tuple``.
|
377 |
+
|
378 |
+
Parameters of TupleKind will be kinds of all the arguments in Tuples, for
|
379 |
+
example
|
380 |
+
|
381 |
+
Parameters
|
382 |
+
==========
|
383 |
+
|
384 |
+
args : tuple(element_kind)
|
385 |
+
element_kind is kind of element.
|
386 |
+
args is tuple of kinds of element
|
387 |
+
|
388 |
+
Examples
|
389 |
+
========
|
390 |
+
|
391 |
+
>>> from sympy import Tuple
|
392 |
+
>>> Tuple(1, 2).kind
|
393 |
+
TupleKind(NumberKind, NumberKind)
|
394 |
+
>>> Tuple(1, 2).kind.element_kind
|
395 |
+
(NumberKind, NumberKind)
|
396 |
+
|
397 |
+
See Also
|
398 |
+
========
|
399 |
+
|
400 |
+
sympy.core.kind.NumberKind
|
401 |
+
MatrixKind
|
402 |
+
sympy.sets.sets.SetKind
|
403 |
+
"""
|
404 |
+
def __new__(cls, *args):
|
405 |
+
obj = super().__new__(cls, *args)
|
406 |
+
obj.element_kind = args
|
407 |
+
return obj
|
408 |
+
|
409 |
+
def __repr__(self):
|
410 |
+
return "TupleKind{}".format(self.element_kind)
|
venv/lib/python3.10/site-packages/sympy/core/coreerrors.py
ADDED
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Definitions of common exceptions for :mod:`sympy.core` module. """
|
2 |
+
|
3 |
+
|
4 |
+
class BaseCoreError(Exception):
|
5 |
+
"""Base class for core related exceptions. """
|
6 |
+
|
7 |
+
|
8 |
+
class NonCommutativeExpression(BaseCoreError):
|
9 |
+
"""Raised when expression didn't have commutative property. """
|
venv/lib/python3.10/site-packages/sympy/core/expr.py
ADDED
The diff for this file is too large to render.
See raw diff
|
|
venv/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)
|
venv/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)
|
venv/lib/python3.10/site-packages/sympy/core/function.py
ADDED
The diff for this file is too large to render.
See raw diff
|
|
venv/lib/python3.10/site-packages/sympy/core/kind.py
ADDED
@@ -0,0 +1,388 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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)
|
venv/lib/python3.10/site-packages/sympy/core/logic.py
ADDED
@@ -0,0 +1,427 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Logic expressions handling
|
2 |
+
|
3 |
+
NOTE
|
4 |
+
----
|
5 |
+
|
6 |
+
at present this is mainly needed for facts.py, feel free however to improve
|
7 |
+
this stuff for general purpose.
|
8 |
+
"""
|
9 |
+
|
10 |
+
from __future__ import annotations
|
11 |
+
from typing import Optional
|
12 |
+
|
13 |
+
# Type of a fuzzy bool
|
14 |
+
FuzzyBool = Optional[bool]
|
15 |
+
|
16 |
+
|
17 |
+
def _torf(args):
|
18 |
+
"""Return True if all args are True, False if they
|
19 |
+
are all False, else None.
|
20 |
+
|
21 |
+
>>> from sympy.core.logic import _torf
|
22 |
+
>>> _torf((True, True))
|
23 |
+
True
|
24 |
+
>>> _torf((False, False))
|
25 |
+
False
|
26 |
+
>>> _torf((True, False))
|
27 |
+
"""
|
28 |
+
sawT = sawF = False
|
29 |
+
for a in args:
|
30 |
+
if a is True:
|
31 |
+
if sawF:
|
32 |
+
return
|
33 |
+
sawT = True
|
34 |
+
elif a is False:
|
35 |
+
if sawT:
|
36 |
+
return
|
37 |
+
sawF = True
|
38 |
+
else:
|
39 |
+
return
|
40 |
+
return sawT
|
41 |
+
|
42 |
+
|
43 |
+
def _fuzzy_group(args, quick_exit=False):
|
44 |
+
"""Return True if all args are True, None if there is any None else False
|
45 |
+
unless ``quick_exit`` is True (then return None as soon as a second False
|
46 |
+
is seen.
|
47 |
+
|
48 |
+
``_fuzzy_group`` is like ``fuzzy_and`` except that it is more
|
49 |
+
conservative in returning a False, waiting to make sure that all
|
50 |
+
arguments are True or False and returning None if any arguments are
|
51 |
+
None. It also has the capability of permiting only a single False and
|
52 |
+
returning None if more than one is seen. For example, the presence of a
|
53 |
+
single transcendental amongst rationals would indicate that the group is
|
54 |
+
no longer rational; but a second transcendental in the group would make the
|
55 |
+
determination impossible.
|
56 |
+
|
57 |
+
|
58 |
+
Examples
|
59 |
+
========
|
60 |
+
|
61 |
+
>>> from sympy.core.logic import _fuzzy_group
|
62 |
+
|
63 |
+
By default, multiple Falses mean the group is broken:
|
64 |
+
|
65 |
+
>>> _fuzzy_group([False, False, True])
|
66 |
+
False
|
67 |
+
|
68 |
+
If multiple Falses mean the group status is unknown then set
|
69 |
+
`quick_exit` to True so None can be returned when the 2nd False is seen:
|
70 |
+
|
71 |
+
>>> _fuzzy_group([False, False, True], quick_exit=True)
|
72 |
+
|
73 |
+
But if only a single False is seen then the group is known to
|
74 |
+
be broken:
|
75 |
+
|
76 |
+
>>> _fuzzy_group([False, True, True], quick_exit=True)
|
77 |
+
False
|
78 |
+
|
79 |
+
"""
|
80 |
+
saw_other = False
|
81 |
+
for a in args:
|
82 |
+
if a is True:
|
83 |
+
continue
|
84 |
+
if a is None:
|
85 |
+
return
|
86 |
+
if quick_exit and saw_other:
|
87 |
+
return
|
88 |
+
saw_other = True
|
89 |
+
return not saw_other
|
90 |
+
|
91 |
+
|
92 |
+
def fuzzy_bool(x):
|
93 |
+
"""Return True, False or None according to x.
|
94 |
+
|
95 |
+
Whereas bool(x) returns True or False, fuzzy_bool allows
|
96 |
+
for the None value and non-false values (which become None), too.
|
97 |
+
|
98 |
+
Examples
|
99 |
+
========
|
100 |
+
|
101 |
+
>>> from sympy.core.logic import fuzzy_bool
|
102 |
+
>>> from sympy.abc import x
|
103 |
+
>>> fuzzy_bool(x), fuzzy_bool(None)
|
104 |
+
(None, None)
|
105 |
+
>>> bool(x), bool(None)
|
106 |
+
(True, False)
|
107 |
+
|
108 |
+
"""
|
109 |
+
if x is None:
|
110 |
+
return None
|
111 |
+
if x in (True, False):
|
112 |
+
return bool(x)
|
113 |
+
|
114 |
+
|
115 |
+
def fuzzy_and(args):
|
116 |
+
"""Return True (all True), False (any False) or None.
|
117 |
+
|
118 |
+
Examples
|
119 |
+
========
|
120 |
+
|
121 |
+
>>> from sympy.core.logic import fuzzy_and
|
122 |
+
>>> from sympy import Dummy
|
123 |
+
|
124 |
+
If you had a list of objects to test the commutivity of
|
125 |
+
and you want the fuzzy_and logic applied, passing an
|
126 |
+
iterator will allow the commutativity to only be computed
|
127 |
+
as many times as necessary. With this list, False can be
|
128 |
+
returned after analyzing the first symbol:
|
129 |
+
|
130 |
+
>>> syms = [Dummy(commutative=False), Dummy()]
|
131 |
+
>>> fuzzy_and(s.is_commutative for s in syms)
|
132 |
+
False
|
133 |
+
|
134 |
+
That False would require less work than if a list of pre-computed
|
135 |
+
items was sent:
|
136 |
+
|
137 |
+
>>> fuzzy_and([s.is_commutative for s in syms])
|
138 |
+
False
|
139 |
+
"""
|
140 |
+
|
141 |
+
rv = True
|
142 |
+
for ai in args:
|
143 |
+
ai = fuzzy_bool(ai)
|
144 |
+
if ai is False:
|
145 |
+
return False
|
146 |
+
if rv: # this will stop updating if a None is ever trapped
|
147 |
+
rv = ai
|
148 |
+
return rv
|
149 |
+
|
150 |
+
|
151 |
+
def fuzzy_not(v):
|
152 |
+
"""
|
153 |
+
Not in fuzzy logic
|
154 |
+
|
155 |
+
Return None if `v` is None else `not v`.
|
156 |
+
|
157 |
+
Examples
|
158 |
+
========
|
159 |
+
|
160 |
+
>>> from sympy.core.logic import fuzzy_not
|
161 |
+
>>> fuzzy_not(True)
|
162 |
+
False
|
163 |
+
>>> fuzzy_not(None)
|
164 |
+
>>> fuzzy_not(False)
|
165 |
+
True
|
166 |
+
|
167 |
+
"""
|
168 |
+
if v is None:
|
169 |
+
return v
|
170 |
+
else:
|
171 |
+
return not v
|
172 |
+
|
173 |
+
|
174 |
+
def fuzzy_or(args):
|
175 |
+
"""
|
176 |
+
Or in fuzzy logic. Returns True (any True), False (all False), or None
|
177 |
+
|
178 |
+
See the docstrings of fuzzy_and and fuzzy_not for more info. fuzzy_or is
|
179 |
+
related to the two by the standard De Morgan's law.
|
180 |
+
|
181 |
+
>>> from sympy.core.logic import fuzzy_or
|
182 |
+
>>> fuzzy_or([True, False])
|
183 |
+
True
|
184 |
+
>>> fuzzy_or([True, None])
|
185 |
+
True
|
186 |
+
>>> fuzzy_or([False, False])
|
187 |
+
False
|
188 |
+
>>> print(fuzzy_or([False, None]))
|
189 |
+
None
|
190 |
+
|
191 |
+
"""
|
192 |
+
rv = False
|
193 |
+
for ai in args:
|
194 |
+
ai = fuzzy_bool(ai)
|
195 |
+
if ai is True:
|
196 |
+
return True
|
197 |
+
if rv is False: # this will stop updating if a None is ever trapped
|
198 |
+
rv = ai
|
199 |
+
return rv
|
200 |
+
|
201 |
+
|
202 |
+
def fuzzy_xor(args):
|
203 |
+
"""Return None if any element of args is not True or False, else
|
204 |
+
True (if there are an odd number of True elements), else False."""
|
205 |
+
t = f = 0
|
206 |
+
for a in args:
|
207 |
+
ai = fuzzy_bool(a)
|
208 |
+
if ai:
|
209 |
+
t += 1
|
210 |
+
elif ai is False:
|
211 |
+
f += 1
|
212 |
+
else:
|
213 |
+
return
|
214 |
+
return t % 2 == 1
|
215 |
+
|
216 |
+
|
217 |
+
def fuzzy_nand(args):
|
218 |
+
"""Return False if all args are True, True if they are all False,
|
219 |
+
else None."""
|
220 |
+
return fuzzy_not(fuzzy_and(args))
|
221 |
+
|
222 |
+
|
223 |
+
class Logic:
|
224 |
+
"""Logical expression"""
|
225 |
+
# {} 'op' -> LogicClass
|
226 |
+
op_2class: dict[str, type[Logic]] = {}
|
227 |
+
|
228 |
+
def __new__(cls, *args):
|
229 |
+
obj = object.__new__(cls)
|
230 |
+
obj.args = args
|
231 |
+
return obj
|
232 |
+
|
233 |
+
def __getnewargs__(self):
|
234 |
+
return self.args
|
235 |
+
|
236 |
+
def __hash__(self):
|
237 |
+
return hash((type(self).__name__,) + tuple(self.args))
|
238 |
+
|
239 |
+
def __eq__(a, b):
|
240 |
+
if not isinstance(b, type(a)):
|
241 |
+
return False
|
242 |
+
else:
|
243 |
+
return a.args == b.args
|
244 |
+
|
245 |
+
def __ne__(a, b):
|
246 |
+
if not isinstance(b, type(a)):
|
247 |
+
return True
|
248 |
+
else:
|
249 |
+
return a.args != b.args
|
250 |
+
|
251 |
+
def __lt__(self, other):
|
252 |
+
if self.__cmp__(other) == -1:
|
253 |
+
return True
|
254 |
+
return False
|
255 |
+
|
256 |
+
def __cmp__(self, other):
|
257 |
+
if type(self) is not type(other):
|
258 |
+
a = str(type(self))
|
259 |
+
b = str(type(other))
|
260 |
+
else:
|
261 |
+
a = self.args
|
262 |
+
b = other.args
|
263 |
+
return (a > b) - (a < b)
|
264 |
+
|
265 |
+
def __str__(self):
|
266 |
+
return '%s(%s)' % (self.__class__.__name__,
|
267 |
+
', '.join(str(a) for a in self.args))
|
268 |
+
|
269 |
+
__repr__ = __str__
|
270 |
+
|
271 |
+
@staticmethod
|
272 |
+
def fromstring(text):
|
273 |
+
"""Logic from string with space around & and | but none after !.
|
274 |
+
|
275 |
+
e.g.
|
276 |
+
|
277 |
+
!a & b | c
|
278 |
+
"""
|
279 |
+
lexpr = None # current logical expression
|
280 |
+
schedop = None # scheduled operation
|
281 |
+
for term in text.split():
|
282 |
+
# operation symbol
|
283 |
+
if term in '&|':
|
284 |
+
if schedop is not None:
|
285 |
+
raise ValueError(
|
286 |
+
'double op forbidden: "%s %s"' % (term, schedop))
|
287 |
+
if lexpr is None:
|
288 |
+
raise ValueError(
|
289 |
+
'%s cannot be in the beginning of expression' % term)
|
290 |
+
schedop = term
|
291 |
+
continue
|
292 |
+
if '&' in term or '|' in term:
|
293 |
+
raise ValueError('& and | must have space around them')
|
294 |
+
if term[0] == '!':
|
295 |
+
if len(term) == 1:
|
296 |
+
raise ValueError('do not include space after "!"')
|
297 |
+
term = Not(term[1:])
|
298 |
+
|
299 |
+
# already scheduled operation, e.g. '&'
|
300 |
+
if schedop:
|
301 |
+
lexpr = Logic.op_2class[schedop](lexpr, term)
|
302 |
+
schedop = None
|
303 |
+
continue
|
304 |
+
|
305 |
+
# this should be atom
|
306 |
+
if lexpr is not None:
|
307 |
+
raise ValueError(
|
308 |
+
'missing op between "%s" and "%s"' % (lexpr, term))
|
309 |
+
|
310 |
+
lexpr = term
|
311 |
+
|
312 |
+
# let's check that we ended up in correct state
|
313 |
+
if schedop is not None:
|
314 |
+
raise ValueError('premature end-of-expression in "%s"' % text)
|
315 |
+
if lexpr is None:
|
316 |
+
raise ValueError('"%s" is empty' % text)
|
317 |
+
|
318 |
+
# everything looks good now
|
319 |
+
return lexpr
|
320 |
+
|
321 |
+
|
322 |
+
class AndOr_Base(Logic):
|
323 |
+
|
324 |
+
def __new__(cls, *args):
|
325 |
+
bargs = []
|
326 |
+
for a in args:
|
327 |
+
if a == cls.op_x_notx:
|
328 |
+
return a
|
329 |
+
elif a == (not cls.op_x_notx):
|
330 |
+
continue # skip this argument
|
331 |
+
bargs.append(a)
|
332 |
+
|
333 |
+
args = sorted(set(cls.flatten(bargs)), key=hash)
|
334 |
+
|
335 |
+
for a in args:
|
336 |
+
if Not(a) in args:
|
337 |
+
return cls.op_x_notx
|
338 |
+
|
339 |
+
if len(args) == 1:
|
340 |
+
return args.pop()
|
341 |
+
elif len(args) == 0:
|
342 |
+
return not cls.op_x_notx
|
343 |
+
|
344 |
+
return Logic.__new__(cls, *args)
|
345 |
+
|
346 |
+
@classmethod
|
347 |
+
def flatten(cls, args):
|
348 |
+
# quick-n-dirty flattening for And and Or
|
349 |
+
args_queue = list(args)
|
350 |
+
res = []
|
351 |
+
|
352 |
+
while True:
|
353 |
+
try:
|
354 |
+
arg = args_queue.pop(0)
|
355 |
+
except IndexError:
|
356 |
+
break
|
357 |
+
if isinstance(arg, Logic):
|
358 |
+
if isinstance(arg, cls):
|
359 |
+
args_queue.extend(arg.args)
|
360 |
+
continue
|
361 |
+
res.append(arg)
|
362 |
+
|
363 |
+
args = tuple(res)
|
364 |
+
return args
|
365 |
+
|
366 |
+
|
367 |
+
class And(AndOr_Base):
|
368 |
+
op_x_notx = False
|
369 |
+
|
370 |
+
def _eval_propagate_not(self):
|
371 |
+
# !(a&b&c ...) == !a | !b | !c ...
|
372 |
+
return Or(*[Not(a) for a in self.args])
|
373 |
+
|
374 |
+
# (a|b|...) & c == (a&c) | (b&c) | ...
|
375 |
+
def expand(self):
|
376 |
+
|
377 |
+
# first locate Or
|
378 |
+
for i, arg in enumerate(self.args):
|
379 |
+
if isinstance(arg, Or):
|
380 |
+
arest = self.args[:i] + self.args[i + 1:]
|
381 |
+
|
382 |
+
orterms = [And(*(arest + (a,))) for a in arg.args]
|
383 |
+
for j in range(len(orterms)):
|
384 |
+
if isinstance(orterms[j], Logic):
|
385 |
+
orterms[j] = orterms[j].expand()
|
386 |
+
|
387 |
+
res = Or(*orterms)
|
388 |
+
return res
|
389 |
+
|
390 |
+
return self
|
391 |
+
|
392 |
+
|
393 |
+
class Or(AndOr_Base):
|
394 |
+
op_x_notx = True
|
395 |
+
|
396 |
+
def _eval_propagate_not(self):
|
397 |
+
# !(a|b|c ...) == !a & !b & !c ...
|
398 |
+
return And(*[Not(a) for a in self.args])
|
399 |
+
|
400 |
+
|
401 |
+
class Not(Logic):
|
402 |
+
|
403 |
+
def __new__(cls, arg):
|
404 |
+
if isinstance(arg, str):
|
405 |
+
return Logic.__new__(cls, arg)
|
406 |
+
|
407 |
+
elif isinstance(arg, bool):
|
408 |
+
return not arg
|
409 |
+
elif isinstance(arg, Not):
|
410 |
+
return arg.args[0]
|
411 |
+
|
412 |
+
elif isinstance(arg, Logic):
|
413 |
+
# XXX this is a hack to expand right from the beginning
|
414 |
+
arg = arg._eval_propagate_not()
|
415 |
+
return arg
|
416 |
+
|
417 |
+
else:
|
418 |
+
raise ValueError('Not: unknown argument %r' % (arg,))
|
419 |
+
|
420 |
+
@property
|
421 |
+
def arg(self):
|
422 |
+
return self.args[0]
|
423 |
+
|
424 |
+
|
425 |
+
Logic.op_2class['&'] = And
|
426 |
+
Logic.op_2class['|'] = Or
|
427 |
+
Logic.op_2class['!'] = Not
|
venv/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
|
venv/lib/python3.10/site-packages/sympy/core/multidimensional.py
ADDED
@@ -0,0 +1,131 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Provides functionality for multidimensional usage of scalar-functions.
|
3 |
+
|
4 |
+
Read the vectorize docstring for more details.
|
5 |
+
"""
|
6 |
+
|
7 |
+
from functools import wraps
|
8 |
+
|
9 |
+
|
10 |
+
def apply_on_element(f, args, kwargs, n):
|
11 |
+
"""
|
12 |
+
Returns a structure with the same dimension as the specified argument,
|
13 |
+
where each basic element is replaced by the function f applied on it. All
|
14 |
+
other arguments stay the same.
|
15 |
+
"""
|
16 |
+
# Get the specified argument.
|
17 |
+
if isinstance(n, int):
|
18 |
+
structure = args[n]
|
19 |
+
is_arg = True
|
20 |
+
elif isinstance(n, str):
|
21 |
+
structure = kwargs[n]
|
22 |
+
is_arg = False
|
23 |
+
|
24 |
+
# Define reduced function that is only dependent on the specified argument.
|
25 |
+
def f_reduced(x):
|
26 |
+
if hasattr(x, "__iter__"):
|
27 |
+
return list(map(f_reduced, x))
|
28 |
+
else:
|
29 |
+
if is_arg:
|
30 |
+
args[n] = x
|
31 |
+
else:
|
32 |
+
kwargs[n] = x
|
33 |
+
return f(*args, **kwargs)
|
34 |
+
|
35 |
+
# f_reduced will call itself recursively so that in the end f is applied to
|
36 |
+
# all basic elements.
|
37 |
+
return list(map(f_reduced, structure))
|
38 |
+
|
39 |
+
|
40 |
+
def iter_copy(structure):
|
41 |
+
"""
|
42 |
+
Returns a copy of an iterable object (also copying all embedded iterables).
|
43 |
+
"""
|
44 |
+
return [iter_copy(i) if hasattr(i, "__iter__") else i for i in structure]
|
45 |
+
|
46 |
+
|
47 |
+
def structure_copy(structure):
|
48 |
+
"""
|
49 |
+
Returns a copy of the given structure (numpy-array, list, iterable, ..).
|
50 |
+
"""
|
51 |
+
if hasattr(structure, "copy"):
|
52 |
+
return structure.copy()
|
53 |
+
return iter_copy(structure)
|
54 |
+
|
55 |
+
|
56 |
+
class vectorize:
|
57 |
+
"""
|
58 |
+
Generalizes a function taking scalars to accept multidimensional arguments.
|
59 |
+
|
60 |
+
Examples
|
61 |
+
========
|
62 |
+
|
63 |
+
>>> from sympy import vectorize, diff, sin, symbols, Function
|
64 |
+
>>> x, y, z = symbols('x y z')
|
65 |
+
>>> f, g, h = list(map(Function, 'fgh'))
|
66 |
+
|
67 |
+
>>> @vectorize(0)
|
68 |
+
... def vsin(x):
|
69 |
+
... return sin(x)
|
70 |
+
|
71 |
+
>>> vsin([1, x, y])
|
72 |
+
[sin(1), sin(x), sin(y)]
|
73 |
+
|
74 |
+
>>> @vectorize(0, 1)
|
75 |
+
... def vdiff(f, y):
|
76 |
+
... return diff(f, y)
|
77 |
+
|
78 |
+
>>> vdiff([f(x, y, z), g(x, y, z), h(x, y, z)], [x, y, z])
|
79 |
+
[[Derivative(f(x, y, z), x), Derivative(f(x, y, z), y), Derivative(f(x, y, z), z)], [Derivative(g(x, y, z), x), Derivative(g(x, y, z), y), Derivative(g(x, y, z), z)], [Derivative(h(x, y, z), x), Derivative(h(x, y, z), y), Derivative(h(x, y, z), z)]]
|
80 |
+
"""
|
81 |
+
def __init__(self, *mdargs):
|
82 |
+
"""
|
83 |
+
The given numbers and strings characterize the arguments that will be
|
84 |
+
treated as data structures, where the decorated function will be applied
|
85 |
+
to every single element.
|
86 |
+
If no argument is given, everything is treated multidimensional.
|
87 |
+
"""
|
88 |
+
for a in mdargs:
|
89 |
+
if not isinstance(a, (int, str)):
|
90 |
+
raise TypeError("a is of invalid type")
|
91 |
+
self.mdargs = mdargs
|
92 |
+
|
93 |
+
def __call__(self, f):
|
94 |
+
"""
|
95 |
+
Returns a wrapper for the one-dimensional function that can handle
|
96 |
+
multidimensional arguments.
|
97 |
+
"""
|
98 |
+
@wraps(f)
|
99 |
+
def wrapper(*args, **kwargs):
|
100 |
+
# Get arguments that should be treated multidimensional
|
101 |
+
if self.mdargs:
|
102 |
+
mdargs = self.mdargs
|
103 |
+
else:
|
104 |
+
mdargs = range(len(args)) + kwargs.keys()
|
105 |
+
|
106 |
+
arglength = len(args)
|
107 |
+
|
108 |
+
for n in mdargs:
|
109 |
+
if isinstance(n, int):
|
110 |
+
if n >= arglength:
|
111 |
+
continue
|
112 |
+
entry = args[n]
|
113 |
+
is_arg = True
|
114 |
+
elif isinstance(n, str):
|
115 |
+
try:
|
116 |
+
entry = kwargs[n]
|
117 |
+
except KeyError:
|
118 |
+
continue
|
119 |
+
is_arg = False
|
120 |
+
if hasattr(entry, "__iter__"):
|
121 |
+
# Create now a copy of the given array and manipulate then
|
122 |
+
# the entries directly.
|
123 |
+
if is_arg:
|
124 |
+
args = list(args)
|
125 |
+
args[n] = structure_copy(entry)
|
126 |
+
else:
|
127 |
+
kwargs[n] = structure_copy(entry)
|
128 |
+
result = apply_on_element(wrapper, args, kwargs, n)
|
129 |
+
return result
|
130 |
+
return f(*args, **kwargs)
|
131 |
+
return wrapper
|
venv/lib/python3.10/site-packages/sympy/core/numbers.py
ADDED
The diff for this file is too large to render.
See raw diff
|
|
venv/lib/python3.10/site-packages/sympy/core/operations.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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from __future__ import annotations
|
2 |
+
from operator import attrgetter
|
3 |
+
from collections import defaultdict
|
4 |
+
|
5 |
+
from sympy.utilities.exceptions import sympy_deprecation_warning
|
6 |
+
|
7 |
+
from .sympify import _sympify as _sympify_, sympify
|
8 |
+
from .basic import Basic
|
9 |
+
from .cache import cacheit
|
10 |
+
from .sorting import ordered
|
11 |
+
from .logic import fuzzy_and
|
12 |
+
from .parameters import global_parameters
|
13 |
+
from sympy.utilities.iterables import sift
|
14 |
+
from sympy.multipledispatch.dispatcher import (Dispatcher,
|
15 |
+
ambiguity_register_error_ignore_dup,
|
16 |
+
str_signature, RaiseNotImplementedError)
|
17 |
+
|
18 |
+
|
19 |
+
class AssocOp(Basic):
|
20 |
+
""" Associative operations, can separate noncommutative and
|
21 |
+
commutative parts.
|
22 |
+
|
23 |
+
(a op b) op c == a op (b op c) == a op b op c.
|
24 |
+
|
25 |
+
Base class for Add and Mul.
|
26 |
+
|
27 |
+
This is an abstract base class, concrete derived classes must define
|
28 |
+
the attribute `identity`.
|
29 |
+
|
30 |
+
.. deprecated:: 1.7
|
31 |
+
|
32 |
+
Using arguments that aren't subclasses of :class:`~.Expr` in core
|
33 |
+
operators (:class:`~.Mul`, :class:`~.Add`, and :class:`~.Pow`) is
|
34 |
+
deprecated. See :ref:`non-expr-args-deprecated` for details.
|
35 |
+
|
36 |
+
Parameters
|
37 |
+
==========
|
38 |
+
|
39 |
+
*args :
|
40 |
+
Arguments which are operated
|
41 |
+
|
42 |
+
evaluate : bool, optional
|
43 |
+
Evaluate the operation. If not passed, refer to ``global_parameters.evaluate``.
|
44 |
+
"""
|
45 |
+
|
46 |
+
# for performance reason, we don't let is_commutative go to assumptions,
|
47 |
+
# and keep it right here
|
48 |
+
__slots__: tuple[str, ...] = ('is_commutative',)
|
49 |
+
|
50 |
+
_args_type: type[Basic] | None = None
|
51 |
+
|
52 |
+
@cacheit
|
53 |
+
def __new__(cls, *args, evaluate=None, _sympify=True):
|
54 |
+
# Allow faster processing by passing ``_sympify=False``, if all arguments
|
55 |
+
# are already sympified.
|
56 |
+
if _sympify:
|
57 |
+
args = list(map(_sympify_, args))
|
58 |
+
|
59 |
+
# Disallow non-Expr args in Add/Mul
|
60 |
+
typ = cls._args_type
|
61 |
+
if typ is not None:
|
62 |
+
from .relational import Relational
|
63 |
+
if any(isinstance(arg, Relational) for arg in args):
|
64 |
+
raise TypeError("Relational cannot be used in %s" % cls.__name__)
|
65 |
+
|
66 |
+
# This should raise TypeError once deprecation period is over:
|
67 |
+
for arg in args:
|
68 |
+
if not isinstance(arg, typ):
|
69 |
+
sympy_deprecation_warning(
|
70 |
+
f"""
|
71 |
+
|
72 |
+
Using non-Expr arguments in {cls.__name__} is deprecated (in this case, one of
|
73 |
+
the arguments has type {type(arg).__name__!r}).
|
74 |
+
|
75 |
+
If you really did intend to use a multiplication or addition operation with
|
76 |
+
this object, use the * or + operator instead.
|
77 |
+
|
78 |
+
""",
|
79 |
+
deprecated_since_version="1.7",
|
80 |
+
active_deprecations_target="non-expr-args-deprecated",
|
81 |
+
stacklevel=4,
|
82 |
+
)
|
83 |
+
|
84 |
+
if evaluate is None:
|
85 |
+
evaluate = global_parameters.evaluate
|
86 |
+
if not evaluate:
|
87 |
+
obj = cls._from_args(args)
|
88 |
+
obj = cls._exec_constructor_postprocessors(obj)
|
89 |
+
return obj
|
90 |
+
|
91 |
+
args = [a for a in args if a is not cls.identity]
|
92 |
+
|
93 |
+
if len(args) == 0:
|
94 |
+
return cls.identity
|
95 |
+
if len(args) == 1:
|
96 |
+
return args[0]
|
97 |
+
|
98 |
+
c_part, nc_part, order_symbols = cls.flatten(args)
|
99 |
+
is_commutative = not nc_part
|
100 |
+
obj = cls._from_args(c_part + nc_part, is_commutative)
|
101 |
+
obj = cls._exec_constructor_postprocessors(obj)
|
102 |
+
|
103 |
+
if order_symbols is not None:
|
104 |
+
from sympy.series.order import Order
|
105 |
+
return Order(obj, *order_symbols)
|
106 |
+
return obj
|
107 |
+
|
108 |
+
@classmethod
|
109 |
+
def _from_args(cls, args, is_commutative=None):
|
110 |
+
"""Create new instance with already-processed args.
|
111 |
+
If the args are not in canonical order, then a non-canonical
|
112 |
+
result will be returned, so use with caution. The order of
|
113 |
+
args may change if the sign of the args is changed."""
|
114 |
+
if len(args) == 0:
|
115 |
+
return cls.identity
|
116 |
+
elif len(args) == 1:
|
117 |
+
return args[0]
|
118 |
+
|
119 |
+
obj = super().__new__(cls, *args)
|
120 |
+
if is_commutative is None:
|
121 |
+
is_commutative = fuzzy_and(a.is_commutative for a in args)
|
122 |
+
obj.is_commutative = is_commutative
|
123 |
+
return obj
|
124 |
+
|
125 |
+
def _new_rawargs(self, *args, reeval=True, **kwargs):
|
126 |
+
"""Create new instance of own class with args exactly as provided by
|
127 |
+
caller but returning the self class identity if args is empty.
|
128 |
+
|
129 |
+
Examples
|
130 |
+
========
|
131 |
+
|
132 |
+
This is handy when we want to optimize things, e.g.
|
133 |
+
|
134 |
+
>>> from sympy import Mul, S
|
135 |
+
>>> from sympy.abc import x, y
|
136 |
+
>>> e = Mul(3, x, y)
|
137 |
+
>>> e.args
|
138 |
+
(3, x, y)
|
139 |
+
>>> Mul(*e.args[1:])
|
140 |
+
x*y
|
141 |
+
>>> e._new_rawargs(*e.args[1:]) # the same as above, but faster
|
142 |
+
x*y
|
143 |
+
|
144 |
+
Note: use this with caution. There is no checking of arguments at
|
145 |
+
all. This is best used when you are rebuilding an Add or Mul after
|
146 |
+
simply removing one or more args. If, for example, modifications,
|
147 |
+
result in extra 1s being inserted they will show up in the result:
|
148 |
+
|
149 |
+
>>> m = (x*y)._new_rawargs(S.One, x); m
|
150 |
+
1*x
|
151 |
+
>>> m == x
|
152 |
+
False
|
153 |
+
>>> m.is_Mul
|
154 |
+
True
|
155 |
+
|
156 |
+
Another issue to be aware of is that the commutativity of the result
|
157 |
+
is based on the commutativity of self. If you are rebuilding the
|
158 |
+
terms that came from a commutative object then there will be no
|
159 |
+
problem, but if self was non-commutative then what you are
|
160 |
+
rebuilding may now be commutative.
|
161 |
+
|
162 |
+
Although this routine tries to do as little as possible with the
|
163 |
+
input, getting the commutativity right is important, so this level
|
164 |
+
of safety is enforced: commutativity will always be recomputed if
|
165 |
+
self is non-commutative and kwarg `reeval=False` has not been
|
166 |
+
passed.
|
167 |
+
"""
|
168 |
+
if reeval and self.is_commutative is False:
|
169 |
+
is_commutative = None
|
170 |
+
else:
|
171 |
+
is_commutative = self.is_commutative
|
172 |
+
return self._from_args(args, is_commutative)
|
173 |
+
|
174 |
+
@classmethod
|
175 |
+
def flatten(cls, seq):
|
176 |
+
"""Return seq so that none of the elements are of type `cls`. This is
|
177 |
+
the vanilla routine that will be used if a class derived from AssocOp
|
178 |
+
does not define its own flatten routine."""
|
179 |
+
# apply associativity, no commutativity property is used
|
180 |
+
new_seq = []
|
181 |
+
while seq:
|
182 |
+
o = seq.pop()
|
183 |
+
if o.__class__ is cls: # classes must match exactly
|
184 |
+
seq.extend(o.args)
|
185 |
+
else:
|
186 |
+
new_seq.append(o)
|
187 |
+
new_seq.reverse()
|
188 |
+
|
189 |
+
# c_part, nc_part, order_symbols
|
190 |
+
return [], new_seq, None
|
191 |
+
|
192 |
+
def _matches_commutative(self, expr, repl_dict=None, old=False):
|
193 |
+
"""
|
194 |
+
Matches Add/Mul "pattern" to an expression "expr".
|
195 |
+
|
196 |
+
repl_dict ... a dictionary of (wild: expression) pairs, that get
|
197 |
+
returned with the results
|
198 |
+
|
199 |
+
This function is the main workhorse for Add/Mul.
|
200 |
+
|
201 |
+
Examples
|
202 |
+
========
|
203 |
+
|
204 |
+
>>> from sympy import symbols, Wild, sin
|
205 |
+
>>> a = Wild("a")
|
206 |
+
>>> b = Wild("b")
|
207 |
+
>>> c = Wild("c")
|
208 |
+
>>> x, y, z = symbols("x y z")
|
209 |
+
>>> (a+sin(b)*c)._matches_commutative(x+sin(y)*z)
|
210 |
+
{a_: x, b_: y, c_: z}
|
211 |
+
|
212 |
+
In the example above, "a+sin(b)*c" is the pattern, and "x+sin(y)*z" is
|
213 |
+
the expression.
|
214 |
+
|
215 |
+
The repl_dict contains parts that were already matched. For example
|
216 |
+
here:
|
217 |
+
|
218 |
+
>>> (x+sin(b)*c)._matches_commutative(x+sin(y)*z, repl_dict={a: x})
|
219 |
+
{a_: x, b_: y, c_: z}
|
220 |
+
|
221 |
+
the only function of the repl_dict is to return it in the
|
222 |
+
result, e.g. if you omit it:
|
223 |
+
|
224 |
+
>>> (x+sin(b)*c)._matches_commutative(x+sin(y)*z)
|
225 |
+
{b_: y, c_: z}
|
226 |
+
|
227 |
+
the "a: x" is not returned in the result, but otherwise it is
|
228 |
+
equivalent.
|
229 |
+
|
230 |
+
"""
|
231 |
+
from .function import _coeff_isneg
|
232 |
+
# make sure expr is Expr if pattern is Expr
|
233 |
+
from .expr import Expr
|
234 |
+
if isinstance(self, Expr) and not isinstance(expr, Expr):
|
235 |
+
return None
|
236 |
+
|
237 |
+
if repl_dict is None:
|
238 |
+
repl_dict = {}
|
239 |
+
|
240 |
+
# handle simple patterns
|
241 |
+
if self == expr:
|
242 |
+
return repl_dict
|
243 |
+
|
244 |
+
d = self._matches_simple(expr, repl_dict)
|
245 |
+
if d is not None:
|
246 |
+
return d
|
247 |
+
|
248 |
+
# eliminate exact part from pattern: (2+a+w1+w2).matches(expr) -> (w1+w2).matches(expr-a-2)
|
249 |
+
from .function import WildFunction
|
250 |
+
from .symbol import Wild
|
251 |
+
wild_part, exact_part = sift(self.args, lambda p:
|
252 |
+
p.has(Wild, WildFunction) and not expr.has(p),
|
253 |
+
binary=True)
|
254 |
+
if not exact_part:
|
255 |
+
wild_part = list(ordered(wild_part))
|
256 |
+
if self.is_Add:
|
257 |
+
# in addition to normal ordered keys, impose
|
258 |
+
# sorting on Muls with leading Number to put
|
259 |
+
# them in order
|
260 |
+
wild_part = sorted(wild_part, key=lambda x:
|
261 |
+
x.args[0] if x.is_Mul and x.args[0].is_Number else
|
262 |
+
0)
|
263 |
+
else:
|
264 |
+
exact = self._new_rawargs(*exact_part)
|
265 |
+
free = expr.free_symbols
|
266 |
+
if free and (exact.free_symbols - free):
|
267 |
+
# there are symbols in the exact part that are not
|
268 |
+
# in the expr; but if there are no free symbols, let
|
269 |
+
# the matching continue
|
270 |
+
return None
|
271 |
+
newexpr = self._combine_inverse(expr, exact)
|
272 |
+
if not old and (expr.is_Add or expr.is_Mul):
|
273 |
+
check = newexpr
|
274 |
+
if _coeff_isneg(check):
|
275 |
+
check = -check
|
276 |
+
if check.count_ops() > expr.count_ops():
|
277 |
+
return None
|
278 |
+
newpattern = self._new_rawargs(*wild_part)
|
279 |
+
return newpattern.matches(newexpr, repl_dict)
|
280 |
+
|
281 |
+
# now to real work ;)
|
282 |
+
i = 0
|
283 |
+
saw = set()
|
284 |
+
while expr not in saw:
|
285 |
+
saw.add(expr)
|
286 |
+
args = tuple(ordered(self.make_args(expr)))
|
287 |
+
if self.is_Add and expr.is_Add:
|
288 |
+
# in addition to normal ordered keys, impose
|
289 |
+
# sorting on Muls with leading Number to put
|
290 |
+
# them in order
|
291 |
+
args = tuple(sorted(args, key=lambda x:
|
292 |
+
x.args[0] if x.is_Mul and x.args[0].is_Number else
|
293 |
+
0))
|
294 |
+
expr_list = (self.identity,) + args
|
295 |
+
for last_op in reversed(expr_list):
|
296 |
+
for w in reversed(wild_part):
|
297 |
+
d1 = w.matches(last_op, repl_dict)
|
298 |
+
if d1 is not None:
|
299 |
+
d2 = self.xreplace(d1).matches(expr, d1)
|
300 |
+
if d2 is not None:
|
301 |
+
return d2
|
302 |
+
|
303 |
+
if i == 0:
|
304 |
+
if self.is_Mul:
|
305 |
+
# make e**i look like Mul
|
306 |
+
if expr.is_Pow and expr.exp.is_Integer:
|
307 |
+
from .mul import Mul
|
308 |
+
if expr.exp > 0:
|
309 |
+
expr = Mul(*[expr.base, expr.base**(expr.exp - 1)], evaluate=False)
|
310 |
+
else:
|
311 |
+
expr = Mul(*[1/expr.base, expr.base**(expr.exp + 1)], evaluate=False)
|
312 |
+
i += 1
|
313 |
+
continue
|
314 |
+
|
315 |
+
elif self.is_Add:
|
316 |
+
# make i*e look like Add
|
317 |
+
c, e = expr.as_coeff_Mul()
|
318 |
+
if abs(c) > 1:
|
319 |
+
from .add import Add
|
320 |
+
if c > 0:
|
321 |
+
expr = Add(*[e, (c - 1)*e], evaluate=False)
|
322 |
+
else:
|
323 |
+
expr = Add(*[-e, (c + 1)*e], evaluate=False)
|
324 |
+
i += 1
|
325 |
+
continue
|
326 |
+
|
327 |
+
# try collection on non-Wild symbols
|
328 |
+
from sympy.simplify.radsimp import collect
|
329 |
+
was = expr
|
330 |
+
did = set()
|
331 |
+
for w in reversed(wild_part):
|
332 |
+
c, w = w.as_coeff_mul(Wild)
|
333 |
+
free = c.free_symbols - did
|
334 |
+
if free:
|
335 |
+
did.update(free)
|
336 |
+
expr = collect(expr, free)
|
337 |
+
if expr != was:
|
338 |
+
i += 0
|
339 |
+
continue
|
340 |
+
|
341 |
+
break # if we didn't continue, there is nothing more to do
|
342 |
+
|
343 |
+
return
|
344 |
+
|
345 |
+
def _has_matcher(self):
|
346 |
+
"""Helper for .has() that checks for containment of
|
347 |
+
subexpressions within an expr by using sets of args
|
348 |
+
of similar nodes, e.g. x + 1 in x + y + 1 checks
|
349 |
+
to see that {x, 1} & {x, y, 1} == {x, 1}
|
350 |
+
"""
|
351 |
+
def _ncsplit(expr):
|
352 |
+
# this is not the same as args_cnc because here
|
353 |
+
# we don't assume expr is a Mul -- hence deal with args --
|
354 |
+
# and always return a set.
|
355 |
+
cpart, ncpart = sift(expr.args,
|
356 |
+
lambda arg: arg.is_commutative is True, binary=True)
|
357 |
+
return set(cpart), ncpart
|
358 |
+
|
359 |
+
c, nc = _ncsplit(self)
|
360 |
+
cls = self.__class__
|
361 |
+
|
362 |
+
def is_in(expr):
|
363 |
+
if isinstance(expr, cls):
|
364 |
+
if expr == self:
|
365 |
+
return True
|
366 |
+
_c, _nc = _ncsplit(expr)
|
367 |
+
if (c & _c) == c:
|
368 |
+
if not nc:
|
369 |
+
return True
|
370 |
+
elif len(nc) <= len(_nc):
|
371 |
+
for i in range(len(_nc) - len(nc) + 1):
|
372 |
+
if _nc[i:i + len(nc)] == nc:
|
373 |
+
return True
|
374 |
+
return False
|
375 |
+
return is_in
|
376 |
+
|
377 |
+
def _eval_evalf(self, prec):
|
378 |
+
"""
|
379 |
+
Evaluate the parts of self that are numbers; if the whole thing
|
380 |
+
was a number with no functions it would have been evaluated, but
|
381 |
+
it wasn't so we must judiciously extract the numbers and reconstruct
|
382 |
+
the object. This is *not* simply replacing numbers with evaluated
|
383 |
+
numbers. Numbers should be handled in the largest pure-number
|
384 |
+
expression as possible. So the code below separates ``self`` into
|
385 |
+
number and non-number parts and evaluates the number parts and
|
386 |
+
walks the args of the non-number part recursively (doing the same
|
387 |
+
thing).
|
388 |
+
"""
|
389 |
+
from .add import Add
|
390 |
+
from .mul import Mul
|
391 |
+
from .symbol import Symbol
|
392 |
+
from .function import AppliedUndef
|
393 |
+
if isinstance(self, (Mul, Add)):
|
394 |
+
x, tail = self.as_independent(Symbol, AppliedUndef)
|
395 |
+
# if x is an AssocOp Function then the _evalf below will
|
396 |
+
# call _eval_evalf (here) so we must break the recursion
|
397 |
+
if not (tail is self.identity or
|
398 |
+
isinstance(x, AssocOp) and x.is_Function or
|
399 |
+
x is self.identity and isinstance(tail, AssocOp)):
|
400 |
+
# here, we have a number so we just call to _evalf with prec;
|
401 |
+
# prec is not the same as n, it is the binary precision so
|
402 |
+
# that's why we don't call to evalf.
|
403 |
+
x = x._evalf(prec) if x is not self.identity else self.identity
|
404 |
+
args = []
|
405 |
+
tail_args = tuple(self.func.make_args(tail))
|
406 |
+
for a in tail_args:
|
407 |
+
# here we call to _eval_evalf since we don't know what we
|
408 |
+
# are dealing with and all other _eval_evalf routines should
|
409 |
+
# be doing the same thing (i.e. taking binary prec and
|
410 |
+
# finding the evalf-able args)
|
411 |
+
newa = a._eval_evalf(prec)
|
412 |
+
if newa is None:
|
413 |
+
args.append(a)
|
414 |
+
else:
|
415 |
+
args.append(newa)
|
416 |
+
return self.func(x, *args)
|
417 |
+
|
418 |
+
# this is the same as above, but there were no pure-number args to
|
419 |
+
# deal with
|
420 |
+
args = []
|
421 |
+
for a in self.args:
|
422 |
+
newa = a._eval_evalf(prec)
|
423 |
+
if newa is None:
|
424 |
+
args.append(a)
|
425 |
+
else:
|
426 |
+
args.append(newa)
|
427 |
+
return self.func(*args)
|
428 |
+
|
429 |
+
@classmethod
|
430 |
+
def make_args(cls, expr):
|
431 |
+
"""
|
432 |
+
Return a sequence of elements `args` such that cls(*args) == expr
|
433 |
+
|
434 |
+
Examples
|
435 |
+
========
|
436 |
+
|
437 |
+
>>> from sympy import Symbol, Mul, Add
|
438 |
+
>>> x, y = map(Symbol, 'xy')
|
439 |
+
|
440 |
+
>>> Mul.make_args(x*y)
|
441 |
+
(x, y)
|
442 |
+
>>> Add.make_args(x*y)
|
443 |
+
(x*y,)
|
444 |
+
>>> set(Add.make_args(x*y + y)) == set([y, x*y])
|
445 |
+
True
|
446 |
+
|
447 |
+
"""
|
448 |
+
if isinstance(expr, cls):
|
449 |
+
return expr.args
|
450 |
+
else:
|
451 |
+
return (sympify(expr),)
|
452 |
+
|
453 |
+
def doit(self, **hints):
|
454 |
+
if hints.get('deep', True):
|
455 |
+
terms = [term.doit(**hints) for term in self.args]
|
456 |
+
else:
|
457 |
+
terms = self.args
|
458 |
+
return self.func(*terms, evaluate=True)
|
459 |
+
|
460 |
+
class ShortCircuit(Exception):
|
461 |
+
pass
|
462 |
+
|
463 |
+
|
464 |
+
class LatticeOp(AssocOp):
|
465 |
+
"""
|
466 |
+
Join/meet operations of an algebraic lattice[1].
|
467 |
+
|
468 |
+
Explanation
|
469 |
+
===========
|
470 |
+
|
471 |
+
These binary operations are associative (op(op(a, b), c) = op(a, op(b, c))),
|
472 |
+
commutative (op(a, b) = op(b, a)) and idempotent (op(a, a) = op(a) = a).
|
473 |
+
Common examples are AND, OR, Union, Intersection, max or min. They have an
|
474 |
+
identity element (op(identity, a) = a) and an absorbing element
|
475 |
+
conventionally called zero (op(zero, a) = zero).
|
476 |
+
|
477 |
+
This is an abstract base class, concrete derived classes must declare
|
478 |
+
attributes zero and identity. All defining properties are then respected.
|
479 |
+
|
480 |
+
Examples
|
481 |
+
========
|
482 |
+
|
483 |
+
>>> from sympy import Integer
|
484 |
+
>>> from sympy.core.operations import LatticeOp
|
485 |
+
>>> class my_join(LatticeOp):
|
486 |
+
... zero = Integer(0)
|
487 |
+
... identity = Integer(1)
|
488 |
+
>>> my_join(2, 3) == my_join(3, 2)
|
489 |
+
True
|
490 |
+
>>> my_join(2, my_join(3, 4)) == my_join(2, 3, 4)
|
491 |
+
True
|
492 |
+
>>> my_join(0, 1, 4, 2, 3, 4)
|
493 |
+
0
|
494 |
+
>>> my_join(1, 2)
|
495 |
+
2
|
496 |
+
|
497 |
+
References
|
498 |
+
==========
|
499 |
+
|
500 |
+
.. [1] https://en.wikipedia.org/wiki/Lattice_%28order%29
|
501 |
+
"""
|
502 |
+
|
503 |
+
is_commutative = True
|
504 |
+
|
505 |
+
def __new__(cls, *args, **options):
|
506 |
+
args = (_sympify_(arg) for arg in args)
|
507 |
+
|
508 |
+
try:
|
509 |
+
# /!\ args is a generator and _new_args_filter
|
510 |
+
# must be careful to handle as such; this
|
511 |
+
# is done so short-circuiting can be done
|
512 |
+
# without having to sympify all values
|
513 |
+
_args = frozenset(cls._new_args_filter(args))
|
514 |
+
except ShortCircuit:
|
515 |
+
return sympify(cls.zero)
|
516 |
+
if not _args:
|
517 |
+
return sympify(cls.identity)
|
518 |
+
elif len(_args) == 1:
|
519 |
+
return set(_args).pop()
|
520 |
+
else:
|
521 |
+
# XXX in almost every other case for __new__, *_args is
|
522 |
+
# passed along, but the expectation here is for _args
|
523 |
+
obj = super(AssocOp, cls).__new__(cls, *ordered(_args))
|
524 |
+
obj._argset = _args
|
525 |
+
return obj
|
526 |
+
|
527 |
+
@classmethod
|
528 |
+
def _new_args_filter(cls, arg_sequence, call_cls=None):
|
529 |
+
"""Generator filtering args"""
|
530 |
+
ncls = call_cls or cls
|
531 |
+
for arg in arg_sequence:
|
532 |
+
if arg == ncls.zero:
|
533 |
+
raise ShortCircuit(arg)
|
534 |
+
elif arg == ncls.identity:
|
535 |
+
continue
|
536 |
+
elif arg.func == ncls:
|
537 |
+
yield from arg.args
|
538 |
+
else:
|
539 |
+
yield arg
|
540 |
+
|
541 |
+
@classmethod
|
542 |
+
def make_args(cls, expr):
|
543 |
+
"""
|
544 |
+
Return a set of args such that cls(*arg_set) == expr.
|
545 |
+
"""
|
546 |
+
if isinstance(expr, cls):
|
547 |
+
return expr._argset
|
548 |
+
else:
|
549 |
+
return frozenset([sympify(expr)])
|
550 |
+
|
551 |
+
@staticmethod
|
552 |
+
def _compare_pretty(a, b):
|
553 |
+
return (str(a) > str(b)) - (str(a) < str(b))
|
554 |
+
|
555 |
+
|
556 |
+
class AssocOpDispatcher:
|
557 |
+
"""
|
558 |
+
Handler dispatcher for associative operators
|
559 |
+
|
560 |
+
.. notes::
|
561 |
+
This approach is experimental, and can be replaced or deleted in the future.
|
562 |
+
See https://github.com/sympy/sympy/pull/19463.
|
563 |
+
|
564 |
+
Explanation
|
565 |
+
===========
|
566 |
+
|
567 |
+
If arguments of different types are passed, the classes which handle the operation for each type
|
568 |
+
are collected. Then, a class which performs the operation is selected by recursive binary dispatching.
|
569 |
+
Dispatching relation can be registered by ``register_handlerclass`` method.
|
570 |
+
|
571 |
+
Priority registration is unordered. You cannot make ``A*B`` and ``B*A`` refer to
|
572 |
+
different handler classes. All logic dealing with the order of arguments must be implemented
|
573 |
+
in the handler class.
|
574 |
+
|
575 |
+
Examples
|
576 |
+
========
|
577 |
+
|
578 |
+
>>> from sympy import Add, Expr, Symbol
|
579 |
+
>>> from sympy.core.add import add
|
580 |
+
|
581 |
+
>>> class NewExpr(Expr):
|
582 |
+
... @property
|
583 |
+
... def _add_handler(self):
|
584 |
+
... return NewAdd
|
585 |
+
>>> class NewAdd(NewExpr, Add):
|
586 |
+
... pass
|
587 |
+
>>> add.register_handlerclass((Add, NewAdd), NewAdd)
|
588 |
+
|
589 |
+
>>> a, b = Symbol('a'), NewExpr()
|
590 |
+
>>> add(a, b) == NewAdd(a, b)
|
591 |
+
True
|
592 |
+
|
593 |
+
"""
|
594 |
+
def __init__(self, name, doc=None):
|
595 |
+
self.name = name
|
596 |
+
self.doc = doc
|
597 |
+
self.handlerattr = "_%s_handler" % name
|
598 |
+
self._handlergetter = attrgetter(self.handlerattr)
|
599 |
+
self._dispatcher = Dispatcher(name)
|
600 |
+
|
601 |
+
def __repr__(self):
|
602 |
+
return "<dispatched %s>" % self.name
|
603 |
+
|
604 |
+
def register_handlerclass(self, classes, typ, on_ambiguity=ambiguity_register_error_ignore_dup):
|
605 |
+
"""
|
606 |
+
Register the handler class for two classes, in both straight and reversed order.
|
607 |
+
|
608 |
+
Paramteters
|
609 |
+
===========
|
610 |
+
|
611 |
+
classes : tuple of two types
|
612 |
+
Classes who are compared with each other.
|
613 |
+
|
614 |
+
typ:
|
615 |
+
Class which is registered to represent *cls1* and *cls2*.
|
616 |
+
Handler method of *self* must be implemented in this class.
|
617 |
+
"""
|
618 |
+
if not len(classes) == 2:
|
619 |
+
raise RuntimeError(
|
620 |
+
"Only binary dispatch is supported, but got %s types: <%s>." % (
|
621 |
+
len(classes), str_signature(classes)
|
622 |
+
))
|
623 |
+
if len(set(classes)) == 1:
|
624 |
+
raise RuntimeError(
|
625 |
+
"Duplicate types <%s> cannot be dispatched." % str_signature(classes)
|
626 |
+
)
|
627 |
+
self._dispatcher.add(tuple(classes), typ, on_ambiguity=on_ambiguity)
|
628 |
+
self._dispatcher.add(tuple(reversed(classes)), typ, on_ambiguity=on_ambiguity)
|
629 |
+
|
630 |
+
@cacheit
|
631 |
+
def __call__(self, *args, _sympify=True, **kwargs):
|
632 |
+
"""
|
633 |
+
Parameters
|
634 |
+
==========
|
635 |
+
|
636 |
+
*args :
|
637 |
+
Arguments which are operated
|
638 |
+
"""
|
639 |
+
if _sympify:
|
640 |
+
args = tuple(map(_sympify_, args))
|
641 |
+
handlers = frozenset(map(self._handlergetter, args))
|
642 |
+
|
643 |
+
# no need to sympify again
|
644 |
+
return self.dispatch(handlers)(*args, _sympify=False, **kwargs)
|
645 |
+
|
646 |
+
@cacheit
|
647 |
+
def dispatch(self, handlers):
|
648 |
+
"""
|
649 |
+
Select the handler class, and return its handler method.
|
650 |
+
"""
|
651 |
+
|
652 |
+
# Quick exit for the case where all handlers are same
|
653 |
+
if len(handlers) == 1:
|
654 |
+
h, = handlers
|
655 |
+
if not isinstance(h, type):
|
656 |
+
raise RuntimeError("Handler {!r} is not a type.".format(h))
|
657 |
+
return h
|
658 |
+
|
659 |
+
# Recursively select with registered binary priority
|
660 |
+
for i, typ in enumerate(handlers):
|
661 |
+
|
662 |
+
if not isinstance(typ, type):
|
663 |
+
raise RuntimeError("Handler {!r} is not a type.".format(typ))
|
664 |
+
|
665 |
+
if i == 0:
|
666 |
+
handler = typ
|
667 |
+
else:
|
668 |
+
prev_handler = handler
|
669 |
+
handler = self._dispatcher.dispatch(prev_handler, typ)
|
670 |
+
|
671 |
+
if not isinstance(handler, type):
|
672 |
+
raise RuntimeError(
|
673 |
+
"Dispatcher for {!r} and {!r} must return a type, but got {!r}".format(
|
674 |
+
prev_handler, typ, handler
|
675 |
+
))
|
676 |
+
|
677 |
+
# return handler class
|
678 |
+
return handler
|
679 |
+
|
680 |
+
@property
|
681 |
+
def __doc__(self):
|
682 |
+
docs = [
|
683 |
+
"Multiply dispatched associative operator: %s" % self.name,
|
684 |
+
"Note that support for this is experimental, see the docs for :class:`AssocOpDispatcher` for details"
|
685 |
+
]
|
686 |
+
|
687 |
+
if self.doc:
|
688 |
+
docs.append(self.doc)
|
689 |
+
|
690 |
+
s = "Registered handler classes\n"
|
691 |
+
s += '=' * len(s)
|
692 |
+
docs.append(s)
|
693 |
+
|
694 |
+
amb_sigs = []
|
695 |
+
|
696 |
+
typ_sigs = defaultdict(list)
|
697 |
+
for sigs in self._dispatcher.ordering[::-1]:
|
698 |
+
key = self._dispatcher.funcs[sigs]
|
699 |
+
typ_sigs[key].append(sigs)
|
700 |
+
|
701 |
+
for typ, sigs in typ_sigs.items():
|
702 |
+
|
703 |
+
sigs_str = ', '.join('<%s>' % str_signature(sig) for sig in sigs)
|
704 |
+
|
705 |
+
if isinstance(typ, RaiseNotImplementedError):
|
706 |
+
amb_sigs.append(sigs_str)
|
707 |
+
continue
|
708 |
+
|
709 |
+
s = 'Inputs: %s\n' % sigs_str
|
710 |
+
s += '-' * len(s) + '\n'
|
711 |
+
s += typ.__name__
|
712 |
+
docs.append(s)
|
713 |
+
|
714 |
+
if amb_sigs:
|
715 |
+
s = "Ambiguous handler classes\n"
|
716 |
+
s += '=' * len(s)
|
717 |
+
docs.append(s)
|
718 |
+
|
719 |
+
s = '\n'.join(amb_sigs)
|
720 |
+
docs.append(s)
|
721 |
+
|
722 |
+
return '\n\n'.join(docs)
|
venv/lib/python3.10/site-packages/sympy/core/random.py
ADDED
@@ -0,0 +1,227 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
When you need to use random numbers in SymPy library code, import from here
|
3 |
+
so there is only one generator working for SymPy. Imports from here should
|
4 |
+
behave the same as if they were being imported from Python's random module.
|
5 |
+
But only the routines currently used in SymPy are included here. To use others
|
6 |
+
import ``rng`` and access the method directly. For example, to capture the
|
7 |
+
current state of the generator use ``rng.getstate()``.
|
8 |
+
|
9 |
+
There is intentionally no Random to import from here. If you want
|
10 |
+
to control the state of the generator, import ``seed`` and call it
|
11 |
+
with or without an argument to set the state.
|
12 |
+
|
13 |
+
Examples
|
14 |
+
========
|
15 |
+
|
16 |
+
>>> from sympy.core.random import random, seed
|
17 |
+
>>> assert random() < 1
|
18 |
+
>>> seed(1); a = random()
|
19 |
+
>>> b = random()
|
20 |
+
>>> seed(1); c = random()
|
21 |
+
>>> assert a == c
|
22 |
+
>>> assert a != b # remote possibility this will fail
|
23 |
+
|
24 |
+
"""
|
25 |
+
from sympy.utilities.iterables import is_sequence
|
26 |
+
from sympy.utilities.misc import as_int
|
27 |
+
|
28 |
+
import random as _random
|
29 |
+
rng = _random.Random()
|
30 |
+
|
31 |
+
choice = rng.choice
|
32 |
+
random = rng.random
|
33 |
+
randint = rng.randint
|
34 |
+
randrange = rng.randrange
|
35 |
+
sample = rng.sample
|
36 |
+
# seed = rng.seed
|
37 |
+
shuffle = rng.shuffle
|
38 |
+
uniform = rng.uniform
|
39 |
+
|
40 |
+
_assumptions_rng = _random.Random()
|
41 |
+
_assumptions_shuffle = _assumptions_rng.shuffle
|
42 |
+
|
43 |
+
|
44 |
+
def seed(a=None, version=2):
|
45 |
+
rng.seed(a=a, version=version)
|
46 |
+
_assumptions_rng.seed(a=a, version=version)
|
47 |
+
|
48 |
+
|
49 |
+
def random_complex_number(a=2, b=-1, c=3, d=1, rational=False, tolerance=None):
|
50 |
+
"""
|
51 |
+
Return a random complex number.
|
52 |
+
|
53 |
+
To reduce chance of hitting branch cuts or anything, we guarantee
|
54 |
+
b <= Im z <= d, a <= Re z <= c
|
55 |
+
|
56 |
+
When rational is True, a rational approximation to a random number
|
57 |
+
is obtained within specified tolerance, if any.
|
58 |
+
"""
|
59 |
+
from sympy.core.numbers import I
|
60 |
+
from sympy.simplify.simplify import nsimplify
|
61 |
+
A, B = uniform(a, c), uniform(b, d)
|
62 |
+
if not rational:
|
63 |
+
return A + I*B
|
64 |
+
return (nsimplify(A, rational=True, tolerance=tolerance) +
|
65 |
+
I*nsimplify(B, rational=True, tolerance=tolerance))
|
66 |
+
|
67 |
+
|
68 |
+
def verify_numerically(f, g, z=None, tol=1.0e-6, a=2, b=-1, c=3, d=1):
|
69 |
+
"""
|
70 |
+
Test numerically that f and g agree when evaluated in the argument z.
|
71 |
+
|
72 |
+
If z is None, all symbols will be tested. This routine does not test
|
73 |
+
whether there are Floats present with precision higher than 15 digits
|
74 |
+
so if there are, your results may not be what you expect due to round-
|
75 |
+
off errors.
|
76 |
+
|
77 |
+
Examples
|
78 |
+
========
|
79 |
+
|
80 |
+
>>> from sympy import sin, cos
|
81 |
+
>>> from sympy.abc import x
|
82 |
+
>>> from sympy.core.random import verify_numerically as tn
|
83 |
+
>>> tn(sin(x)**2 + cos(x)**2, 1, x)
|
84 |
+
True
|
85 |
+
"""
|
86 |
+
from sympy.core.symbol import Symbol
|
87 |
+
from sympy.core.sympify import sympify
|
88 |
+
from sympy.core.numbers import comp
|
89 |
+
f, g = (sympify(i) for i in (f, g))
|
90 |
+
if z is None:
|
91 |
+
z = f.free_symbols | g.free_symbols
|
92 |
+
elif isinstance(z, Symbol):
|
93 |
+
z = [z]
|
94 |
+
reps = list(zip(z, [random_complex_number(a, b, c, d) for _ in z]))
|
95 |
+
z1 = f.subs(reps).n()
|
96 |
+
z2 = g.subs(reps).n()
|
97 |
+
return comp(z1, z2, tol)
|
98 |
+
|
99 |
+
|
100 |
+
def test_derivative_numerically(f, z, tol=1.0e-6, a=2, b=-1, c=3, d=1):
|
101 |
+
"""
|
102 |
+
Test numerically that the symbolically computed derivative of f
|
103 |
+
with respect to z is correct.
|
104 |
+
|
105 |
+
This routine does not test whether there are Floats present with
|
106 |
+
precision higher than 15 digits so if there are, your results may
|
107 |
+
not be what you expect due to round-off errors.
|
108 |
+
|
109 |
+
Examples
|
110 |
+
========
|
111 |
+
|
112 |
+
>>> from sympy import sin
|
113 |
+
>>> from sympy.abc import x
|
114 |
+
>>> from sympy.core.random import test_derivative_numerically as td
|
115 |
+
>>> td(sin(x), x)
|
116 |
+
True
|
117 |
+
"""
|
118 |
+
from sympy.core.numbers import comp
|
119 |
+
from sympy.core.function import Derivative
|
120 |
+
z0 = random_complex_number(a, b, c, d)
|
121 |
+
f1 = f.diff(z).subs(z, z0)
|
122 |
+
f2 = Derivative(f, z).doit_numerically(z0)
|
123 |
+
return comp(f1.n(), f2.n(), tol)
|
124 |
+
|
125 |
+
|
126 |
+
def _randrange(seed=None):
|
127 |
+
"""Return a randrange generator.
|
128 |
+
|
129 |
+
``seed`` can be
|
130 |
+
|
131 |
+
* None - return randomly seeded generator
|
132 |
+
* int - return a generator seeded with the int
|
133 |
+
* list - the values to be returned will be taken from the list
|
134 |
+
in the order given; the provided list is not modified.
|
135 |
+
|
136 |
+
Examples
|
137 |
+
========
|
138 |
+
|
139 |
+
>>> from sympy.core.random import _randrange
|
140 |
+
>>> rr = _randrange()
|
141 |
+
>>> rr(1000) # doctest: +SKIP
|
142 |
+
999
|
143 |
+
>>> rr = _randrange(3)
|
144 |
+
>>> rr(1000) # doctest: +SKIP
|
145 |
+
238
|
146 |
+
>>> rr = _randrange([0, 5, 1, 3, 4])
|
147 |
+
>>> rr(3), rr(3)
|
148 |
+
(0, 1)
|
149 |
+
"""
|
150 |
+
if seed is None:
|
151 |
+
return randrange
|
152 |
+
elif isinstance(seed, int):
|
153 |
+
rng.seed(seed)
|
154 |
+
return randrange
|
155 |
+
elif is_sequence(seed):
|
156 |
+
seed = list(seed) # make a copy
|
157 |
+
seed.reverse()
|
158 |
+
|
159 |
+
def give(a, b=None, seq=seed):
|
160 |
+
if b is None:
|
161 |
+
a, b = 0, a
|
162 |
+
a, b = as_int(a), as_int(b)
|
163 |
+
w = b - a
|
164 |
+
if w < 1:
|
165 |
+
raise ValueError('_randrange got empty range')
|
166 |
+
try:
|
167 |
+
x = seq.pop()
|
168 |
+
except IndexError:
|
169 |
+
raise ValueError('_randrange sequence was too short')
|
170 |
+
if a <= x < b:
|
171 |
+
return x
|
172 |
+
else:
|
173 |
+
return give(a, b, seq)
|
174 |
+
return give
|
175 |
+
else:
|
176 |
+
raise ValueError('_randrange got an unexpected seed')
|
177 |
+
|
178 |
+
|
179 |
+
def _randint(seed=None):
|
180 |
+
"""Return a randint generator.
|
181 |
+
|
182 |
+
``seed`` can be
|
183 |
+
|
184 |
+
* None - return randomly seeded generator
|
185 |
+
* int - return a generator seeded with the int
|
186 |
+
* list - the values to be returned will be taken from the list
|
187 |
+
in the order given; the provided list is not modified.
|
188 |
+
|
189 |
+
Examples
|
190 |
+
========
|
191 |
+
|
192 |
+
>>> from sympy.core.random import _randint
|
193 |
+
>>> ri = _randint()
|
194 |
+
>>> ri(1, 1000) # doctest: +SKIP
|
195 |
+
999
|
196 |
+
>>> ri = _randint(3)
|
197 |
+
>>> ri(1, 1000) # doctest: +SKIP
|
198 |
+
238
|
199 |
+
>>> ri = _randint([0, 5, 1, 2, 4])
|
200 |
+
>>> ri(1, 3), ri(1, 3)
|
201 |
+
(1, 2)
|
202 |
+
"""
|
203 |
+
if seed is None:
|
204 |
+
return randint
|
205 |
+
elif isinstance(seed, int):
|
206 |
+
rng.seed(seed)
|
207 |
+
return randint
|
208 |
+
elif is_sequence(seed):
|
209 |
+
seed = list(seed) # make a copy
|
210 |
+
seed.reverse()
|
211 |
+
|
212 |
+
def give(a, b, seq=seed):
|
213 |
+
a, b = as_int(a), as_int(b)
|
214 |
+
w = b - a
|
215 |
+
if w < 0:
|
216 |
+
raise ValueError('_randint got empty range')
|
217 |
+
try:
|
218 |
+
x = seq.pop()
|
219 |
+
except IndexError:
|
220 |
+
raise ValueError('_randint sequence was too short')
|
221 |
+
if a <= x <= b:
|
222 |
+
return x
|
223 |
+
else:
|
224 |
+
return give(a, b, seq)
|
225 |
+
return give
|
226 |
+
else:
|
227 |
+
raise ValueError('_randint got an unexpected seed')
|
venv/lib/python3.10/site-packages/sympy/core/rules.py
ADDED
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Replacement rules.
|
3 |
+
"""
|
4 |
+
|
5 |
+
class Transform:
|
6 |
+
"""
|
7 |
+
Immutable mapping that can be used as a generic transformation rule.
|
8 |
+
|
9 |
+
Parameters
|
10 |
+
==========
|
11 |
+
|
12 |
+
transform : callable
|
13 |
+
Computes the value corresponding to any key.
|
14 |
+
|
15 |
+
filter : callable, optional
|
16 |
+
If supplied, specifies which objects are in the mapping.
|
17 |
+
|
18 |
+
Examples
|
19 |
+
========
|
20 |
+
|
21 |
+
>>> from sympy.core.rules import Transform
|
22 |
+
>>> from sympy.abc import x
|
23 |
+
|
24 |
+
This Transform will return, as a value, one more than the key:
|
25 |
+
|
26 |
+
>>> add1 = Transform(lambda x: x + 1)
|
27 |
+
>>> add1[1]
|
28 |
+
2
|
29 |
+
>>> add1[x]
|
30 |
+
x + 1
|
31 |
+
|
32 |
+
By default, all values are considered to be in the dictionary. If a filter
|
33 |
+
is supplied, only the objects for which it returns True are considered as
|
34 |
+
being in the dictionary:
|
35 |
+
|
36 |
+
>>> add1_odd = Transform(lambda x: x + 1, lambda x: x%2 == 1)
|
37 |
+
>>> 2 in add1_odd
|
38 |
+
False
|
39 |
+
>>> add1_odd.get(2, 0)
|
40 |
+
0
|
41 |
+
>>> 3 in add1_odd
|
42 |
+
True
|
43 |
+
>>> add1_odd[3]
|
44 |
+
4
|
45 |
+
>>> add1_odd.get(3, 0)
|
46 |
+
4
|
47 |
+
"""
|
48 |
+
|
49 |
+
def __init__(self, transform, filter=lambda x: True):
|
50 |
+
self._transform = transform
|
51 |
+
self._filter = filter
|
52 |
+
|
53 |
+
def __contains__(self, item):
|
54 |
+
return self._filter(item)
|
55 |
+
|
56 |
+
def __getitem__(self, key):
|
57 |
+
if self._filter(key):
|
58 |
+
return self._transform(key)
|
59 |
+
else:
|
60 |
+
raise KeyError(key)
|
61 |
+
|
62 |
+
def get(self, item, default=None):
|
63 |
+
if item in self:
|
64 |
+
return self[item]
|
65 |
+
else:
|
66 |
+
return default
|
venv/lib/python3.10/site-packages/sympy/core/singleton.py
ADDED
@@ -0,0 +1,174 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Singleton mechanism"""
|
2 |
+
|
3 |
+
|
4 |
+
from .core import Registry
|
5 |
+
from .sympify import sympify
|
6 |
+
|
7 |
+
|
8 |
+
class SingletonRegistry(Registry):
|
9 |
+
"""
|
10 |
+
The registry for the singleton classes (accessible as ``S``).
|
11 |
+
|
12 |
+
Explanation
|
13 |
+
===========
|
14 |
+
|
15 |
+
This class serves as two separate things.
|
16 |
+
|
17 |
+
The first thing it is is the ``SingletonRegistry``. Several classes in
|
18 |
+
SymPy appear so often that they are singletonized, that is, using some
|
19 |
+
metaprogramming they are made so that they can only be instantiated once
|
20 |
+
(see the :class:`sympy.core.singleton.Singleton` class for details). For
|
21 |
+
instance, every time you create ``Integer(0)``, this will return the same
|
22 |
+
instance, :class:`sympy.core.numbers.Zero`. All singleton instances are
|
23 |
+
attributes of the ``S`` object, so ``Integer(0)`` can also be accessed as
|
24 |
+
``S.Zero``.
|
25 |
+
|
26 |
+
Singletonization offers two advantages: it saves memory, and it allows
|
27 |
+
fast comparison. It saves memory because no matter how many times the
|
28 |
+
singletonized objects appear in expressions in memory, they all point to
|
29 |
+
the same single instance in memory. The fast comparison comes from the
|
30 |
+
fact that you can use ``is`` to compare exact instances in Python
|
31 |
+
(usually, you need to use ``==`` to compare things). ``is`` compares
|
32 |
+
objects by memory address, and is very fast.
|
33 |
+
|
34 |
+
Examples
|
35 |
+
========
|
36 |
+
|
37 |
+
>>> from sympy import S, Integer
|
38 |
+
>>> a = Integer(0)
|
39 |
+
>>> a is S.Zero
|
40 |
+
True
|
41 |
+
|
42 |
+
For the most part, the fact that certain objects are singletonized is an
|
43 |
+
implementation detail that users should not need to worry about. In SymPy
|
44 |
+
library code, ``is`` comparison is often used for performance purposes
|
45 |
+
The primary advantage of ``S`` for end users is the convenient access to
|
46 |
+
certain instances that are otherwise difficult to type, like ``S.Half``
|
47 |
+
(instead of ``Rational(1, 2)``).
|
48 |
+
|
49 |
+
When using ``is`` comparison, make sure the argument is sympified. For
|
50 |
+
instance,
|
51 |
+
|
52 |
+
>>> x = 0
|
53 |
+
>>> x is S.Zero
|
54 |
+
False
|
55 |
+
|
56 |
+
This problem is not an issue when using ``==``, which is recommended for
|
57 |
+
most use-cases:
|
58 |
+
|
59 |
+
>>> 0 == S.Zero
|
60 |
+
True
|
61 |
+
|
62 |
+
The second thing ``S`` is is a shortcut for
|
63 |
+
:func:`sympy.core.sympify.sympify`. :func:`sympy.core.sympify.sympify` is
|
64 |
+
the function that converts Python objects such as ``int(1)`` into SymPy
|
65 |
+
objects such as ``Integer(1)``. It also converts the string form of an
|
66 |
+
expression into a SymPy expression, like ``sympify("x**2")`` ->
|
67 |
+
``Symbol("x")**2``. ``S(1)`` is the same thing as ``sympify(1)``
|
68 |
+
(basically, ``S.__call__`` has been defined to call ``sympify``).
|
69 |
+
|
70 |
+
This is for convenience, since ``S`` is a single letter. It's mostly
|
71 |
+
useful for defining rational numbers. Consider an expression like ``x +
|
72 |
+
1/2``. If you enter this directly in Python, it will evaluate the ``1/2``
|
73 |
+
and give ``0.5``, because both arguments are ints (see also
|
74 |
+
:ref:`tutorial-gotchas-final-notes`). However, in SymPy, you usually want
|
75 |
+
the quotient of two integers to give an exact rational number. The way
|
76 |
+
Python's evaluation works, at least one side of an operator needs to be a
|
77 |
+
SymPy object for the SymPy evaluation to take over. You could write this
|
78 |
+
as ``x + Rational(1, 2)``, but this is a lot more typing. A shorter
|
79 |
+
version is ``x + S(1)/2``. Since ``S(1)`` returns ``Integer(1)``, the
|
80 |
+
division will return a ``Rational`` type, since it will call
|
81 |
+
``Integer.__truediv__``, which knows how to return a ``Rational``.
|
82 |
+
|
83 |
+
"""
|
84 |
+
__slots__ = ()
|
85 |
+
|
86 |
+
# Also allow things like S(5)
|
87 |
+
__call__ = staticmethod(sympify)
|
88 |
+
|
89 |
+
def __init__(self):
|
90 |
+
self._classes_to_install = {}
|
91 |
+
# Dict of classes that have been registered, but that have not have been
|
92 |
+
# installed as an attribute of this SingletonRegistry.
|
93 |
+
# Installation automatically happens at the first attempt to access the
|
94 |
+
# attribute.
|
95 |
+
# The purpose of this is to allow registration during class
|
96 |
+
# initialization during import, but not trigger object creation until
|
97 |
+
# actual use (which should not happen until after all imports are
|
98 |
+
# finished).
|
99 |
+
|
100 |
+
def register(self, cls):
|
101 |
+
# Make sure a duplicate class overwrites the old one
|
102 |
+
if hasattr(self, cls.__name__):
|
103 |
+
delattr(self, cls.__name__)
|
104 |
+
self._classes_to_install[cls.__name__] = cls
|
105 |
+
|
106 |
+
def __getattr__(self, name):
|
107 |
+
"""Python calls __getattr__ if no attribute of that name was installed
|
108 |
+
yet.
|
109 |
+
|
110 |
+
Explanation
|
111 |
+
===========
|
112 |
+
|
113 |
+
This __getattr__ checks whether a class with the requested name was
|
114 |
+
already registered but not installed; if no, raises an AttributeError.
|
115 |
+
Otherwise, retrieves the class, calculates its singleton value, installs
|
116 |
+
it as an attribute of the given name, and unregisters the class."""
|
117 |
+
if name not in self._classes_to_install:
|
118 |
+
raise AttributeError(
|
119 |
+
"Attribute '%s' was not installed on SymPy registry %s" % (
|
120 |
+
name, self))
|
121 |
+
class_to_install = self._classes_to_install[name]
|
122 |
+
value_to_install = class_to_install()
|
123 |
+
self.__setattr__(name, value_to_install)
|
124 |
+
del self._classes_to_install[name]
|
125 |
+
return value_to_install
|
126 |
+
|
127 |
+
def __repr__(self):
|
128 |
+
return "S"
|
129 |
+
|
130 |
+
S = SingletonRegistry()
|
131 |
+
|
132 |
+
|
133 |
+
class Singleton(type):
|
134 |
+
"""
|
135 |
+
Metaclass for singleton classes.
|
136 |
+
|
137 |
+
Explanation
|
138 |
+
===========
|
139 |
+
|
140 |
+
A singleton class has only one instance which is returned every time the
|
141 |
+
class is instantiated. Additionally, this instance can be accessed through
|
142 |
+
the global registry object ``S`` as ``S.<class_name>``.
|
143 |
+
|
144 |
+
Examples
|
145 |
+
========
|
146 |
+
|
147 |
+
>>> from sympy import S, Basic
|
148 |
+
>>> from sympy.core.singleton import Singleton
|
149 |
+
>>> class MySingleton(Basic, metaclass=Singleton):
|
150 |
+
... pass
|
151 |
+
>>> Basic() is Basic()
|
152 |
+
False
|
153 |
+
>>> MySingleton() is MySingleton()
|
154 |
+
True
|
155 |
+
>>> S.MySingleton is MySingleton()
|
156 |
+
True
|
157 |
+
|
158 |
+
Notes
|
159 |
+
=====
|
160 |
+
|
161 |
+
Instance creation is delayed until the first time the value is accessed.
|
162 |
+
(SymPy versions before 1.0 would create the instance during class
|
163 |
+
creation time, which would be prone to import cycles.)
|
164 |
+
"""
|
165 |
+
def __init__(cls, *args, **kwargs):
|
166 |
+
cls._instance = obj = Basic.__new__(cls)
|
167 |
+
cls.__new__ = lambda cls: obj
|
168 |
+
cls.__getnewargs__ = lambda obj: ()
|
169 |
+
cls.__getstate__ = lambda obj: None
|
170 |
+
S.register(cls)
|
171 |
+
|
172 |
+
|
173 |
+
# Delayed to avoid cyclic import
|
174 |
+
from .basic import Basic
|
venv/lib/python3.10/site-packages/sympy/core/symbol.py
ADDED
@@ -0,0 +1,945 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from __future__ import annotations
|
2 |
+
|
3 |
+
from .assumptions import StdFactKB, _assume_defined
|
4 |
+
from .basic import Basic, Atom
|
5 |
+
from .cache import cacheit
|
6 |
+
from .containers import Tuple
|
7 |
+
from .expr import Expr, AtomicExpr
|
8 |
+
from .function import AppliedUndef, FunctionClass
|
9 |
+
from .kind import NumberKind, UndefinedKind
|
10 |
+
from .logic import fuzzy_bool
|
11 |
+
from .singleton import S
|
12 |
+
from .sorting import ordered
|
13 |
+
from .sympify import sympify
|
14 |
+
from sympy.logic.boolalg import Boolean
|
15 |
+
from sympy.utilities.iterables import sift, is_sequence
|
16 |
+
from sympy.utilities.misc import filldedent
|
17 |
+
|
18 |
+
import string
|
19 |
+
import re as _re
|
20 |
+
import random
|
21 |
+
from itertools import product
|
22 |
+
from typing import Any
|
23 |
+
|
24 |
+
|
25 |
+
class Str(Atom):
|
26 |
+
"""
|
27 |
+
Represents string in SymPy.
|
28 |
+
|
29 |
+
Explanation
|
30 |
+
===========
|
31 |
+
|
32 |
+
Previously, ``Symbol`` was used where string is needed in ``args`` of SymPy
|
33 |
+
objects, e.g. denoting the name of the instance. However, since ``Symbol``
|
34 |
+
represents mathematical scalar, this class should be used instead.
|
35 |
+
|
36 |
+
"""
|
37 |
+
__slots__ = ('name',)
|
38 |
+
|
39 |
+
def __new__(cls, name, **kwargs):
|
40 |
+
if not isinstance(name, str):
|
41 |
+
raise TypeError("name should be a string, not %s" % repr(type(name)))
|
42 |
+
obj = Expr.__new__(cls, **kwargs)
|
43 |
+
obj.name = name
|
44 |
+
return obj
|
45 |
+
|
46 |
+
def __getnewargs__(self):
|
47 |
+
return (self.name,)
|
48 |
+
|
49 |
+
def _hashable_content(self):
|
50 |
+
return (self.name,)
|
51 |
+
|
52 |
+
|
53 |
+
def _filter_assumptions(kwargs):
|
54 |
+
"""Split the given dict into assumptions and non-assumptions.
|
55 |
+
Keys are taken as assumptions if they correspond to an
|
56 |
+
entry in ``_assume_defined``.
|
57 |
+
"""
|
58 |
+
assumptions, nonassumptions = map(dict, sift(kwargs.items(),
|
59 |
+
lambda i: i[0] in _assume_defined,
|
60 |
+
binary=True))
|
61 |
+
Symbol._sanitize(assumptions)
|
62 |
+
return assumptions, nonassumptions
|
63 |
+
|
64 |
+
def _symbol(s, matching_symbol=None, **assumptions):
|
65 |
+
"""Return s if s is a Symbol, else if s is a string, return either
|
66 |
+
the matching_symbol if the names are the same or else a new symbol
|
67 |
+
with the same assumptions as the matching symbol (or the
|
68 |
+
assumptions as provided).
|
69 |
+
|
70 |
+
Examples
|
71 |
+
========
|
72 |
+
|
73 |
+
>>> from sympy import Symbol
|
74 |
+
>>> from sympy.core.symbol import _symbol
|
75 |
+
>>> _symbol('y')
|
76 |
+
y
|
77 |
+
>>> _.is_real is None
|
78 |
+
True
|
79 |
+
>>> _symbol('y', real=True).is_real
|
80 |
+
True
|
81 |
+
|
82 |
+
>>> x = Symbol('x')
|
83 |
+
>>> _symbol(x, real=True)
|
84 |
+
x
|
85 |
+
>>> _.is_real is None # ignore attribute if s is a Symbol
|
86 |
+
True
|
87 |
+
|
88 |
+
Below, the variable sym has the name 'foo':
|
89 |
+
|
90 |
+
>>> sym = Symbol('foo', real=True)
|
91 |
+
|
92 |
+
Since 'x' is not the same as sym's name, a new symbol is created:
|
93 |
+
|
94 |
+
>>> _symbol('x', sym).name
|
95 |
+
'x'
|
96 |
+
|
97 |
+
It will acquire any assumptions give:
|
98 |
+
|
99 |
+
>>> _symbol('x', sym, real=False).is_real
|
100 |
+
False
|
101 |
+
|
102 |
+
Since 'foo' is the same as sym's name, sym is returned
|
103 |
+
|
104 |
+
>>> _symbol('foo', sym)
|
105 |
+
foo
|
106 |
+
|
107 |
+
Any assumptions given are ignored:
|
108 |
+
|
109 |
+
>>> _symbol('foo', sym, real=False).is_real
|
110 |
+
True
|
111 |
+
|
112 |
+
NB: the symbol here may not be the same as a symbol with the same
|
113 |
+
name defined elsewhere as a result of different assumptions.
|
114 |
+
|
115 |
+
See Also
|
116 |
+
========
|
117 |
+
|
118 |
+
sympy.core.symbol.Symbol
|
119 |
+
|
120 |
+
"""
|
121 |
+
if isinstance(s, str):
|
122 |
+
if matching_symbol and matching_symbol.name == s:
|
123 |
+
return matching_symbol
|
124 |
+
return Symbol(s, **assumptions)
|
125 |
+
elif isinstance(s, Symbol):
|
126 |
+
return s
|
127 |
+
else:
|
128 |
+
raise ValueError('symbol must be string for symbol name or Symbol')
|
129 |
+
|
130 |
+
def uniquely_named_symbol(xname, exprs=(), compare=str, modify=None, **assumptions):
|
131 |
+
"""
|
132 |
+
Return a symbol whose name is derivated from *xname* but is unique
|
133 |
+
from any other symbols in *exprs*.
|
134 |
+
|
135 |
+
*xname* and symbol names in *exprs* are passed to *compare* to be
|
136 |
+
converted to comparable forms. If ``compare(xname)`` is not unique,
|
137 |
+
it is recursively passed to *modify* until unique name is acquired.
|
138 |
+
|
139 |
+
Parameters
|
140 |
+
==========
|
141 |
+
|
142 |
+
xname : str or Symbol
|
143 |
+
Base name for the new symbol.
|
144 |
+
|
145 |
+
exprs : Expr or iterable of Expr
|
146 |
+
Expressions whose symbols are compared to *xname*.
|
147 |
+
|
148 |
+
compare : function
|
149 |
+
Unary function which transforms *xname* and symbol names from
|
150 |
+
*exprs* to comparable form.
|
151 |
+
|
152 |
+
modify : function
|
153 |
+
Unary function which modifies the string. Default is appending
|
154 |
+
the number, or increasing the number if exists.
|
155 |
+
|
156 |
+
Examples
|
157 |
+
========
|
158 |
+
|
159 |
+
By default, a number is appended to *xname* to generate unique name.
|
160 |
+
If the number already exists, it is recursively increased.
|
161 |
+
|
162 |
+
>>> from sympy.core.symbol import uniquely_named_symbol, Symbol
|
163 |
+
>>> uniquely_named_symbol('x', Symbol('x'))
|
164 |
+
x0
|
165 |
+
>>> uniquely_named_symbol('x', (Symbol('x'), Symbol('x0')))
|
166 |
+
x1
|
167 |
+
>>> uniquely_named_symbol('x0', (Symbol('x1'), Symbol('x0')))
|
168 |
+
x2
|
169 |
+
|
170 |
+
Name generation can be controlled by passing *modify* parameter.
|
171 |
+
|
172 |
+
>>> from sympy.abc import x
|
173 |
+
>>> uniquely_named_symbol('x', x, modify=lambda s: 2*s)
|
174 |
+
xx
|
175 |
+
|
176 |
+
"""
|
177 |
+
def numbered_string_incr(s, start=0):
|
178 |
+
if not s:
|
179 |
+
return str(start)
|
180 |
+
i = len(s) - 1
|
181 |
+
while i != -1:
|
182 |
+
if not s[i].isdigit():
|
183 |
+
break
|
184 |
+
i -= 1
|
185 |
+
n = str(int(s[i + 1:] or start - 1) + 1)
|
186 |
+
return s[:i + 1] + n
|
187 |
+
|
188 |
+
default = None
|
189 |
+
if is_sequence(xname):
|
190 |
+
xname, default = xname
|
191 |
+
x = compare(xname)
|
192 |
+
if not exprs:
|
193 |
+
return _symbol(x, default, **assumptions)
|
194 |
+
if not is_sequence(exprs):
|
195 |
+
exprs = [exprs]
|
196 |
+
names = set().union(
|
197 |
+
[i.name for e in exprs for i in e.atoms(Symbol)] +
|
198 |
+
[i.func.name for e in exprs for i in e.atoms(AppliedUndef)])
|
199 |
+
if modify is None:
|
200 |
+
modify = numbered_string_incr
|
201 |
+
while any(x == compare(s) for s in names):
|
202 |
+
x = modify(x)
|
203 |
+
return _symbol(x, default, **assumptions)
|
204 |
+
_uniquely_named_symbol = uniquely_named_symbol
|
205 |
+
|
206 |
+
class Symbol(AtomicExpr, Boolean):
|
207 |
+
"""
|
208 |
+
Assumptions:
|
209 |
+
commutative = True
|
210 |
+
|
211 |
+
You can override the default assumptions in the constructor.
|
212 |
+
|
213 |
+
Examples
|
214 |
+
========
|
215 |
+
|
216 |
+
>>> from sympy import symbols
|
217 |
+
>>> A,B = symbols('A,B', commutative = False)
|
218 |
+
>>> bool(A*B != B*A)
|
219 |
+
True
|
220 |
+
>>> bool(A*B*2 == 2*A*B) == True # multiplication by scalars is commutative
|
221 |
+
True
|
222 |
+
|
223 |
+
"""
|
224 |
+
|
225 |
+
is_comparable = False
|
226 |
+
|
227 |
+
__slots__ = ('name', '_assumptions_orig', '_assumptions0')
|
228 |
+
|
229 |
+
name: str
|
230 |
+
|
231 |
+
is_Symbol = True
|
232 |
+
is_symbol = True
|
233 |
+
|
234 |
+
@property
|
235 |
+
def kind(self):
|
236 |
+
if self.is_commutative:
|
237 |
+
return NumberKind
|
238 |
+
return UndefinedKind
|
239 |
+
|
240 |
+
@property
|
241 |
+
def _diff_wrt(self):
|
242 |
+
"""Allow derivatives wrt Symbols.
|
243 |
+
|
244 |
+
Examples
|
245 |
+
========
|
246 |
+
|
247 |
+
>>> from sympy import Symbol
|
248 |
+
>>> x = Symbol('x')
|
249 |
+
>>> x._diff_wrt
|
250 |
+
True
|
251 |
+
"""
|
252 |
+
return True
|
253 |
+
|
254 |
+
@staticmethod
|
255 |
+
def _sanitize(assumptions, obj=None):
|
256 |
+
"""Remove None, convert values to bool, check commutativity *in place*.
|
257 |
+
"""
|
258 |
+
|
259 |
+
# be strict about commutativity: cannot be None
|
260 |
+
is_commutative = fuzzy_bool(assumptions.get('commutative', True))
|
261 |
+
if is_commutative is None:
|
262 |
+
whose = '%s ' % obj.__name__ if obj else ''
|
263 |
+
raise ValueError(
|
264 |
+
'%scommutativity must be True or False.' % whose)
|
265 |
+
|
266 |
+
# sanitize other assumptions so 1 -> True and 0 -> False
|
267 |
+
for key in list(assumptions.keys()):
|
268 |
+
v = assumptions[key]
|
269 |
+
if v is None:
|
270 |
+
assumptions.pop(key)
|
271 |
+
continue
|
272 |
+
assumptions[key] = bool(v)
|
273 |
+
|
274 |
+
def _merge(self, assumptions):
|
275 |
+
base = self.assumptions0
|
276 |
+
for k in set(assumptions) & set(base):
|
277 |
+
if assumptions[k] != base[k]:
|
278 |
+
raise ValueError(filldedent('''
|
279 |
+
non-matching assumptions for %s: existing value
|
280 |
+
is %s and new value is %s''' % (
|
281 |
+
k, base[k], assumptions[k])))
|
282 |
+
base.update(assumptions)
|
283 |
+
return base
|
284 |
+
|
285 |
+
def __new__(cls, name, **assumptions):
|
286 |
+
"""Symbols are identified by name and assumptions::
|
287 |
+
|
288 |
+
>>> from sympy import Symbol
|
289 |
+
>>> Symbol("x") == Symbol("x")
|
290 |
+
True
|
291 |
+
>>> Symbol("x", real=True) == Symbol("x", real=False)
|
292 |
+
False
|
293 |
+
|
294 |
+
"""
|
295 |
+
cls._sanitize(assumptions, cls)
|
296 |
+
return Symbol.__xnew_cached_(cls, name, **assumptions)
|
297 |
+
|
298 |
+
@staticmethod
|
299 |
+
def __xnew__(cls, name, **assumptions): # never cached (e.g. dummy)
|
300 |
+
if not isinstance(name, str):
|
301 |
+
raise TypeError("name should be a string, not %s" % repr(type(name)))
|
302 |
+
|
303 |
+
# This is retained purely so that srepr can include commutative=True if
|
304 |
+
# that was explicitly specified but not if it was not. Ideally srepr
|
305 |
+
# should not distinguish these cases because the symbols otherwise
|
306 |
+
# compare equal and are considered equivalent.
|
307 |
+
#
|
308 |
+
# See https://github.com/sympy/sympy/issues/8873
|
309 |
+
#
|
310 |
+
assumptions_orig = assumptions.copy()
|
311 |
+
|
312 |
+
# The only assumption that is assumed by default is comutative=True:
|
313 |
+
assumptions.setdefault('commutative', True)
|
314 |
+
|
315 |
+
assumptions_kb = StdFactKB(assumptions)
|
316 |
+
assumptions0 = dict(assumptions_kb)
|
317 |
+
|
318 |
+
obj = Expr.__new__(cls)
|
319 |
+
obj.name = name
|
320 |
+
|
321 |
+
obj._assumptions = assumptions_kb
|
322 |
+
obj._assumptions_orig = assumptions_orig
|
323 |
+
obj._assumptions0 = assumptions0
|
324 |
+
|
325 |
+
# The three assumptions dicts are all a little different:
|
326 |
+
#
|
327 |
+
# >>> from sympy import Symbol
|
328 |
+
# >>> x = Symbol('x', finite=True)
|
329 |
+
# >>> x.is_positive # query an assumption
|
330 |
+
# >>> x._assumptions
|
331 |
+
# {'finite': True, 'infinite': False, 'commutative': True, 'positive': None}
|
332 |
+
# >>> x._assumptions0
|
333 |
+
# {'finite': True, 'infinite': False, 'commutative': True}
|
334 |
+
# >>> x._assumptions_orig
|
335 |
+
# {'finite': True}
|
336 |
+
#
|
337 |
+
# Two symbols with the same name are equal if their _assumptions0 are
|
338 |
+
# the same. Arguably it should be _assumptions_orig that is being
|
339 |
+
# compared because that is more transparent to the user (it is
|
340 |
+
# what was passed to the constructor modulo changes made by _sanitize).
|
341 |
+
|
342 |
+
return obj
|
343 |
+
|
344 |
+
@staticmethod
|
345 |
+
@cacheit
|
346 |
+
def __xnew_cached_(cls, name, **assumptions): # symbols are always cached
|
347 |
+
return Symbol.__xnew__(cls, name, **assumptions)
|
348 |
+
|
349 |
+
def __getnewargs_ex__(self):
|
350 |
+
return ((self.name,), self._assumptions_orig)
|
351 |
+
|
352 |
+
# NOTE: __setstate__ is not needed for pickles created by __getnewargs_ex__
|
353 |
+
# but was used before Symbol was changed to use __getnewargs_ex__ in v1.9.
|
354 |
+
# Pickles created in previous SymPy versions will still need __setstate__
|
355 |
+
# so that they can be unpickled in SymPy > v1.9.
|
356 |
+
|
357 |
+
def __setstate__(self, state):
|
358 |
+
for name, value in state.items():
|
359 |
+
setattr(self, name, value)
|
360 |
+
|
361 |
+
def _hashable_content(self):
|
362 |
+
# Note: user-specified assumptions not hashed, just derived ones
|
363 |
+
return (self.name,) + tuple(sorted(self.assumptions0.items()))
|
364 |
+
|
365 |
+
def _eval_subs(self, old, new):
|
366 |
+
if old.is_Pow:
|
367 |
+
from sympy.core.power import Pow
|
368 |
+
return Pow(self, S.One, evaluate=False)._eval_subs(old, new)
|
369 |
+
|
370 |
+
def _eval_refine(self, assumptions):
|
371 |
+
return self
|
372 |
+
|
373 |
+
@property
|
374 |
+
def assumptions0(self):
|
375 |
+
return self._assumptions0.copy()
|
376 |
+
|
377 |
+
@cacheit
|
378 |
+
def sort_key(self, order=None):
|
379 |
+
return self.class_key(), (1, (self.name,)), S.One.sort_key(), S.One
|
380 |
+
|
381 |
+
def as_dummy(self):
|
382 |
+
# only put commutativity in explicitly if it is False
|
383 |
+
return Dummy(self.name) if self.is_commutative is not False \
|
384 |
+
else Dummy(self.name, commutative=self.is_commutative)
|
385 |
+
|
386 |
+
def as_real_imag(self, deep=True, **hints):
|
387 |
+
if hints.get('ignore') == self:
|
388 |
+
return None
|
389 |
+
else:
|
390 |
+
from sympy.functions.elementary.complexes import im, re
|
391 |
+
return (re(self), im(self))
|
392 |
+
|
393 |
+
def is_constant(self, *wrt, **flags):
|
394 |
+
if not wrt:
|
395 |
+
return False
|
396 |
+
return self not in wrt
|
397 |
+
|
398 |
+
@property
|
399 |
+
def free_symbols(self):
|
400 |
+
return {self}
|
401 |
+
|
402 |
+
binary_symbols = free_symbols # in this case, not always
|
403 |
+
|
404 |
+
def as_set(self):
|
405 |
+
return S.UniversalSet
|
406 |
+
|
407 |
+
|
408 |
+
class Dummy(Symbol):
|
409 |
+
"""Dummy symbols are each unique, even if they have the same name:
|
410 |
+
|
411 |
+
Examples
|
412 |
+
========
|
413 |
+
|
414 |
+
>>> from sympy import Dummy
|
415 |
+
>>> Dummy("x") == Dummy("x")
|
416 |
+
False
|
417 |
+
|
418 |
+
If a name is not supplied then a string value of an internal count will be
|
419 |
+
used. This is useful when a temporary variable is needed and the name
|
420 |
+
of the variable used in the expression is not important.
|
421 |
+
|
422 |
+
>>> Dummy() #doctest: +SKIP
|
423 |
+
_Dummy_10
|
424 |
+
|
425 |
+
"""
|
426 |
+
|
427 |
+
# In the rare event that a Dummy object needs to be recreated, both the
|
428 |
+
# `name` and `dummy_index` should be passed. This is used by `srepr` for
|
429 |
+
# example:
|
430 |
+
# >>> d1 = Dummy()
|
431 |
+
# >>> d2 = eval(srepr(d1))
|
432 |
+
# >>> d2 == d1
|
433 |
+
# True
|
434 |
+
#
|
435 |
+
# If a new session is started between `srepr` and `eval`, there is a very
|
436 |
+
# small chance that `d2` will be equal to a previously-created Dummy.
|
437 |
+
|
438 |
+
_count = 0
|
439 |
+
_prng = random.Random()
|
440 |
+
_base_dummy_index = _prng.randint(10**6, 9*10**6)
|
441 |
+
|
442 |
+
__slots__ = ('dummy_index',)
|
443 |
+
|
444 |
+
is_Dummy = True
|
445 |
+
|
446 |
+
def __new__(cls, name=None, dummy_index=None, **assumptions):
|
447 |
+
if dummy_index is not None:
|
448 |
+
assert name is not None, "If you specify a dummy_index, you must also provide a name"
|
449 |
+
|
450 |
+
if name is None:
|
451 |
+
name = "Dummy_" + str(Dummy._count)
|
452 |
+
|
453 |
+
if dummy_index is None:
|
454 |
+
dummy_index = Dummy._base_dummy_index + Dummy._count
|
455 |
+
Dummy._count += 1
|
456 |
+
|
457 |
+
cls._sanitize(assumptions, cls)
|
458 |
+
obj = Symbol.__xnew__(cls, name, **assumptions)
|
459 |
+
|
460 |
+
obj.dummy_index = dummy_index
|
461 |
+
|
462 |
+
return obj
|
463 |
+
|
464 |
+
def __getnewargs_ex__(self):
|
465 |
+
return ((self.name, self.dummy_index), self._assumptions_orig)
|
466 |
+
|
467 |
+
@cacheit
|
468 |
+
def sort_key(self, order=None):
|
469 |
+
return self.class_key(), (
|
470 |
+
2, (self.name, self.dummy_index)), S.One.sort_key(), S.One
|
471 |
+
|
472 |
+
def _hashable_content(self):
|
473 |
+
return Symbol._hashable_content(self) + (self.dummy_index,)
|
474 |
+
|
475 |
+
|
476 |
+
class Wild(Symbol):
|
477 |
+
"""
|
478 |
+
A Wild symbol matches anything, or anything
|
479 |
+
without whatever is explicitly excluded.
|
480 |
+
|
481 |
+
Parameters
|
482 |
+
==========
|
483 |
+
|
484 |
+
name : str
|
485 |
+
Name of the Wild instance.
|
486 |
+
|
487 |
+
exclude : iterable, optional
|
488 |
+
Instances in ``exclude`` will not be matched.
|
489 |
+
|
490 |
+
properties : iterable of functions, optional
|
491 |
+
Functions, each taking an expressions as input
|
492 |
+
and returns a ``bool``. All functions in ``properties``
|
493 |
+
need to return ``True`` in order for the Wild instance
|
494 |
+
to match the expression.
|
495 |
+
|
496 |
+
Examples
|
497 |
+
========
|
498 |
+
|
499 |
+
>>> from sympy import Wild, WildFunction, cos, pi
|
500 |
+
>>> from sympy.abc import x, y, z
|
501 |
+
>>> a = Wild('a')
|
502 |
+
>>> x.match(a)
|
503 |
+
{a_: x}
|
504 |
+
>>> pi.match(a)
|
505 |
+
{a_: pi}
|
506 |
+
>>> (3*x**2).match(a*x)
|
507 |
+
{a_: 3*x}
|
508 |
+
>>> cos(x).match(a)
|
509 |
+
{a_: cos(x)}
|
510 |
+
>>> b = Wild('b', exclude=[x])
|
511 |
+
>>> (3*x**2).match(b*x)
|
512 |
+
>>> b.match(a)
|
513 |
+
{a_: b_}
|
514 |
+
>>> A = WildFunction('A')
|
515 |
+
>>> A.match(a)
|
516 |
+
{a_: A_}
|
517 |
+
|
518 |
+
Tips
|
519 |
+
====
|
520 |
+
|
521 |
+
When using Wild, be sure to use the exclude
|
522 |
+
keyword to make the pattern more precise.
|
523 |
+
Without the exclude pattern, you may get matches
|
524 |
+
that are technically correct, but not what you
|
525 |
+
wanted. For example, using the above without
|
526 |
+
exclude:
|
527 |
+
|
528 |
+
>>> from sympy import symbols
|
529 |
+
>>> a, b = symbols('a b', cls=Wild)
|
530 |
+
>>> (2 + 3*y).match(a*x + b*y)
|
531 |
+
{a_: 2/x, b_: 3}
|
532 |
+
|
533 |
+
This is technically correct, because
|
534 |
+
(2/x)*x + 3*y == 2 + 3*y, but you probably
|
535 |
+
wanted it to not match at all. The issue is that
|
536 |
+
you really did not want a and b to include x and y,
|
537 |
+
and the exclude parameter lets you specify exactly
|
538 |
+
this. With the exclude parameter, the pattern will
|
539 |
+
not match.
|
540 |
+
|
541 |
+
>>> a = Wild('a', exclude=[x, y])
|
542 |
+
>>> b = Wild('b', exclude=[x, y])
|
543 |
+
>>> (2 + 3*y).match(a*x + b*y)
|
544 |
+
|
545 |
+
Exclude also helps remove ambiguity from matches.
|
546 |
+
|
547 |
+
>>> E = 2*x**3*y*z
|
548 |
+
>>> a, b = symbols('a b', cls=Wild)
|
549 |
+
>>> E.match(a*b)
|
550 |
+
{a_: 2*y*z, b_: x**3}
|
551 |
+
>>> a = Wild('a', exclude=[x, y])
|
552 |
+
>>> E.match(a*b)
|
553 |
+
{a_: z, b_: 2*x**3*y}
|
554 |
+
>>> a = Wild('a', exclude=[x, y, z])
|
555 |
+
>>> E.match(a*b)
|
556 |
+
{a_: 2, b_: x**3*y*z}
|
557 |
+
|
558 |
+
Wild also accepts a ``properties`` parameter:
|
559 |
+
|
560 |
+
>>> a = Wild('a', properties=[lambda k: k.is_Integer])
|
561 |
+
>>> E.match(a*b)
|
562 |
+
{a_: 2, b_: x**3*y*z}
|
563 |
+
|
564 |
+
"""
|
565 |
+
is_Wild = True
|
566 |
+
|
567 |
+
__slots__ = ('exclude', 'properties')
|
568 |
+
|
569 |
+
def __new__(cls, name, exclude=(), properties=(), **assumptions):
|
570 |
+
exclude = tuple([sympify(x) for x in exclude])
|
571 |
+
properties = tuple(properties)
|
572 |
+
cls._sanitize(assumptions, cls)
|
573 |
+
return Wild.__xnew__(cls, name, exclude, properties, **assumptions)
|
574 |
+
|
575 |
+
def __getnewargs__(self):
|
576 |
+
return (self.name, self.exclude, self.properties)
|
577 |
+
|
578 |
+
@staticmethod
|
579 |
+
@cacheit
|
580 |
+
def __xnew__(cls, name, exclude, properties, **assumptions):
|
581 |
+
obj = Symbol.__xnew__(cls, name, **assumptions)
|
582 |
+
obj.exclude = exclude
|
583 |
+
obj.properties = properties
|
584 |
+
return obj
|
585 |
+
|
586 |
+
def _hashable_content(self):
|
587 |
+
return super()._hashable_content() + (self.exclude, self.properties)
|
588 |
+
|
589 |
+
# TODO add check against another Wild
|
590 |
+
def matches(self, expr, repl_dict=None, old=False):
|
591 |
+
if any(expr.has(x) for x in self.exclude):
|
592 |
+
return None
|
593 |
+
if not all(f(expr) for f in self.properties):
|
594 |
+
return None
|
595 |
+
if repl_dict is None:
|
596 |
+
repl_dict = {}
|
597 |
+
else:
|
598 |
+
repl_dict = repl_dict.copy()
|
599 |
+
repl_dict[self] = expr
|
600 |
+
return repl_dict
|
601 |
+
|
602 |
+
|
603 |
+
_range = _re.compile('([0-9]*:[0-9]+|[a-zA-Z]?:[a-zA-Z])')
|
604 |
+
|
605 |
+
|
606 |
+
def symbols(names, *, cls=Symbol, **args) -> Any:
|
607 |
+
r"""
|
608 |
+
Transform strings into instances of :class:`Symbol` class.
|
609 |
+
|
610 |
+
:func:`symbols` function returns a sequence of symbols with names taken
|
611 |
+
from ``names`` argument, which can be a comma or whitespace delimited
|
612 |
+
string, or a sequence of strings::
|
613 |
+
|
614 |
+
>>> from sympy import symbols, Function
|
615 |
+
|
616 |
+
>>> x, y, z = symbols('x,y,z')
|
617 |
+
>>> a, b, c = symbols('a b c')
|
618 |
+
|
619 |
+
The type of output is dependent on the properties of input arguments::
|
620 |
+
|
621 |
+
>>> symbols('x')
|
622 |
+
x
|
623 |
+
>>> symbols('x,')
|
624 |
+
(x,)
|
625 |
+
>>> symbols('x,y')
|
626 |
+
(x, y)
|
627 |
+
>>> symbols(('a', 'b', 'c'))
|
628 |
+
(a, b, c)
|
629 |
+
>>> symbols(['a', 'b', 'c'])
|
630 |
+
[a, b, c]
|
631 |
+
>>> symbols({'a', 'b', 'c'})
|
632 |
+
{a, b, c}
|
633 |
+
|
634 |
+
If an iterable container is needed for a single symbol, set the ``seq``
|
635 |
+
argument to ``True`` or terminate the symbol name with a comma::
|
636 |
+
|
637 |
+
>>> symbols('x', seq=True)
|
638 |
+
(x,)
|
639 |
+
|
640 |
+
To reduce typing, range syntax is supported to create indexed symbols.
|
641 |
+
Ranges are indicated by a colon and the type of range is determined by
|
642 |
+
the character to the right of the colon. If the character is a digit
|
643 |
+
then all contiguous digits to the left are taken as the nonnegative
|
644 |
+
starting value (or 0 if there is no digit left of the colon) and all
|
645 |
+
contiguous digits to the right are taken as 1 greater than the ending
|
646 |
+
value::
|
647 |
+
|
648 |
+
>>> symbols('x:10')
|
649 |
+
(x0, x1, x2, x3, x4, x5, x6, x7, x8, x9)
|
650 |
+
|
651 |
+
>>> symbols('x5:10')
|
652 |
+
(x5, x6, x7, x8, x9)
|
653 |
+
>>> symbols('x5(:2)')
|
654 |
+
(x50, x51)
|
655 |
+
|
656 |
+
>>> symbols('x5:10,y:5')
|
657 |
+
(x5, x6, x7, x8, x9, y0, y1, y2, y3, y4)
|
658 |
+
|
659 |
+
>>> symbols(('x5:10', 'y:5'))
|
660 |
+
((x5, x6, x7, x8, x9), (y0, y1, y2, y3, y4))
|
661 |
+
|
662 |
+
If the character to the right of the colon is a letter, then the single
|
663 |
+
letter to the left (or 'a' if there is none) is taken as the start
|
664 |
+
and all characters in the lexicographic range *through* the letter to
|
665 |
+
the right are used as the range::
|
666 |
+
|
667 |
+
>>> symbols('x:z')
|
668 |
+
(x, y, z)
|
669 |
+
>>> symbols('x:c') # null range
|
670 |
+
()
|
671 |
+
>>> symbols('x(:c)')
|
672 |
+
(xa, xb, xc)
|
673 |
+
|
674 |
+
>>> symbols(':c')
|
675 |
+
(a, b, c)
|
676 |
+
|
677 |
+
>>> symbols('a:d, x:z')
|
678 |
+
(a, b, c, d, x, y, z)
|
679 |
+
|
680 |
+
>>> symbols(('a:d', 'x:z'))
|
681 |
+
((a, b, c, d), (x, y, z))
|
682 |
+
|
683 |
+
Multiple ranges are supported; contiguous numerical ranges should be
|
684 |
+
separated by parentheses to disambiguate the ending number of one
|
685 |
+
range from the starting number of the next::
|
686 |
+
|
687 |
+
>>> symbols('x:2(1:3)')
|
688 |
+
(x01, x02, x11, x12)
|
689 |
+
>>> symbols(':3:2') # parsing is from left to right
|
690 |
+
(00, 01, 10, 11, 20, 21)
|
691 |
+
|
692 |
+
Only one pair of parentheses surrounding ranges are removed, so to
|
693 |
+
include parentheses around ranges, double them. And to include spaces,
|
694 |
+
commas, or colons, escape them with a backslash::
|
695 |
+
|
696 |
+
>>> symbols('x((a:b))')
|
697 |
+
(x(a), x(b))
|
698 |
+
>>> symbols(r'x(:1\,:2)') # or r'x((:1)\,(:2))'
|
699 |
+
(x(0,0), x(0,1))
|
700 |
+
|
701 |
+
All newly created symbols have assumptions set according to ``args``::
|
702 |
+
|
703 |
+
>>> a = symbols('a', integer=True)
|
704 |
+
>>> a.is_integer
|
705 |
+
True
|
706 |
+
|
707 |
+
>>> x, y, z = symbols('x,y,z', real=True)
|
708 |
+
>>> x.is_real and y.is_real and z.is_real
|
709 |
+
True
|
710 |
+
|
711 |
+
Despite its name, :func:`symbols` can create symbol-like objects like
|
712 |
+
instances of Function or Wild classes. To achieve this, set ``cls``
|
713 |
+
keyword argument to the desired type::
|
714 |
+
|
715 |
+
>>> symbols('f,g,h', cls=Function)
|
716 |
+
(f, g, h)
|
717 |
+
|
718 |
+
>>> type(_[0])
|
719 |
+
<class 'sympy.core.function.UndefinedFunction'>
|
720 |
+
|
721 |
+
"""
|
722 |
+
result = []
|
723 |
+
|
724 |
+
if isinstance(names, str):
|
725 |
+
marker = 0
|
726 |
+
splitters = r'\,', r'\:', r'\ '
|
727 |
+
literals: list[tuple[str, str]] = []
|
728 |
+
for splitter in splitters:
|
729 |
+
if splitter in names:
|
730 |
+
while chr(marker) in names:
|
731 |
+
marker += 1
|
732 |
+
lit_char = chr(marker)
|
733 |
+
marker += 1
|
734 |
+
names = names.replace(splitter, lit_char)
|
735 |
+
literals.append((lit_char, splitter[1:]))
|
736 |
+
def literal(s):
|
737 |
+
if literals:
|
738 |
+
for c, l in literals:
|
739 |
+
s = s.replace(c, l)
|
740 |
+
return s
|
741 |
+
|
742 |
+
names = names.strip()
|
743 |
+
as_seq = names.endswith(',')
|
744 |
+
if as_seq:
|
745 |
+
names = names[:-1].rstrip()
|
746 |
+
if not names:
|
747 |
+
raise ValueError('no symbols given')
|
748 |
+
|
749 |
+
# split on commas
|
750 |
+
names = [n.strip() for n in names.split(',')]
|
751 |
+
if not all(n for n in names):
|
752 |
+
raise ValueError('missing symbol between commas')
|
753 |
+
# split on spaces
|
754 |
+
for i in range(len(names) - 1, -1, -1):
|
755 |
+
names[i: i + 1] = names[i].split()
|
756 |
+
|
757 |
+
seq = args.pop('seq', as_seq)
|
758 |
+
|
759 |
+
for name in names:
|
760 |
+
if not name:
|
761 |
+
raise ValueError('missing symbol')
|
762 |
+
|
763 |
+
if ':' not in name:
|
764 |
+
symbol = cls(literal(name), **args)
|
765 |
+
result.append(symbol)
|
766 |
+
continue
|
767 |
+
|
768 |
+
split: list[str] = _range.split(name)
|
769 |
+
split_list: list[list[str]] = []
|
770 |
+
# remove 1 layer of bounding parentheses around ranges
|
771 |
+
for i in range(len(split) - 1):
|
772 |
+
if i and ':' in split[i] and split[i] != ':' and \
|
773 |
+
split[i - 1].endswith('(') and \
|
774 |
+
split[i + 1].startswith(')'):
|
775 |
+
split[i - 1] = split[i - 1][:-1]
|
776 |
+
split[i + 1] = split[i + 1][1:]
|
777 |
+
for s in split:
|
778 |
+
if ':' in s:
|
779 |
+
if s.endswith(':'):
|
780 |
+
raise ValueError('missing end range')
|
781 |
+
a, b = s.split(':')
|
782 |
+
if b[-1] in string.digits:
|
783 |
+
a_i = 0 if not a else int(a)
|
784 |
+
b_i = int(b)
|
785 |
+
split_list.append([str(c) for c in range(a_i, b_i)])
|
786 |
+
else:
|
787 |
+
a = a or 'a'
|
788 |
+
split_list.append([string.ascii_letters[c] for c in range(
|
789 |
+
string.ascii_letters.index(a),
|
790 |
+
string.ascii_letters.index(b) + 1)]) # inclusive
|
791 |
+
if not split_list[-1]:
|
792 |
+
break
|
793 |
+
else:
|
794 |
+
split_list.append([s])
|
795 |
+
else:
|
796 |
+
seq = True
|
797 |
+
if len(split_list) == 1:
|
798 |
+
names = split_list[0]
|
799 |
+
else:
|
800 |
+
names = [''.join(s) for s in product(*split_list)]
|
801 |
+
if literals:
|
802 |
+
result.extend([cls(literal(s), **args) for s in names])
|
803 |
+
else:
|
804 |
+
result.extend([cls(s, **args) for s in names])
|
805 |
+
|
806 |
+
if not seq and len(result) <= 1:
|
807 |
+
if not result:
|
808 |
+
return ()
|
809 |
+
return result[0]
|
810 |
+
|
811 |
+
return tuple(result)
|
812 |
+
else:
|
813 |
+
for name in names:
|
814 |
+
result.append(symbols(name, cls=cls, **args))
|
815 |
+
|
816 |
+
return type(names)(result)
|
817 |
+
|
818 |
+
|
819 |
+
def var(names, **args):
|
820 |
+
"""
|
821 |
+
Create symbols and inject them into the global namespace.
|
822 |
+
|
823 |
+
Explanation
|
824 |
+
===========
|
825 |
+
|
826 |
+
This calls :func:`symbols` with the same arguments and puts the results
|
827 |
+
into the *global* namespace. It's recommended not to use :func:`var` in
|
828 |
+
library code, where :func:`symbols` has to be used::
|
829 |
+
|
830 |
+
Examples
|
831 |
+
========
|
832 |
+
|
833 |
+
>>> from sympy import var
|
834 |
+
|
835 |
+
>>> var('x')
|
836 |
+
x
|
837 |
+
>>> x # noqa: F821
|
838 |
+
x
|
839 |
+
|
840 |
+
>>> var('a,ab,abc')
|
841 |
+
(a, ab, abc)
|
842 |
+
>>> abc # noqa: F821
|
843 |
+
abc
|
844 |
+
|
845 |
+
>>> var('x,y', real=True)
|
846 |
+
(x, y)
|
847 |
+
>>> x.is_real and y.is_real # noqa: F821
|
848 |
+
True
|
849 |
+
|
850 |
+
See :func:`symbols` documentation for more details on what kinds of
|
851 |
+
arguments can be passed to :func:`var`.
|
852 |
+
|
853 |
+
"""
|
854 |
+
def traverse(symbols, frame):
|
855 |
+
"""Recursively inject symbols to the global namespace. """
|
856 |
+
for symbol in symbols:
|
857 |
+
if isinstance(symbol, Basic):
|
858 |
+
frame.f_globals[symbol.name] = symbol
|
859 |
+
elif isinstance(symbol, FunctionClass):
|
860 |
+
frame.f_globals[symbol.__name__] = symbol
|
861 |
+
else:
|
862 |
+
traverse(symbol, frame)
|
863 |
+
|
864 |
+
from inspect import currentframe
|
865 |
+
frame = currentframe().f_back
|
866 |
+
|
867 |
+
try:
|
868 |
+
syms = symbols(names, **args)
|
869 |
+
|
870 |
+
if syms is not None:
|
871 |
+
if isinstance(syms, Basic):
|
872 |
+
frame.f_globals[syms.name] = syms
|
873 |
+
elif isinstance(syms, FunctionClass):
|
874 |
+
frame.f_globals[syms.__name__] = syms
|
875 |
+
else:
|
876 |
+
traverse(syms, frame)
|
877 |
+
finally:
|
878 |
+
del frame # break cyclic dependencies as stated in inspect docs
|
879 |
+
|
880 |
+
return syms
|
881 |
+
|
882 |
+
def disambiguate(*iter):
|
883 |
+
"""
|
884 |
+
Return a Tuple containing the passed expressions with symbols
|
885 |
+
that appear the same when printed replaced with numerically
|
886 |
+
subscripted symbols, and all Dummy symbols replaced with Symbols.
|
887 |
+
|
888 |
+
Parameters
|
889 |
+
==========
|
890 |
+
|
891 |
+
iter: list of symbols or expressions.
|
892 |
+
|
893 |
+
Examples
|
894 |
+
========
|
895 |
+
|
896 |
+
>>> from sympy.core.symbol import disambiguate
|
897 |
+
>>> from sympy import Dummy, Symbol, Tuple
|
898 |
+
>>> from sympy.abc import y
|
899 |
+
|
900 |
+
>>> tup = Symbol('_x'), Dummy('x'), Dummy('x')
|
901 |
+
>>> disambiguate(*tup)
|
902 |
+
(x_2, x, x_1)
|
903 |
+
|
904 |
+
>>> eqs = Tuple(Symbol('x')/y, Dummy('x')/y)
|
905 |
+
>>> disambiguate(*eqs)
|
906 |
+
(x_1/y, x/y)
|
907 |
+
|
908 |
+
>>> ix = Symbol('x', integer=True)
|
909 |
+
>>> vx = Symbol('x')
|
910 |
+
>>> disambiguate(vx + ix)
|
911 |
+
(x + x_1,)
|
912 |
+
|
913 |
+
To make your own mapping of symbols to use, pass only the free symbols
|
914 |
+
of the expressions and create a dictionary:
|
915 |
+
|
916 |
+
>>> free = eqs.free_symbols
|
917 |
+
>>> mapping = dict(zip(free, disambiguate(*free)))
|
918 |
+
>>> eqs.xreplace(mapping)
|
919 |
+
(x_1/y, x/y)
|
920 |
+
|
921 |
+
"""
|
922 |
+
new_iter = Tuple(*iter)
|
923 |
+
key = lambda x:tuple(sorted(x.assumptions0.items()))
|
924 |
+
syms = ordered(new_iter.free_symbols, keys=key)
|
925 |
+
mapping = {}
|
926 |
+
for s in syms:
|
927 |
+
mapping.setdefault(str(s).lstrip('_'), []).append(s)
|
928 |
+
reps = {}
|
929 |
+
for k in mapping:
|
930 |
+
# the first or only symbol doesn't get subscripted but make
|
931 |
+
# sure that it's a Symbol, not a Dummy
|
932 |
+
mapk0 = Symbol("%s" % (k), **mapping[k][0].assumptions0)
|
933 |
+
if mapping[k][0] != mapk0:
|
934 |
+
reps[mapping[k][0]] = mapk0
|
935 |
+
# the others get subscripts (and are made into Symbols)
|
936 |
+
skip = 0
|
937 |
+
for i in range(1, len(mapping[k])):
|
938 |
+
while True:
|
939 |
+
name = "%s_%i" % (k, i + skip)
|
940 |
+
if name not in mapping:
|
941 |
+
break
|
942 |
+
skip += 1
|
943 |
+
ki = mapping[k][i]
|
944 |
+
reps[ki] = Sym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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""sympify -- convert objects SymPy internal format"""
|
2 |
+
|
3 |
+
from __future__ import annotations
|
4 |
+
from typing import Any, Callable
|
5 |
+
|
6 |
+
from inspect import getmro
|
7 |
+
import string
|
8 |
+
from sympy.core.random import choice
|
9 |
+
|
10 |
+
from .parameters import global_parameters
|
11 |
+
|
12 |
+
from sympy.utilities.exceptions import sympy_deprecation_warning
|
13 |
+
from sympy.utilities.iterables import iterable
|
14 |
+
|
15 |
+
|
16 |
+
class SympifyError(ValueError):
|
17 |
+
def __init__(self, expr, base_exc=None):
|
18 |
+
self.expr = expr
|
19 |
+
self.base_exc = base_exc
|
20 |
+
|
21 |
+
def __str__(self):
|
22 |
+
if self.base_exc is None:
|
23 |
+
return "SympifyError: %r" % (self.expr,)
|
24 |
+
|
25 |
+
return ("Sympify of expression '%s' failed, because of exception being "
|
26 |
+
"raised:\n%s: %s" % (self.expr, self.base_exc.__class__.__name__,
|
27 |
+
str(self.base_exc)))
|
28 |
+
|
29 |
+
|
30 |
+
converter: dict[type[Any], Callable[[Any], Basic]] = {}
|
31 |
+
|
32 |
+
#holds the conversions defined in SymPy itself, i.e. non-user defined conversions
|
33 |
+
_sympy_converter: dict[type[Any], Callable[[Any], Basic]] = {}
|
34 |
+
|
35 |
+
#alias for clearer use in the library
|
36 |
+
_external_converter = converter
|
37 |
+
|
38 |
+
class CantSympify:
|
39 |
+
"""
|
40 |
+
Mix in this trait to a class to disallow sympification of its instances.
|
41 |
+
|
42 |
+
Examples
|
43 |
+
========
|
44 |
+
|
45 |
+
>>> from sympy import sympify
|
46 |
+
>>> from sympy.core.sympify import CantSympify
|
47 |
+
|
48 |
+
>>> class Something(dict):
|
49 |
+
... pass
|
50 |
+
...
|
51 |
+
>>> sympify(Something())
|
52 |
+
{}
|
53 |
+
|
54 |
+
>>> class Something(dict, CantSympify):
|
55 |
+
... pass
|
56 |
+
...
|
57 |
+
>>> sympify(Something())
|
58 |
+
Traceback (most recent call last):
|
59 |
+
...
|
60 |
+
SympifyError: SympifyError: {}
|
61 |
+
|
62 |
+
"""
|
63 |
+
|
64 |
+
__slots__ = ()
|
65 |
+
|
66 |
+
|
67 |
+
def _is_numpy_instance(a):
|
68 |
+
"""
|
69 |
+
Checks if an object is an instance of a type from the numpy module.
|
70 |
+
"""
|
71 |
+
# This check avoids unnecessarily importing NumPy. We check the whole
|
72 |
+
# __mro__ in case any base type is a numpy type.
|
73 |
+
return any(type_.__module__ == 'numpy'
|
74 |
+
for type_ in type(a).__mro__)
|
75 |
+
|
76 |
+
|
77 |
+
def _convert_numpy_types(a, **sympify_args):
|
78 |
+
"""
|
79 |
+
Converts a numpy datatype input to an appropriate SymPy type.
|
80 |
+
"""
|
81 |
+
import numpy as np
|
82 |
+
if not isinstance(a, np.floating):
|
83 |
+
if np.iscomplex(a):
|
84 |
+
return _sympy_converter[complex](a.item())
|
85 |
+
else:
|
86 |
+
return sympify(a.item(), **sympify_args)
|
87 |
+
else:
|
88 |
+
try:
|
89 |
+
from .numbers import Float
|
90 |
+
prec = np.finfo(a).nmant + 1
|
91 |
+
# E.g. double precision means prec=53 but nmant=52
|
92 |
+
# Leading bit of mantissa is always 1, so is not stored
|
93 |
+
a = str(list(np.reshape(np.asarray(a),
|
94 |
+
(1, np.size(a)))[0]))[1:-1]
|
95 |
+
return Float(a, precision=prec)
|
96 |
+
except NotImplementedError:
|
97 |
+
raise SympifyError('Translation for numpy float : %s '
|
98 |
+
'is not implemented' % a)
|
99 |
+
|
100 |
+
|
101 |
+
def sympify(a, locals=None, convert_xor=True, strict=False, rational=False,
|
102 |
+
evaluate=None):
|
103 |
+
"""
|
104 |
+
Converts an arbitrary expression to a type that can be used inside SymPy.
|
105 |
+
|
106 |
+
Explanation
|
107 |
+
===========
|
108 |
+
|
109 |
+
It will convert Python ints into instances of :class:`~.Integer`, floats
|
110 |
+
into instances of :class:`~.Float`, etc. It is also able to coerce
|
111 |
+
symbolic expressions which inherit from :class:`~.Basic`. This can be
|
112 |
+
useful in cooperation with SAGE.
|
113 |
+
|
114 |
+
.. warning::
|
115 |
+
Note that this function uses ``eval``, and thus shouldn't be used on
|
116 |
+
unsanitized input.
|
117 |
+
|
118 |
+
If the argument is already a type that SymPy understands, it will do
|
119 |
+
nothing but return that value. This can be used at the beginning of a
|
120 |
+
function to ensure you are working with the correct type.
|
121 |
+
|
122 |
+
Examples
|
123 |
+
========
|
124 |
+
|
125 |
+
>>> from sympy import sympify
|
126 |
+
|
127 |
+
>>> sympify(2).is_integer
|
128 |
+
True
|
129 |
+
>>> sympify(2).is_real
|
130 |
+
True
|
131 |
+
|
132 |
+
>>> sympify(2.0).is_real
|
133 |
+
True
|
134 |
+
>>> sympify("2.0").is_real
|
135 |
+
True
|
136 |
+
>>> sympify("2e-45").is_real
|
137 |
+
True
|
138 |
+
|
139 |
+
If the expression could not be converted, a SympifyError is raised.
|
140 |
+
|
141 |
+
>>> sympify("x***2")
|
142 |
+
Traceback (most recent call last):
|
143 |
+
...
|
144 |
+
SympifyError: SympifyError: "could not parse 'x***2'"
|
145 |
+
|
146 |
+
Locals
|
147 |
+
------
|
148 |
+
|
149 |
+
The sympification happens with access to everything that is loaded
|
150 |
+
by ``from sympy import *``; anything used in a string that is not
|
151 |
+
defined by that import will be converted to a symbol. In the following,
|
152 |
+
the ``bitcount`` function is treated as a symbol and the ``O`` is
|
153 |
+
interpreted as the :class:`~.Order` object (used with series) and it raises
|
154 |
+
an error when used improperly:
|
155 |
+
|
156 |
+
>>> s = 'bitcount(42)'
|
157 |
+
>>> sympify(s)
|
158 |
+
bitcount(42)
|
159 |
+
>>> sympify("O(x)")
|
160 |
+
O(x)
|
161 |
+
>>> sympify("O + 1")
|
162 |
+
Traceback (most recent call last):
|
163 |
+
...
|
164 |
+
TypeError: unbound method...
|
165 |
+
|
166 |
+
In order to have ``bitcount`` be recognized it can be imported into a
|
167 |
+
namespace dictionary and passed as locals:
|
168 |
+
|
169 |
+
>>> ns = {}
|
170 |
+
>>> exec('from sympy.core.evalf import bitcount', ns)
|
171 |
+
>>> sympify(s, locals=ns)
|
172 |
+
6
|
173 |
+
|
174 |
+
In order to have the ``O`` interpreted as a Symbol, identify it as such
|
175 |
+
in the namespace dictionary. This can be done in a variety of ways; all
|
176 |
+
three of the following are possibilities:
|
177 |
+
|
178 |
+
>>> from sympy import Symbol
|
179 |
+
>>> ns["O"] = Symbol("O") # method 1
|
180 |
+
>>> exec('from sympy.abc import O', ns) # method 2
|
181 |
+
>>> ns.update(dict(O=Symbol("O"))) # method 3
|
182 |
+
>>> sympify("O + 1", locals=ns)
|
183 |
+
O + 1
|
184 |
+
|
185 |
+
If you want *all* single-letter and Greek-letter variables to be symbols
|
186 |
+
then you can use the clashing-symbols dictionaries that have been defined
|
187 |
+
there as private variables: ``_clash1`` (single-letter variables),
|
188 |
+
``_clash2`` (the multi-letter Greek names) or ``_clash`` (both single and
|
189 |
+
multi-letter names that are defined in ``abc``).
|
190 |
+
|
191 |
+
>>> from sympy.abc import _clash1
|
192 |
+
>>> set(_clash1) # if this fails, see issue #23903
|
193 |
+
{'E', 'I', 'N', 'O', 'Q', 'S'}
|
194 |
+
>>> sympify('I & Q', _clash1)
|
195 |
+
I & Q
|
196 |
+
|
197 |
+
Strict
|
198 |
+
------
|
199 |
+
|
200 |
+
If the option ``strict`` is set to ``True``, only the types for which an
|
201 |
+
explicit conversion has been defined are converted. In the other
|
202 |
+
cases, a SympifyError is raised.
|
203 |
+
|
204 |
+
>>> print(sympify(None))
|
205 |
+
None
|
206 |
+
>>> sympify(None, strict=True)
|
207 |
+
Traceback (most recent call last):
|
208 |
+
...
|
209 |
+
SympifyError: SympifyError: None
|
210 |
+
|
211 |
+
.. deprecated:: 1.6
|
212 |
+
|
213 |
+
``sympify(obj)`` automatically falls back to ``str(obj)`` when all
|
214 |
+
other conversion methods fail, but this is deprecated. ``strict=True``
|
215 |
+
will disable this deprecated behavior. See
|
216 |
+
:ref:`deprecated-sympify-string-fallback`.
|
217 |
+
|
218 |
+
Evaluation
|
219 |
+
----------
|
220 |
+
|
221 |
+
If the option ``evaluate`` is set to ``False``, then arithmetic and
|
222 |
+
operators will be converted into their SymPy equivalents and the
|
223 |
+
``evaluate=False`` option will be added. Nested ``Add`` or ``Mul`` will
|
224 |
+
be denested first. This is done via an AST transformation that replaces
|
225 |
+
operators with their SymPy equivalents, so if an operand redefines any
|
226 |
+
of those operations, the redefined operators will not be used. If
|
227 |
+
argument a is not a string, the mathematical expression is evaluated
|
228 |
+
before being passed to sympify, so adding ``evaluate=False`` will still
|
229 |
+
return the evaluated result of expression.
|
230 |
+
|
231 |
+
>>> sympify('2**2 / 3 + 5')
|
232 |
+
19/3
|
233 |
+
>>> sympify('2**2 / 3 + 5', evaluate=False)
|
234 |
+
2**2/3 + 5
|
235 |
+
>>> sympify('4/2+7', evaluate=True)
|
236 |
+
9
|
237 |
+
>>> sympify('4/2+7', evaluate=False)
|
238 |
+
4/2 + 7
|
239 |
+
>>> sympify(4/2+7, evaluate=False)
|
240 |
+
9.00000000000000
|
241 |
+
|
242 |
+
Extending
|
243 |
+
---------
|
244 |
+
|
245 |
+
To extend ``sympify`` to convert custom objects (not derived from ``Basic``),
|
246 |
+
just define a ``_sympy_`` method to your class. You can do that even to
|
247 |
+
classes that you do not own by subclassing or adding the method at runtime.
|
248 |
+
|
249 |
+
>>> from sympy import Matrix
|
250 |
+
>>> class MyList1(object):
|
251 |
+
... def __iter__(self):
|
252 |
+
... yield 1
|
253 |
+
... yield 2
|
254 |
+
... return
|
255 |
+
... def __getitem__(self, i): return list(self)[i]
|
256 |
+
... def _sympy_(self): return Matrix(self)
|
257 |
+
>>> sympify(MyList1())
|
258 |
+
Matrix([
|
259 |
+
[1],
|
260 |
+
[2]])
|
261 |
+
|
262 |
+
If you do not have control over the class definition you could also use the
|
263 |
+
``converter`` global dictionary. The key is the class and the value is a
|
264 |
+
function that takes a single argument and returns the desired SymPy
|
265 |
+
object, e.g. ``converter[MyList] = lambda x: Matrix(x)``.
|
266 |
+
|
267 |
+
>>> class MyList2(object): # XXX Do not do this if you control the class!
|
268 |
+
... def __iter__(self): # Use _sympy_!
|
269 |
+
... yield 1
|
270 |
+
... yield 2
|
271 |
+
... return
|
272 |
+
... def __getitem__(self, i): return list(self)[i]
|
273 |
+
>>> from sympy.core.sympify import converter
|
274 |
+
>>> converter[MyList2] = lambda x: Matrix(x)
|
275 |
+
>>> sympify(MyList2())
|
276 |
+
Matrix([
|
277 |
+
[1],
|
278 |
+
[2]])
|
279 |
+
|
280 |
+
Notes
|
281 |
+
=====
|
282 |
+
|
283 |
+
The keywords ``rational`` and ``convert_xor`` are only used
|
284 |
+
when the input is a string.
|
285 |
+
|
286 |
+
convert_xor
|
287 |
+
-----------
|
288 |
+
|
289 |
+
>>> sympify('x^y',convert_xor=True)
|
290 |
+
x**y
|
291 |
+
>>> sympify('x^y',convert_xor=False)
|
292 |
+
x ^ y
|
293 |
+
|
294 |
+
rational
|
295 |
+
--------
|
296 |
+
|
297 |
+
>>> sympify('0.1',rational=False)
|
298 |
+
0.1
|
299 |
+
>>> sympify('0.1',rational=True)
|
300 |
+
1/10
|
301 |
+
|
302 |
+
Sometimes autosimplification during sympification results in expressions
|
303 |
+
that are very different in structure than what was entered. Until such
|
304 |
+
autosimplification is no longer done, the ``kernS`` function might be of
|
305 |
+
some use. In the example below you can see how an expression reduces to
|
306 |
+
$-1$ by autosimplification, but does not do so when ``kernS`` is used.
|
307 |
+
|
308 |
+
>>> from sympy.core.sympify import kernS
|
309 |
+
>>> from sympy.abc import x
|
310 |
+
>>> -2*(-(-x + 1/x)/(x*(x - 1/x)**2) - 1/(x*(x - 1/x))) - 1
|
311 |
+
-1
|
312 |
+
>>> s = '-2*(-(-x + 1/x)/(x*(x - 1/x)**2) - 1/(x*(x - 1/x))) - 1'
|
313 |
+
>>> sympify(s)
|
314 |
+
-1
|
315 |
+
>>> kernS(s)
|
316 |
+
-2*(-(-x + 1/x)/(x*(x - 1/x)**2) - 1/(x*(x - 1/x))) - 1
|
317 |
+
|
318 |
+
Parameters
|
319 |
+
==========
|
320 |
+
|
321 |
+
a :
|
322 |
+
- any object defined in SymPy
|
323 |
+
- standard numeric Python types: ``int``, ``long``, ``float``, ``Decimal``
|
324 |
+
- strings (like ``"0.09"``, ``"2e-19"`` or ``'sin(x)'``)
|
325 |
+
- booleans, including ``None`` (will leave ``None`` unchanged)
|
326 |
+
- dicts, lists, sets or tuples containing any of the above
|
327 |
+
|
328 |
+
convert_xor : bool, optional
|
329 |
+
If true, treats ``^`` as exponentiation.
|
330 |
+
If False, treats ``^`` as XOR itself.
|
331 |
+
Used only when input is a string.
|
332 |
+
|
333 |
+
locals : any object defined in SymPy, optional
|
334 |
+
In order to have strings be recognized it can be imported
|
335 |
+
into a namespace dictionary and passed as locals.
|
336 |
+
|
337 |
+
strict : bool, optional
|
338 |
+
If the option strict is set to ``True``, only the types for which
|
339 |
+
an explicit conversion has been defined are converted. In the
|
340 |
+
other cases, a SympifyError is raised.
|
341 |
+
|
342 |
+
rational : bool, optional
|
343 |
+
If ``True``, converts floats into :class:`~.Rational`.
|
344 |
+
If ``False``, it lets floats remain as it is.
|
345 |
+
Used only when input is a string.
|
346 |
+
|
347 |
+
evaluate : bool, optional
|
348 |
+
If False, then arithmetic and operators will be converted into
|
349 |
+
their SymPy equivalents. If True the expression will be evaluated
|
350 |
+
and the result will be returned.
|
351 |
+
|
352 |
+
"""
|
353 |
+
# XXX: If a is a Basic subclass rather than instance (e.g. sin rather than
|
354 |
+
# sin(x)) then a.__sympy__ will be the property. Only on the instance will
|
355 |
+
# a.__sympy__ give the *value* of the property (True). Since sympify(sin)
|
356 |
+
# was used for a long time we allow it to pass. However if strict=True as
|
357 |
+
# is the case in internal calls to _sympify then we only allow
|
358 |
+
# is_sympy=True.
|
359 |
+
#
|
360 |
+
# https://github.com/sympy/sympy/issues/20124
|
361 |
+
is_sympy = getattr(a, '__sympy__', None)
|
362 |
+
if is_sympy is True:
|
363 |
+
return a
|
364 |
+
elif is_sympy is not None:
|
365 |
+
if not strict:
|
366 |
+
return a
|
367 |
+
else:
|
368 |
+
raise SympifyError(a)
|
369 |
+
|
370 |
+
if isinstance(a, CantSympify):
|
371 |
+
raise SympifyError(a)
|
372 |
+
|
373 |
+
cls = getattr(a, "__class__", None)
|
374 |
+
|
375 |
+
#Check if there exists a converter for any of the types in the mro
|
376 |
+
for superclass in getmro(cls):
|
377 |
+
#First check for user defined converters
|
378 |
+
conv = _external_converter.get(superclass)
|
379 |
+
if conv is None:
|
380 |
+
#if none exists, check for SymPy defined converters
|
381 |
+
conv = _sympy_converter.get(superclass)
|
382 |
+
if conv is not None:
|
383 |
+
return conv(a)
|
384 |
+
|
385 |
+
if cls is type(None):
|
386 |
+
if strict:
|
387 |
+
raise SympifyError(a)
|
388 |
+
else:
|
389 |
+
return a
|
390 |
+
|
391 |
+
if evaluate is None:
|
392 |
+
evaluate = global_parameters.evaluate
|
393 |
+
|
394 |
+
# Support for basic numpy datatypes
|
395 |
+
if _is_numpy_instance(a):
|
396 |
+
import numpy as np
|
397 |
+
if np.isscalar(a):
|
398 |
+
return _convert_numpy_types(a, locals=locals,
|
399 |
+
convert_xor=convert_xor, strict=strict, rational=rational,
|
400 |
+
evaluate=evaluate)
|
401 |
+
|
402 |
+
_sympy_ = getattr(a, "_sympy_", None)
|
403 |
+
if _sympy_ is not None:
|
404 |
+
try:
|
405 |
+
return a._sympy_()
|
406 |
+
# XXX: Catches AttributeError: 'SymPyConverter' object has no
|
407 |
+
# attribute 'tuple'
|
408 |
+
# This is probably a bug somewhere but for now we catch it here.
|
409 |
+
except AttributeError:
|
410 |
+
pass
|
411 |
+
|
412 |
+
if not strict:
|
413 |
+
# Put numpy array conversion _before_ float/int, see
|
414 |
+
# <https://github.com/sympy/sympy/issues/13924>.
|
415 |
+
flat = getattr(a, "flat", None)
|
416 |
+
if flat is not None:
|
417 |
+
shape = getattr(a, "shape", None)
|
418 |
+
if shape is not None:
|
419 |
+
from sympy.tensor.array import Array
|
420 |
+
return Array(a.flat, a.shape) # works with e.g. NumPy arrays
|
421 |
+
|
422 |
+
if not isinstance(a, str):
|
423 |
+
if _is_numpy_instance(a):
|
424 |
+
import numpy as np
|
425 |
+
assert not isinstance(a, np.number)
|
426 |
+
if isinstance(a, np.ndarray):
|
427 |
+
# Scalar arrays (those with zero dimensions) have sympify
|
428 |
+
# called on the scalar element.
|
429 |
+
if a.ndim == 0:
|
430 |
+
try:
|
431 |
+
return sympify(a.item(),
|
432 |
+
locals=locals,
|
433 |
+
convert_xor=convert_xor,
|
434 |
+
strict=strict,
|
435 |
+
rational=rational,
|
436 |
+
evaluate=evaluate)
|
437 |
+
except SympifyError:
|
438 |
+
pass
|
439 |
+
else:
|
440 |
+
# float and int can coerce size-one numpy arrays to their lone
|
441 |
+
# element. See issue https://github.com/numpy/numpy/issues/10404.
|
442 |
+
for coerce in (float, int):
|
443 |
+
try:
|
444 |
+
return sympify(coerce(a))
|
445 |
+
except (TypeError, ValueError, AttributeError, SympifyError):
|
446 |
+
continue
|
447 |
+
|
448 |
+
if strict:
|
449 |
+
raise SympifyError(a)
|
450 |
+
|
451 |
+
if iterable(a):
|
452 |
+
try:
|
453 |
+
return type(a)([sympify(x, locals=locals, convert_xor=convert_xor,
|
454 |
+
rational=rational, evaluate=evaluate) for x in a])
|
455 |
+
except TypeError:
|
456 |
+
# Not all iterables are rebuildable with their type.
|
457 |
+
pass
|
458 |
+
|
459 |
+
if not isinstance(a, str):
|
460 |
+
try:
|
461 |
+
a = str(a)
|
462 |
+
except Exception as exc:
|
463 |
+
raise SympifyError(a, exc)
|
464 |
+
sympy_deprecation_warning(
|
465 |
+
f"""
|
466 |
+
The string fallback in sympify() is deprecated.
|
467 |
+
|
468 |
+
To explicitly convert the string form of an object, use
|
469 |
+
sympify(str(obj)). To add define sympify behavior on custom
|
470 |
+
objects, use sympy.core.sympify.converter or define obj._sympy_
|
471 |
+
(see the sympify() docstring).
|
472 |
+
|
473 |
+
sympify() performed the string fallback resulting in the following string:
|
474 |
+
|
475 |
+
{a!r}
|
476 |
+
""",
|
477 |
+
deprecated_since_version='1.6',
|
478 |
+
active_deprecations_target="deprecated-sympify-string-fallback",
|
479 |
+
)
|
480 |
+
|
481 |
+
from sympy.parsing.sympy_parser import (parse_expr, TokenError,
|
482 |
+
standard_transformations)
|
483 |
+
from sympy.parsing.sympy_parser import convert_xor as t_convert_xor
|
484 |
+
from sympy.parsing.sympy_parser import rationalize as t_rationalize
|
485 |
+
|
486 |
+
transformations = standard_transformations
|
487 |
+
|
488 |
+
if rational:
|
489 |
+
transformations += (t_rationalize,)
|
490 |
+
if convert_xor:
|
491 |
+
transformations += (t_convert_xor,)
|
492 |
+
|
493 |
+
try:
|
494 |
+
a = a.replace('\n', '')
|
495 |
+
expr = parse_expr(a, local_dict=locals, transformations=transformations, evaluate=evaluate)
|
496 |
+
except (TokenError, SyntaxError) as exc:
|
497 |
+
raise SympifyError('could not parse %r' % a, exc)
|
498 |
+
|
499 |
+
return expr
|
500 |
+
|
501 |
+
|
502 |
+
def _sympify(a):
|
503 |
+
"""
|
504 |
+
Short version of :func:`~.sympify` for internal usage for ``__add__`` and
|
505 |
+
``__eq__`` methods where it is ok to allow some things (like Python
|
506 |
+
integers and floats) in the expression. This excludes things (like strings)
|
507 |
+
that are unwise to allow into such an expression.
|
508 |
+
|
509 |
+
>>> from sympy import Integer
|
510 |
+
>>> Integer(1) == 1
|
511 |
+
True
|
512 |
+
|
513 |
+
>>> Integer(1) == '1'
|
514 |
+
False
|
515 |
+
|
516 |
+
>>> from sympy.abc import x
|
517 |
+
>>> x + 1
|
518 |
+
x + 1
|
519 |
+
|
520 |
+
>>> x + '1'
|
521 |
+
Traceback (most recent call last):
|
522 |
+
...
|
523 |
+
TypeError: unsupported operand type(s) for +: 'Symbol' and 'str'
|
524 |
+
|
525 |
+
see: sympify
|
526 |
+
|
527 |
+
"""
|
528 |
+
return sympify(a, strict=True)
|
529 |
+
|
530 |
+
|
531 |
+
def kernS(s):
|
532 |
+
"""Use a hack to try keep autosimplification from distributing a
|
533 |
+
a number into an Add; this modification does not
|
534 |
+
prevent the 2-arg Mul from becoming an Add, however.
|
535 |
+
|
536 |
+
Examples
|
537 |
+
========
|
538 |
+
|
539 |
+
>>> from sympy.core.sympify import kernS
|
540 |
+
>>> from sympy.abc import x, y
|
541 |
+
|
542 |
+
The 2-arg Mul distributes a number (or minus sign) across the terms
|
543 |
+
of an expression, but kernS will prevent that:
|
544 |
+
|
545 |
+
>>> 2*(x + y), -(x + 1)
|
546 |
+
(2*x + 2*y, -x - 1)
|
547 |
+
>>> kernS('2*(x + y)')
|
548 |
+
2*(x + y)
|
549 |
+
>>> kernS('-(x + 1)')
|
550 |
+
-(x + 1)
|
551 |
+
|
552 |
+
If use of the hack fails, the un-hacked string will be passed to sympify...
|
553 |
+
and you get what you get.
|
554 |
+
|
555 |
+
XXX This hack should not be necessary once issue 4596 has been resolved.
|
556 |
+
"""
|
557 |
+
hit = False
|
558 |
+
quoted = '"' in s or "'" in s
|
559 |
+
if '(' in s and not quoted:
|
560 |
+
if s.count('(') != s.count(")"):
|
561 |
+
raise SympifyError('unmatched left parenthesis')
|
562 |
+
|
563 |
+
# strip all space from s
|
564 |
+
s = ''.join(s.split())
|
565 |
+
olds = s
|
566 |
+
# now use space to represent a symbol that
|
567 |
+
# will
|
568 |
+
# step 1. turn potential 2-arg Muls into 3-arg versions
|
569 |
+
# 1a. *( -> * *(
|
570 |
+
s = s.replace('*(', '* *(')
|
571 |
+
# 1b. close up exponentials
|
572 |
+
s = s.replace('** *', '**')
|
573 |
+
# 2. handle the implied multiplication of a negated
|
574 |
+
# parenthesized expression in two steps
|
575 |
+
# 2a: -(...) --> -( *(...)
|
576 |
+
target = '-( *('
|
577 |
+
s = s.replace('-(', target)
|
578 |
+
# 2b: double the matching closing parenthesis
|
579 |
+
# -( *(...) --> -( *(...))
|
580 |
+
i = nest = 0
|
581 |
+
assert target.endswith('(') # assumption below
|
582 |
+
while True:
|
583 |
+
j = s.find(target, i)
|
584 |
+
if j == -1:
|
585 |
+
break
|
586 |
+
j += len(target) - 1
|
587 |
+
for j in range(j, len(s)):
|
588 |
+
if s[j] == "(":
|
589 |
+
nest += 1
|
590 |
+
elif s[j] == ")":
|
591 |
+
nest -= 1
|
592 |
+
if nest == 0:
|
593 |
+
break
|
594 |
+
s = s[:j] + ")" + s[j:]
|
595 |
+
i = j + 2 # the first char after 2nd )
|
596 |
+
if ' ' in s:
|
597 |
+
# get a unique kern
|
598 |
+
kern = '_'
|
599 |
+
while kern in s:
|
600 |
+
kern += choice(string.ascii_letters + string.digits)
|
601 |
+
s = s.replace(' ', kern)
|
602 |
+
hit = kern in s
|
603 |
+
else:
|
604 |
+
hit = False
|
605 |
+
|
606 |
+
for i in range(2):
|
607 |
+
try:
|
608 |
+
expr = sympify(s)
|
609 |
+
break
|
610 |
+
except TypeError: # the kern might cause unknown errors...
|
611 |
+
if hit:
|
612 |
+
s = olds # maybe it didn't like the kern; use un-kerned s
|
613 |
+
hit = False
|
614 |
+
continue
|
615 |
+
expr = sympify(s) # let original error raise
|
616 |
+
|
617 |
+
if not hit:
|
618 |
+
return expr
|
619 |
+
|
620 |
+
from .symbol import Symbol
|
621 |
+
rep = {Symbol(kern): 1}
|
622 |
+
def _clear(expr):
|
623 |
+
if isinstance(expr, (list, tuple, set)):
|
624 |
+
return type(expr)([_clear(e) for e in expr])
|
625 |
+
if hasattr(expr, 'subs'):
|
626 |
+
return expr.subs(rep, hack2=True)
|
627 |
+
return expr
|
628 |
+
expr = _clear(expr)
|
629 |
+
# hope that kern is not there anymore
|
630 |
+
return expr
|
631 |
+
|
632 |
+
|
633 |
+
# Avoid circular import
|
634 |
+
from .basic import Basic
|
venv/lib/python3.10/site-packages/sympy/core/tests/__init__.py
ADDED
File without changes
|
venv/lib/python3.10/site-packages/sympy/core/tests/__pycache__/test_args.cpython-310.pyc
ADDED
Binary file (217 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/core/tests/__pycache__/test_assumptions.cpython-310.pyc
ADDED
Binary file (33.6 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/core/tests/__pycache__/test_basic.cpython-310.pyc
ADDED
Binary file (11.7 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/core/tests/__pycache__/test_complex.cpython-310.pyc
ADDED
Binary file (13.3 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/core/tests/__pycache__/test_count_ops.cpython-310.pyc
ADDED
Binary file (6.12 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/core/tests/__pycache__/test_evalf.cpython-310.pyc
ADDED
Binary file (31.4 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/core/tests/__pycache__/test_expand.cpython-310.pyc
ADDED
Binary file (13.8 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/core/tests/__pycache__/test_multidimensional.cpython-310.pyc
ADDED
Binary file (1.26 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/core/tests/__pycache__/test_numbers.cpython-310.pyc
ADDED
Binary file (76.8 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/core/tests/__pycache__/test_operations.cpython-310.pyc
ADDED
Binary file (4.41 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/core/tests/__pycache__/test_relational.cpython-310.pyc
ADDED
Binary file (44.7 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/core/tests/__pycache__/test_singleton.cpython-310.pyc
ADDED
Binary file (2.03 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/core/tests/__pycache__/test_subs.cpython-310.pyc
ADDED
Binary file (33.2 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/core/tests/__pycache__/test_truediv.cpython-310.pyc
ADDED
Binary file (1.33 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/core/tests/__pycache__/test_var.cpython-310.pyc
ADDED
Binary file (1.91 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/core/tests/test_args.py
ADDED
The diff for this file is too large to render.
See raw diff
|
|
venv/lib/python3.10/site-packages/sympy/core/tests/test_cache.py
ADDED
@@ -0,0 +1,91 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import sys
|
2 |
+
from sympy.core.cache import cacheit, cached_property, lazy_function
|
3 |
+
from sympy.testing.pytest import raises
|
4 |
+
|
5 |
+
def test_cacheit_doc():
|
6 |
+
@cacheit
|
7 |
+
def testfn():
|
8 |
+
"test docstring"
|
9 |
+
pass
|
10 |
+
|
11 |
+
assert testfn.__doc__ == "test docstring"
|
12 |
+
assert testfn.__name__ == "testfn"
|
13 |
+
|
14 |
+
def test_cacheit_unhashable():
|
15 |
+
@cacheit
|
16 |
+
def testit(x):
|
17 |
+
return x
|
18 |
+
|
19 |
+
assert testit(1) == 1
|
20 |
+
assert testit(1) == 1
|
21 |
+
a = {}
|
22 |
+
assert testit(a) == {}
|
23 |
+
a[1] = 2
|
24 |
+
assert testit(a) == {1: 2}
|
25 |
+
|
26 |
+
def test_cachit_exception():
|
27 |
+
# Make sure the cache doesn't call functions multiple times when they
|
28 |
+
# raise TypeError
|
29 |
+
|
30 |
+
a = []
|
31 |
+
|
32 |
+
@cacheit
|
33 |
+
def testf(x):
|
34 |
+
a.append(0)
|
35 |
+
raise TypeError
|
36 |
+
|
37 |
+
raises(TypeError, lambda: testf(1))
|
38 |
+
assert len(a) == 1
|
39 |
+
|
40 |
+
a.clear()
|
41 |
+
# Unhashable type
|
42 |
+
raises(TypeError, lambda: testf([]))
|
43 |
+
assert len(a) == 1
|
44 |
+
|
45 |
+
@cacheit
|
46 |
+
def testf2(x):
|
47 |
+
a.append(0)
|
48 |
+
raise TypeError("Error")
|
49 |
+
|
50 |
+
a.clear()
|
51 |
+
raises(TypeError, lambda: testf2(1))
|
52 |
+
assert len(a) == 1
|
53 |
+
|
54 |
+
a.clear()
|
55 |
+
# Unhashable type
|
56 |
+
raises(TypeError, lambda: testf2([]))
|
57 |
+
assert len(a) == 1
|
58 |
+
|
59 |
+
def test_cached_property():
|
60 |
+
class A:
|
61 |
+
def __init__(self, value):
|
62 |
+
self.value = value
|
63 |
+
self.calls = 0
|
64 |
+
|
65 |
+
@cached_property
|
66 |
+
def prop(self):
|
67 |
+
self.calls = self.calls + 1
|
68 |
+
return self.value
|
69 |
+
|
70 |
+
a = A(2)
|
71 |
+
assert a.calls == 0
|
72 |
+
assert a.prop == 2
|
73 |
+
assert a.calls == 1
|
74 |
+
assert a.prop == 2
|
75 |
+
assert a.calls == 1
|
76 |
+
b = A(None)
|
77 |
+
assert b.prop == None
|
78 |
+
|
79 |
+
|
80 |
+
def test_lazy_function():
|
81 |
+
module_name='xmlrpc.client'
|
82 |
+
function_name = 'gzip_decode'
|
83 |
+
lazy = lazy_function(module_name, function_name)
|
84 |
+
assert lazy(b'') == b''
|
85 |
+
assert module_name in sys.modules
|
86 |
+
assert function_name in str(lazy)
|
87 |
+
repr_lazy = repr(lazy)
|
88 |
+
assert 'LazyFunction' in repr_lazy
|
89 |
+
assert function_name in repr_lazy
|
90 |
+
|
91 |
+
lazy = lazy_function('sympy.core.cache', 'cheap')
|
venv/lib/python3.10/site-packages/sympy/core/tests/test_compatibility.py
ADDED
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.testing.pytest import warns_deprecated_sympy
|
2 |
+
|
3 |
+
def test_compatibility_submodule():
|
4 |
+
# Test the sympy.core.compatibility deprecation warning
|
5 |
+
with warns_deprecated_sympy():
|
6 |
+
import sympy.core.compatibility # noqa:F401
|
venv/lib/python3.10/site-packages/sympy/core/tests/test_complex.py
ADDED
@@ -0,0 +1,226 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.core.function import expand_complex
|
2 |
+
from sympy.core.numbers import (I, Integer, Rational, pi)
|
3 |
+
from sympy.core.power import Pow
|
4 |
+
from sympy.core.singleton import S
|
5 |
+
from sympy.core.symbol import (Symbol, symbols)
|
6 |
+
from sympy.functions.elementary.complexes import (Abs, conjugate, im, re, sign)
|
7 |
+
from sympy.functions.elementary.exponential import exp
|
8 |
+
from sympy.functions.elementary.hyperbolic import (cosh, coth, sinh, tanh)
|
9 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
10 |
+
from sympy.functions.elementary.trigonometric import (cos, cot, sin, tan)
|
11 |
+
|
12 |
+
def test_complex():
|
13 |
+
a = Symbol("a", real=True)
|
14 |
+
b = Symbol("b", real=True)
|
15 |
+
e = (a + I*b)*(a - I*b)
|
16 |
+
assert e.expand() == a**2 + b**2
|
17 |
+
assert sqrt(I) == Pow(I, S.Half)
|
18 |
+
|
19 |
+
|
20 |
+
def test_conjugate():
|
21 |
+
a = Symbol("a", real=True)
|
22 |
+
b = Symbol("b", real=True)
|
23 |
+
c = Symbol("c", imaginary=True)
|
24 |
+
d = Symbol("d", imaginary=True)
|
25 |
+
x = Symbol('x')
|
26 |
+
z = a + I*b + c + I*d
|
27 |
+
zc = a - I*b - c + I*d
|
28 |
+
assert conjugate(z) == zc
|
29 |
+
assert conjugate(exp(z)) == exp(zc)
|
30 |
+
assert conjugate(exp(I*x)) == exp(-I*conjugate(x))
|
31 |
+
assert conjugate(z**5) == zc**5
|
32 |
+
assert conjugate(abs(x)) == abs(x)
|
33 |
+
assert conjugate(sign(z)) == sign(zc)
|
34 |
+
assert conjugate(sin(z)) == sin(zc)
|
35 |
+
assert conjugate(cos(z)) == cos(zc)
|
36 |
+
assert conjugate(tan(z)) == tan(zc)
|
37 |
+
assert conjugate(cot(z)) == cot(zc)
|
38 |
+
assert conjugate(sinh(z)) == sinh(zc)
|
39 |
+
assert conjugate(cosh(z)) == cosh(zc)
|
40 |
+
assert conjugate(tanh(z)) == tanh(zc)
|
41 |
+
assert conjugate(coth(z)) == coth(zc)
|
42 |
+
|
43 |
+
|
44 |
+
def test_abs1():
|
45 |
+
a = Symbol("a", real=True)
|
46 |
+
b = Symbol("b", real=True)
|
47 |
+
assert abs(a) == Abs(a)
|
48 |
+
assert abs(-a) == abs(a)
|
49 |
+
assert abs(a + I*b) == sqrt(a**2 + b**2)
|
50 |
+
|
51 |
+
|
52 |
+
def test_abs2():
|
53 |
+
a = Symbol("a", real=False)
|
54 |
+
b = Symbol("b", real=False)
|
55 |
+
assert abs(a) != a
|
56 |
+
assert abs(-a) != a
|
57 |
+
assert abs(a + I*b) != sqrt(a**2 + b**2)
|
58 |
+
|
59 |
+
|
60 |
+
def test_evalc():
|
61 |
+
x = Symbol("x", real=True)
|
62 |
+
y = Symbol("y", real=True)
|
63 |
+
z = Symbol("z")
|
64 |
+
assert ((x + I*y)**2).expand(complex=True) == x**2 + 2*I*x*y - y**2
|
65 |
+
assert expand_complex(z**(2*I)) == (re((re(z) + I*im(z))**(2*I)) +
|
66 |
+
I*im((re(z) + I*im(z))**(2*I)))
|
67 |
+
assert expand_complex(
|
68 |
+
z**(2*I), deep=False) == I*im(z**(2*I)) + re(z**(2*I))
|
69 |
+
|
70 |
+
assert exp(I*x) != cos(x) + I*sin(x)
|
71 |
+
assert exp(I*x).expand(complex=True) == cos(x) + I*sin(x)
|
72 |
+
assert exp(I*x + y).expand(complex=True) == exp(y)*cos(x) + I*sin(x)*exp(y)
|
73 |
+
|
74 |
+
assert sin(I*x).expand(complex=True) == I * sinh(x)
|
75 |
+
assert sin(x + I*y).expand(complex=True) == sin(x)*cosh(y) + \
|
76 |
+
I * sinh(y) * cos(x)
|
77 |
+
|
78 |
+
assert cos(I*x).expand(complex=True) == cosh(x)
|
79 |
+
assert cos(x + I*y).expand(complex=True) == cos(x)*cosh(y) - \
|
80 |
+
I * sinh(y) * sin(x)
|
81 |
+
|
82 |
+
assert tan(I*x).expand(complex=True) == tanh(x) * I
|
83 |
+
assert tan(x + I*y).expand(complex=True) == (
|
84 |
+
sin(2*x)/(cos(2*x) + cosh(2*y)) +
|
85 |
+
I*sinh(2*y)/(cos(2*x) + cosh(2*y)))
|
86 |
+
|
87 |
+
assert sinh(I*x).expand(complex=True) == I * sin(x)
|
88 |
+
assert sinh(x + I*y).expand(complex=True) == sinh(x)*cos(y) + \
|
89 |
+
I * sin(y) * cosh(x)
|
90 |
+
|
91 |
+
assert cosh(I*x).expand(complex=True) == cos(x)
|
92 |
+
assert cosh(x + I*y).expand(complex=True) == cosh(x)*cos(y) + \
|
93 |
+
I * sin(y) * sinh(x)
|
94 |
+
|
95 |
+
assert tanh(I*x).expand(complex=True) == tan(x) * I
|
96 |
+
assert tanh(x + I*y).expand(complex=True) == (
|
97 |
+
(sinh(x)*cosh(x) + I*cos(y)*sin(y)) /
|
98 |
+
(sinh(x)**2 + cos(y)**2)).expand()
|
99 |
+
|
100 |
+
|
101 |
+
def test_pythoncomplex():
|
102 |
+
x = Symbol("x")
|
103 |
+
assert 4j*x != 4*x*I
|
104 |
+
assert 4j*x == 4.0*x*I
|
105 |
+
assert 4.1j*x != 4*x*I
|
106 |
+
|
107 |
+
|
108 |
+
def test_rootcomplex():
|
109 |
+
R = Rational
|
110 |
+
assert ((+1 + I)**R(1, 2)).expand(
|
111 |
+
complex=True) == 2**R(1, 4)*cos( pi/8) + 2**R(1, 4)*sin( pi/8)*I
|
112 |
+
assert ((-1 - I)**R(1, 2)).expand(
|
113 |
+
complex=True) == 2**R(1, 4)*cos(3*pi/8) - 2**R(1, 4)*sin(3*pi/8)*I
|
114 |
+
assert (sqrt(-10)*I).as_real_imag() == (-sqrt(10), 0)
|
115 |
+
|
116 |
+
|
117 |
+
def test_expand_inverse():
|
118 |
+
assert (1/(1 + I)).expand(complex=True) == (1 - I)/2
|
119 |
+
assert ((1 + 2*I)**(-2)).expand(complex=True) == (-3 - 4*I)/25
|
120 |
+
assert ((1 + I)**(-8)).expand(complex=True) == Rational(1, 16)
|
121 |
+
|
122 |
+
|
123 |
+
def test_expand_complex():
|
124 |
+
assert ((2 + 3*I)**10).expand(complex=True) == -341525 - 145668*I
|
125 |
+
# the following two tests are to ensure the SymPy uses an efficient
|
126 |
+
# algorithm for calculating powers of complex numbers. They should execute
|
127 |
+
# in something like 0.01s.
|
128 |
+
assert ((2 + 3*I)**1000).expand(complex=True) == \
|
129 |
+
-81079464736246615951519029367296227340216902563389546989376269312984127074385455204551402940331021387412262494620336565547972162814110386834027871072723273110439771695255662375718498785908345629702081336606863762777939617745464755635193139022811989314881997210583159045854968310911252660312523907616129080027594310008539817935736331124833163907518549408018652090650537035647520296539436440394920287688149200763245475036722326561143851304795139005599209239350981457301460233967137708519975586996623552182807311159141501424576682074392689622074945519232029999 + \
|
130 |
+
46938745946789557590804551905243206242164799136976022474337918748798900569942573265747576032611189047943842446167719177749107138603040963603119861476016947257034472364028585381714774667326478071264878108114128915685688115488744955550920239128462489496563930809677159214598114273887061533057125164518549173898349061972857446844052995037423459472376202251620778517659247970283904820245958198842631651569984310559418135975795868314764489884749573052997832686979294085577689571149679540256349988338406458116270429842222666345146926395233040564229555893248370000*I
|
131 |
+
assert ((2 + 3*I/4)**1000).expand(complex=True) == \
|
132 |
+
Integer(1)*37079892761199059751745775382463070250205990218394308874593455293485167797989691280095867197640410033222367257278387021789651672598831503296531725827158233077451476545928116965316544607115843772405184272449644892857783761260737279675075819921259597776770965829089907990486964515784097181964312256560561065607846661496055417619388874421218472707497847700629822858068783288579581649321248495739224020822198695759609598745114438265083593711851665996586461937988748911532242908776883696631067311443171682974330675406616373422505939887984366289623091300746049101284856530270685577940283077888955692921951247230006346681086274961362500646889925803654263491848309446197554307105991537357310209426736453173441104334496173618419659521888945605315751089087820455852582920963561495787655250624781448951403353654348109893478206364632640344111022531861683064175862889459084900614967785405977231549003280842218501570429860550379522498497412180001/114813069527425452423283320117768198402231770208869520047764273682576626139237031385665948631650626991844596463898746277344711896086305533142593135616665318539129989145312280000688779148240044871428926990063486244781615463646388363947317026040466353970904996558162398808944629605623311649536164221970332681344168908984458505602379484807914058900934776500429002716706625830522008132236281291761267883317206598995396418127021779858404042159853183251540889433902091920554957783589672039160081957216630582755380425583726015528348786419432054508915275783882625175435528800822842770817965453762184851149029376 + \
|
133 |
+
I*421638390580169706973991429333213477486930178424989246669892530737775352519112934278994501272111385966211392610029433824534634841747911783746811994443436271013377059560245191441549885048056920190833693041257216263519792201852046825443439142932464031501882145407459174948712992271510309541474392303461939389368955986650538525895866713074543004916049550090364398070215427272240155060576252568700906004691224321432509053286859100920489253598392100207663785243368195857086816912514025693453058403158416856847185079684216151337200057494966741268925263085619240941610301610538225414050394612058339070756009433535451561664522479191267503989904464718368605684297071150902631208673621618217106272361061676184840810762902463998065947687814692402219182668782278472952758690939877465065070481351343206840649517150634973307937551168752642148704904383991876969408056379195860410677814566225456558230131911142229028179902418223009651437985670625/1793954211366022694113801876840128100034871409513586250746316776290259783425578615401030447369541046747571819748417910583511123376348523955353017744010395602173906080395504375010762174191250701116076984219741972574712741619474818186676828531882286780795390571221287481389759837587864244524002565968286448146002639202882164150037179450123657170327105882819203167448541028601906377066191895183769810676831353109303069033234715310287563158747705988305326397404720186258671215368588625611876280581509852855552819149745718992630449787803625851701801184123166018366180137512856918294030710215034138299203584
|
134 |
+
assert ((2 + 3*I)**-1000).expand(complex=True) == \
|
135 |
+
Integer(1)*-81079464736246615951519029367296227340216902563389546989376269312984127074385455204551402940331021387412262494620336565547972162814110386834027871072723273110439771695255662375718498785908345629702081336606863762777939617745464755635193139022811989314881997210583159045854968310911252660312523907616129080027594310008539817935736331124833163907518549408018652090650537035647520296539436440394920287688149200763245475036722326561143851304795139005599209239350981457301460233967137708519975586996623552182807311159141501424576682074392689622074945519232029999/8777125472973511649630750050295188683351430110097915876250894978429797369155961290321829625004920141758416719066805645579710744290541337680113772670040386863849283653078324415471816788604945889094925784900885812724984087843737442111926413818245854362613018058774368703971604921858023116665586358870612944209398056562604561248859926344335598822815885851096698226775053153403320782439987679978321289537645645163767251396759519805603090332694449553371530571613352311006350058217982509738362083094920649452123351717366337410243853659113315547584871655479914439219520157174729130746351059075207407866012574386726064196992865627149566238044625779078186624347183905913357718850537058578084932880569701242598663149911276357125355850792073635533676541250531086757377369962506979378337216411188347761901006460813413505861461267545723590468627854202034450569581626648934062198718362303420281555886394558137408159453103395918783625713213314350531051312551733021627153081075080140680608080529736975658786227362251632725009435866547613598753584705455955419696609282059191031962604169242974038517575645939316377801594539335940001 - Integer(1)*46938745946789557590804551905243206242164799136976022474337918748798900569942573265747576032611189047943842446167719177749107138603040963603119861476016947257034472364028585381714774667326478071264878108114128915685688115488744955550920239128462489496563930809677159214598114273887061533057125164518549173898349061972857446844052995037423459472376202251620778517659247970283904820245958198842631651569984310559418135975795868314764489884749573052997832686979294085577689571149679540256349988338406458116270429842222666345146926395233040564229555893248370000*I/8777125472973511649630750050295188683351430110097915876250894978429797369155961290321829625004920141758416719066805645579710744290541337680113772670040386863849283653078324415471816788604945889094925784900885812724984087843737442111926413818245854362613018058774368703971604921858023116665586358870612944209398056562604561248859926344335598822815885851096698226775053153403320782439987679978321289537645645163767251396759519805603090332694449553371530571613352311006350058217982509738362083094920649452123351717366337410243853659113315547584871655479914439219520157174729130746351059075207407866012574386726064196992865627149566238044625779078186624347183905913357718850537058578084932880569701242598663149911276357125355850792073635533676541250531086757377369962506979378337216411188347761901006460813413505861461267545723590468627854202034450569581626648934062198718362303420281555886394558137408159453103395918783625713213314350531051312551733021627153081075080140680608080529736975658786227362251632725009435866547613598753584705455955419696609282059191031962604169242974038517575645939316377801594539335940001
|
136 |
+
assert ((2 + 3*I/4)**-1000).expand(complex=True) == \
|
137 |
+
Integer(1)*4257256305661027385394552848555894604806501409793288342610746813288539790051927148781268212212078237301273165351052934681382567968787279534591114913777456610214738290619922068269909423637926549603264174216950025398244509039145410016404821694746262142525173737175066432954496592560621330313807235750500564940782099283410261748370262433487444897446779072067625787246390824312580440138770014838135245148574339248259670887549732495841810961088930810608893772914812838358159009303794863047635845688453859317690488124382253918725010358589723156019888846606295866740117645571396817375322724096486161308083462637370825829567578309445855481578518239186117686659177284332344643124760453112513611749309168470605289172320376911472635805822082051716625171429727162039621902266619821870482519063133136820085579315127038372190224739238686708451840610064871885616258831386810233957438253532027049148030157164346719204500373766157143311767338973363806106967439378604898250533766359989107510507493549529158818602327525235240510049484816090584478644771183158342479140194633579061295740839490629457435283873180259847394582069479062820225159699506175855369539201399183443253793905149785994830358114153241481884290274629611529758663543080724574566578220908907477622643689220814376054314972190402285121776593824615083669045183404206291739005554569305329760211752815718335731118664756831942466773261465213581616104242113894521054475516019456867271362053692785300826523328020796670205463390909136593859765912483565093461468865534470710132881677639651348709376/2103100954337624833663208713697737151593634525061637972297915388685604042449504336765884978184588688426595940401280828953096857809292320006227881797146858511436638446932833617514351442216409828605662238790280753075176269765767010004889778647709740770757817960711900340755635772183674511158570690702969774966791073165467918123298694584729211212414462628433370481195120564586361368504153395406845170075275051749019600057116719726628746724489572189061061036426955163696859127711110719502594479795200686212257570291758725259007379710596548777812659422174199194837355646482046783616494013289495563083118517507178847555801163089723056310287760875135196081975602765511153122381201303871673391366630940702817360340900568748719988954847590748960761446218262344767250783946365392689256634180417145926390656439421745644011831124277463643383712803287985472471755648426749842410972650924240795946699346613614779460399530274263580007672855851663196114585312432954432654691485867618908420370875753749297487803461900447407917655296784879220450937110470920633595689721819488638484547259978337741496090602390463594556401615298457456112485536498177883358587125449801777718900375736758266215245325999241624148841915093787519330809347240990363802360596034171167818310322276373120180985148650099673289383722502488957717848531612020897298448601714154586319660314294591620415272119454982220034319689607295960162971300417552364254983071768070124456169427638371140064235083443242844616326538396503937972586505546495649094344512270582463639152160238137952390380581401171977159154009407415523525096743009110916334144716516647041176989758534635251844947906038080852185583742296318878233394998111078843229681030277039104786225656992262073797524057992347971177720807155842376332851559276430280477639539393920006008737472164850104411971830120295750221200029811143140323763349636629725073624360001 - Integer(1)*3098214262599218784594285246258841485430681674561917573155883806818465520660668045042109232930382494608383663464454841313154390741655282039877410154577448327874989496074260116195788919037407420625081798124301494353693248757853222257918294662198297114746822817460991242508743651430439120439020484502408313310689912381846149597061657483084652685283853595100434135149479564507015504022249330340259111426799121454516345905101620532787348293877485702600390665276070250119465888154331218827342488849948540687659846652377277250614246402784754153678374932540789808703029043827352976139228402417432199779415751301480406673762521987999573209628597459357964214510139892316208670927074795773830798600837815329291912002136924506221066071242281626618211060464126372574400100990746934953437169840312584285942093951405864225230033279614235191326102697164613004299868695519642598882914862568516635347204441042798206770888274175592401790040170576311989738272102077819127459014286741435419468254146418098278519775722104890854275995510700298782146199325790002255362719776098816136732897323406228294203133323296591166026338391813696715894870956511298793595675308998014158717167429941371979636895553724830981754579086664608880698350866487717403917070872269853194118364230971216854931998642990452908852258008095741042117326241406479532880476938937997238098399302185675832474590293188864060116934035867037219176916416481757918864533515526389079998129329045569609325290897577497835388451456680707076072624629697883854217331728051953671643278797380171857920000*I/2103100954337624833663208713697737151593634525061637972297915388685604042449504336765884978184588688426595940401280828953096857809292320006227881797146858511436638446932833617514351442216409828605662238790280753075176269765767010004889778647709740770757817960711900340755635772183674511158570690702969774966791073165467918123298694584729211212414462628433370481195120564586361368504153395406845170075275051749019600057116719726628746724489572189061061036426955163696859127711110719502594479795200686212257570291758725259007379710596548777812659422174199194837355646482046783616494013289495563083118517507178847555801163089723056310287760875135196081975602765511153122381201303871673391366630940702817360340900568748719988954847590748960761446218262344767250783946365392689256634180417145926390656439421745644011831124277463643383712803287985472471755648426749842410972650924240795946699346613614779460399530274263580007672855851663196114585312432954432654691485867618908420370875753749297487803461900447407917655296784879220450937110470920633595689721819488638484547259978337741496090602390463594556401615298457456112485536498177883358587125449801777718900375736758266215245325999241624148841915093787519330809347240990363802360596034171167818310322276373120180985148650099673289383722502488957717848531612020897298448601714154586319660314294591620415272119454982220034319689607295960162971300417552364254983071768070124456169427638371140064235083443242844616326538396503937972586505546495649094344512270582463639152160238137952390380581401171977159154009407415523525096743009110916334144716516647041176989758534635251844947906038080852185583742296318878233394998111078843229681030277039104786225656992262073797524057992347971177720807155842376332851559276430280477639539393920006008737472164850104411971830120295750221200029811143140323763349636629725073624360001
|
138 |
+
|
139 |
+
a = Symbol('a', real=True)
|
140 |
+
b = Symbol('b', real=True)
|
141 |
+
assert exp(a*(2 + I*b)).expand(complex=True) == \
|
142 |
+
I*exp(2*a)*sin(a*b) + exp(2*a)*cos(a*b)
|
143 |
+
|
144 |
+
|
145 |
+
def test_expand():
|
146 |
+
f = (16 - 2*sqrt(29))**2
|
147 |
+
assert f.expand() == 372 - 64*sqrt(29)
|
148 |
+
f = (Integer(1)/2 + I/2)**10
|
149 |
+
assert f.expand() == I/32
|
150 |
+
f = (Integer(1)/2 + I)**10
|
151 |
+
assert f.expand() == Integer(237)/1024 - 779*I/256
|
152 |
+
|
153 |
+
|
154 |
+
def test_re_im1652():
|
155 |
+
x = Symbol('x')
|
156 |
+
assert re(x) == re(conjugate(x))
|
157 |
+
assert im(x) == - im(conjugate(x))
|
158 |
+
assert im(x)*re(conjugate(x)) + im(conjugate(x)) * re(x) == 0
|
159 |
+
|
160 |
+
|
161 |
+
def test_issue_5084():
|
162 |
+
x = Symbol('x')
|
163 |
+
assert ((x + x*I)/(1 + I)).as_real_imag() == (re((x + I*x)/(1 + I)
|
164 |
+
), im((x + I*x)/(1 + I)))
|
165 |
+
|
166 |
+
|
167 |
+
def test_issue_5236():
|
168 |
+
assert (cos(1 + I)**3).as_real_imag() == (-3*sin(1)**2*sinh(1)**2*cos(1)*cosh(1) +
|
169 |
+
cos(1)**3*cosh(1)**3, -3*cos(1)**2*cosh(1)**2*sin(1)*sinh(1) + sin(1)**3*sinh(1)**3)
|
170 |
+
|
171 |
+
|
172 |
+
def test_real_imag():
|
173 |
+
x, y, z = symbols('x, y, z')
|
174 |
+
X, Y, Z = symbols('X, Y, Z', commutative=False)
|
175 |
+
a = Symbol('a', real=True)
|
176 |
+
assert (2*a*x).as_real_imag() == (2*a*re(x), 2*a*im(x))
|
177 |
+
|
178 |
+
# issue 5395:
|
179 |
+
assert (x*x.conjugate()).as_real_imag() == (Abs(x)**2, 0)
|
180 |
+
assert im(x*x.conjugate()) == 0
|
181 |
+
assert im(x*y.conjugate()*z*y) == im(x*z)*Abs(y)**2
|
182 |
+
assert im(x*y.conjugate()*x*y) == im(x**2)*Abs(y)**2
|
183 |
+
assert im(Z*y.conjugate()*X*y) == im(Z*X)*Abs(y)**2
|
184 |
+
assert im(X*X.conjugate()) == im(X*X.conjugate(), evaluate=False)
|
185 |
+
assert (sin(x)*sin(x).conjugate()).as_real_imag() == \
|
186 |
+
(Abs(sin(x))**2, 0)
|
187 |
+
|
188 |
+
# issue 6573:
|
189 |
+
assert (x**2).as_real_imag() == (re(x)**2 - im(x)**2, 2*re(x)*im(x))
|
190 |
+
|
191 |
+
# issue 6428:
|
192 |
+
r = Symbol('r', real=True)
|
193 |
+
i = Symbol('i', imaginary=True)
|
194 |
+
assert (i*r*x).as_real_imag() == (I*i*r*im(x), -I*i*r*re(x))
|
195 |
+
assert (i*r*x*(y + 2)).as_real_imag() == (
|
196 |
+
I*i*r*(re(y) + 2)*im(x) + I*i*r*re(x)*im(y),
|
197 |
+
-I*i*r*(re(y) + 2)*re(x) + I*i*r*im(x)*im(y))
|
198 |
+
|
199 |
+
# issue 7106:
|
200 |
+
assert ((1 + I)/(1 - I)).as_real_imag() == (0, 1)
|
201 |
+
assert ((1 + 2*I)*(1 + 3*I)).as_real_imag() == (-5, 5)
|
202 |
+
|
203 |
+
|
204 |
+
def test_pow_issue_1724():
|
205 |
+
e = ((S.NegativeOne)**(S.One/3))
|
206 |
+
assert e.conjugate().n() == e.n().conjugate()
|
207 |
+
e = S('-2/3 - (-29/54 + sqrt(93)/18)**(1/3) - 1/(9*(-29/54 + sqrt(93)/18)**(1/3))')
|
208 |
+
assert e.conjugate().n() == e.n().conjugate()
|
209 |
+
e = 2**I
|
210 |
+
assert e.conjugate().n() == e.n().conjugate()
|
211 |
+
|
212 |
+
|
213 |
+
def test_issue_5429():
|
214 |
+
assert sqrt(I).conjugate() != sqrt(I)
|
215 |
+
|
216 |
+
def test_issue_4124():
|
217 |
+
from sympy.core.numbers import oo
|
218 |
+
assert expand_complex(I*oo) == oo*I
|
219 |
+
|
220 |
+
def test_issue_11518():
|
221 |
+
x = Symbol("x", real=True)
|
222 |
+
y = Symbol("y", real=True)
|
223 |
+
r = sqrt(x**2 + y**2)
|
224 |
+
assert conjugate(r) == r
|
225 |
+
s = abs(x + I * y)
|
226 |
+
assert conjugate(s) == r
|
venv/lib/python3.10/site-packages/sympy/core/tests/test_constructor_postprocessor.py
ADDED
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.core.basic import Basic
|
2 |
+
from sympy.core.mul import Mul
|
3 |
+
from sympy.core.symbol import (Symbol, symbols)
|
4 |
+
|
5 |
+
from sympy.testing.pytest import XFAIL
|
6 |
+
|
7 |
+
class SymbolInMulOnce(Symbol):
|
8 |
+
# Test class for a symbol that can only appear once in a `Mul` expression.
|
9 |
+
pass
|
10 |
+
|
11 |
+
|
12 |
+
Basic._constructor_postprocessor_mapping[SymbolInMulOnce] = {
|
13 |
+
"Mul": [lambda x: x],
|
14 |
+
"Pow": [lambda x: x.base if isinstance(x.base, SymbolInMulOnce) else x],
|
15 |
+
"Add": [lambda x: x],
|
16 |
+
}
|
17 |
+
|
18 |
+
|
19 |
+
def _postprocess_SymbolRemovesOtherSymbols(expr):
|
20 |
+
args = tuple(i for i in expr.args if not isinstance(i, Symbol) or isinstance(i, SymbolRemovesOtherSymbols))
|
21 |
+
if args == expr.args:
|
22 |
+
return expr
|
23 |
+
return Mul.fromiter(args)
|
24 |
+
|
25 |
+
|
26 |
+
class SymbolRemovesOtherSymbols(Symbol):
|
27 |
+
# Test class for a symbol that removes other symbols in `Mul`.
|
28 |
+
pass
|
29 |
+
|
30 |
+
Basic._constructor_postprocessor_mapping[SymbolRemovesOtherSymbols] = {
|
31 |
+
"Mul": [_postprocess_SymbolRemovesOtherSymbols],
|
32 |
+
}
|
33 |
+
|
34 |
+
class SubclassSymbolInMulOnce(SymbolInMulOnce):
|
35 |
+
pass
|
36 |
+
|
37 |
+
class SubclassSymbolRemovesOtherSymbols(SymbolRemovesOtherSymbols):
|
38 |
+
pass
|
39 |
+
|
40 |
+
|
41 |
+
def test_constructor_postprocessors1():
|
42 |
+
x = SymbolInMulOnce("x")
|
43 |
+
y = SymbolInMulOnce("y")
|
44 |
+
assert isinstance(3*x, Mul)
|
45 |
+
assert (3*x).args == (3, x)
|
46 |
+
assert x*x == x
|
47 |
+
assert 3*x*x == 3*x
|
48 |
+
assert 2*x*x + x == 3*x
|
49 |
+
assert x**3*y*y == x*y
|
50 |
+
assert x**5 + y*x**3 == x + x*y
|
51 |
+
|
52 |
+
w = SymbolRemovesOtherSymbols("w")
|
53 |
+
assert x*w == w
|
54 |
+
assert (3*w).args == (3, w)
|
55 |
+
assert set((w + x).args) == {x, w}
|
56 |
+
|
57 |
+
def test_constructor_postprocessors2():
|
58 |
+
x = SubclassSymbolInMulOnce("x")
|
59 |
+
y = SubclassSymbolInMulOnce("y")
|
60 |
+
assert isinstance(3*x, Mul)
|
61 |
+
assert (3*x).args == (3, x)
|
62 |
+
assert x*x == x
|
63 |
+
assert 3*x*x == 3*x
|
64 |
+
assert 2*x*x + x == 3*x
|
65 |
+
assert x**3*y*y == x*y
|
66 |
+
assert x**5 + y*x**3 == x + x*y
|
67 |
+
|
68 |
+
w = SubclassSymbolRemovesOtherSymbols("w")
|
69 |
+
assert x*w == w
|
70 |
+
assert (3*w).args == (3, w)
|
71 |
+
assert set((w + x).args) == {x, w}
|
72 |
+
|
73 |
+
|
74 |
+
@XFAIL
|
75 |
+
def test_subexpression_postprocessors():
|
76 |
+
# The postprocessors used to work with subexpressions, but the
|
77 |
+
# functionality was removed. See #15948.
|
78 |
+
a = symbols("a")
|
79 |
+
x = SymbolInMulOnce("x")
|
80 |
+
w = SymbolRemovesOtherSymbols("w")
|
81 |
+
assert 3*a*w**2 == 3*w**2
|
82 |
+
assert 3*a*x**3*w**2 == 3*w**2
|
83 |
+
|
84 |
+
x = SubclassSymbolInMulOnce("x")
|
85 |
+
w = SubclassSymbolRemovesOtherSymbols("w")
|
86 |
+
assert 3*a*w**2 == 3*w**2
|
87 |
+
assert 3*a*x**3*w**2 == 3*w**2
|
venv/lib/python3.10/site-packages/sympy/core/tests/test_count_ops.py
ADDED
@@ -0,0 +1,155 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.concrete.summations import Sum
|
2 |
+
from sympy.core.basic import Basic
|
3 |
+
from sympy.core.function import (Derivative, Function, count_ops)
|
4 |
+
from sympy.core.numbers import (I, Rational, pi)
|
5 |
+
from sympy.core.relational import (Eq, Rel)
|
6 |
+
from sympy.core.singleton import S
|
7 |
+
from sympy.core.symbol import (Symbol, symbols)
|
8 |
+
from sympy.functions.elementary.exponential import exp
|
9 |
+
from sympy.functions.elementary.trigonometric import (cos, sin)
|
10 |
+
from sympy.integrals.integrals import Integral
|
11 |
+
from sympy.logic.boolalg import (And, Equivalent, ITE, Implies, Nand,
|
12 |
+
Nor, Not, Or, Xor)
|
13 |
+
from sympy.matrices.expressions.matexpr import MatrixSymbol
|
14 |
+
from sympy.core.containers import Tuple
|
15 |
+
|
16 |
+
x, y, z = symbols('x,y,z')
|
17 |
+
a, b, c = symbols('a,b,c')
|
18 |
+
|
19 |
+
def test_count_ops_non_visual():
|
20 |
+
def count(val):
|
21 |
+
return count_ops(val, visual=False)
|
22 |
+
assert count(x) == 0
|
23 |
+
assert count(x) is not S.Zero
|
24 |
+
assert count(x + y) == 1
|
25 |
+
assert count(x + y) is not S.One
|
26 |
+
assert count(x + y*x + 2*y) == 4
|
27 |
+
assert count({x + y: x}) == 1
|
28 |
+
assert count({x + y: S(2) + x}) is not S.One
|
29 |
+
assert count(x < y) == 1
|
30 |
+
assert count(Or(x,y)) == 1
|
31 |
+
assert count(And(x,y)) == 1
|
32 |
+
assert count(Not(x)) == 1
|
33 |
+
assert count(Nor(x,y)) == 2
|
34 |
+
assert count(Nand(x,y)) == 2
|
35 |
+
assert count(Xor(x,y)) == 1
|
36 |
+
assert count(Implies(x,y)) == 1
|
37 |
+
assert count(Equivalent(x,y)) == 1
|
38 |
+
assert count(ITE(x,y,z)) == 1
|
39 |
+
assert count(ITE(True,x,y)) == 0
|
40 |
+
|
41 |
+
|
42 |
+
def test_count_ops_visual():
|
43 |
+
ADD, MUL, POW, SIN, COS, EXP, AND, D, G, M = symbols(
|
44 |
+
'Add Mul Pow sin cos exp And Derivative Integral Sum'.upper())
|
45 |
+
DIV, SUB, NEG = symbols('DIV SUB NEG')
|
46 |
+
LT, LE, GT, GE, EQ, NE = symbols('LT LE GT GE EQ NE')
|
47 |
+
NOT, OR, AND, XOR, IMPLIES, EQUIVALENT, _ITE, BASIC, TUPLE = symbols(
|
48 |
+
'Not Or And Xor Implies Equivalent ITE Basic Tuple'.upper())
|
49 |
+
|
50 |
+
def count(val):
|
51 |
+
return count_ops(val, visual=True)
|
52 |
+
|
53 |
+
assert count(7) is S.Zero
|
54 |
+
assert count(S(7)) is S.Zero
|
55 |
+
assert count(-1) == NEG
|
56 |
+
assert count(-2) == NEG
|
57 |
+
assert count(S(2)/3) == DIV
|
58 |
+
assert count(Rational(2, 3)) == DIV
|
59 |
+
assert count(pi/3) == DIV
|
60 |
+
assert count(-pi/3) == DIV + NEG
|
61 |
+
assert count(I - 1) == SUB
|
62 |
+
assert count(1 - I) == SUB
|
63 |
+
assert count(1 - 2*I) == SUB + MUL
|
64 |
+
|
65 |
+
assert count(x) is S.Zero
|
66 |
+
assert count(-x) == NEG
|
67 |
+
assert count(-2*x/3) == NEG + DIV + MUL
|
68 |
+
assert count(Rational(-2, 3)*x) == NEG + DIV + MUL
|
69 |
+
assert count(1/x) == DIV
|
70 |
+
assert count(1/(x*y)) == DIV + MUL
|
71 |
+
assert count(-1/x) == NEG + DIV
|
72 |
+
assert count(-2/x) == NEG + DIV
|
73 |
+
assert count(x/y) == DIV
|
74 |
+
assert count(-x/y) == NEG + DIV
|
75 |
+
|
76 |
+
assert count(x**2) == POW
|
77 |
+
assert count(-x**2) == POW + NEG
|
78 |
+
assert count(-2*x**2) == POW + MUL + NEG
|
79 |
+
|
80 |
+
assert count(x + pi/3) == ADD + DIV
|
81 |
+
assert count(x + S.One/3) == ADD + DIV
|
82 |
+
assert count(x + Rational(1, 3)) == ADD + DIV
|
83 |
+
assert count(x + y) == ADD
|
84 |
+
assert count(x - y) == SUB
|
85 |
+
assert count(y - x) == SUB
|
86 |
+
assert count(-1/(x - y)) == DIV + NEG + SUB
|
87 |
+
assert count(-1/(y - x)) == DIV + NEG + SUB
|
88 |
+
assert count(1 + x**y) == ADD + POW
|
89 |
+
assert count(1 + x + y) == 2*ADD
|
90 |
+
assert count(1 + x + y + z) == 3*ADD
|
91 |
+
assert count(1 + x**y + 2*x*y + y**2) == 3*ADD + 2*POW + 2*MUL
|
92 |
+
assert count(2*z + y + x + 1) == 3*ADD + MUL
|
93 |
+
assert count(2*z + y**17 + x + 1) == 3*ADD + MUL + POW
|
94 |
+
assert count(2*z + y**17 + x + sin(x)) == 3*ADD + POW + MUL + SIN
|
95 |
+
assert count(2*z + y**17 + x + sin(x**2)) == 3*ADD + MUL + 2*POW + SIN
|
96 |
+
assert count(2*z + y**17 + x + sin(
|
97 |
+
x**2) + exp(cos(x))) == 4*ADD + MUL + 2*POW + EXP + COS + SIN
|
98 |
+
|
99 |
+
assert count(Derivative(x, x)) == D
|
100 |
+
assert count(Integral(x, x) + 2*x/(1 + x)) == G + DIV + MUL + 2*ADD
|
101 |
+
assert count(Sum(x, (x, 1, x + 1)) + 2*x/(1 + x)) == M + DIV + MUL + 3*ADD
|
102 |
+
assert count(Basic()) is S.Zero
|
103 |
+
|
104 |
+
assert count({x + 1: sin(x)}) == ADD + SIN
|
105 |
+
assert count([x + 1, sin(x) + y, None]) == ADD + SIN + ADD
|
106 |
+
assert count({x + 1: sin(x), y: cos(x) + 1}) == SIN + COS + 2*ADD
|
107 |
+
assert count({}) is S.Zero
|
108 |
+
assert count([x + 1, sin(x)*y, None]) == SIN + ADD + MUL
|
109 |
+
assert count([]) is S.Zero
|
110 |
+
|
111 |
+
assert count(Basic()) == 0
|
112 |
+
assert count(Basic(Basic(),Basic(x,x+y))) == ADD + 2*BASIC
|
113 |
+
assert count(Basic(x, x + y)) == ADD + BASIC
|
114 |
+
assert [count(Rel(x, y, op)) for op in '< <= > >= == <> !='.split()
|
115 |
+
] == [LT, LE, GT, GE, EQ, NE, NE]
|
116 |
+
assert count(Or(x, y)) == OR
|
117 |
+
assert count(And(x, y)) == AND
|
118 |
+
assert count(Or(x, Or(y, And(z, a)))) == AND + OR
|
119 |
+
assert count(Nor(x, y)) == NOT + OR
|
120 |
+
assert count(Nand(x, y)) == NOT + AND
|
121 |
+
assert count(Xor(x, y)) == XOR
|
122 |
+
assert count(Implies(x, y)) == IMPLIES
|
123 |
+
assert count(Equivalent(x, y)) == EQUIVALENT
|
124 |
+
assert count(ITE(x, y, z)) == _ITE
|
125 |
+
assert count([Or(x, y), And(x, y), Basic(x + y)]
|
126 |
+
) == ADD + AND + BASIC + OR
|
127 |
+
|
128 |
+
assert count(Basic(Tuple(x))) == BASIC + TUPLE
|
129 |
+
#It checks that TUPLE is counted as an operation.
|
130 |
+
|
131 |
+
assert count(Eq(x + y, S(2))) == ADD + EQ
|
132 |
+
|
133 |
+
|
134 |
+
def test_issue_9324():
|
135 |
+
def count(val):
|
136 |
+
return count_ops(val, visual=False)
|
137 |
+
|
138 |
+
M = MatrixSymbol('M', 10, 10)
|
139 |
+
assert count(M[0, 0]) == 0
|
140 |
+
assert count(2 * M[0, 0] + M[5, 7]) == 2
|
141 |
+
P = MatrixSymbol('P', 3, 3)
|
142 |
+
Q = MatrixSymbol('Q', 3, 3)
|
143 |
+
assert count(P + Q) == 1
|
144 |
+
m = Symbol('m', integer=True)
|
145 |
+
n = Symbol('n', integer=True)
|
146 |
+
M = MatrixSymbol('M', m + n, m * m)
|
147 |
+
assert count(M[0, 1]) == 2
|
148 |
+
|
149 |
+
|
150 |
+
def test_issue_21532():
|
151 |
+
f = Function('f')
|
152 |
+
g = Function('g')
|
153 |
+
FUNC_F, FUNC_G = symbols('FUNC_F, FUNC_G')
|
154 |
+
assert f(x).count_ops(visual=True) == FUNC_F
|
155 |
+
assert g(x).count_ops(visual=True) == FUNC_G
|