Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- evalkit_tf437/lib/python3.10/site-packages/sympy/functions/__init__.py +115 -0
- evalkit_tf437/lib/python3.10/site-packages/sympy/functions/elementary/__init__.py +1 -0
- evalkit_tf437/lib/python3.10/site-packages/sympy/functions/elementary/__pycache__/exponential.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/sympy/functions/elementary/__pycache__/hyperbolic.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/sympy/functions/elementary/__pycache__/integers.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/sympy/functions/elementary/__pycache__/miscellaneous.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/sympy/functions/elementary/__pycache__/trigonometric.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/sympy/functions/elementary/_trigonometric_special.py +261 -0
- evalkit_tf437/lib/python3.10/site-packages/sympy/functions/elementary/complexes.py +1473 -0
- evalkit_tf437/lib/python3.10/site-packages/sympy/functions/elementary/exponential.py +1293 -0
- evalkit_tf437/lib/python3.10/site-packages/sympy/functions/elementary/hyperbolic.py +2285 -0
- evalkit_tf437/lib/python3.10/site-packages/sympy/functions/elementary/integers.py +645 -0
- evalkit_tf437/lib/python3.10/site-packages/sympy/functions/elementary/miscellaneous.py +915 -0
- evalkit_tf437/lib/python3.10/site-packages/sympy/functions/elementary/piecewise.py +1516 -0
- evalkit_tf437/lib/python3.10/site-packages/sympy/functions/elementary/tests/__init__.py +0 -0
- evalkit_tf437/lib/python3.10/site-packages/sympy/functions/elementary/tests/__pycache__/test_integers.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/sympy/functions/elementary/tests/__pycache__/test_interface.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/sympy/functions/elementary/tests/test_complexes.py +1028 -0
- evalkit_tf437/lib/python3.10/site-packages/sympy/functions/elementary/tests/test_exponential.py +809 -0
- evalkit_tf437/lib/python3.10/site-packages/sympy/functions/elementary/tests/test_hyperbolic.py +1542 -0
- evalkit_tf437/lib/python3.10/site-packages/sympy/functions/elementary/tests/test_interface.py +72 -0
- evalkit_tf437/lib/python3.10/site-packages/sympy/testing/__init__.py +10 -0
- evalkit_tf437/lib/python3.10/site-packages/sympy/testing/__pycache__/__init__.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/sympy/testing/__pycache__/matrices.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/sympy/testing/__pycache__/pytest.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/sympy/testing/__pycache__/quality_unicode.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/sympy/testing/__pycache__/randtest.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/sympy/testing/__pycache__/runtests.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/sympy/testing/__pycache__/runtests_pytest.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/sympy/testing/__pycache__/tmpfiles.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/sympy/testing/matrices.py +8 -0
- evalkit_tf437/lib/python3.10/site-packages/sympy/testing/pytest.py +401 -0
- evalkit_tf437/lib/python3.10/site-packages/sympy/testing/quality_unicode.py +102 -0
- evalkit_tf437/lib/python3.10/site-packages/sympy/testing/randtest.py +19 -0
- evalkit_tf437/lib/python3.10/site-packages/sympy/testing/runtests.py +2409 -0
- evalkit_tf437/lib/python3.10/site-packages/sympy/testing/runtests_pytest.py +475 -0
- evalkit_tf437/lib/python3.10/site-packages/sympy/testing/tests/__init__.py +0 -0
- evalkit_tf437/lib/python3.10/site-packages/sympy/testing/tests/__pycache__/__init__.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/sympy/testing/tests/__pycache__/diagnose_imports.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/sympy/testing/tests/__pycache__/test_code_quality.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/sympy/testing/tests/__pycache__/test_deprecated.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/sympy/testing/tests/__pycache__/test_module_imports.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/sympy/testing/tests/__pycache__/test_pytest.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/sympy/testing/tests/__pycache__/test_runtests_pytest.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/sympy/testing/tests/diagnose_imports.py +218 -0
- evalkit_tf437/lib/python3.10/site-packages/sympy/testing/tests/test_code_quality.py +510 -0
- evalkit_tf437/lib/python3.10/site-packages/sympy/testing/tests/test_deprecated.py +5 -0
- evalkit_tf437/lib/python3.10/site-packages/sympy/testing/tests/test_module_imports.py +42 -0
- evalkit_tf437/lib/python3.10/site-packages/sympy/testing/tests/test_pytest.py +211 -0
- evalkit_tf437/lib/python3.10/site-packages/sympy/testing/tests/test_runtests_pytest.py +178 -0
evalkit_tf437/lib/python3.10/site-packages/sympy/functions/__init__.py
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""A functions module, includes all the standard functions.
|
| 2 |
+
|
| 3 |
+
Combinatorial - factorial, fibonacci, harmonic, bernoulli...
|
| 4 |
+
Elementary - hyperbolic, trigonometric, exponential, floor and ceiling, sqrt...
|
| 5 |
+
Special - gamma, zeta,spherical harmonics...
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from sympy.functions.combinatorial.factorials import (factorial, factorial2,
|
| 9 |
+
rf, ff, binomial, RisingFactorial, FallingFactorial, subfactorial)
|
| 10 |
+
from sympy.functions.combinatorial.numbers import (carmichael, fibonacci, lucas, tribonacci,
|
| 11 |
+
harmonic, bernoulli, bell, euler, catalan, genocchi, andre, partition, divisor_sigma,
|
| 12 |
+
udivisor_sigma, legendre_symbol, jacobi_symbol, kronecker_symbol, mobius,
|
| 13 |
+
primenu, primeomega, totient, reduced_totient, primepi, motzkin)
|
| 14 |
+
from sympy.functions.elementary.miscellaneous import (sqrt, root, Min, Max,
|
| 15 |
+
Id, real_root, cbrt, Rem)
|
| 16 |
+
from sympy.functions.elementary.complexes import (re, im, sign, Abs,
|
| 17 |
+
conjugate, arg, polar_lift, periodic_argument, unbranched_argument,
|
| 18 |
+
principal_branch, transpose, adjoint, polarify, unpolarify)
|
| 19 |
+
from sympy.functions.elementary.trigonometric import (sin, cos, tan,
|
| 20 |
+
sec, csc, cot, sinc, asin, acos, atan, asec, acsc, acot, atan2)
|
| 21 |
+
from sympy.functions.elementary.exponential import (exp_polar, exp, log,
|
| 22 |
+
LambertW)
|
| 23 |
+
from sympy.functions.elementary.hyperbolic import (sinh, cosh, tanh, coth,
|
| 24 |
+
sech, csch, asinh, acosh, atanh, acoth, asech, acsch)
|
| 25 |
+
from sympy.functions.elementary.integers import floor, ceiling, frac
|
| 26 |
+
from sympy.functions.elementary.piecewise import (Piecewise, piecewise_fold,
|
| 27 |
+
piecewise_exclusive)
|
| 28 |
+
from sympy.functions.special.error_functions import (erf, erfc, erfi, erf2,
|
| 29 |
+
erfinv, erfcinv, erf2inv, Ei, expint, E1, li, Li, Si, Ci, Shi, Chi,
|
| 30 |
+
fresnels, fresnelc)
|
| 31 |
+
from sympy.functions.special.gamma_functions import (gamma, lowergamma,
|
| 32 |
+
uppergamma, polygamma, loggamma, digamma, trigamma, multigamma)
|
| 33 |
+
from sympy.functions.special.zeta_functions import (dirichlet_eta, zeta,
|
| 34 |
+
lerchphi, polylog, stieltjes, riemann_xi)
|
| 35 |
+
from sympy.functions.special.tensor_functions import (Eijk, LeviCivita,
|
| 36 |
+
KroneckerDelta)
|
| 37 |
+
from sympy.functions.special.singularity_functions import SingularityFunction
|
| 38 |
+
from sympy.functions.special.delta_functions import DiracDelta, Heaviside
|
| 39 |
+
from sympy.functions.special.bsplines import bspline_basis, bspline_basis_set, interpolating_spline
|
| 40 |
+
from sympy.functions.special.bessel import (besselj, bessely, besseli, besselk,
|
| 41 |
+
hankel1, hankel2, jn, yn, jn_zeros, hn1, hn2, airyai, airybi, airyaiprime, airybiprime, marcumq)
|
| 42 |
+
from sympy.functions.special.hyper import hyper, meijerg, appellf1
|
| 43 |
+
from sympy.functions.special.polynomials import (legendre, assoc_legendre,
|
| 44 |
+
hermite, hermite_prob, chebyshevt, chebyshevu, chebyshevu_root,
|
| 45 |
+
chebyshevt_root, laguerre, assoc_laguerre, gegenbauer, jacobi, jacobi_normalized)
|
| 46 |
+
from sympy.functions.special.spherical_harmonics import Ynm, Ynm_c, Znm
|
| 47 |
+
from sympy.functions.special.elliptic_integrals import (elliptic_k,
|
| 48 |
+
elliptic_f, elliptic_e, elliptic_pi)
|
| 49 |
+
from sympy.functions.special.beta_functions import beta, betainc, betainc_regularized
|
| 50 |
+
from sympy.functions.special.mathieu_functions import (mathieus, mathieuc,
|
| 51 |
+
mathieusprime, mathieucprime)
|
| 52 |
+
ln = log
|
| 53 |
+
|
| 54 |
+
__all__ = [
|
| 55 |
+
'factorial', 'factorial2', 'rf', 'ff', 'binomial', 'RisingFactorial',
|
| 56 |
+
'FallingFactorial', 'subfactorial',
|
| 57 |
+
|
| 58 |
+
'carmichael', 'fibonacci', 'lucas', 'motzkin', 'tribonacci', 'harmonic',
|
| 59 |
+
'bernoulli', 'bell', 'euler', 'catalan', 'genocchi', 'andre', 'partition',
|
| 60 |
+
'divisor_sigma', 'udivisor_sigma', 'legendre_symbol', 'jacobi_symbol', 'kronecker_symbol',
|
| 61 |
+
'mobius', 'primenu', 'primeomega', 'totient', 'reduced_totient', 'primepi',
|
| 62 |
+
|
| 63 |
+
'sqrt', 'root', 'Min', 'Max', 'Id', 'real_root', 'cbrt', 'Rem',
|
| 64 |
+
|
| 65 |
+
're', 'im', 'sign', 'Abs', 'conjugate', 'arg', 'polar_lift',
|
| 66 |
+
'periodic_argument', 'unbranched_argument', 'principal_branch',
|
| 67 |
+
'transpose', 'adjoint', 'polarify', 'unpolarify',
|
| 68 |
+
|
| 69 |
+
'sin', 'cos', 'tan', 'sec', 'csc', 'cot', 'sinc', 'asin', 'acos', 'atan',
|
| 70 |
+
'asec', 'acsc', 'acot', 'atan2',
|
| 71 |
+
|
| 72 |
+
'exp_polar', 'exp', 'ln', 'log', 'LambertW',
|
| 73 |
+
|
| 74 |
+
'sinh', 'cosh', 'tanh', 'coth', 'sech', 'csch', 'asinh', 'acosh', 'atanh',
|
| 75 |
+
'acoth', 'asech', 'acsch',
|
| 76 |
+
|
| 77 |
+
'floor', 'ceiling', 'frac',
|
| 78 |
+
|
| 79 |
+
'Piecewise', 'piecewise_fold', 'piecewise_exclusive',
|
| 80 |
+
|
| 81 |
+
'erf', 'erfc', 'erfi', 'erf2', 'erfinv', 'erfcinv', 'erf2inv', 'Ei',
|
| 82 |
+
'expint', 'E1', 'li', 'Li', 'Si', 'Ci', 'Shi', 'Chi', 'fresnels',
|
| 83 |
+
'fresnelc',
|
| 84 |
+
|
| 85 |
+
'gamma', 'lowergamma', 'uppergamma', 'polygamma', 'loggamma', 'digamma',
|
| 86 |
+
'trigamma', 'multigamma',
|
| 87 |
+
|
| 88 |
+
'dirichlet_eta', 'zeta', 'lerchphi', 'polylog', 'stieltjes', 'riemann_xi',
|
| 89 |
+
|
| 90 |
+
'Eijk', 'LeviCivita', 'KroneckerDelta',
|
| 91 |
+
|
| 92 |
+
'SingularityFunction',
|
| 93 |
+
|
| 94 |
+
'DiracDelta', 'Heaviside',
|
| 95 |
+
|
| 96 |
+
'bspline_basis', 'bspline_basis_set', 'interpolating_spline',
|
| 97 |
+
|
| 98 |
+
'besselj', 'bessely', 'besseli', 'besselk', 'hankel1', 'hankel2', 'jn',
|
| 99 |
+
'yn', 'jn_zeros', 'hn1', 'hn2', 'airyai', 'airybi', 'airyaiprime',
|
| 100 |
+
'airybiprime', 'marcumq',
|
| 101 |
+
|
| 102 |
+
'hyper', 'meijerg', 'appellf1',
|
| 103 |
+
|
| 104 |
+
'legendre', 'assoc_legendre', 'hermite', 'hermite_prob', 'chebyshevt',
|
| 105 |
+
'chebyshevu', 'chebyshevu_root', 'chebyshevt_root', 'laguerre',
|
| 106 |
+
'assoc_laguerre', 'gegenbauer', 'jacobi', 'jacobi_normalized',
|
| 107 |
+
|
| 108 |
+
'Ynm', 'Ynm_c', 'Znm',
|
| 109 |
+
|
| 110 |
+
'elliptic_k', 'elliptic_f', 'elliptic_e', 'elliptic_pi',
|
| 111 |
+
|
| 112 |
+
'beta', 'betainc', 'betainc_regularized',
|
| 113 |
+
|
| 114 |
+
'mathieus', 'mathieuc', 'mathieusprime', 'mathieucprime',
|
| 115 |
+
]
|
evalkit_tf437/lib/python3.10/site-packages/sympy/functions/elementary/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
# Stub __init__.py for sympy.functions.elementary
|
evalkit_tf437/lib/python3.10/site-packages/sympy/functions/elementary/__pycache__/exponential.cpython-310.pyc
ADDED
|
Binary file (34.8 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/sympy/functions/elementary/__pycache__/hyperbolic.cpython-310.pyc
ADDED
|
Binary file (58.1 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/sympy/functions/elementary/__pycache__/integers.cpython-310.pyc
ADDED
|
Binary file (16.4 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/sympy/functions/elementary/__pycache__/miscellaneous.cpython-310.pyc
ADDED
|
Binary file (30.8 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/sympy/functions/elementary/__pycache__/trigonometric.cpython-310.pyc
ADDED
|
Binary file (93 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/sympy/functions/elementary/_trigonometric_special.py
ADDED
|
@@ -0,0 +1,261 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
r"""A module for special angle formulas for trigonometric functions
|
| 2 |
+
|
| 3 |
+
TODO
|
| 4 |
+
====
|
| 5 |
+
|
| 6 |
+
This module should be developed in the future to contain direct square root
|
| 7 |
+
representation of
|
| 8 |
+
|
| 9 |
+
.. math
|
| 10 |
+
F(\frac{n}{m} \pi)
|
| 11 |
+
|
| 12 |
+
for every
|
| 13 |
+
|
| 14 |
+
- $m \in \{ 3, 5, 17, 257, 65537 \}$
|
| 15 |
+
- $n \in \mathbb{N}$, $0 \le n < m$
|
| 16 |
+
- $F \in \{\sin, \cos, \tan, \csc, \sec, \cot\}$
|
| 17 |
+
|
| 18 |
+
Without multi-step rewrites
|
| 19 |
+
(e.g. $\tan \to \cos/\sin \to \cos/\sqrt \to \ sqrt$)
|
| 20 |
+
or using chebyshev identities
|
| 21 |
+
(e.g. $\cos \to \cos + \cos^2 + \cdots \to \sqrt{} + \sqrt{}^2 + \cdots $),
|
| 22 |
+
which are trivial to implement in sympy,
|
| 23 |
+
and had used to give overly complicated expressions.
|
| 24 |
+
|
| 25 |
+
The reference can be found below, if anyone may need help implementing them.
|
| 26 |
+
|
| 27 |
+
References
|
| 28 |
+
==========
|
| 29 |
+
|
| 30 |
+
.. [*] Gottlieb, Christian. (1999). The Simple and straightforward construction
|
| 31 |
+
of the regular 257-gon. The Mathematical Intelligencer. 21. 31-37.
|
| 32 |
+
10.1007/BF03024829.
|
| 33 |
+
.. [*] https://resources.wolframcloud.com/FunctionRepository/resources/Cos2PiOverFermatPrime
|
| 34 |
+
"""
|
| 35 |
+
from __future__ import annotations
|
| 36 |
+
from typing import Callable
|
| 37 |
+
from functools import reduce
|
| 38 |
+
from sympy.core.expr import Expr
|
| 39 |
+
from sympy.core.singleton import S
|
| 40 |
+
from sympy.core.intfunc import igcdex
|
| 41 |
+
from sympy.core.numbers import Integer
|
| 42 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
| 43 |
+
from sympy.core.cache import cacheit
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def migcdex(*x: int) -> tuple[tuple[int, ...], int]:
|
| 47 |
+
r"""Compute extended gcd for multiple integers.
|
| 48 |
+
|
| 49 |
+
Explanation
|
| 50 |
+
===========
|
| 51 |
+
|
| 52 |
+
Given the integers $x_1, \cdots, x_n$ and
|
| 53 |
+
an extended gcd for multiple arguments are defined as a solution
|
| 54 |
+
$(y_1, \cdots, y_n), g$ for the diophantine equation
|
| 55 |
+
$x_1 y_1 + \cdots + x_n y_n = g$ such that
|
| 56 |
+
$g = \gcd(x_1, \cdots, x_n)$.
|
| 57 |
+
|
| 58 |
+
Examples
|
| 59 |
+
========
|
| 60 |
+
|
| 61 |
+
>>> from sympy.functions.elementary._trigonometric_special import migcdex
|
| 62 |
+
>>> migcdex()
|
| 63 |
+
((), 0)
|
| 64 |
+
>>> migcdex(4)
|
| 65 |
+
((1,), 4)
|
| 66 |
+
>>> migcdex(4, 6)
|
| 67 |
+
((-1, 1), 2)
|
| 68 |
+
>>> migcdex(6, 10, 15)
|
| 69 |
+
((1, 1, -1), 1)
|
| 70 |
+
"""
|
| 71 |
+
if not x:
|
| 72 |
+
return (), 0
|
| 73 |
+
|
| 74 |
+
if len(x) == 1:
|
| 75 |
+
return (1,), x[0]
|
| 76 |
+
|
| 77 |
+
if len(x) == 2:
|
| 78 |
+
u, v, h = igcdex(x[0], x[1])
|
| 79 |
+
return (u, v), h
|
| 80 |
+
|
| 81 |
+
y, g = migcdex(*x[1:])
|
| 82 |
+
u, v, h = igcdex(x[0], g)
|
| 83 |
+
return (u, *(v * i for i in y)), h
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def ipartfrac(*denoms: int) -> tuple[int, ...]:
|
| 87 |
+
r"""Compute the partial fraction decomposition.
|
| 88 |
+
|
| 89 |
+
Explanation
|
| 90 |
+
===========
|
| 91 |
+
|
| 92 |
+
Given a rational number $\frac{1}{q_1 \cdots q_n}$ where all
|
| 93 |
+
$q_1, \cdots, q_n$ are pairwise coprime,
|
| 94 |
+
|
| 95 |
+
A partial fraction decomposition is defined as
|
| 96 |
+
|
| 97 |
+
.. math::
|
| 98 |
+
\frac{1}{q_1 \cdots q_n} = \frac{p_1}{q_1} + \cdots + \frac{p_n}{q_n}
|
| 99 |
+
|
| 100 |
+
And it can be derived from solving the following diophantine equation for
|
| 101 |
+
the $p_1, \cdots, p_n$
|
| 102 |
+
|
| 103 |
+
.. math::
|
| 104 |
+
1 = p_1 \prod_{i \ne 1}q_i + \cdots + p_n \prod_{i \ne n}q_i
|
| 105 |
+
|
| 106 |
+
Where $q_1, \cdots, q_n$ being pairwise coprime implies
|
| 107 |
+
$\gcd(\prod_{i \ne 1}q_i, \cdots, \prod_{i \ne n}q_i) = 1$,
|
| 108 |
+
which guarantees the existence of the solution.
|
| 109 |
+
|
| 110 |
+
It is sufficient to compute partial fraction decomposition only
|
| 111 |
+
for numerator $1$ because partial fraction decomposition for any
|
| 112 |
+
$\frac{n}{q_1 \cdots q_n}$ can be easily computed by multiplying
|
| 113 |
+
the result by $n$ afterwards.
|
| 114 |
+
|
| 115 |
+
Parameters
|
| 116 |
+
==========
|
| 117 |
+
|
| 118 |
+
denoms : int
|
| 119 |
+
The pairwise coprime integer denominators $q_i$ which defines the
|
| 120 |
+
rational number $\frac{1}{q_1 \cdots q_n}$
|
| 121 |
+
|
| 122 |
+
Returns
|
| 123 |
+
=======
|
| 124 |
+
|
| 125 |
+
tuple[int, ...]
|
| 126 |
+
The list of numerators which semantically corresponds to $p_i$ of the
|
| 127 |
+
partial fraction decomposition
|
| 128 |
+
$\frac{1}{q_1 \cdots q_n} = \frac{p_1}{q_1} + \cdots + \frac{p_n}{q_n}$
|
| 129 |
+
|
| 130 |
+
Examples
|
| 131 |
+
========
|
| 132 |
+
|
| 133 |
+
>>> from sympy import Rational, Mul
|
| 134 |
+
>>> from sympy.functions.elementary._trigonometric_special import ipartfrac
|
| 135 |
+
|
| 136 |
+
>>> denoms = 2, 3, 5
|
| 137 |
+
>>> numers = ipartfrac(2, 3, 5)
|
| 138 |
+
>>> numers
|
| 139 |
+
(1, 7, -14)
|
| 140 |
+
|
| 141 |
+
>>> Rational(1, Mul(*denoms))
|
| 142 |
+
1/30
|
| 143 |
+
>>> out = 0
|
| 144 |
+
>>> for n, d in zip(numers, denoms):
|
| 145 |
+
... out += Rational(n, d)
|
| 146 |
+
>>> out
|
| 147 |
+
1/30
|
| 148 |
+
"""
|
| 149 |
+
if not denoms:
|
| 150 |
+
return ()
|
| 151 |
+
|
| 152 |
+
def mul(x: int, y: int) -> int:
|
| 153 |
+
return x * y
|
| 154 |
+
|
| 155 |
+
denom = reduce(mul, denoms)
|
| 156 |
+
a = [denom // x for x in denoms]
|
| 157 |
+
h, _ = migcdex(*a)
|
| 158 |
+
return h
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def fermat_coords(n: int) -> list[int] | None:
|
| 162 |
+
"""If n can be factored in terms of Fermat primes with
|
| 163 |
+
multiplicity of each being 1, return those primes, else
|
| 164 |
+
None
|
| 165 |
+
"""
|
| 166 |
+
primes = []
|
| 167 |
+
for p in [3, 5, 17, 257, 65537]:
|
| 168 |
+
quotient, remainder = divmod(n, p)
|
| 169 |
+
if remainder == 0:
|
| 170 |
+
n = quotient
|
| 171 |
+
primes.append(p)
|
| 172 |
+
if n == 1:
|
| 173 |
+
return primes
|
| 174 |
+
return None
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
@cacheit
|
| 178 |
+
def cos_3() -> Expr:
|
| 179 |
+
r"""Computes $\cos \frac{\pi}{3}$ in square roots"""
|
| 180 |
+
return S.Half
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
@cacheit
|
| 184 |
+
def cos_5() -> Expr:
|
| 185 |
+
r"""Computes $\cos \frac{\pi}{5}$ in square roots"""
|
| 186 |
+
return (sqrt(5) + 1) / 4
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
@cacheit
|
| 190 |
+
def cos_17() -> Expr:
|
| 191 |
+
r"""Computes $\cos \frac{\pi}{17}$ in square roots"""
|
| 192 |
+
return sqrt(
|
| 193 |
+
(15 + sqrt(17)) / 32 + sqrt(2) * (sqrt(17 - sqrt(17)) +
|
| 194 |
+
sqrt(sqrt(2) * (-8 * sqrt(17 + sqrt(17)) - (1 - sqrt(17))
|
| 195 |
+
* sqrt(17 - sqrt(17))) + 6 * sqrt(17) + 34)) / 32)
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
@cacheit
|
| 199 |
+
def cos_257() -> Expr:
|
| 200 |
+
r"""Computes $\cos \frac{\pi}{257}$ in square roots
|
| 201 |
+
|
| 202 |
+
References
|
| 203 |
+
==========
|
| 204 |
+
|
| 205 |
+
.. [*] https://math.stackexchange.com/questions/516142/how-does-cos2-pi-257-look-like-in-real-radicals
|
| 206 |
+
.. [*] https://r-knott.surrey.ac.uk/Fibonacci/simpleTrig.html
|
| 207 |
+
"""
|
| 208 |
+
def f1(a: Expr, b: Expr) -> tuple[Expr, Expr]:
|
| 209 |
+
return (a + sqrt(a**2 + b)) / 2, (a - sqrt(a**2 + b)) / 2
|
| 210 |
+
|
| 211 |
+
def f2(a: Expr, b: Expr) -> Expr:
|
| 212 |
+
return (a - sqrt(a**2 + b))/2
|
| 213 |
+
|
| 214 |
+
t1, t2 = f1(S.NegativeOne, Integer(256))
|
| 215 |
+
z1, z3 = f1(t1, Integer(64))
|
| 216 |
+
z2, z4 = f1(t2, Integer(64))
|
| 217 |
+
y1, y5 = f1(z1, 4*(5 + t1 + 2*z1))
|
| 218 |
+
y6, y2 = f1(z2, 4*(5 + t2 + 2*z2))
|
| 219 |
+
y3, y7 = f1(z3, 4*(5 + t1 + 2*z3))
|
| 220 |
+
y8, y4 = f1(z4, 4*(5 + t2 + 2*z4))
|
| 221 |
+
x1, x9 = f1(y1, -4*(t1 + y1 + y3 + 2*y6))
|
| 222 |
+
x2, x10 = f1(y2, -4*(t2 + y2 + y4 + 2*y7))
|
| 223 |
+
x3, x11 = f1(y3, -4*(t1 + y3 + y5 + 2*y8))
|
| 224 |
+
x4, x12 = f1(y4, -4*(t2 + y4 + y6 + 2*y1))
|
| 225 |
+
x5, x13 = f1(y5, -4*(t1 + y5 + y7 + 2*y2))
|
| 226 |
+
x6, x14 = f1(y6, -4*(t2 + y6 + y8 + 2*y3))
|
| 227 |
+
x15, x7 = f1(y7, -4*(t1 + y7 + y1 + 2*y4))
|
| 228 |
+
x8, x16 = f1(y8, -4*(t2 + y8 + y2 + 2*y5))
|
| 229 |
+
v1 = f2(x1, -4*(x1 + x2 + x3 + x6))
|
| 230 |
+
v2 = f2(x2, -4*(x2 + x3 + x4 + x7))
|
| 231 |
+
v3 = f2(x8, -4*(x8 + x9 + x10 + x13))
|
| 232 |
+
v4 = f2(x9, -4*(x9 + x10 + x11 + x14))
|
| 233 |
+
v5 = f2(x10, -4*(x10 + x11 + x12 + x15))
|
| 234 |
+
v6 = f2(x16, -4*(x16 + x1 + x2 + x5))
|
| 235 |
+
u1 = -f2(-v1, -4*(v2 + v3))
|
| 236 |
+
u2 = -f2(-v4, -4*(v5 + v6))
|
| 237 |
+
w1 = -2*f2(-u1, -4*u2)
|
| 238 |
+
return sqrt(sqrt(2)*sqrt(w1 + 4)/8 + S.Half)
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
def cos_table() -> dict[int, Callable[[], Expr]]:
|
| 242 |
+
r"""Lazily evaluated table for $\cos \frac{\pi}{n}$ in square roots for
|
| 243 |
+
$n \in \{3, 5, 17, 257, 65537\}$.
|
| 244 |
+
|
| 245 |
+
Notes
|
| 246 |
+
=====
|
| 247 |
+
|
| 248 |
+
65537 is the only other known Fermat prime and it is nearly impossible to
|
| 249 |
+
build in the current SymPy due to performance issues.
|
| 250 |
+
|
| 251 |
+
References
|
| 252 |
+
==========
|
| 253 |
+
|
| 254 |
+
https://r-knott.surrey.ac.uk/Fibonacci/simpleTrig.html
|
| 255 |
+
"""
|
| 256 |
+
return {
|
| 257 |
+
3: cos_3,
|
| 258 |
+
5: cos_5,
|
| 259 |
+
17: cos_17,
|
| 260 |
+
257: cos_257
|
| 261 |
+
}
|
evalkit_tf437/lib/python3.10/site-packages/sympy/functions/elementary/complexes.py
ADDED
|
@@ -0,0 +1,1473 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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prtools import factor_terms
|
| 6 |
+
from sympy.core.function import (Function, Derivative, ArgumentIndexError,
|
| 7 |
+
AppliedUndef, expand_mul)
|
| 8 |
+
from sympy.core.logic import fuzzy_not, fuzzy_or
|
| 9 |
+
from sympy.core.numbers import pi, I, oo
|
| 10 |
+
from sympy.core.power import Pow
|
| 11 |
+
from sympy.core.relational import Eq
|
| 12 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
| 13 |
+
from sympy.functions.elementary.piecewise import Piecewise
|
| 14 |
+
|
| 15 |
+
###############################################################################
|
| 16 |
+
######################### REAL and IMAGINARY PARTS ############################
|
| 17 |
+
###############################################################################
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class re(Function):
|
| 21 |
+
"""
|
| 22 |
+
Returns real part of expression. This function performs only
|
| 23 |
+
elementary analysis and so it will fail to decompose properly
|
| 24 |
+
more complicated expressions. If completely simplified result
|
| 25 |
+
is needed then use ``Basic.as_real_imag()`` or perform complex
|
| 26 |
+
expansion on instance of this function.
|
| 27 |
+
|
| 28 |
+
Examples
|
| 29 |
+
========
|
| 30 |
+
|
| 31 |
+
>>> from sympy import re, im, I, E, symbols
|
| 32 |
+
>>> x, y = symbols('x y', real=True)
|
| 33 |
+
>>> re(2*E)
|
| 34 |
+
2*E
|
| 35 |
+
>>> re(2*I + 17)
|
| 36 |
+
17
|
| 37 |
+
>>> re(2*I)
|
| 38 |
+
0
|
| 39 |
+
>>> re(im(x) + x*I + 2)
|
| 40 |
+
2
|
| 41 |
+
>>> re(5 + I + 2)
|
| 42 |
+
7
|
| 43 |
+
|
| 44 |
+
Parameters
|
| 45 |
+
==========
|
| 46 |
+
|
| 47 |
+
arg : Expr
|
| 48 |
+
Real or complex expression.
|
| 49 |
+
|
| 50 |
+
Returns
|
| 51 |
+
=======
|
| 52 |
+
|
| 53 |
+
expr : Expr
|
| 54 |
+
Real part of expression.
|
| 55 |
+
|
| 56 |
+
See Also
|
| 57 |
+
========
|
| 58 |
+
|
| 59 |
+
im
|
| 60 |
+
"""
|
| 61 |
+
|
| 62 |
+
args: tTuple[Expr]
|
| 63 |
+
|
| 64 |
+
is_extended_real = True
|
| 65 |
+
unbranched = True # implicitly works on the projection to C
|
| 66 |
+
_singularities = True # non-holomorphic
|
| 67 |
+
|
| 68 |
+
@classmethod
|
| 69 |
+
def eval(cls, arg):
|
| 70 |
+
if arg is S.NaN:
|
| 71 |
+
return S.NaN
|
| 72 |
+
elif arg is S.ComplexInfinity:
|
| 73 |
+
return S.NaN
|
| 74 |
+
elif arg.is_extended_real:
|
| 75 |
+
return arg
|
| 76 |
+
elif arg.is_imaginary or (I*arg).is_extended_real:
|
| 77 |
+
return S.Zero
|
| 78 |
+
elif arg.is_Matrix:
|
| 79 |
+
return arg.as_real_imag()[0]
|
| 80 |
+
elif arg.is_Function and isinstance(arg, conjugate):
|
| 81 |
+
return re(arg.args[0])
|
| 82 |
+
else:
|
| 83 |
+
|
| 84 |
+
included, reverted, excluded = [], [], []
|
| 85 |
+
args = Add.make_args(arg)
|
| 86 |
+
for term in args:
|
| 87 |
+
coeff = term.as_coefficient(I)
|
| 88 |
+
|
| 89 |
+
if coeff is not None:
|
| 90 |
+
if not coeff.is_extended_real:
|
| 91 |
+
reverted.append(coeff)
|
| 92 |
+
elif not term.has(I) and term.is_extended_real:
|
| 93 |
+
excluded.append(term)
|
| 94 |
+
else:
|
| 95 |
+
# Try to do some advanced expansion. If
|
| 96 |
+
# impossible, don't try to do re(arg) again
|
| 97 |
+
# (because this is what we are trying to do now).
|
| 98 |
+
real_imag = term.as_real_imag(ignore=arg)
|
| 99 |
+
if real_imag:
|
| 100 |
+
excluded.append(real_imag[0])
|
| 101 |
+
else:
|
| 102 |
+
included.append(term)
|
| 103 |
+
|
| 104 |
+
if len(args) != len(included):
|
| 105 |
+
a, b, c = (Add(*xs) for xs in [included, reverted, excluded])
|
| 106 |
+
|
| 107 |
+
return cls(a) - im(b) + c
|
| 108 |
+
|
| 109 |
+
def as_real_imag(self, deep=True, **hints):
|
| 110 |
+
"""
|
| 111 |
+
Returns the real number with a zero imaginary part.
|
| 112 |
+
|
| 113 |
+
"""
|
| 114 |
+
return (self, S.Zero)
|
| 115 |
+
|
| 116 |
+
def _eval_derivative(self, x):
|
| 117 |
+
if x.is_extended_real or self.args[0].is_extended_real:
|
| 118 |
+
return re(Derivative(self.args[0], x, evaluate=True))
|
| 119 |
+
if x.is_imaginary or self.args[0].is_imaginary:
|
| 120 |
+
return -I \
|
| 121 |
+
* im(Derivative(self.args[0], x, evaluate=True))
|
| 122 |
+
|
| 123 |
+
def _eval_rewrite_as_im(self, arg, **kwargs):
|
| 124 |
+
return self.args[0] - I*im(self.args[0])
|
| 125 |
+
|
| 126 |
+
def _eval_is_algebraic(self):
|
| 127 |
+
return self.args[0].is_algebraic
|
| 128 |
+
|
| 129 |
+
def _eval_is_zero(self):
|
| 130 |
+
# is_imaginary implies nonzero
|
| 131 |
+
return fuzzy_or([self.args[0].is_imaginary, self.args[0].is_zero])
|
| 132 |
+
|
| 133 |
+
def _eval_is_finite(self):
|
| 134 |
+
if self.args[0].is_finite:
|
| 135 |
+
return True
|
| 136 |
+
|
| 137 |
+
def _eval_is_complex(self):
|
| 138 |
+
if self.args[0].is_finite:
|
| 139 |
+
return True
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
class im(Function):
|
| 143 |
+
"""
|
| 144 |
+
Returns imaginary part of expression. This function performs only
|
| 145 |
+
elementary analysis and so it will fail to decompose properly more
|
| 146 |
+
complicated expressions. If completely simplified result is needed then
|
| 147 |
+
use ``Basic.as_real_imag()`` or perform complex expansion on instance of
|
| 148 |
+
this function.
|
| 149 |
+
|
| 150 |
+
Examples
|
| 151 |
+
========
|
| 152 |
+
|
| 153 |
+
>>> from sympy import re, im, E, I
|
| 154 |
+
>>> from sympy.abc import x, y
|
| 155 |
+
>>> im(2*E)
|
| 156 |
+
0
|
| 157 |
+
>>> im(2*I + 17)
|
| 158 |
+
2
|
| 159 |
+
>>> im(x*I)
|
| 160 |
+
re(x)
|
| 161 |
+
>>> im(re(x) + y)
|
| 162 |
+
im(y)
|
| 163 |
+
>>> im(2 + 3*I)
|
| 164 |
+
3
|
| 165 |
+
|
| 166 |
+
Parameters
|
| 167 |
+
==========
|
| 168 |
+
|
| 169 |
+
arg : Expr
|
| 170 |
+
Real or complex expression.
|
| 171 |
+
|
| 172 |
+
Returns
|
| 173 |
+
=======
|
| 174 |
+
|
| 175 |
+
expr : Expr
|
| 176 |
+
Imaginary part of expression.
|
| 177 |
+
|
| 178 |
+
See Also
|
| 179 |
+
========
|
| 180 |
+
|
| 181 |
+
re
|
| 182 |
+
"""
|
| 183 |
+
|
| 184 |
+
args: tTuple[Expr]
|
| 185 |
+
|
| 186 |
+
is_extended_real = True
|
| 187 |
+
unbranched = True # implicitly works on the projection to C
|
| 188 |
+
_singularities = True # non-holomorphic
|
| 189 |
+
|
| 190 |
+
@classmethod
|
| 191 |
+
def eval(cls, arg):
|
| 192 |
+
if arg is S.NaN:
|
| 193 |
+
return S.NaN
|
| 194 |
+
elif arg is S.ComplexInfinity:
|
| 195 |
+
return S.NaN
|
| 196 |
+
elif arg.is_extended_real:
|
| 197 |
+
return S.Zero
|
| 198 |
+
elif arg.is_imaginary or (I*arg).is_extended_real:
|
| 199 |
+
return -I * arg
|
| 200 |
+
elif arg.is_Matrix:
|
| 201 |
+
return arg.as_real_imag()[1]
|
| 202 |
+
elif arg.is_Function and isinstance(arg, conjugate):
|
| 203 |
+
return -im(arg.args[0])
|
| 204 |
+
else:
|
| 205 |
+
included, reverted, excluded = [], [], []
|
| 206 |
+
args = Add.make_args(arg)
|
| 207 |
+
for term in args:
|
| 208 |
+
coeff = term.as_coefficient(I)
|
| 209 |
+
|
| 210 |
+
if coeff is not None:
|
| 211 |
+
if not coeff.is_extended_real:
|
| 212 |
+
reverted.append(coeff)
|
| 213 |
+
else:
|
| 214 |
+
excluded.append(coeff)
|
| 215 |
+
elif term.has(I) or not term.is_extended_real:
|
| 216 |
+
# Try to do some advanced expansion. If
|
| 217 |
+
# impossible, don't try to do im(arg) again
|
| 218 |
+
# (because this is what we are trying to do now).
|
| 219 |
+
real_imag = term.as_real_imag(ignore=arg)
|
| 220 |
+
if real_imag:
|
| 221 |
+
excluded.append(real_imag[1])
|
| 222 |
+
else:
|
| 223 |
+
included.append(term)
|
| 224 |
+
|
| 225 |
+
if len(args) != len(included):
|
| 226 |
+
a, b, c = (Add(*xs) for xs in [included, reverted, excluded])
|
| 227 |
+
|
| 228 |
+
return cls(a) + re(b) + c
|
| 229 |
+
|
| 230 |
+
def as_real_imag(self, deep=True, **hints):
|
| 231 |
+
"""
|
| 232 |
+
Return the imaginary part with a zero real part.
|
| 233 |
+
|
| 234 |
+
"""
|
| 235 |
+
return (self, S.Zero)
|
| 236 |
+
|
| 237 |
+
def _eval_derivative(self, x):
|
| 238 |
+
if x.is_extended_real or self.args[0].is_extended_real:
|
| 239 |
+
return im(Derivative(self.args[0], x, evaluate=True))
|
| 240 |
+
if x.is_imaginary or self.args[0].is_imaginary:
|
| 241 |
+
return -I \
|
| 242 |
+
* re(Derivative(self.args[0], x, evaluate=True))
|
| 243 |
+
|
| 244 |
+
def _eval_rewrite_as_re(self, arg, **kwargs):
|
| 245 |
+
return -I*(self.args[0] - re(self.args[0]))
|
| 246 |
+
|
| 247 |
+
def _eval_is_algebraic(self):
|
| 248 |
+
return self.args[0].is_algebraic
|
| 249 |
+
|
| 250 |
+
def _eval_is_zero(self):
|
| 251 |
+
return self.args[0].is_extended_real
|
| 252 |
+
|
| 253 |
+
def _eval_is_finite(self):
|
| 254 |
+
if self.args[0].is_finite:
|
| 255 |
+
return True
|
| 256 |
+
|
| 257 |
+
def _eval_is_complex(self):
|
| 258 |
+
if self.args[0].is_finite:
|
| 259 |
+
return True
|
| 260 |
+
|
| 261 |
+
###############################################################################
|
| 262 |
+
############### SIGN, ABSOLUTE VALUE, ARGUMENT and CONJUGATION ################
|
| 263 |
+
###############################################################################
|
| 264 |
+
|
| 265 |
+
class sign(Function):
|
| 266 |
+
"""
|
| 267 |
+
Returns the complex sign of an expression:
|
| 268 |
+
|
| 269 |
+
Explanation
|
| 270 |
+
===========
|
| 271 |
+
|
| 272 |
+
If the expression is real the sign will be:
|
| 273 |
+
|
| 274 |
+
* $1$ if expression is positive
|
| 275 |
+
* $0$ if expression is equal to zero
|
| 276 |
+
* $-1$ if expression is negative
|
| 277 |
+
|
| 278 |
+
If the expression is imaginary the sign will be:
|
| 279 |
+
|
| 280 |
+
* $I$ if im(expression) is positive
|
| 281 |
+
* $-I$ if im(expression) is negative
|
| 282 |
+
|
| 283 |
+
Otherwise an unevaluated expression will be returned. When evaluated, the
|
| 284 |
+
result (in general) will be ``cos(arg(expr)) + I*sin(arg(expr))``.
|
| 285 |
+
|
| 286 |
+
Examples
|
| 287 |
+
========
|
| 288 |
+
|
| 289 |
+
>>> from sympy import sign, I
|
| 290 |
+
|
| 291 |
+
>>> sign(-1)
|
| 292 |
+
-1
|
| 293 |
+
>>> sign(0)
|
| 294 |
+
0
|
| 295 |
+
>>> sign(-3*I)
|
| 296 |
+
-I
|
| 297 |
+
>>> sign(1 + I)
|
| 298 |
+
sign(1 + I)
|
| 299 |
+
>>> _.evalf()
|
| 300 |
+
0.707106781186548 + 0.707106781186548*I
|
| 301 |
+
|
| 302 |
+
Parameters
|
| 303 |
+
==========
|
| 304 |
+
|
| 305 |
+
arg : Expr
|
| 306 |
+
Real or imaginary expression.
|
| 307 |
+
|
| 308 |
+
Returns
|
| 309 |
+
=======
|
| 310 |
+
|
| 311 |
+
expr : Expr
|
| 312 |
+
Complex sign of expression.
|
| 313 |
+
|
| 314 |
+
See Also
|
| 315 |
+
========
|
| 316 |
+
|
| 317 |
+
Abs, conjugate
|
| 318 |
+
"""
|
| 319 |
+
|
| 320 |
+
is_complex = True
|
| 321 |
+
_singularities = True
|
| 322 |
+
|
| 323 |
+
def doit(self, **hints):
|
| 324 |
+
s = super().doit()
|
| 325 |
+
if s == self and self.args[0].is_zero is False:
|
| 326 |
+
return self.args[0] / Abs(self.args[0])
|
| 327 |
+
return s
|
| 328 |
+
|
| 329 |
+
@classmethod
|
| 330 |
+
def eval(cls, arg):
|
| 331 |
+
# handle what we can
|
| 332 |
+
if arg.is_Mul:
|
| 333 |
+
c, args = arg.as_coeff_mul()
|
| 334 |
+
unk = []
|
| 335 |
+
s = sign(c)
|
| 336 |
+
for a in args:
|
| 337 |
+
if a.is_extended_negative:
|
| 338 |
+
s = -s
|
| 339 |
+
elif a.is_extended_positive:
|
| 340 |
+
pass
|
| 341 |
+
else:
|
| 342 |
+
if a.is_imaginary:
|
| 343 |
+
ai = im(a)
|
| 344 |
+
if ai.is_comparable: # i.e. a = I*real
|
| 345 |
+
s *= I
|
| 346 |
+
if ai.is_extended_negative:
|
| 347 |
+
# can't use sign(ai) here since ai might not be
|
| 348 |
+
# a Number
|
| 349 |
+
s = -s
|
| 350 |
+
else:
|
| 351 |
+
unk.append(a)
|
| 352 |
+
else:
|
| 353 |
+
unk.append(a)
|
| 354 |
+
if c is S.One and len(unk) == len(args):
|
| 355 |
+
return None
|
| 356 |
+
return s * cls(arg._new_rawargs(*unk))
|
| 357 |
+
if arg is S.NaN:
|
| 358 |
+
return S.NaN
|
| 359 |
+
if arg.is_zero: # it may be an Expr that is zero
|
| 360 |
+
return S.Zero
|
| 361 |
+
if arg.is_extended_positive:
|
| 362 |
+
return S.One
|
| 363 |
+
if arg.is_extended_negative:
|
| 364 |
+
return S.NegativeOne
|
| 365 |
+
if arg.is_Function:
|
| 366 |
+
if isinstance(arg, sign):
|
| 367 |
+
return arg
|
| 368 |
+
if arg.is_imaginary:
|
| 369 |
+
if arg.is_Pow and arg.exp is S.Half:
|
| 370 |
+
# we catch this because non-trivial sqrt args are not expanded
|
| 371 |
+
# e.g. sqrt(1-sqrt(2)) --x--> to I*sqrt(sqrt(2) - 1)
|
| 372 |
+
return I
|
| 373 |
+
arg2 = -I * arg
|
| 374 |
+
if arg2.is_extended_positive:
|
| 375 |
+
return I
|
| 376 |
+
if arg2.is_extended_negative:
|
| 377 |
+
return -I
|
| 378 |
+
|
| 379 |
+
def _eval_Abs(self):
|
| 380 |
+
if fuzzy_not(self.args[0].is_zero):
|
| 381 |
+
return S.One
|
| 382 |
+
|
| 383 |
+
def _eval_conjugate(self):
|
| 384 |
+
return sign(conjugate(self.args[0]))
|
| 385 |
+
|
| 386 |
+
def _eval_derivative(self, x):
|
| 387 |
+
if self.args[0].is_extended_real:
|
| 388 |
+
from sympy.functions.special.delta_functions import DiracDelta
|
| 389 |
+
return 2 * Derivative(self.args[0], x, evaluate=True) \
|
| 390 |
+
* DiracDelta(self.args[0])
|
| 391 |
+
elif self.args[0].is_imaginary:
|
| 392 |
+
from sympy.functions.special.delta_functions import DiracDelta
|
| 393 |
+
return 2 * Derivative(self.args[0], x, evaluate=True) \
|
| 394 |
+
* DiracDelta(-I * self.args[0])
|
| 395 |
+
|
| 396 |
+
def _eval_is_nonnegative(self):
|
| 397 |
+
if self.args[0].is_nonnegative:
|
| 398 |
+
return True
|
| 399 |
+
|
| 400 |
+
def _eval_is_nonpositive(self):
|
| 401 |
+
if self.args[0].is_nonpositive:
|
| 402 |
+
return True
|
| 403 |
+
|
| 404 |
+
def _eval_is_imaginary(self):
|
| 405 |
+
return self.args[0].is_imaginary
|
| 406 |
+
|
| 407 |
+
def _eval_is_integer(self):
|
| 408 |
+
return self.args[0].is_extended_real
|
| 409 |
+
|
| 410 |
+
def _eval_is_zero(self):
|
| 411 |
+
return self.args[0].is_zero
|
| 412 |
+
|
| 413 |
+
def _eval_power(self, other):
|
| 414 |
+
if (
|
| 415 |
+
fuzzy_not(self.args[0].is_zero) and
|
| 416 |
+
other.is_integer and
|
| 417 |
+
other.is_even
|
| 418 |
+
):
|
| 419 |
+
return S.One
|
| 420 |
+
|
| 421 |
+
def _eval_nseries(self, x, n, logx, cdir=0):
|
| 422 |
+
arg0 = self.args[0]
|
| 423 |
+
x0 = arg0.subs(x, 0)
|
| 424 |
+
if x0 != 0:
|
| 425 |
+
return self.func(x0)
|
| 426 |
+
if cdir != 0:
|
| 427 |
+
cdir = arg0.dir(x, cdir)
|
| 428 |
+
return -S.One if re(cdir) < 0 else S.One
|
| 429 |
+
|
| 430 |
+
def _eval_rewrite_as_Piecewise(self, arg, **kwargs):
|
| 431 |
+
if arg.is_extended_real:
|
| 432 |
+
return Piecewise((1, arg > 0), (-1, arg < 0), (0, True))
|
| 433 |
+
|
| 434 |
+
def _eval_rewrite_as_Heaviside(self, arg, **kwargs):
|
| 435 |
+
from sympy.functions.special.delta_functions import Heaviside
|
| 436 |
+
if arg.is_extended_real:
|
| 437 |
+
return Heaviside(arg) * 2 - 1
|
| 438 |
+
|
| 439 |
+
def _eval_rewrite_as_Abs(self, arg, **kwargs):
|
| 440 |
+
return Piecewise((0, Eq(arg, 0)), (arg / Abs(arg), True))
|
| 441 |
+
|
| 442 |
+
def _eval_simplify(self, **kwargs):
|
| 443 |
+
return self.func(factor_terms(self.args[0])) # XXX include doit?
|
| 444 |
+
|
| 445 |
+
|
| 446 |
+
class Abs(Function):
|
| 447 |
+
"""
|
| 448 |
+
Return the absolute value of the argument.
|
| 449 |
+
|
| 450 |
+
Explanation
|
| 451 |
+
===========
|
| 452 |
+
|
| 453 |
+
This is an extension of the built-in function ``abs()`` to accept symbolic
|
| 454 |
+
values. If you pass a SymPy expression to the built-in ``abs()``, it will
|
| 455 |
+
pass it automatically to ``Abs()``.
|
| 456 |
+
|
| 457 |
+
Examples
|
| 458 |
+
========
|
| 459 |
+
|
| 460 |
+
>>> from sympy import Abs, Symbol, S, I
|
| 461 |
+
>>> Abs(-1)
|
| 462 |
+
1
|
| 463 |
+
>>> x = Symbol('x', real=True)
|
| 464 |
+
>>> Abs(-x)
|
| 465 |
+
Abs(x)
|
| 466 |
+
>>> Abs(x**2)
|
| 467 |
+
x**2
|
| 468 |
+
>>> abs(-x) # The Python built-in
|
| 469 |
+
Abs(x)
|
| 470 |
+
>>> Abs(3*x + 2*I)
|
| 471 |
+
sqrt(9*x**2 + 4)
|
| 472 |
+
>>> Abs(8*I)
|
| 473 |
+
8
|
| 474 |
+
|
| 475 |
+
Note that the Python built-in will return either an Expr or int depending on
|
| 476 |
+
the argument::
|
| 477 |
+
|
| 478 |
+
>>> type(abs(-1))
|
| 479 |
+
<... 'int'>
|
| 480 |
+
>>> type(abs(S.NegativeOne))
|
| 481 |
+
<class 'sympy.core.numbers.One'>
|
| 482 |
+
|
| 483 |
+
Abs will always return a SymPy object.
|
| 484 |
+
|
| 485 |
+
Parameters
|
| 486 |
+
==========
|
| 487 |
+
|
| 488 |
+
arg : Expr
|
| 489 |
+
Real or complex expression.
|
| 490 |
+
|
| 491 |
+
Returns
|
| 492 |
+
=======
|
| 493 |
+
|
| 494 |
+
expr : Expr
|
| 495 |
+
Absolute value returned can be an expression or integer depending on
|
| 496 |
+
input arg.
|
| 497 |
+
|
| 498 |
+
See Also
|
| 499 |
+
========
|
| 500 |
+
|
| 501 |
+
sign, conjugate
|
| 502 |
+
"""
|
| 503 |
+
|
| 504 |
+
args: tTuple[Expr]
|
| 505 |
+
|
| 506 |
+
is_extended_real = True
|
| 507 |
+
is_extended_negative = False
|
| 508 |
+
is_extended_nonnegative = True
|
| 509 |
+
unbranched = True
|
| 510 |
+
_singularities = True # non-holomorphic
|
| 511 |
+
|
| 512 |
+
def fdiff(self, argindex=1):
|
| 513 |
+
"""
|
| 514 |
+
Get the first derivative of the argument to Abs().
|
| 515 |
+
|
| 516 |
+
"""
|
| 517 |
+
if argindex == 1:
|
| 518 |
+
return sign(self.args[0])
|
| 519 |
+
else:
|
| 520 |
+
raise ArgumentIndexError(self, argindex)
|
| 521 |
+
|
| 522 |
+
@classmethod
|
| 523 |
+
def eval(cls, arg):
|
| 524 |
+
from sympy.simplify.simplify import signsimp
|
| 525 |
+
|
| 526 |
+
if hasattr(arg, '_eval_Abs'):
|
| 527 |
+
obj = arg._eval_Abs()
|
| 528 |
+
if obj is not None:
|
| 529 |
+
return obj
|
| 530 |
+
if not isinstance(arg, Expr):
|
| 531 |
+
raise TypeError("Bad argument type for Abs(): %s" % type(arg))
|
| 532 |
+
|
| 533 |
+
# handle what we can
|
| 534 |
+
arg = signsimp(arg, evaluate=False)
|
| 535 |
+
n, d = arg.as_numer_denom()
|
| 536 |
+
if d.free_symbols and not n.free_symbols:
|
| 537 |
+
return cls(n)/cls(d)
|
| 538 |
+
|
| 539 |
+
if arg.is_Mul:
|
| 540 |
+
known = []
|
| 541 |
+
unk = []
|
| 542 |
+
for t in arg.args:
|
| 543 |
+
if t.is_Pow and t.exp.is_integer and t.exp.is_negative:
|
| 544 |
+
bnew = cls(t.base)
|
| 545 |
+
if isinstance(bnew, cls):
|
| 546 |
+
unk.append(t)
|
| 547 |
+
else:
|
| 548 |
+
known.append(Pow(bnew, t.exp))
|
| 549 |
+
else:
|
| 550 |
+
tnew = cls(t)
|
| 551 |
+
if isinstance(tnew, cls):
|
| 552 |
+
unk.append(t)
|
| 553 |
+
else:
|
| 554 |
+
known.append(tnew)
|
| 555 |
+
known = Mul(*known)
|
| 556 |
+
unk = cls(Mul(*unk), evaluate=False) if unk else S.One
|
| 557 |
+
return known*unk
|
| 558 |
+
if arg is S.NaN:
|
| 559 |
+
return S.NaN
|
| 560 |
+
if arg is S.ComplexInfinity:
|
| 561 |
+
return oo
|
| 562 |
+
from sympy.functions.elementary.exponential import exp, log
|
| 563 |
+
|
| 564 |
+
if arg.is_Pow:
|
| 565 |
+
base, exponent = arg.as_base_exp()
|
| 566 |
+
if base.is_extended_real:
|
| 567 |
+
if exponent.is_integer:
|
| 568 |
+
if exponent.is_even:
|
| 569 |
+
return arg
|
| 570 |
+
if base is S.NegativeOne:
|
| 571 |
+
return S.One
|
| 572 |
+
return Abs(base)**exponent
|
| 573 |
+
if base.is_extended_nonnegative:
|
| 574 |
+
return base**re(exponent)
|
| 575 |
+
if base.is_extended_negative:
|
| 576 |
+
return (-base)**re(exponent)*exp(-pi*im(exponent))
|
| 577 |
+
return
|
| 578 |
+
elif not base.has(Symbol): # complex base
|
| 579 |
+
# express base**exponent as exp(exponent*log(base))
|
| 580 |
+
a, b = log(base).as_real_imag()
|
| 581 |
+
z = a + I*b
|
| 582 |
+
return exp(re(exponent*z))
|
| 583 |
+
if isinstance(arg, exp):
|
| 584 |
+
return exp(re(arg.args[0]))
|
| 585 |
+
if isinstance(arg, AppliedUndef):
|
| 586 |
+
if arg.is_positive:
|
| 587 |
+
return arg
|
| 588 |
+
elif arg.is_negative:
|
| 589 |
+
return -arg
|
| 590 |
+
return
|
| 591 |
+
if arg.is_Add and arg.has(oo, S.NegativeInfinity):
|
| 592 |
+
if any(a.is_infinite for a in arg.as_real_imag()):
|
| 593 |
+
return oo
|
| 594 |
+
if arg.is_zero:
|
| 595 |
+
return S.Zero
|
| 596 |
+
if arg.is_extended_nonnegative:
|
| 597 |
+
return arg
|
| 598 |
+
if arg.is_extended_nonpositive:
|
| 599 |
+
return -arg
|
| 600 |
+
if arg.is_imaginary:
|
| 601 |
+
arg2 = -I * arg
|
| 602 |
+
if arg2.is_extended_nonnegative:
|
| 603 |
+
return arg2
|
| 604 |
+
if arg.is_extended_real:
|
| 605 |
+
return
|
| 606 |
+
# reject result if all new conjugates are just wrappers around
|
| 607 |
+
# an expression that was already in the arg
|
| 608 |
+
conj = signsimp(arg.conjugate(), evaluate=False)
|
| 609 |
+
new_conj = conj.atoms(conjugate) - arg.atoms(conjugate)
|
| 610 |
+
if new_conj and all(arg.has(i.args[0]) for i in new_conj):
|
| 611 |
+
return
|
| 612 |
+
if arg != conj and arg != -conj:
|
| 613 |
+
ignore = arg.atoms(Abs)
|
| 614 |
+
abs_free_arg = arg.xreplace({i: Dummy(real=True) for i in ignore})
|
| 615 |
+
unk = [a for a in abs_free_arg.free_symbols if a.is_extended_real is None]
|
| 616 |
+
if not unk or not all(conj.has(conjugate(u)) for u in unk):
|
| 617 |
+
return sqrt(expand_mul(arg*conj))
|
| 618 |
+
|
| 619 |
+
def _eval_is_real(self):
|
| 620 |
+
if self.args[0].is_finite:
|
| 621 |
+
return True
|
| 622 |
+
|
| 623 |
+
def _eval_is_integer(self):
|
| 624 |
+
if self.args[0].is_extended_real:
|
| 625 |
+
return self.args[0].is_integer
|
| 626 |
+
|
| 627 |
+
def _eval_is_extended_nonzero(self):
|
| 628 |
+
return fuzzy_not(self._args[0].is_zero)
|
| 629 |
+
|
| 630 |
+
def _eval_is_zero(self):
|
| 631 |
+
return self._args[0].is_zero
|
| 632 |
+
|
| 633 |
+
def _eval_is_extended_positive(self):
|
| 634 |
+
return fuzzy_not(self._args[0].is_zero)
|
| 635 |
+
|
| 636 |
+
def _eval_is_rational(self):
|
| 637 |
+
if self.args[0].is_extended_real:
|
| 638 |
+
return self.args[0].is_rational
|
| 639 |
+
|
| 640 |
+
def _eval_is_even(self):
|
| 641 |
+
if self.args[0].is_extended_real:
|
| 642 |
+
return self.args[0].is_even
|
| 643 |
+
|
| 644 |
+
def _eval_is_odd(self):
|
| 645 |
+
if self.args[0].is_extended_real:
|
| 646 |
+
return self.args[0].is_odd
|
| 647 |
+
|
| 648 |
+
def _eval_is_algebraic(self):
|
| 649 |
+
return self.args[0].is_algebraic
|
| 650 |
+
|
| 651 |
+
def _eval_power(self, exponent):
|
| 652 |
+
if self.args[0].is_extended_real and exponent.is_integer:
|
| 653 |
+
if exponent.is_even:
|
| 654 |
+
return self.args[0]**exponent
|
| 655 |
+
elif exponent is not S.NegativeOne and exponent.is_Integer:
|
| 656 |
+
return self.args[0]**(exponent - 1)*self
|
| 657 |
+
return
|
| 658 |
+
|
| 659 |
+
def _eval_nseries(self, x, n, logx, cdir=0):
|
| 660 |
+
from sympy.functions.elementary.exponential import log
|
| 661 |
+
direction = self.args[0].leadterm(x)[0]
|
| 662 |
+
if direction.has(log(x)):
|
| 663 |
+
direction = direction.subs(log(x), logx)
|
| 664 |
+
s = self.args[0]._eval_nseries(x, n=n, logx=logx)
|
| 665 |
+
return (sign(direction)*s).expand()
|
| 666 |
+
|
| 667 |
+
def _eval_derivative(self, x):
|
| 668 |
+
if self.args[0].is_extended_real or self.args[0].is_imaginary:
|
| 669 |
+
return Derivative(self.args[0], x, evaluate=True) \
|
| 670 |
+
* sign(conjugate(self.args[0]))
|
| 671 |
+
rv = (re(self.args[0]) * Derivative(re(self.args[0]), x,
|
| 672 |
+
evaluate=True) + im(self.args[0]) * Derivative(im(self.args[0]),
|
| 673 |
+
x, evaluate=True)) / Abs(self.args[0])
|
| 674 |
+
return rv.rewrite(sign)
|
| 675 |
+
|
| 676 |
+
def _eval_rewrite_as_Heaviside(self, arg, **kwargs):
|
| 677 |
+
# Note this only holds for real arg (since Heaviside is not defined
|
| 678 |
+
# for complex arguments).
|
| 679 |
+
from sympy.functions.special.delta_functions import Heaviside
|
| 680 |
+
if arg.is_extended_real:
|
| 681 |
+
return arg*(Heaviside(arg) - Heaviside(-arg))
|
| 682 |
+
|
| 683 |
+
def _eval_rewrite_as_Piecewise(self, arg, **kwargs):
|
| 684 |
+
if arg.is_extended_real:
|
| 685 |
+
return Piecewise((arg, arg >= 0), (-arg, True))
|
| 686 |
+
elif arg.is_imaginary:
|
| 687 |
+
return Piecewise((I*arg, I*arg >= 0), (-I*arg, True))
|
| 688 |
+
|
| 689 |
+
def _eval_rewrite_as_sign(self, arg, **kwargs):
|
| 690 |
+
return arg/sign(arg)
|
| 691 |
+
|
| 692 |
+
def _eval_rewrite_as_conjugate(self, arg, **kwargs):
|
| 693 |
+
return sqrt(arg*conjugate(arg))
|
| 694 |
+
|
| 695 |
+
|
| 696 |
+
class arg(Function):
|
| 697 |
+
r"""
|
| 698 |
+
Returns the argument (in radians) of a complex number. The argument is
|
| 699 |
+
evaluated in consistent convention with ``atan2`` where the branch-cut is
|
| 700 |
+
taken along the negative real axis and ``arg(z)`` is in the interval
|
| 701 |
+
$(-\pi,\pi]$. For a positive number, the argument is always 0; the
|
| 702 |
+
argument of a negative number is $\pi$; and the argument of 0
|
| 703 |
+
is undefined and returns ``nan``. So the ``arg`` function will never nest
|
| 704 |
+
greater than 3 levels since at the 4th application, the result must be
|
| 705 |
+
nan; for a real number, nan is returned on the 3rd application.
|
| 706 |
+
|
| 707 |
+
Examples
|
| 708 |
+
========
|
| 709 |
+
|
| 710 |
+
>>> from sympy import arg, I, sqrt, Dummy
|
| 711 |
+
>>> from sympy.abc import x
|
| 712 |
+
>>> arg(2.0)
|
| 713 |
+
0
|
| 714 |
+
>>> arg(I)
|
| 715 |
+
pi/2
|
| 716 |
+
>>> arg(sqrt(2) + I*sqrt(2))
|
| 717 |
+
pi/4
|
| 718 |
+
>>> arg(sqrt(3)/2 + I/2)
|
| 719 |
+
pi/6
|
| 720 |
+
>>> arg(4 + 3*I)
|
| 721 |
+
atan(3/4)
|
| 722 |
+
>>> arg(0.8 + 0.6*I)
|
| 723 |
+
0.643501108793284
|
| 724 |
+
>>> arg(arg(arg(arg(x))))
|
| 725 |
+
nan
|
| 726 |
+
>>> real = Dummy(real=True)
|
| 727 |
+
>>> arg(arg(arg(real)))
|
| 728 |
+
nan
|
| 729 |
+
|
| 730 |
+
Parameters
|
| 731 |
+
==========
|
| 732 |
+
|
| 733 |
+
arg : Expr
|
| 734 |
+
Real or complex expression.
|
| 735 |
+
|
| 736 |
+
Returns
|
| 737 |
+
=======
|
| 738 |
+
|
| 739 |
+
value : Expr
|
| 740 |
+
Returns arc tangent of arg measured in radians.
|
| 741 |
+
|
| 742 |
+
"""
|
| 743 |
+
|
| 744 |
+
is_extended_real = True
|
| 745 |
+
is_real = True
|
| 746 |
+
is_finite = True
|
| 747 |
+
_singularities = True # non-holomorphic
|
| 748 |
+
|
| 749 |
+
@classmethod
|
| 750 |
+
def eval(cls, arg):
|
| 751 |
+
a = arg
|
| 752 |
+
for i in range(3):
|
| 753 |
+
if isinstance(a, cls):
|
| 754 |
+
a = a.args[0]
|
| 755 |
+
else:
|
| 756 |
+
if i == 2 and a.is_extended_real:
|
| 757 |
+
return S.NaN
|
| 758 |
+
break
|
| 759 |
+
else:
|
| 760 |
+
return S.NaN
|
| 761 |
+
from sympy.functions.elementary.exponential import exp, exp_polar
|
| 762 |
+
if isinstance(arg, exp_polar):
|
| 763 |
+
return periodic_argument(arg, oo)
|
| 764 |
+
elif isinstance(arg, exp):
|
| 765 |
+
i_ = im(arg.args[0])
|
| 766 |
+
if i_.is_comparable:
|
| 767 |
+
i_ %= 2*S.Pi
|
| 768 |
+
if i_ > S.Pi:
|
| 769 |
+
i_ -= 2*S.Pi
|
| 770 |
+
return i_
|
| 771 |
+
|
| 772 |
+
if not arg.is_Atom:
|
| 773 |
+
c, arg_ = factor_terms(arg).as_coeff_Mul()
|
| 774 |
+
if arg_.is_Mul:
|
| 775 |
+
arg_ = Mul(*[a if (sign(a) not in (-1, 1)) else
|
| 776 |
+
sign(a) for a in arg_.args])
|
| 777 |
+
arg_ = sign(c)*arg_
|
| 778 |
+
else:
|
| 779 |
+
arg_ = arg
|
| 780 |
+
if any(i.is_extended_positive is None for i in arg_.atoms(AppliedUndef)):
|
| 781 |
+
return
|
| 782 |
+
from sympy.functions.elementary.trigonometric import atan2
|
| 783 |
+
x, y = arg_.as_real_imag()
|
| 784 |
+
rv = atan2(y, x)
|
| 785 |
+
if rv.is_number:
|
| 786 |
+
return rv
|
| 787 |
+
if arg_ != arg:
|
| 788 |
+
return cls(arg_, evaluate=False)
|
| 789 |
+
|
| 790 |
+
def _eval_derivative(self, t):
|
| 791 |
+
x, y = self.args[0].as_real_imag()
|
| 792 |
+
return (x * Derivative(y, t, evaluate=True) - y *
|
| 793 |
+
Derivative(x, t, evaluate=True)) / (x**2 + y**2)
|
| 794 |
+
|
| 795 |
+
def _eval_rewrite_as_atan2(self, arg, **kwargs):
|
| 796 |
+
from sympy.functions.elementary.trigonometric import atan2
|
| 797 |
+
x, y = self.args[0].as_real_imag()
|
| 798 |
+
return atan2(y, x)
|
| 799 |
+
|
| 800 |
+
|
| 801 |
+
class conjugate(Function):
|
| 802 |
+
"""
|
| 803 |
+
Returns the *complex conjugate* [1]_ of an argument.
|
| 804 |
+
In mathematics, the complex conjugate of a complex number
|
| 805 |
+
is given by changing the sign of the imaginary part.
|
| 806 |
+
|
| 807 |
+
Thus, the conjugate of the complex number
|
| 808 |
+
:math:`a + ib` (where $a$ and $b$ are real numbers) is :math:`a - ib`
|
| 809 |
+
|
| 810 |
+
Examples
|
| 811 |
+
========
|
| 812 |
+
|
| 813 |
+
>>> from sympy import conjugate, I
|
| 814 |
+
>>> conjugate(2)
|
| 815 |
+
2
|
| 816 |
+
>>> conjugate(I)
|
| 817 |
+
-I
|
| 818 |
+
>>> conjugate(3 + 2*I)
|
| 819 |
+
3 - 2*I
|
| 820 |
+
>>> conjugate(5 - I)
|
| 821 |
+
5 + I
|
| 822 |
+
|
| 823 |
+
Parameters
|
| 824 |
+
==========
|
| 825 |
+
|
| 826 |
+
arg : Expr
|
| 827 |
+
Real or complex expression.
|
| 828 |
+
|
| 829 |
+
Returns
|
| 830 |
+
=======
|
| 831 |
+
|
| 832 |
+
arg : Expr
|
| 833 |
+
Complex conjugate of arg as real, imaginary or mixed expression.
|
| 834 |
+
|
| 835 |
+
See Also
|
| 836 |
+
========
|
| 837 |
+
|
| 838 |
+
sign, Abs
|
| 839 |
+
|
| 840 |
+
References
|
| 841 |
+
==========
|
| 842 |
+
|
| 843 |
+
.. [1] https://en.wikipedia.org/wiki/Complex_conjugation
|
| 844 |
+
"""
|
| 845 |
+
_singularities = True # non-holomorphic
|
| 846 |
+
|
| 847 |
+
@classmethod
|
| 848 |
+
def eval(cls, arg):
|
| 849 |
+
obj = arg._eval_conjugate()
|
| 850 |
+
if obj is not None:
|
| 851 |
+
return obj
|
| 852 |
+
|
| 853 |
+
def inverse(self):
|
| 854 |
+
return conjugate
|
| 855 |
+
|
| 856 |
+
def _eval_Abs(self):
|
| 857 |
+
return Abs(self.args[0], evaluate=True)
|
| 858 |
+
|
| 859 |
+
def _eval_adjoint(self):
|
| 860 |
+
return transpose(self.args[0])
|
| 861 |
+
|
| 862 |
+
def _eval_conjugate(self):
|
| 863 |
+
return self.args[0]
|
| 864 |
+
|
| 865 |
+
def _eval_derivative(self, x):
|
| 866 |
+
if x.is_real:
|
| 867 |
+
return conjugate(Derivative(self.args[0], x, evaluate=True))
|
| 868 |
+
elif x.is_imaginary:
|
| 869 |
+
return -conjugate(Derivative(self.args[0], x, evaluate=True))
|
| 870 |
+
|
| 871 |
+
def _eval_transpose(self):
|
| 872 |
+
return adjoint(self.args[0])
|
| 873 |
+
|
| 874 |
+
def _eval_is_algebraic(self):
|
| 875 |
+
return self.args[0].is_algebraic
|
| 876 |
+
|
| 877 |
+
|
| 878 |
+
class transpose(Function):
|
| 879 |
+
"""
|
| 880 |
+
Linear map transposition.
|
| 881 |
+
|
| 882 |
+
Examples
|
| 883 |
+
========
|
| 884 |
+
|
| 885 |
+
>>> from sympy import transpose, Matrix, MatrixSymbol
|
| 886 |
+
>>> A = MatrixSymbol('A', 25, 9)
|
| 887 |
+
>>> transpose(A)
|
| 888 |
+
A.T
|
| 889 |
+
>>> B = MatrixSymbol('B', 9, 22)
|
| 890 |
+
>>> transpose(B)
|
| 891 |
+
B.T
|
| 892 |
+
>>> transpose(A*B)
|
| 893 |
+
B.T*A.T
|
| 894 |
+
>>> M = Matrix([[4, 5], [2, 1], [90, 12]])
|
| 895 |
+
>>> M
|
| 896 |
+
Matrix([
|
| 897 |
+
[ 4, 5],
|
| 898 |
+
[ 2, 1],
|
| 899 |
+
[90, 12]])
|
| 900 |
+
>>> transpose(M)
|
| 901 |
+
Matrix([
|
| 902 |
+
[4, 2, 90],
|
| 903 |
+
[5, 1, 12]])
|
| 904 |
+
|
| 905 |
+
Parameters
|
| 906 |
+
==========
|
| 907 |
+
|
| 908 |
+
arg : Matrix
|
| 909 |
+
Matrix or matrix expression to take the transpose of.
|
| 910 |
+
|
| 911 |
+
Returns
|
| 912 |
+
=======
|
| 913 |
+
|
| 914 |
+
value : Matrix
|
| 915 |
+
Transpose of arg.
|
| 916 |
+
|
| 917 |
+
"""
|
| 918 |
+
|
| 919 |
+
@classmethod
|
| 920 |
+
def eval(cls, arg):
|
| 921 |
+
obj = arg._eval_transpose()
|
| 922 |
+
if obj is not None:
|
| 923 |
+
return obj
|
| 924 |
+
|
| 925 |
+
def _eval_adjoint(self):
|
| 926 |
+
return conjugate(self.args[0])
|
| 927 |
+
|
| 928 |
+
def _eval_conjugate(self):
|
| 929 |
+
return adjoint(self.args[0])
|
| 930 |
+
|
| 931 |
+
def _eval_transpose(self):
|
| 932 |
+
return self.args[0]
|
| 933 |
+
|
| 934 |
+
|
| 935 |
+
class adjoint(Function):
|
| 936 |
+
"""
|
| 937 |
+
Conjugate transpose or Hermite conjugation.
|
| 938 |
+
|
| 939 |
+
Examples
|
| 940 |
+
========
|
| 941 |
+
|
| 942 |
+
>>> from sympy import adjoint, MatrixSymbol
|
| 943 |
+
>>> A = MatrixSymbol('A', 10, 5)
|
| 944 |
+
>>> adjoint(A)
|
| 945 |
+
Adjoint(A)
|
| 946 |
+
|
| 947 |
+
Parameters
|
| 948 |
+
==========
|
| 949 |
+
|
| 950 |
+
arg : Matrix
|
| 951 |
+
Matrix or matrix expression to take the adjoint of.
|
| 952 |
+
|
| 953 |
+
Returns
|
| 954 |
+
=======
|
| 955 |
+
|
| 956 |
+
value : Matrix
|
| 957 |
+
Represents the conjugate transpose or Hermite
|
| 958 |
+
conjugation of arg.
|
| 959 |
+
|
| 960 |
+
"""
|
| 961 |
+
|
| 962 |
+
@classmethod
|
| 963 |
+
def eval(cls, arg):
|
| 964 |
+
obj = arg._eval_adjoint()
|
| 965 |
+
if obj is not None:
|
| 966 |
+
return obj
|
| 967 |
+
obj = arg._eval_transpose()
|
| 968 |
+
if obj is not None:
|
| 969 |
+
return conjugate(obj)
|
| 970 |
+
|
| 971 |
+
def _eval_adjoint(self):
|
| 972 |
+
return self.args[0]
|
| 973 |
+
|
| 974 |
+
def _eval_conjugate(self):
|
| 975 |
+
return transpose(self.args[0])
|
| 976 |
+
|
| 977 |
+
def _eval_transpose(self):
|
| 978 |
+
return conjugate(self.args[0])
|
| 979 |
+
|
| 980 |
+
def _latex(self, printer, exp=None, *args):
|
| 981 |
+
arg = printer._print(self.args[0])
|
| 982 |
+
tex = r'%s^{\dagger}' % arg
|
| 983 |
+
if exp:
|
| 984 |
+
tex = r'\left(%s\right)^{%s}' % (tex, exp)
|
| 985 |
+
return tex
|
| 986 |
+
|
| 987 |
+
def _pretty(self, printer, *args):
|
| 988 |
+
from sympy.printing.pretty.stringpict import prettyForm
|
| 989 |
+
pform = printer._print(self.args[0], *args)
|
| 990 |
+
if printer._use_unicode:
|
| 991 |
+
pform = pform**prettyForm('\N{DAGGER}')
|
| 992 |
+
else:
|
| 993 |
+
pform = pform**prettyForm('+')
|
| 994 |
+
return pform
|
| 995 |
+
|
| 996 |
+
###############################################################################
|
| 997 |
+
############### HANDLING OF POLAR NUMBERS #####################################
|
| 998 |
+
###############################################################################
|
| 999 |
+
|
| 1000 |
+
|
| 1001 |
+
class polar_lift(Function):
|
| 1002 |
+
"""
|
| 1003 |
+
Lift argument to the Riemann surface of the logarithm, using the
|
| 1004 |
+
standard branch.
|
| 1005 |
+
|
| 1006 |
+
Examples
|
| 1007 |
+
========
|
| 1008 |
+
|
| 1009 |
+
>>> from sympy import Symbol, polar_lift, I
|
| 1010 |
+
>>> p = Symbol('p', polar=True)
|
| 1011 |
+
>>> x = Symbol('x')
|
| 1012 |
+
>>> polar_lift(4)
|
| 1013 |
+
4*exp_polar(0)
|
| 1014 |
+
>>> polar_lift(-4)
|
| 1015 |
+
4*exp_polar(I*pi)
|
| 1016 |
+
>>> polar_lift(-I)
|
| 1017 |
+
exp_polar(-I*pi/2)
|
| 1018 |
+
>>> polar_lift(I + 2)
|
| 1019 |
+
polar_lift(2 + I)
|
| 1020 |
+
|
| 1021 |
+
>>> polar_lift(4*x)
|
| 1022 |
+
4*polar_lift(x)
|
| 1023 |
+
>>> polar_lift(4*p)
|
| 1024 |
+
4*p
|
| 1025 |
+
|
| 1026 |
+
Parameters
|
| 1027 |
+
==========
|
| 1028 |
+
|
| 1029 |
+
arg : Expr
|
| 1030 |
+
Real or complex expression.
|
| 1031 |
+
|
| 1032 |
+
See Also
|
| 1033 |
+
========
|
| 1034 |
+
|
| 1035 |
+
sympy.functions.elementary.exponential.exp_polar
|
| 1036 |
+
periodic_argument
|
| 1037 |
+
"""
|
| 1038 |
+
|
| 1039 |
+
is_polar = True
|
| 1040 |
+
is_comparable = False # Cannot be evalf'd.
|
| 1041 |
+
|
| 1042 |
+
@classmethod
|
| 1043 |
+
def eval(cls, arg):
|
| 1044 |
+
from sympy.functions.elementary.complexes import arg as argument
|
| 1045 |
+
if arg.is_number:
|
| 1046 |
+
ar = argument(arg)
|
| 1047 |
+
# In general we want to affirm that something is known,
|
| 1048 |
+
# e.g. `not ar.has(argument) and not ar.has(atan)`
|
| 1049 |
+
# but for now we will just be more restrictive and
|
| 1050 |
+
# see that it has evaluated to one of the known values.
|
| 1051 |
+
if ar in (0, pi/2, -pi/2, pi):
|
| 1052 |
+
from sympy.functions.elementary.exponential import exp_polar
|
| 1053 |
+
return exp_polar(I*ar)*abs(arg)
|
| 1054 |
+
|
| 1055 |
+
if arg.is_Mul:
|
| 1056 |
+
args = arg.args
|
| 1057 |
+
else:
|
| 1058 |
+
args = [arg]
|
| 1059 |
+
included = []
|
| 1060 |
+
excluded = []
|
| 1061 |
+
positive = []
|
| 1062 |
+
for arg in args:
|
| 1063 |
+
if arg.is_polar:
|
| 1064 |
+
included += [arg]
|
| 1065 |
+
elif arg.is_positive:
|
| 1066 |
+
positive += [arg]
|
| 1067 |
+
else:
|
| 1068 |
+
excluded += [arg]
|
| 1069 |
+
if len(excluded) < len(args):
|
| 1070 |
+
if excluded:
|
| 1071 |
+
return Mul(*(included + positive))*polar_lift(Mul(*excluded))
|
| 1072 |
+
elif included:
|
| 1073 |
+
return Mul(*(included + positive))
|
| 1074 |
+
else:
|
| 1075 |
+
from sympy.functions.elementary.exponential import exp_polar
|
| 1076 |
+
return Mul(*positive)*exp_polar(0)
|
| 1077 |
+
|
| 1078 |
+
def _eval_evalf(self, prec):
|
| 1079 |
+
""" Careful! any evalf of polar numbers is flaky """
|
| 1080 |
+
return self.args[0]._eval_evalf(prec)
|
| 1081 |
+
|
| 1082 |
+
def _eval_Abs(self):
|
| 1083 |
+
return Abs(self.args[0], evaluate=True)
|
| 1084 |
+
|
| 1085 |
+
|
| 1086 |
+
class periodic_argument(Function):
|
| 1087 |
+
r"""
|
| 1088 |
+
Represent the argument on a quotient of the Riemann surface of the
|
| 1089 |
+
logarithm. That is, given a period $P$, always return a value in
|
| 1090 |
+
$(-P/2, P/2]$, by using $\exp(PI) = 1$.
|
| 1091 |
+
|
| 1092 |
+
Examples
|
| 1093 |
+
========
|
| 1094 |
+
|
| 1095 |
+
>>> from sympy import exp_polar, periodic_argument
|
| 1096 |
+
>>> from sympy import I, pi
|
| 1097 |
+
>>> periodic_argument(exp_polar(10*I*pi), 2*pi)
|
| 1098 |
+
0
|
| 1099 |
+
>>> periodic_argument(exp_polar(5*I*pi), 4*pi)
|
| 1100 |
+
pi
|
| 1101 |
+
>>> from sympy import exp_polar, periodic_argument
|
| 1102 |
+
>>> from sympy import I, pi
|
| 1103 |
+
>>> periodic_argument(exp_polar(5*I*pi), 2*pi)
|
| 1104 |
+
pi
|
| 1105 |
+
>>> periodic_argument(exp_polar(5*I*pi), 3*pi)
|
| 1106 |
+
-pi
|
| 1107 |
+
>>> periodic_argument(exp_polar(5*I*pi), pi)
|
| 1108 |
+
0
|
| 1109 |
+
|
| 1110 |
+
Parameters
|
| 1111 |
+
==========
|
| 1112 |
+
|
| 1113 |
+
ar : Expr
|
| 1114 |
+
A polar number.
|
| 1115 |
+
|
| 1116 |
+
period : Expr
|
| 1117 |
+
The period $P$.
|
| 1118 |
+
|
| 1119 |
+
See Also
|
| 1120 |
+
========
|
| 1121 |
+
|
| 1122 |
+
sympy.functions.elementary.exponential.exp_polar
|
| 1123 |
+
polar_lift : Lift argument to the Riemann surface of the logarithm
|
| 1124 |
+
principal_branch
|
| 1125 |
+
"""
|
| 1126 |
+
|
| 1127 |
+
@classmethod
|
| 1128 |
+
def _getunbranched(cls, ar):
|
| 1129 |
+
from sympy.functions.elementary.exponential import exp_polar, log
|
| 1130 |
+
if ar.is_Mul:
|
| 1131 |
+
args = ar.args
|
| 1132 |
+
else:
|
| 1133 |
+
args = [ar]
|
| 1134 |
+
unbranched = 0
|
| 1135 |
+
for a in args:
|
| 1136 |
+
if not a.is_polar:
|
| 1137 |
+
unbranched += arg(a)
|
| 1138 |
+
elif isinstance(a, exp_polar):
|
| 1139 |
+
unbranched += a.exp.as_real_imag()[1]
|
| 1140 |
+
elif a.is_Pow:
|
| 1141 |
+
re, im = a.exp.as_real_imag()
|
| 1142 |
+
unbranched += re*unbranched_argument(
|
| 1143 |
+
a.base) + im*log(abs(a.base))
|
| 1144 |
+
elif isinstance(a, polar_lift):
|
| 1145 |
+
unbranched += arg(a.args[0])
|
| 1146 |
+
else:
|
| 1147 |
+
return None
|
| 1148 |
+
return unbranched
|
| 1149 |
+
|
| 1150 |
+
@classmethod
|
| 1151 |
+
def eval(cls, ar, period):
|
| 1152 |
+
# Our strategy is to evaluate the argument on the Riemann surface of the
|
| 1153 |
+
# logarithm, and then reduce.
|
| 1154 |
+
# NOTE evidently this means it is a rather bad idea to use this with
|
| 1155 |
+
# period != 2*pi and non-polar numbers.
|
| 1156 |
+
if not period.is_extended_positive:
|
| 1157 |
+
return None
|
| 1158 |
+
if period == oo and isinstance(ar, principal_branch):
|
| 1159 |
+
return periodic_argument(*ar.args)
|
| 1160 |
+
if isinstance(ar, polar_lift) and period >= 2*pi:
|
| 1161 |
+
return periodic_argument(ar.args[0], period)
|
| 1162 |
+
if ar.is_Mul:
|
| 1163 |
+
newargs = [x for x in ar.args if not x.is_positive]
|
| 1164 |
+
if len(newargs) != len(ar.args):
|
| 1165 |
+
return periodic_argument(Mul(*newargs), period)
|
| 1166 |
+
unbranched = cls._getunbranched(ar)
|
| 1167 |
+
if unbranched is None:
|
| 1168 |
+
return None
|
| 1169 |
+
from sympy.functions.elementary.trigonometric import atan, atan2
|
| 1170 |
+
if unbranched.has(periodic_argument, atan2, atan):
|
| 1171 |
+
return None
|
| 1172 |
+
if period == oo:
|
| 1173 |
+
return unbranched
|
| 1174 |
+
if period != oo:
|
| 1175 |
+
from sympy.functions.elementary.integers import ceiling
|
| 1176 |
+
n = ceiling(unbranched/period - S.Half)*period
|
| 1177 |
+
if not n.has(ceiling):
|
| 1178 |
+
return unbranched - n
|
| 1179 |
+
|
| 1180 |
+
def _eval_evalf(self, prec):
|
| 1181 |
+
z, period = self.args
|
| 1182 |
+
if period == oo:
|
| 1183 |
+
unbranched = periodic_argument._getunbranched(z)
|
| 1184 |
+
if unbranched is None:
|
| 1185 |
+
return self
|
| 1186 |
+
return unbranched._eval_evalf(prec)
|
| 1187 |
+
ub = periodic_argument(z, oo)._eval_evalf(prec)
|
| 1188 |
+
from sympy.functions.elementary.integers import ceiling
|
| 1189 |
+
return (ub - ceiling(ub/period - S.Half)*period)._eval_evalf(prec)
|
| 1190 |
+
|
| 1191 |
+
|
| 1192 |
+
def unbranched_argument(arg):
|
| 1193 |
+
'''
|
| 1194 |
+
Returns periodic argument of arg with period as infinity.
|
| 1195 |
+
|
| 1196 |
+
Examples
|
| 1197 |
+
========
|
| 1198 |
+
|
| 1199 |
+
>>> from sympy import exp_polar, unbranched_argument
|
| 1200 |
+
>>> from sympy import I, pi
|
| 1201 |
+
>>> unbranched_argument(exp_polar(15*I*pi))
|
| 1202 |
+
15*pi
|
| 1203 |
+
>>> unbranched_argument(exp_polar(7*I*pi))
|
| 1204 |
+
7*pi
|
| 1205 |
+
|
| 1206 |
+
See also
|
| 1207 |
+
========
|
| 1208 |
+
|
| 1209 |
+
periodic_argument
|
| 1210 |
+
'''
|
| 1211 |
+
return periodic_argument(arg, oo)
|
| 1212 |
+
|
| 1213 |
+
|
| 1214 |
+
class principal_branch(Function):
|
| 1215 |
+
"""
|
| 1216 |
+
Represent a polar number reduced to its principal branch on a quotient
|
| 1217 |
+
of the Riemann surface of the logarithm.
|
| 1218 |
+
|
| 1219 |
+
Explanation
|
| 1220 |
+
===========
|
| 1221 |
+
|
| 1222 |
+
This is a function of two arguments. The first argument is a polar
|
| 1223 |
+
number `z`, and the second one a positive real number or infinity, `p`.
|
| 1224 |
+
The result is ``z mod exp_polar(I*p)``.
|
| 1225 |
+
|
| 1226 |
+
Examples
|
| 1227 |
+
========
|
| 1228 |
+
|
| 1229 |
+
>>> from sympy import exp_polar, principal_branch, oo, I, pi
|
| 1230 |
+
>>> from sympy.abc import z
|
| 1231 |
+
>>> principal_branch(z, oo)
|
| 1232 |
+
z
|
| 1233 |
+
>>> principal_branch(exp_polar(2*pi*I)*3, 2*pi)
|
| 1234 |
+
3*exp_polar(0)
|
| 1235 |
+
>>> principal_branch(exp_polar(2*pi*I)*3*z, 2*pi)
|
| 1236 |
+
3*principal_branch(z, 2*pi)
|
| 1237 |
+
|
| 1238 |
+
Parameters
|
| 1239 |
+
==========
|
| 1240 |
+
|
| 1241 |
+
x : Expr
|
| 1242 |
+
A polar number.
|
| 1243 |
+
|
| 1244 |
+
period : Expr
|
| 1245 |
+
Positive real number or infinity.
|
| 1246 |
+
|
| 1247 |
+
See Also
|
| 1248 |
+
========
|
| 1249 |
+
|
| 1250 |
+
sympy.functions.elementary.exponential.exp_polar
|
| 1251 |
+
polar_lift : Lift argument to the Riemann surface of the logarithm
|
| 1252 |
+
periodic_argument
|
| 1253 |
+
"""
|
| 1254 |
+
|
| 1255 |
+
is_polar = True
|
| 1256 |
+
is_comparable = False # cannot always be evalf'd
|
| 1257 |
+
|
| 1258 |
+
@classmethod
|
| 1259 |
+
def eval(self, x, period):
|
| 1260 |
+
from sympy.functions.elementary.exponential import exp_polar
|
| 1261 |
+
if isinstance(x, polar_lift):
|
| 1262 |
+
return principal_branch(x.args[0], period)
|
| 1263 |
+
if period == oo:
|
| 1264 |
+
return x
|
| 1265 |
+
ub = periodic_argument(x, oo)
|
| 1266 |
+
barg = periodic_argument(x, period)
|
| 1267 |
+
if ub != barg and not ub.has(periodic_argument) \
|
| 1268 |
+
and not barg.has(periodic_argument):
|
| 1269 |
+
pl = polar_lift(x)
|
| 1270 |
+
|
| 1271 |
+
def mr(expr):
|
| 1272 |
+
if not isinstance(expr, Symbol):
|
| 1273 |
+
return polar_lift(expr)
|
| 1274 |
+
return expr
|
| 1275 |
+
pl = pl.replace(polar_lift, mr)
|
| 1276 |
+
# Recompute unbranched argument
|
| 1277 |
+
ub = periodic_argument(pl, oo)
|
| 1278 |
+
if not pl.has(polar_lift):
|
| 1279 |
+
if ub != barg:
|
| 1280 |
+
res = exp_polar(I*(barg - ub))*pl
|
| 1281 |
+
else:
|
| 1282 |
+
res = pl
|
| 1283 |
+
if not res.is_polar and not res.has(exp_polar):
|
| 1284 |
+
res *= exp_polar(0)
|
| 1285 |
+
return res
|
| 1286 |
+
|
| 1287 |
+
if not x.free_symbols:
|
| 1288 |
+
c, m = x, ()
|
| 1289 |
+
else:
|
| 1290 |
+
c, m = x.as_coeff_mul(*x.free_symbols)
|
| 1291 |
+
others = []
|
| 1292 |
+
for y in m:
|
| 1293 |
+
if y.is_positive:
|
| 1294 |
+
c *= y
|
| 1295 |
+
else:
|
| 1296 |
+
others += [y]
|
| 1297 |
+
m = tuple(others)
|
| 1298 |
+
arg = periodic_argument(c, period)
|
| 1299 |
+
if arg.has(periodic_argument):
|
| 1300 |
+
return None
|
| 1301 |
+
if arg.is_number and (unbranched_argument(c) != arg or
|
| 1302 |
+
(arg == 0 and m != () and c != 1)):
|
| 1303 |
+
if arg == 0:
|
| 1304 |
+
return abs(c)*principal_branch(Mul(*m), period)
|
| 1305 |
+
return principal_branch(exp_polar(I*arg)*Mul(*m), period)*abs(c)
|
| 1306 |
+
if arg.is_number and ((abs(arg) < period/2) == True or arg == period/2) \
|
| 1307 |
+
and m == ():
|
| 1308 |
+
return exp_polar(arg*I)*abs(c)
|
| 1309 |
+
|
| 1310 |
+
def _eval_evalf(self, prec):
|
| 1311 |
+
z, period = self.args
|
| 1312 |
+
p = periodic_argument(z, period)._eval_evalf(prec)
|
| 1313 |
+
if abs(p) > pi or p == -pi:
|
| 1314 |
+
return self # Cannot evalf for this argument.
|
| 1315 |
+
from sympy.functions.elementary.exponential import exp
|
| 1316 |
+
return (abs(z)*exp(I*p))._eval_evalf(prec)
|
| 1317 |
+
|
| 1318 |
+
|
| 1319 |
+
def _polarify(eq, lift, pause=False):
|
| 1320 |
+
from sympy.integrals.integrals import Integral
|
| 1321 |
+
if eq.is_polar:
|
| 1322 |
+
return eq
|
| 1323 |
+
if eq.is_number and not pause:
|
| 1324 |
+
return polar_lift(eq)
|
| 1325 |
+
if isinstance(eq, Symbol) and not pause and lift:
|
| 1326 |
+
return polar_lift(eq)
|
| 1327 |
+
elif eq.is_Atom:
|
| 1328 |
+
return eq
|
| 1329 |
+
elif eq.is_Add:
|
| 1330 |
+
r = eq.func(*[_polarify(arg, lift, pause=True) for arg in eq.args])
|
| 1331 |
+
if lift:
|
| 1332 |
+
return polar_lift(r)
|
| 1333 |
+
return r
|
| 1334 |
+
elif eq.is_Pow and eq.base == S.Exp1:
|
| 1335 |
+
return eq.func(S.Exp1, _polarify(eq.exp, lift, pause=False))
|
| 1336 |
+
elif eq.is_Function:
|
| 1337 |
+
return eq.func(*[_polarify(arg, lift, pause=False) for arg in eq.args])
|
| 1338 |
+
elif isinstance(eq, Integral):
|
| 1339 |
+
# Don't lift the integration variable
|
| 1340 |
+
func = _polarify(eq.function, lift, pause=pause)
|
| 1341 |
+
limits = []
|
| 1342 |
+
for limit in eq.args[1:]:
|
| 1343 |
+
var = _polarify(limit[0], lift=False, pause=pause)
|
| 1344 |
+
rest = _polarify(limit[1:], lift=lift, pause=pause)
|
| 1345 |
+
limits.append((var,) + rest)
|
| 1346 |
+
return Integral(*((func,) + tuple(limits)))
|
| 1347 |
+
else:
|
| 1348 |
+
return eq.func(*[_polarify(arg, lift, pause=pause)
|
| 1349 |
+
if isinstance(arg, Expr) else arg for arg in eq.args])
|
| 1350 |
+
|
| 1351 |
+
|
| 1352 |
+
def polarify(eq, subs=True, lift=False):
|
| 1353 |
+
"""
|
| 1354 |
+
Turn all numbers in eq into their polar equivalents (under the standard
|
| 1355 |
+
choice of argument).
|
| 1356 |
+
|
| 1357 |
+
Note that no attempt is made to guess a formal convention of adding
|
| 1358 |
+
polar numbers, expressions like $1 + x$ will generally not be altered.
|
| 1359 |
+
|
| 1360 |
+
Note also that this function does not promote ``exp(x)`` to ``exp_polar(x)``.
|
| 1361 |
+
|
| 1362 |
+
If ``subs`` is ``True``, all symbols which are not already polar will be
|
| 1363 |
+
substituted for polar dummies; in this case the function behaves much
|
| 1364 |
+
like :func:`~.posify`.
|
| 1365 |
+
|
| 1366 |
+
If ``lift`` is ``True``, both addition statements and non-polar symbols are
|
| 1367 |
+
changed to their ``polar_lift()``ed versions.
|
| 1368 |
+
Note that ``lift=True`` implies ``subs=False``.
|
| 1369 |
+
|
| 1370 |
+
Examples
|
| 1371 |
+
========
|
| 1372 |
+
|
| 1373 |
+
>>> from sympy import polarify, sin, I
|
| 1374 |
+
>>> from sympy.abc import x, y
|
| 1375 |
+
>>> expr = (-x)**y
|
| 1376 |
+
>>> expr.expand()
|
| 1377 |
+
(-x)**y
|
| 1378 |
+
>>> polarify(expr)
|
| 1379 |
+
((_x*exp_polar(I*pi))**_y, {_x: x, _y: y})
|
| 1380 |
+
>>> polarify(expr)[0].expand()
|
| 1381 |
+
_x**_y*exp_polar(_y*I*pi)
|
| 1382 |
+
>>> polarify(x, lift=True)
|
| 1383 |
+
polar_lift(x)
|
| 1384 |
+
>>> polarify(x*(1+y), lift=True)
|
| 1385 |
+
polar_lift(x)*polar_lift(y + 1)
|
| 1386 |
+
|
| 1387 |
+
Adds are treated carefully:
|
| 1388 |
+
|
| 1389 |
+
>>> polarify(1 + sin((1 + I)*x))
|
| 1390 |
+
(sin(_x*polar_lift(1 + I)) + 1, {_x: x})
|
| 1391 |
+
"""
|
| 1392 |
+
if lift:
|
| 1393 |
+
subs = False
|
| 1394 |
+
eq = _polarify(sympify(eq), lift)
|
| 1395 |
+
if not subs:
|
| 1396 |
+
return eq
|
| 1397 |
+
reps = {s: Dummy(s.name, polar=True) for s in eq.free_symbols}
|
| 1398 |
+
eq = eq.subs(reps)
|
| 1399 |
+
return eq, {r: s for s, r in reps.items()}
|
| 1400 |
+
|
| 1401 |
+
|
| 1402 |
+
def _unpolarify(eq, exponents_only, pause=False):
|
| 1403 |
+
if not isinstance(eq, Basic) or eq.is_Atom:
|
| 1404 |
+
return eq
|
| 1405 |
+
|
| 1406 |
+
if not pause:
|
| 1407 |
+
from sympy.functions.elementary.exponential import exp, exp_polar
|
| 1408 |
+
if isinstance(eq, exp_polar):
|
| 1409 |
+
return exp(_unpolarify(eq.exp, exponents_only))
|
| 1410 |
+
if isinstance(eq, principal_branch) and eq.args[1] == 2*pi:
|
| 1411 |
+
return _unpolarify(eq.args[0], exponents_only)
|
| 1412 |
+
if (
|
| 1413 |
+
eq.is_Add or eq.is_Mul or eq.is_Boolean or
|
| 1414 |
+
eq.is_Relational and (
|
| 1415 |
+
eq.rel_op in ('==', '!=') and 0 in eq.args or
|
| 1416 |
+
eq.rel_op not in ('==', '!='))
|
| 1417 |
+
):
|
| 1418 |
+
return eq.func(*[_unpolarify(x, exponents_only) for x in eq.args])
|
| 1419 |
+
if isinstance(eq, polar_lift):
|
| 1420 |
+
return _unpolarify(eq.args[0], exponents_only)
|
| 1421 |
+
|
| 1422 |
+
if eq.is_Pow:
|
| 1423 |
+
expo = _unpolarify(eq.exp, exponents_only)
|
| 1424 |
+
base = _unpolarify(eq.base, exponents_only,
|
| 1425 |
+
not (expo.is_integer and not pause))
|
| 1426 |
+
return base**expo
|
| 1427 |
+
|
| 1428 |
+
if eq.is_Function and getattr(eq.func, 'unbranched', False):
|
| 1429 |
+
return eq.func(*[_unpolarify(x, exponents_only, exponents_only)
|
| 1430 |
+
for x in eq.args])
|
| 1431 |
+
|
| 1432 |
+
return eq.func(*[_unpolarify(x, exponents_only, True) for x in eq.args])
|
| 1433 |
+
|
| 1434 |
+
|
| 1435 |
+
def unpolarify(eq, subs=None, exponents_only=False):
|
| 1436 |
+
"""
|
| 1437 |
+
If `p` denotes the projection from the Riemann surface of the logarithm to
|
| 1438 |
+
the complex line, return a simplified version `eq'` of `eq` such that
|
| 1439 |
+
`p(eq') = p(eq)`.
|
| 1440 |
+
Also apply the substitution subs in the end. (This is a convenience, since
|
| 1441 |
+
``unpolarify``, in a certain sense, undoes :func:`polarify`.)
|
| 1442 |
+
|
| 1443 |
+
Examples
|
| 1444 |
+
========
|
| 1445 |
+
|
| 1446 |
+
>>> from sympy import unpolarify, polar_lift, sin, I
|
| 1447 |
+
>>> unpolarify(polar_lift(I + 2))
|
| 1448 |
+
2 + I
|
| 1449 |
+
>>> unpolarify(sin(polar_lift(I + 7)))
|
| 1450 |
+
sin(7 + I)
|
| 1451 |
+
"""
|
| 1452 |
+
if isinstance(eq, bool):
|
| 1453 |
+
return eq
|
| 1454 |
+
|
| 1455 |
+
eq = sympify(eq)
|
| 1456 |
+
if subs is not None:
|
| 1457 |
+
return unpolarify(eq.subs(subs))
|
| 1458 |
+
changed = True
|
| 1459 |
+
pause = False
|
| 1460 |
+
if exponents_only:
|
| 1461 |
+
pause = True
|
| 1462 |
+
while changed:
|
| 1463 |
+
changed = False
|
| 1464 |
+
res = _unpolarify(eq, exponents_only, pause)
|
| 1465 |
+
if res != eq:
|
| 1466 |
+
changed = True
|
| 1467 |
+
eq = res
|
| 1468 |
+
if isinstance(res, bool):
|
| 1469 |
+
return res
|
| 1470 |
+
# Finally, replacing Exp(0) by 1 is always correct.
|
| 1471 |
+
# So is polar_lift(0) -> 0.
|
| 1472 |
+
from sympy.functions.elementary.exponential import exp_polar
|
| 1473 |
+
return res.subs({exp_polar(0): 1, polar_lift(0): 0})
|
evalkit_tf437/lib/python3.10/site-packages/sympy/functions/elementary/exponential.py
ADDED
|
@@ -0,0 +1,1293 @@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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from itertools import product
|
| 2 |
+
from typing import Tuple as tTuple
|
| 3 |
+
|
| 4 |
+
from sympy.core.add import Add
|
| 5 |
+
from sympy.core.cache import cacheit
|
| 6 |
+
from sympy.core.expr import Expr
|
| 7 |
+
from sympy.core.function import (Function, ArgumentIndexError, expand_log,
|
| 8 |
+
expand_mul, FunctionClass, PoleError, expand_multinomial, expand_complex)
|
| 9 |
+
from sympy.core.logic import fuzzy_and, fuzzy_not, fuzzy_or
|
| 10 |
+
from sympy.core.mul import Mul
|
| 11 |
+
from sympy.core.numbers import Integer, Rational, pi, I
|
| 12 |
+
from sympy.core.parameters import global_parameters
|
| 13 |
+
from sympy.core.power import Pow
|
| 14 |
+
from sympy.core.singleton import S
|
| 15 |
+
from sympy.core.symbol import Wild, Dummy
|
| 16 |
+
from sympy.core.sympify import sympify
|
| 17 |
+
from sympy.functions.combinatorial.factorials import factorial
|
| 18 |
+
from sympy.functions.elementary.complexes import arg, unpolarify, im, re, Abs
|
| 19 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
| 20 |
+
from sympy.ntheory import multiplicity, perfect_power
|
| 21 |
+
from sympy.ntheory.factor_ import factorint
|
| 22 |
+
|
| 23 |
+
# NOTE IMPORTANT
|
| 24 |
+
# The series expansion code in this file is an important part of the gruntz
|
| 25 |
+
# algorithm for determining limits. _eval_nseries has to return a generalized
|
| 26 |
+
# power series with coefficients in C(log(x), log).
|
| 27 |
+
# In more detail, the result of _eval_nseries(self, x, n) must be
|
| 28 |
+
# c_0*x**e_0 + ... (finitely many terms)
|
| 29 |
+
# where e_i are numbers (not necessarily integers) and c_i involve only
|
| 30 |
+
# numbers, the function log, and log(x). [This also means it must not contain
|
| 31 |
+
# log(x(1+p)), this *has* to be expanded to log(x)+log(1+p) if x.is_positive and
|
| 32 |
+
# p.is_positive.]
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class ExpBase(Function):
|
| 36 |
+
|
| 37 |
+
unbranched = True
|
| 38 |
+
_singularities = (S.ComplexInfinity,)
|
| 39 |
+
|
| 40 |
+
@property
|
| 41 |
+
def kind(self):
|
| 42 |
+
return self.exp.kind
|
| 43 |
+
|
| 44 |
+
def inverse(self, argindex=1):
|
| 45 |
+
"""
|
| 46 |
+
Returns the inverse function of ``exp(x)``.
|
| 47 |
+
"""
|
| 48 |
+
return log
|
| 49 |
+
|
| 50 |
+
def as_numer_denom(self):
|
| 51 |
+
"""
|
| 52 |
+
Returns this with a positive exponent as a 2-tuple (a fraction).
|
| 53 |
+
|
| 54 |
+
Examples
|
| 55 |
+
========
|
| 56 |
+
|
| 57 |
+
>>> from sympy import exp
|
| 58 |
+
>>> from sympy.abc import x
|
| 59 |
+
>>> exp(-x).as_numer_denom()
|
| 60 |
+
(1, exp(x))
|
| 61 |
+
>>> exp(x).as_numer_denom()
|
| 62 |
+
(exp(x), 1)
|
| 63 |
+
"""
|
| 64 |
+
# this should be the same as Pow.as_numer_denom wrt
|
| 65 |
+
# exponent handling
|
| 66 |
+
if not self.is_commutative:
|
| 67 |
+
return self, S.One
|
| 68 |
+
exp = self.exp
|
| 69 |
+
neg_exp = exp.is_negative
|
| 70 |
+
if not neg_exp and not (-exp).is_negative:
|
| 71 |
+
neg_exp = exp.could_extract_minus_sign()
|
| 72 |
+
if neg_exp:
|
| 73 |
+
return S.One, self.func(-exp)
|
| 74 |
+
return self, S.One
|
| 75 |
+
|
| 76 |
+
@property
|
| 77 |
+
def exp(self):
|
| 78 |
+
"""
|
| 79 |
+
Returns the exponent of the function.
|
| 80 |
+
"""
|
| 81 |
+
return self.args[0]
|
| 82 |
+
|
| 83 |
+
def as_base_exp(self):
|
| 84 |
+
"""
|
| 85 |
+
Returns the 2-tuple (base, exponent).
|
| 86 |
+
"""
|
| 87 |
+
return self.func(1), Mul(*self.args)
|
| 88 |
+
|
| 89 |
+
def _eval_adjoint(self):
|
| 90 |
+
return self.func(self.exp.adjoint())
|
| 91 |
+
|
| 92 |
+
def _eval_conjugate(self):
|
| 93 |
+
return self.func(self.exp.conjugate())
|
| 94 |
+
|
| 95 |
+
def _eval_transpose(self):
|
| 96 |
+
return self.func(self.exp.transpose())
|
| 97 |
+
|
| 98 |
+
def _eval_is_finite(self):
|
| 99 |
+
arg = self.exp
|
| 100 |
+
if arg.is_infinite:
|
| 101 |
+
if arg.is_extended_negative:
|
| 102 |
+
return True
|
| 103 |
+
if arg.is_extended_positive:
|
| 104 |
+
return False
|
| 105 |
+
if arg.is_finite:
|
| 106 |
+
return True
|
| 107 |
+
|
| 108 |
+
def _eval_is_rational(self):
|
| 109 |
+
s = self.func(*self.args)
|
| 110 |
+
if s.func == self.func:
|
| 111 |
+
z = s.exp.is_zero
|
| 112 |
+
if z:
|
| 113 |
+
return True
|
| 114 |
+
elif s.exp.is_rational and fuzzy_not(z):
|
| 115 |
+
return False
|
| 116 |
+
else:
|
| 117 |
+
return s.is_rational
|
| 118 |
+
|
| 119 |
+
def _eval_is_zero(self):
|
| 120 |
+
return self.exp is S.NegativeInfinity
|
| 121 |
+
|
| 122 |
+
def _eval_power(self, other):
|
| 123 |
+
"""exp(arg)**e -> exp(arg*e) if assumptions allow it.
|
| 124 |
+
"""
|
| 125 |
+
b, e = self.as_base_exp()
|
| 126 |
+
return Pow._eval_power(Pow(b, e, evaluate=False), other)
|
| 127 |
+
|
| 128 |
+
def _eval_expand_power_exp(self, **hints):
|
| 129 |
+
from sympy.concrete.products import Product
|
| 130 |
+
from sympy.concrete.summations import Sum
|
| 131 |
+
arg = self.args[0]
|
| 132 |
+
if arg.is_Add and arg.is_commutative:
|
| 133 |
+
return Mul.fromiter(self.func(x) for x in arg.args)
|
| 134 |
+
elif isinstance(arg, Sum) and arg.is_commutative:
|
| 135 |
+
return Product(self.func(arg.function), *arg.limits)
|
| 136 |
+
return self.func(arg)
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
class exp_polar(ExpBase):
|
| 140 |
+
r"""
|
| 141 |
+
Represent a *polar number* (see g-function Sphinx documentation).
|
| 142 |
+
|
| 143 |
+
Explanation
|
| 144 |
+
===========
|
| 145 |
+
|
| 146 |
+
``exp_polar`` represents the function
|
| 147 |
+
`Exp: \mathbb{C} \rightarrow \mathcal{S}`, sending the complex number
|
| 148 |
+
`z = a + bi` to the polar number `r = exp(a), \theta = b`. It is one of
|
| 149 |
+
the main functions to construct polar numbers.
|
| 150 |
+
|
| 151 |
+
Examples
|
| 152 |
+
========
|
| 153 |
+
|
| 154 |
+
>>> from sympy import exp_polar, pi, I, exp
|
| 155 |
+
|
| 156 |
+
The main difference is that polar numbers do not "wrap around" at `2 \pi`:
|
| 157 |
+
|
| 158 |
+
>>> exp(2*pi*I)
|
| 159 |
+
1
|
| 160 |
+
>>> exp_polar(2*pi*I)
|
| 161 |
+
exp_polar(2*I*pi)
|
| 162 |
+
|
| 163 |
+
apart from that they behave mostly like classical complex numbers:
|
| 164 |
+
|
| 165 |
+
>>> exp_polar(2)*exp_polar(3)
|
| 166 |
+
exp_polar(5)
|
| 167 |
+
|
| 168 |
+
See Also
|
| 169 |
+
========
|
| 170 |
+
|
| 171 |
+
sympy.simplify.powsimp.powsimp
|
| 172 |
+
polar_lift
|
| 173 |
+
periodic_argument
|
| 174 |
+
principal_branch
|
| 175 |
+
"""
|
| 176 |
+
|
| 177 |
+
is_polar = True
|
| 178 |
+
is_comparable = False # cannot be evalf'd
|
| 179 |
+
|
| 180 |
+
def _eval_Abs(self): # Abs is never a polar number
|
| 181 |
+
return exp(re(self.args[0]))
|
| 182 |
+
|
| 183 |
+
def _eval_evalf(self, prec):
|
| 184 |
+
""" Careful! any evalf of polar numbers is flaky """
|
| 185 |
+
i = im(self.args[0])
|
| 186 |
+
try:
|
| 187 |
+
bad = (i <= -pi or i > pi)
|
| 188 |
+
except TypeError:
|
| 189 |
+
bad = True
|
| 190 |
+
if bad:
|
| 191 |
+
return self # cannot evalf for this argument
|
| 192 |
+
res = exp(self.args[0])._eval_evalf(prec)
|
| 193 |
+
if i > 0 and im(res) < 0:
|
| 194 |
+
# i ~ pi, but exp(I*i) evaluated to argument slightly bigger than pi
|
| 195 |
+
return re(res)
|
| 196 |
+
return res
|
| 197 |
+
|
| 198 |
+
def _eval_power(self, other):
|
| 199 |
+
return self.func(self.args[0]*other)
|
| 200 |
+
|
| 201 |
+
def _eval_is_extended_real(self):
|
| 202 |
+
if self.args[0].is_extended_real:
|
| 203 |
+
return True
|
| 204 |
+
|
| 205 |
+
def as_base_exp(self):
|
| 206 |
+
# XXX exp_polar(0) is special!
|
| 207 |
+
if self.args[0] == 0:
|
| 208 |
+
return self, S.One
|
| 209 |
+
return ExpBase.as_base_exp(self)
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
class ExpMeta(FunctionClass):
|
| 213 |
+
def __instancecheck__(cls, instance):
|
| 214 |
+
if exp in instance.__class__.__mro__:
|
| 215 |
+
return True
|
| 216 |
+
return isinstance(instance, Pow) and instance.base is S.Exp1
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
class exp(ExpBase, metaclass=ExpMeta):
|
| 220 |
+
"""
|
| 221 |
+
The exponential function, :math:`e^x`.
|
| 222 |
+
|
| 223 |
+
Examples
|
| 224 |
+
========
|
| 225 |
+
|
| 226 |
+
>>> from sympy import exp, I, pi
|
| 227 |
+
>>> from sympy.abc import x
|
| 228 |
+
>>> exp(x)
|
| 229 |
+
exp(x)
|
| 230 |
+
>>> exp(x).diff(x)
|
| 231 |
+
exp(x)
|
| 232 |
+
>>> exp(I*pi)
|
| 233 |
+
-1
|
| 234 |
+
|
| 235 |
+
Parameters
|
| 236 |
+
==========
|
| 237 |
+
|
| 238 |
+
arg : Expr
|
| 239 |
+
|
| 240 |
+
See Also
|
| 241 |
+
========
|
| 242 |
+
|
| 243 |
+
log
|
| 244 |
+
"""
|
| 245 |
+
|
| 246 |
+
def fdiff(self, argindex=1):
|
| 247 |
+
"""
|
| 248 |
+
Returns the first derivative of this function.
|
| 249 |
+
"""
|
| 250 |
+
if argindex == 1:
|
| 251 |
+
return self
|
| 252 |
+
else:
|
| 253 |
+
raise ArgumentIndexError(self, argindex)
|
| 254 |
+
|
| 255 |
+
def _eval_refine(self, assumptions):
|
| 256 |
+
from sympy.assumptions import ask, Q
|
| 257 |
+
arg = self.args[0]
|
| 258 |
+
if arg.is_Mul:
|
| 259 |
+
Ioo = I*S.Infinity
|
| 260 |
+
if arg in [Ioo, -Ioo]:
|
| 261 |
+
return S.NaN
|
| 262 |
+
|
| 263 |
+
coeff = arg.as_coefficient(pi*I)
|
| 264 |
+
if coeff:
|
| 265 |
+
if ask(Q.integer(2*coeff)):
|
| 266 |
+
if ask(Q.even(coeff)):
|
| 267 |
+
return S.One
|
| 268 |
+
elif ask(Q.odd(coeff)):
|
| 269 |
+
return S.NegativeOne
|
| 270 |
+
elif ask(Q.even(coeff + S.Half)):
|
| 271 |
+
return -I
|
| 272 |
+
elif ask(Q.odd(coeff + S.Half)):
|
| 273 |
+
return I
|
| 274 |
+
|
| 275 |
+
@classmethod
|
| 276 |
+
def eval(cls, arg):
|
| 277 |
+
from sympy.calculus import AccumBounds
|
| 278 |
+
from sympy.matrices.matrixbase import MatrixBase
|
| 279 |
+
from sympy.sets.setexpr import SetExpr
|
| 280 |
+
from sympy.simplify.simplify import logcombine
|
| 281 |
+
if isinstance(arg, MatrixBase):
|
| 282 |
+
return arg.exp()
|
| 283 |
+
elif global_parameters.exp_is_pow:
|
| 284 |
+
return Pow(S.Exp1, arg)
|
| 285 |
+
elif arg.is_Number:
|
| 286 |
+
if arg is S.NaN:
|
| 287 |
+
return S.NaN
|
| 288 |
+
elif arg.is_zero:
|
| 289 |
+
return S.One
|
| 290 |
+
elif arg is S.One:
|
| 291 |
+
return S.Exp1
|
| 292 |
+
elif arg is S.Infinity:
|
| 293 |
+
return S.Infinity
|
| 294 |
+
elif arg is S.NegativeInfinity:
|
| 295 |
+
return S.Zero
|
| 296 |
+
elif arg is S.ComplexInfinity:
|
| 297 |
+
return S.NaN
|
| 298 |
+
elif isinstance(arg, log):
|
| 299 |
+
return arg.args[0]
|
| 300 |
+
elif isinstance(arg, AccumBounds):
|
| 301 |
+
return AccumBounds(exp(arg.min), exp(arg.max))
|
| 302 |
+
elif isinstance(arg, SetExpr):
|
| 303 |
+
return arg._eval_func(cls)
|
| 304 |
+
elif arg.is_Mul:
|
| 305 |
+
coeff = arg.as_coefficient(pi*I)
|
| 306 |
+
if coeff:
|
| 307 |
+
if (2*coeff).is_integer:
|
| 308 |
+
if coeff.is_even:
|
| 309 |
+
return S.One
|
| 310 |
+
elif coeff.is_odd:
|
| 311 |
+
return S.NegativeOne
|
| 312 |
+
elif (coeff + S.Half).is_even:
|
| 313 |
+
return -I
|
| 314 |
+
elif (coeff + S.Half).is_odd:
|
| 315 |
+
return I
|
| 316 |
+
elif coeff.is_Rational:
|
| 317 |
+
ncoeff = coeff % 2 # restrict to [0, 2pi)
|
| 318 |
+
if ncoeff > 1: # restrict to (-pi, pi]
|
| 319 |
+
ncoeff -= 2
|
| 320 |
+
if ncoeff != coeff:
|
| 321 |
+
return cls(ncoeff*pi*I)
|
| 322 |
+
|
| 323 |
+
# Warning: code in risch.py will be very sensitive to changes
|
| 324 |
+
# in this (see DifferentialExtension).
|
| 325 |
+
|
| 326 |
+
# look for a single log factor
|
| 327 |
+
|
| 328 |
+
coeff, terms = arg.as_coeff_Mul()
|
| 329 |
+
|
| 330 |
+
# but it can't be multiplied by oo
|
| 331 |
+
if coeff in [S.NegativeInfinity, S.Infinity]:
|
| 332 |
+
if terms.is_number:
|
| 333 |
+
if coeff is S.NegativeInfinity:
|
| 334 |
+
terms = -terms
|
| 335 |
+
if re(terms).is_zero and terms is not S.Zero:
|
| 336 |
+
return S.NaN
|
| 337 |
+
if re(terms).is_positive and im(terms) is not S.Zero:
|
| 338 |
+
return S.ComplexInfinity
|
| 339 |
+
if re(terms).is_negative:
|
| 340 |
+
return S.Zero
|
| 341 |
+
return None
|
| 342 |
+
|
| 343 |
+
coeffs, log_term = [coeff], None
|
| 344 |
+
for term in Mul.make_args(terms):
|
| 345 |
+
term_ = logcombine(term)
|
| 346 |
+
if isinstance(term_, log):
|
| 347 |
+
if log_term is None:
|
| 348 |
+
log_term = term_.args[0]
|
| 349 |
+
else:
|
| 350 |
+
return None
|
| 351 |
+
elif term.is_comparable:
|
| 352 |
+
coeffs.append(term)
|
| 353 |
+
else:
|
| 354 |
+
return None
|
| 355 |
+
|
| 356 |
+
return log_term**Mul(*coeffs) if log_term else None
|
| 357 |
+
|
| 358 |
+
elif arg.is_Add:
|
| 359 |
+
out = []
|
| 360 |
+
add = []
|
| 361 |
+
argchanged = False
|
| 362 |
+
for a in arg.args:
|
| 363 |
+
if a is S.One:
|
| 364 |
+
add.append(a)
|
| 365 |
+
continue
|
| 366 |
+
newa = cls(a)
|
| 367 |
+
if isinstance(newa, cls):
|
| 368 |
+
if newa.args[0] != a:
|
| 369 |
+
add.append(newa.args[0])
|
| 370 |
+
argchanged = True
|
| 371 |
+
else:
|
| 372 |
+
add.append(a)
|
| 373 |
+
else:
|
| 374 |
+
out.append(newa)
|
| 375 |
+
if out or argchanged:
|
| 376 |
+
return Mul(*out)*cls(Add(*add), evaluate=False)
|
| 377 |
+
|
| 378 |
+
if arg.is_zero:
|
| 379 |
+
return S.One
|
| 380 |
+
|
| 381 |
+
@property
|
| 382 |
+
def base(self):
|
| 383 |
+
"""
|
| 384 |
+
Returns the base of the exponential function.
|
| 385 |
+
"""
|
| 386 |
+
return S.Exp1
|
| 387 |
+
|
| 388 |
+
@staticmethod
|
| 389 |
+
@cacheit
|
| 390 |
+
def taylor_term(n, x, *previous_terms):
|
| 391 |
+
"""
|
| 392 |
+
Calculates the next term in the Taylor series expansion.
|
| 393 |
+
"""
|
| 394 |
+
if n < 0:
|
| 395 |
+
return S.Zero
|
| 396 |
+
if n == 0:
|
| 397 |
+
return S.One
|
| 398 |
+
x = sympify(x)
|
| 399 |
+
if previous_terms:
|
| 400 |
+
p = previous_terms[-1]
|
| 401 |
+
if p is not None:
|
| 402 |
+
return p * x / n
|
| 403 |
+
return x**n/factorial(n)
|
| 404 |
+
|
| 405 |
+
def as_real_imag(self, deep=True, **hints):
|
| 406 |
+
"""
|
| 407 |
+
Returns this function as a 2-tuple representing a complex number.
|
| 408 |
+
|
| 409 |
+
Examples
|
| 410 |
+
========
|
| 411 |
+
|
| 412 |
+
>>> from sympy import exp, I
|
| 413 |
+
>>> from sympy.abc import x
|
| 414 |
+
>>> exp(x).as_real_imag()
|
| 415 |
+
(exp(re(x))*cos(im(x)), exp(re(x))*sin(im(x)))
|
| 416 |
+
>>> exp(1).as_real_imag()
|
| 417 |
+
(E, 0)
|
| 418 |
+
>>> exp(I).as_real_imag()
|
| 419 |
+
(cos(1), sin(1))
|
| 420 |
+
>>> exp(1+I).as_real_imag()
|
| 421 |
+
(E*cos(1), E*sin(1))
|
| 422 |
+
|
| 423 |
+
See Also
|
| 424 |
+
========
|
| 425 |
+
|
| 426 |
+
sympy.functions.elementary.complexes.re
|
| 427 |
+
sympy.functions.elementary.complexes.im
|
| 428 |
+
"""
|
| 429 |
+
from sympy.functions.elementary.trigonometric import cos, sin
|
| 430 |
+
re, im = self.args[0].as_real_imag()
|
| 431 |
+
if deep:
|
| 432 |
+
re = re.expand(deep, **hints)
|
| 433 |
+
im = im.expand(deep, **hints)
|
| 434 |
+
cos, sin = cos(im), sin(im)
|
| 435 |
+
return (exp(re)*cos, exp(re)*sin)
|
| 436 |
+
|
| 437 |
+
def _eval_subs(self, old, new):
|
| 438 |
+
# keep processing of power-like args centralized in Pow
|
| 439 |
+
if old.is_Pow: # handle (exp(3*log(x))).subs(x**2, z) -> z**(3/2)
|
| 440 |
+
old = exp(old.exp*log(old.base))
|
| 441 |
+
elif old is S.Exp1 and new.is_Function:
|
| 442 |
+
old = exp
|
| 443 |
+
if isinstance(old, exp) or old is S.Exp1:
|
| 444 |
+
f = lambda a: Pow(*a.as_base_exp(), evaluate=False) if (
|
| 445 |
+
a.is_Pow or isinstance(a, exp)) else a
|
| 446 |
+
return Pow._eval_subs(f(self), f(old), new)
|
| 447 |
+
|
| 448 |
+
if old is exp and not new.is_Function:
|
| 449 |
+
return new**self.exp._subs(old, new)
|
| 450 |
+
return Function._eval_subs(self, old, new)
|
| 451 |
+
|
| 452 |
+
def _eval_is_extended_real(self):
|
| 453 |
+
if self.args[0].is_extended_real:
|
| 454 |
+
return True
|
| 455 |
+
elif self.args[0].is_imaginary:
|
| 456 |
+
arg2 = -S(2) * I * self.args[0] / pi
|
| 457 |
+
return arg2.is_even
|
| 458 |
+
|
| 459 |
+
def _eval_is_complex(self):
|
| 460 |
+
def complex_extended_negative(arg):
|
| 461 |
+
yield arg.is_complex
|
| 462 |
+
yield arg.is_extended_negative
|
| 463 |
+
return fuzzy_or(complex_extended_negative(self.args[0]))
|
| 464 |
+
|
| 465 |
+
def _eval_is_algebraic(self):
|
| 466 |
+
if (self.exp / pi / I).is_rational:
|
| 467 |
+
return True
|
| 468 |
+
if fuzzy_not(self.exp.is_zero):
|
| 469 |
+
if self.exp.is_algebraic:
|
| 470 |
+
return False
|
| 471 |
+
elif (self.exp / pi).is_rational:
|
| 472 |
+
return False
|
| 473 |
+
|
| 474 |
+
def _eval_is_extended_positive(self):
|
| 475 |
+
if self.exp.is_extended_real:
|
| 476 |
+
return self.args[0] is not S.NegativeInfinity
|
| 477 |
+
elif self.exp.is_imaginary:
|
| 478 |
+
arg2 = -I * self.args[0] / pi
|
| 479 |
+
return arg2.is_even
|
| 480 |
+
|
| 481 |
+
def _eval_nseries(self, x, n, logx, cdir=0):
|
| 482 |
+
# NOTE Please see the comment at the beginning of this file, labelled
|
| 483 |
+
# IMPORTANT.
|
| 484 |
+
from sympy.functions.elementary.complexes import sign
|
| 485 |
+
from sympy.functions.elementary.integers import ceiling
|
| 486 |
+
from sympy.series.limits import limit
|
| 487 |
+
from sympy.series.order import Order
|
| 488 |
+
from sympy.simplify.powsimp import powsimp
|
| 489 |
+
arg = self.exp
|
| 490 |
+
arg_series = arg._eval_nseries(x, n=n, logx=logx)
|
| 491 |
+
if arg_series.is_Order:
|
| 492 |
+
return 1 + arg_series
|
| 493 |
+
arg0 = limit(arg_series.removeO(), x, 0)
|
| 494 |
+
if arg0 is S.NegativeInfinity:
|
| 495 |
+
return Order(x**n, x)
|
| 496 |
+
if arg0 is S.Infinity:
|
| 497 |
+
return self
|
| 498 |
+
if arg0.is_infinite:
|
| 499 |
+
raise PoleError("Cannot expand %s around 0" % (self))
|
| 500 |
+
# checking for indecisiveness/ sign terms in arg0
|
| 501 |
+
if any(isinstance(arg, sign) for arg in arg0.args):
|
| 502 |
+
return self
|
| 503 |
+
t = Dummy("t")
|
| 504 |
+
nterms = n
|
| 505 |
+
try:
|
| 506 |
+
cf = Order(arg.as_leading_term(x, logx=logx), x).getn()
|
| 507 |
+
except (NotImplementedError, PoleError):
|
| 508 |
+
cf = 0
|
| 509 |
+
if cf and cf > 0:
|
| 510 |
+
nterms = ceiling(n/cf)
|
| 511 |
+
exp_series = exp(t)._taylor(t, nterms)
|
| 512 |
+
r = exp(arg0)*exp_series.subs(t, arg_series - arg0)
|
| 513 |
+
rep = {logx: log(x)} if logx is not None else {}
|
| 514 |
+
if r.subs(rep) == self:
|
| 515 |
+
return r
|
| 516 |
+
if cf and cf > 1:
|
| 517 |
+
r += Order((arg_series - arg0)**n, x)/x**((cf-1)*n)
|
| 518 |
+
else:
|
| 519 |
+
r += Order((arg_series - arg0)**n, x)
|
| 520 |
+
r = r.expand()
|
| 521 |
+
r = powsimp(r, deep=True, combine='exp')
|
| 522 |
+
# powsimp may introduce unexpanded (-1)**Rational; see PR #17201
|
| 523 |
+
simplerat = lambda x: x.is_Rational and x.q in [3, 4, 6]
|
| 524 |
+
w = Wild('w', properties=[simplerat])
|
| 525 |
+
r = r.replace(S.NegativeOne**w, expand_complex(S.NegativeOne**w))
|
| 526 |
+
return r
|
| 527 |
+
|
| 528 |
+
def _taylor(self, x, n):
|
| 529 |
+
l = []
|
| 530 |
+
g = None
|
| 531 |
+
for i in range(n):
|
| 532 |
+
g = self.taylor_term(i, self.args[0], g)
|
| 533 |
+
g = g.nseries(x, n=n)
|
| 534 |
+
l.append(g.removeO())
|
| 535 |
+
return Add(*l)
|
| 536 |
+
|
| 537 |
+
def _eval_as_leading_term(self, x, logx=None, cdir=0):
|
| 538 |
+
from sympy.calculus.util import AccumBounds
|
| 539 |
+
arg = self.args[0].cancel().as_leading_term(x, logx=logx)
|
| 540 |
+
arg0 = arg.subs(x, 0)
|
| 541 |
+
if arg is S.NaN:
|
| 542 |
+
return S.NaN
|
| 543 |
+
if isinstance(arg0, AccumBounds):
|
| 544 |
+
# This check addresses a corner case involving AccumBounds.
|
| 545 |
+
# if isinstance(arg, AccumBounds) is True, then arg0 can either be 0,
|
| 546 |
+
# AccumBounds(-oo, 0) or AccumBounds(-oo, oo).
|
| 547 |
+
# Check out function: test_issue_18473() in test_exponential.py and
|
| 548 |
+
# test_limits.py for more information.
|
| 549 |
+
if re(cdir) < S.Zero:
|
| 550 |
+
return exp(-arg0)
|
| 551 |
+
return exp(arg0)
|
| 552 |
+
if arg0 is S.NaN:
|
| 553 |
+
arg0 = arg.limit(x, 0)
|
| 554 |
+
if arg0.is_infinite is False:
|
| 555 |
+
return exp(arg0)
|
| 556 |
+
raise PoleError("Cannot expand %s around 0" % (self))
|
| 557 |
+
|
| 558 |
+
def _eval_rewrite_as_sin(self, arg, **kwargs):
|
| 559 |
+
from sympy.functions.elementary.trigonometric import sin
|
| 560 |
+
return sin(I*arg + pi/2) - I*sin(I*arg)
|
| 561 |
+
|
| 562 |
+
def _eval_rewrite_as_cos(self, arg, **kwargs):
|
| 563 |
+
from sympy.functions.elementary.trigonometric import cos
|
| 564 |
+
return cos(I*arg) + I*cos(I*arg + pi/2)
|
| 565 |
+
|
| 566 |
+
def _eval_rewrite_as_tanh(self, arg, **kwargs):
|
| 567 |
+
from sympy.functions.elementary.hyperbolic import tanh
|
| 568 |
+
return (1 + tanh(arg/2))/(1 - tanh(arg/2))
|
| 569 |
+
|
| 570 |
+
def _eval_rewrite_as_sqrt(self, arg, **kwargs):
|
| 571 |
+
from sympy.functions.elementary.trigonometric import sin, cos
|
| 572 |
+
if arg.is_Mul:
|
| 573 |
+
coeff = arg.coeff(pi*I)
|
| 574 |
+
if coeff and coeff.is_number:
|
| 575 |
+
cosine, sine = cos(pi*coeff), sin(pi*coeff)
|
| 576 |
+
if not isinstance(cosine, cos) and not isinstance (sine, sin):
|
| 577 |
+
return cosine + I*sine
|
| 578 |
+
|
| 579 |
+
def _eval_rewrite_as_Pow(self, arg, **kwargs):
|
| 580 |
+
if arg.is_Mul:
|
| 581 |
+
logs = [a for a in arg.args if isinstance(a, log) and len(a.args) == 1]
|
| 582 |
+
if logs:
|
| 583 |
+
return Pow(logs[0].args[0], arg.coeff(logs[0]))
|
| 584 |
+
|
| 585 |
+
|
| 586 |
+
def match_real_imag(expr):
|
| 587 |
+
r"""
|
| 588 |
+
Try to match expr with $a + Ib$ for real $a$ and $b$.
|
| 589 |
+
|
| 590 |
+
``match_real_imag`` returns a tuple containing the real and imaginary
|
| 591 |
+
parts of expr or ``(None, None)`` if direct matching is not possible. Contrary
|
| 592 |
+
to :func:`~.re`, :func:`~.im``, and ``as_real_imag()``, this helper will not force things
|
| 593 |
+
by returning expressions themselves containing ``re()`` or ``im()`` and it
|
| 594 |
+
does not expand its argument either.
|
| 595 |
+
|
| 596 |
+
"""
|
| 597 |
+
r_, i_ = expr.as_independent(I, as_Add=True)
|
| 598 |
+
if i_ == 0 and r_.is_real:
|
| 599 |
+
return (r_, i_)
|
| 600 |
+
i_ = i_.as_coefficient(I)
|
| 601 |
+
if i_ and i_.is_real and r_.is_real:
|
| 602 |
+
return (r_, i_)
|
| 603 |
+
else:
|
| 604 |
+
return (None, None) # simpler to check for than None
|
| 605 |
+
|
| 606 |
+
|
| 607 |
+
class log(Function):
|
| 608 |
+
r"""
|
| 609 |
+
The natural logarithm function `\ln(x)` or `\log(x)`.
|
| 610 |
+
|
| 611 |
+
Explanation
|
| 612 |
+
===========
|
| 613 |
+
|
| 614 |
+
Logarithms are taken with the natural base, `e`. To get
|
| 615 |
+
a logarithm of a different base ``b``, use ``log(x, b)``,
|
| 616 |
+
which is essentially short-hand for ``log(x)/log(b)``.
|
| 617 |
+
|
| 618 |
+
``log`` represents the principal branch of the natural
|
| 619 |
+
logarithm. As such it has a branch cut along the negative
|
| 620 |
+
real axis and returns values having a complex argument in
|
| 621 |
+
`(-\pi, \pi]`.
|
| 622 |
+
|
| 623 |
+
Examples
|
| 624 |
+
========
|
| 625 |
+
|
| 626 |
+
>>> from sympy import log, sqrt, S, I
|
| 627 |
+
>>> log(8, 2)
|
| 628 |
+
3
|
| 629 |
+
>>> log(S(8)/3, 2)
|
| 630 |
+
-log(3)/log(2) + 3
|
| 631 |
+
>>> log(-1 + I*sqrt(3))
|
| 632 |
+
log(2) + 2*I*pi/3
|
| 633 |
+
|
| 634 |
+
See Also
|
| 635 |
+
========
|
| 636 |
+
|
| 637 |
+
exp
|
| 638 |
+
|
| 639 |
+
"""
|
| 640 |
+
|
| 641 |
+
args: tTuple[Expr]
|
| 642 |
+
|
| 643 |
+
_singularities = (S.Zero, S.ComplexInfinity)
|
| 644 |
+
|
| 645 |
+
def fdiff(self, argindex=1):
|
| 646 |
+
"""
|
| 647 |
+
Returns the first derivative of the function.
|
| 648 |
+
"""
|
| 649 |
+
if argindex == 1:
|
| 650 |
+
return 1/self.args[0]
|
| 651 |
+
else:
|
| 652 |
+
raise ArgumentIndexError(self, argindex)
|
| 653 |
+
|
| 654 |
+
def inverse(self, argindex=1):
|
| 655 |
+
r"""
|
| 656 |
+
Returns `e^x`, the inverse function of `\log(x)`.
|
| 657 |
+
"""
|
| 658 |
+
return exp
|
| 659 |
+
|
| 660 |
+
@classmethod
|
| 661 |
+
def eval(cls, arg, base=None):
|
| 662 |
+
from sympy.calculus import AccumBounds
|
| 663 |
+
from sympy.sets.setexpr import SetExpr
|
| 664 |
+
|
| 665 |
+
arg = sympify(arg)
|
| 666 |
+
|
| 667 |
+
if base is not None:
|
| 668 |
+
base = sympify(base)
|
| 669 |
+
if base == 1:
|
| 670 |
+
if arg == 1:
|
| 671 |
+
return S.NaN
|
| 672 |
+
else:
|
| 673 |
+
return S.ComplexInfinity
|
| 674 |
+
try:
|
| 675 |
+
# handle extraction of powers of the base now
|
| 676 |
+
# or else expand_log in Mul would have to handle this
|
| 677 |
+
n = multiplicity(base, arg)
|
| 678 |
+
if n:
|
| 679 |
+
return n + log(arg / base**n) / log(base)
|
| 680 |
+
else:
|
| 681 |
+
return log(arg)/log(base)
|
| 682 |
+
except ValueError:
|
| 683 |
+
pass
|
| 684 |
+
if base is not S.Exp1:
|
| 685 |
+
return cls(arg)/cls(base)
|
| 686 |
+
else:
|
| 687 |
+
return cls(arg)
|
| 688 |
+
|
| 689 |
+
if arg.is_Number:
|
| 690 |
+
if arg.is_zero:
|
| 691 |
+
return S.ComplexInfinity
|
| 692 |
+
elif arg is S.One:
|
| 693 |
+
return S.Zero
|
| 694 |
+
elif arg is S.Infinity:
|
| 695 |
+
return S.Infinity
|
| 696 |
+
elif arg is S.NegativeInfinity:
|
| 697 |
+
return S.Infinity
|
| 698 |
+
elif arg is S.NaN:
|
| 699 |
+
return S.NaN
|
| 700 |
+
elif arg.is_Rational and arg.p == 1:
|
| 701 |
+
return -cls(arg.q)
|
| 702 |
+
|
| 703 |
+
if arg.is_Pow and arg.base is S.Exp1 and arg.exp.is_extended_real:
|
| 704 |
+
return arg.exp
|
| 705 |
+
if isinstance(arg, exp) and arg.exp.is_extended_real:
|
| 706 |
+
return arg.exp
|
| 707 |
+
elif isinstance(arg, exp) and arg.exp.is_number:
|
| 708 |
+
r_, i_ = match_real_imag(arg.exp)
|
| 709 |
+
if i_ and i_.is_comparable:
|
| 710 |
+
i_ %= 2*pi
|
| 711 |
+
if i_ > pi:
|
| 712 |
+
i_ -= 2*pi
|
| 713 |
+
return r_ + expand_mul(i_ * I, deep=False)
|
| 714 |
+
elif isinstance(arg, exp_polar):
|
| 715 |
+
return unpolarify(arg.exp)
|
| 716 |
+
elif isinstance(arg, AccumBounds):
|
| 717 |
+
if arg.min.is_positive:
|
| 718 |
+
return AccumBounds(log(arg.min), log(arg.max))
|
| 719 |
+
elif arg.min.is_zero:
|
| 720 |
+
return AccumBounds(S.NegativeInfinity, log(arg.max))
|
| 721 |
+
else:
|
| 722 |
+
return S.NaN
|
| 723 |
+
elif isinstance(arg, SetExpr):
|
| 724 |
+
return arg._eval_func(cls)
|
| 725 |
+
|
| 726 |
+
if arg.is_number:
|
| 727 |
+
if arg.is_negative:
|
| 728 |
+
return pi * I + cls(-arg)
|
| 729 |
+
elif arg is S.ComplexInfinity:
|
| 730 |
+
return S.ComplexInfinity
|
| 731 |
+
elif arg is S.Exp1:
|
| 732 |
+
return S.One
|
| 733 |
+
|
| 734 |
+
if arg.is_zero:
|
| 735 |
+
return S.ComplexInfinity
|
| 736 |
+
|
| 737 |
+
# don't autoexpand Pow or Mul (see the issue 3351):
|
| 738 |
+
if not arg.is_Add:
|
| 739 |
+
coeff = arg.as_coefficient(I)
|
| 740 |
+
|
| 741 |
+
if coeff is not None:
|
| 742 |
+
if coeff is S.Infinity:
|
| 743 |
+
return S.Infinity
|
| 744 |
+
elif coeff is S.NegativeInfinity:
|
| 745 |
+
return S.Infinity
|
| 746 |
+
elif coeff.is_Rational:
|
| 747 |
+
if coeff.is_nonnegative:
|
| 748 |
+
return pi * I * S.Half + cls(coeff)
|
| 749 |
+
else:
|
| 750 |
+
return -pi * I * S.Half + cls(-coeff)
|
| 751 |
+
|
| 752 |
+
if arg.is_number and arg.is_algebraic:
|
| 753 |
+
# Match arg = coeff*(r_ + i_*I) with coeff>0, r_ and i_ real.
|
| 754 |
+
coeff, arg_ = arg.as_independent(I, as_Add=False)
|
| 755 |
+
if coeff.is_negative:
|
| 756 |
+
coeff *= -1
|
| 757 |
+
arg_ *= -1
|
| 758 |
+
arg_ = expand_mul(arg_, deep=False)
|
| 759 |
+
r_, i_ = arg_.as_independent(I, as_Add=True)
|
| 760 |
+
i_ = i_.as_coefficient(I)
|
| 761 |
+
if coeff.is_real and i_ and i_.is_real and r_.is_real:
|
| 762 |
+
if r_.is_zero:
|
| 763 |
+
if i_.is_positive:
|
| 764 |
+
return pi * I * S.Half + cls(coeff * i_)
|
| 765 |
+
elif i_.is_negative:
|
| 766 |
+
return -pi * I * S.Half + cls(coeff * -i_)
|
| 767 |
+
else:
|
| 768 |
+
from sympy.simplify import ratsimp
|
| 769 |
+
# Check for arguments involving rational multiples of pi
|
| 770 |
+
t = (i_/r_).cancel()
|
| 771 |
+
t1 = (-t).cancel()
|
| 772 |
+
atan_table = _log_atan_table()
|
| 773 |
+
if t in atan_table:
|
| 774 |
+
modulus = ratsimp(coeff * Abs(arg_))
|
| 775 |
+
if r_.is_positive:
|
| 776 |
+
return cls(modulus) + I * atan_table[t]
|
| 777 |
+
else:
|
| 778 |
+
return cls(modulus) + I * (atan_table[t] - pi)
|
| 779 |
+
elif t1 in atan_table:
|
| 780 |
+
modulus = ratsimp(coeff * Abs(arg_))
|
| 781 |
+
if r_.is_positive:
|
| 782 |
+
return cls(modulus) + I * (-atan_table[t1])
|
| 783 |
+
else:
|
| 784 |
+
return cls(modulus) + I * (pi - atan_table[t1])
|
| 785 |
+
|
| 786 |
+
def as_base_exp(self):
|
| 787 |
+
"""
|
| 788 |
+
Returns this function in the form (base, exponent).
|
| 789 |
+
"""
|
| 790 |
+
return self, S.One
|
| 791 |
+
|
| 792 |
+
@staticmethod
|
| 793 |
+
@cacheit
|
| 794 |
+
def taylor_term(n, x, *previous_terms): # of log(1+x)
|
| 795 |
+
r"""
|
| 796 |
+
Returns the next term in the Taylor series expansion of `\log(1+x)`.
|
| 797 |
+
"""
|
| 798 |
+
from sympy.simplify.powsimp import powsimp
|
| 799 |
+
if n < 0:
|
| 800 |
+
return S.Zero
|
| 801 |
+
x = sympify(x)
|
| 802 |
+
if n == 0:
|
| 803 |
+
return x
|
| 804 |
+
if previous_terms:
|
| 805 |
+
p = previous_terms[-1]
|
| 806 |
+
if p is not None:
|
| 807 |
+
return powsimp((-n) * p * x / (n + 1), deep=True, combine='exp')
|
| 808 |
+
return (1 - 2*(n % 2)) * x**(n + 1)/(n + 1)
|
| 809 |
+
|
| 810 |
+
def _eval_expand_log(self, deep=True, **hints):
|
| 811 |
+
from sympy.concrete import Sum, Product
|
| 812 |
+
force = hints.get('force', False)
|
| 813 |
+
factor = hints.get('factor', False)
|
| 814 |
+
if (len(self.args) == 2):
|
| 815 |
+
return expand_log(self.func(*self.args), deep=deep, force=force)
|
| 816 |
+
arg = self.args[0]
|
| 817 |
+
if arg.is_Integer:
|
| 818 |
+
# remove perfect powers
|
| 819 |
+
p = perfect_power(arg)
|
| 820 |
+
logarg = None
|
| 821 |
+
coeff = 1
|
| 822 |
+
if p is not False:
|
| 823 |
+
arg, coeff = p
|
| 824 |
+
logarg = self.func(arg)
|
| 825 |
+
# expand as product of its prime factors if factor=True
|
| 826 |
+
if factor:
|
| 827 |
+
p = factorint(arg)
|
| 828 |
+
if arg not in p.keys():
|
| 829 |
+
logarg = sum(n*log(val) for val, n in p.items())
|
| 830 |
+
if logarg is not None:
|
| 831 |
+
return coeff*logarg
|
| 832 |
+
elif arg.is_Rational:
|
| 833 |
+
return log(arg.p) - log(arg.q)
|
| 834 |
+
elif arg.is_Mul:
|
| 835 |
+
expr = []
|
| 836 |
+
nonpos = []
|
| 837 |
+
for x in arg.args:
|
| 838 |
+
if force or x.is_positive or x.is_polar:
|
| 839 |
+
a = self.func(x)
|
| 840 |
+
if isinstance(a, log):
|
| 841 |
+
expr.append(self.func(x)._eval_expand_log(**hints))
|
| 842 |
+
else:
|
| 843 |
+
expr.append(a)
|
| 844 |
+
elif x.is_negative:
|
| 845 |
+
a = self.func(-x)
|
| 846 |
+
expr.append(a)
|
| 847 |
+
nonpos.append(S.NegativeOne)
|
| 848 |
+
else:
|
| 849 |
+
nonpos.append(x)
|
| 850 |
+
return Add(*expr) + log(Mul(*nonpos))
|
| 851 |
+
elif arg.is_Pow or isinstance(arg, exp):
|
| 852 |
+
if force or (arg.exp.is_extended_real and (arg.base.is_positive or ((arg.exp+1)
|
| 853 |
+
.is_positive and (arg.exp-1).is_nonpositive))) or arg.base.is_polar:
|
| 854 |
+
b = arg.base
|
| 855 |
+
e = arg.exp
|
| 856 |
+
a = self.func(b)
|
| 857 |
+
if isinstance(a, log):
|
| 858 |
+
return unpolarify(e) * a._eval_expand_log(**hints)
|
| 859 |
+
else:
|
| 860 |
+
return unpolarify(e) * a
|
| 861 |
+
elif isinstance(arg, Product):
|
| 862 |
+
if force or arg.function.is_positive:
|
| 863 |
+
return Sum(log(arg.function), *arg.limits)
|
| 864 |
+
|
| 865 |
+
return self.func(arg)
|
| 866 |
+
|
| 867 |
+
def _eval_simplify(self, **kwargs):
|
| 868 |
+
from sympy.simplify.simplify import expand_log, simplify, inversecombine
|
| 869 |
+
if len(self.args) == 2: # it's unevaluated
|
| 870 |
+
return simplify(self.func(*self.args), **kwargs)
|
| 871 |
+
|
| 872 |
+
expr = self.func(simplify(self.args[0], **kwargs))
|
| 873 |
+
if kwargs['inverse']:
|
| 874 |
+
expr = inversecombine(expr)
|
| 875 |
+
expr = expand_log(expr, deep=True)
|
| 876 |
+
return min([expr, self], key=kwargs['measure'])
|
| 877 |
+
|
| 878 |
+
def as_real_imag(self, deep=True, **hints):
|
| 879 |
+
"""
|
| 880 |
+
Returns this function as a complex coordinate.
|
| 881 |
+
|
| 882 |
+
Examples
|
| 883 |
+
========
|
| 884 |
+
|
| 885 |
+
>>> from sympy import I, log
|
| 886 |
+
>>> from sympy.abc import x
|
| 887 |
+
>>> log(x).as_real_imag()
|
| 888 |
+
(log(Abs(x)), arg(x))
|
| 889 |
+
>>> log(I).as_real_imag()
|
| 890 |
+
(0, pi/2)
|
| 891 |
+
>>> log(1 + I).as_real_imag()
|
| 892 |
+
(log(sqrt(2)), pi/4)
|
| 893 |
+
>>> log(I*x).as_real_imag()
|
| 894 |
+
(log(Abs(x)), arg(I*x))
|
| 895 |
+
|
| 896 |
+
"""
|
| 897 |
+
sarg = self.args[0]
|
| 898 |
+
if deep:
|
| 899 |
+
sarg = self.args[0].expand(deep, **hints)
|
| 900 |
+
sarg_abs = Abs(sarg)
|
| 901 |
+
if sarg_abs == sarg:
|
| 902 |
+
return self, S.Zero
|
| 903 |
+
sarg_arg = arg(sarg)
|
| 904 |
+
if hints.get('log', False): # Expand the log
|
| 905 |
+
hints['complex'] = False
|
| 906 |
+
return (log(sarg_abs).expand(deep, **hints), sarg_arg)
|
| 907 |
+
else:
|
| 908 |
+
return log(sarg_abs), sarg_arg
|
| 909 |
+
|
| 910 |
+
def _eval_is_rational(self):
|
| 911 |
+
s = self.func(*self.args)
|
| 912 |
+
if s.func == self.func:
|
| 913 |
+
if (self.args[0] - 1).is_zero:
|
| 914 |
+
return True
|
| 915 |
+
if s.args[0].is_rational and fuzzy_not((self.args[0] - 1).is_zero):
|
| 916 |
+
return False
|
| 917 |
+
else:
|
| 918 |
+
return s.is_rational
|
| 919 |
+
|
| 920 |
+
def _eval_is_algebraic(self):
|
| 921 |
+
s = self.func(*self.args)
|
| 922 |
+
if s.func == self.func:
|
| 923 |
+
if (self.args[0] - 1).is_zero:
|
| 924 |
+
return True
|
| 925 |
+
elif fuzzy_not((self.args[0] - 1).is_zero):
|
| 926 |
+
if self.args[0].is_algebraic:
|
| 927 |
+
return False
|
| 928 |
+
else:
|
| 929 |
+
return s.is_algebraic
|
| 930 |
+
|
| 931 |
+
def _eval_is_extended_real(self):
|
| 932 |
+
return self.args[0].is_extended_positive
|
| 933 |
+
|
| 934 |
+
def _eval_is_complex(self):
|
| 935 |
+
z = self.args[0]
|
| 936 |
+
return fuzzy_and([z.is_complex, fuzzy_not(z.is_zero)])
|
| 937 |
+
|
| 938 |
+
def _eval_is_finite(self):
|
| 939 |
+
arg = self.args[0]
|
| 940 |
+
if arg.is_zero:
|
| 941 |
+
return False
|
| 942 |
+
return arg.is_finite
|
| 943 |
+
|
| 944 |
+
def _eval_is_extended_positive(self):
|
| 945 |
+
return (self.args[0] - 1).is_extended_positive
|
| 946 |
+
|
| 947 |
+
def _eval_is_zero(self):
|
| 948 |
+
return (self.args[0] - 1).is_zero
|
| 949 |
+
|
| 950 |
+
def _eval_is_extended_nonnegative(self):
|
| 951 |
+
return (self.args[0] - 1).is_extended_nonnegative
|
| 952 |
+
|
| 953 |
+
def _eval_nseries(self, x, n, logx, cdir=0):
|
| 954 |
+
# NOTE Please see the comment at the beginning of this file, labelled
|
| 955 |
+
# IMPORTANT.
|
| 956 |
+
from sympy.series.order import Order
|
| 957 |
+
from sympy.simplify.simplify import logcombine
|
| 958 |
+
from sympy.core.symbol import Dummy
|
| 959 |
+
|
| 960 |
+
if self.args[0] == x:
|
| 961 |
+
return log(x) if logx is None else logx
|
| 962 |
+
arg = self.args[0]
|
| 963 |
+
t = Dummy('t', positive=True)
|
| 964 |
+
if cdir == 0:
|
| 965 |
+
cdir = 1
|
| 966 |
+
z = arg.subs(x, cdir*t)
|
| 967 |
+
|
| 968 |
+
k, l = Wild("k"), Wild("l")
|
| 969 |
+
r = z.match(k*t**l)
|
| 970 |
+
if r is not None:
|
| 971 |
+
k, l = r[k], r[l]
|
| 972 |
+
if l != 0 and not l.has(t) and not k.has(t):
|
| 973 |
+
r = l*log(x) if logx is None else l*logx
|
| 974 |
+
r += log(k) - l*log(cdir) # XXX true regardless of assumptions?
|
| 975 |
+
return r
|
| 976 |
+
|
| 977 |
+
def coeff_exp(term, x):
|
| 978 |
+
coeff, exp = S.One, S.Zero
|
| 979 |
+
for factor in Mul.make_args(term):
|
| 980 |
+
if factor.has(x):
|
| 981 |
+
base, exp = factor.as_base_exp()
|
| 982 |
+
if base != x:
|
| 983 |
+
try:
|
| 984 |
+
return term.leadterm(x)
|
| 985 |
+
except ValueError:
|
| 986 |
+
return term, S.Zero
|
| 987 |
+
else:
|
| 988 |
+
coeff *= factor
|
| 989 |
+
return coeff, exp
|
| 990 |
+
|
| 991 |
+
# TODO new and probably slow
|
| 992 |
+
try:
|
| 993 |
+
a, b = z.leadterm(t, logx=logx, cdir=1)
|
| 994 |
+
except (ValueError, NotImplementedError, PoleError):
|
| 995 |
+
s = z._eval_nseries(t, n=n, logx=logx, cdir=1)
|
| 996 |
+
while s.is_Order:
|
| 997 |
+
n += 1
|
| 998 |
+
s = z._eval_nseries(t, n=n, logx=logx, cdir=1)
|
| 999 |
+
try:
|
| 1000 |
+
a, b = s.removeO().leadterm(t, cdir=1)
|
| 1001 |
+
except ValueError:
|
| 1002 |
+
a, b = s.removeO().as_leading_term(t, cdir=1), S.Zero
|
| 1003 |
+
|
| 1004 |
+
p = (z/(a*t**b) - 1)._eval_nseries(t, n=n, logx=logx, cdir=1)
|
| 1005 |
+
if p.has(exp):
|
| 1006 |
+
p = logcombine(p)
|
| 1007 |
+
if isinstance(p, Order):
|
| 1008 |
+
n = p.getn()
|
| 1009 |
+
_, d = coeff_exp(p, t)
|
| 1010 |
+
logx = log(x) if logx is None else logx
|
| 1011 |
+
|
| 1012 |
+
if not d.is_positive:
|
| 1013 |
+
res = log(a) - b*log(cdir) + b*logx
|
| 1014 |
+
_res = res
|
| 1015 |
+
logflags = {"deep": True, "log": True, "mul": False, "power_exp": False,
|
| 1016 |
+
"power_base": False, "multinomial": False, "basic": False, "force": True,
|
| 1017 |
+
"factor": False}
|
| 1018 |
+
expr = self.expand(**logflags)
|
| 1019 |
+
if (not a.could_extract_minus_sign() and
|
| 1020 |
+
logx.could_extract_minus_sign()):
|
| 1021 |
+
_res = _res.subs(-logx, -log(x)).expand(**logflags)
|
| 1022 |
+
else:
|
| 1023 |
+
_res = _res.subs(logx, log(x)).expand(**logflags)
|
| 1024 |
+
if _res == expr:
|
| 1025 |
+
return res
|
| 1026 |
+
return res + Order(x**n, x)
|
| 1027 |
+
|
| 1028 |
+
def mul(d1, d2):
|
| 1029 |
+
res = {}
|
| 1030 |
+
for e1, e2 in product(d1, d2):
|
| 1031 |
+
ex = e1 + e2
|
| 1032 |
+
if ex < n:
|
| 1033 |
+
res[ex] = res.get(ex, S.Zero) + d1[e1]*d2[e2]
|
| 1034 |
+
return res
|
| 1035 |
+
|
| 1036 |
+
pterms = {}
|
| 1037 |
+
|
| 1038 |
+
for term in Add.make_args(p.removeO()):
|
| 1039 |
+
co1, e1 = coeff_exp(term, t)
|
| 1040 |
+
pterms[e1] = pterms.get(e1, S.Zero) + co1
|
| 1041 |
+
|
| 1042 |
+
k = S.One
|
| 1043 |
+
terms = {}
|
| 1044 |
+
pk = pterms
|
| 1045 |
+
|
| 1046 |
+
while k*d < n:
|
| 1047 |
+
coeff = -S.NegativeOne**k/k
|
| 1048 |
+
for ex in pk:
|
| 1049 |
+
_ = terms.get(ex, S.Zero) + coeff*pk[ex]
|
| 1050 |
+
terms[ex] = _.nsimplify()
|
| 1051 |
+
pk = mul(pk, pterms)
|
| 1052 |
+
k += S.One
|
| 1053 |
+
|
| 1054 |
+
res = log(a) - b*log(cdir) + b*logx
|
| 1055 |
+
for ex in terms:
|
| 1056 |
+
res += terms[ex]*t**(ex)
|
| 1057 |
+
|
| 1058 |
+
if a.is_negative and im(z) != 0:
|
| 1059 |
+
from sympy.functions.special.delta_functions import Heaviside
|
| 1060 |
+
for i, term in enumerate(z.lseries(t)):
|
| 1061 |
+
if not term.is_real or i == 5:
|
| 1062 |
+
break
|
| 1063 |
+
if i < 5:
|
| 1064 |
+
coeff, _ = term.as_coeff_exponent(t)
|
| 1065 |
+
res += -2*I*pi*Heaviside(-im(coeff), 0)
|
| 1066 |
+
|
| 1067 |
+
res = res.subs(t, x/cdir)
|
| 1068 |
+
return res + Order(x**n, x)
|
| 1069 |
+
|
| 1070 |
+
def _eval_as_leading_term(self, x, logx=None, cdir=0):
|
| 1071 |
+
# NOTE
|
| 1072 |
+
# Refer https://github.com/sympy/sympy/pull/23592 for more information
|
| 1073 |
+
# on each of the following steps involved in this method.
|
| 1074 |
+
arg0 = self.args[0].together()
|
| 1075 |
+
|
| 1076 |
+
# STEP 1
|
| 1077 |
+
t = Dummy('t', positive=True)
|
| 1078 |
+
if cdir == 0:
|
| 1079 |
+
cdir = 1
|
| 1080 |
+
z = arg0.subs(x, cdir*t)
|
| 1081 |
+
|
| 1082 |
+
# STEP 2
|
| 1083 |
+
try:
|
| 1084 |
+
c, e = z.leadterm(t, logx=logx, cdir=1)
|
| 1085 |
+
except ValueError:
|
| 1086 |
+
arg = arg0.as_leading_term(x, logx=logx, cdir=cdir)
|
| 1087 |
+
return log(arg)
|
| 1088 |
+
if c.has(t):
|
| 1089 |
+
c = c.subs(t, x/cdir)
|
| 1090 |
+
if e != 0:
|
| 1091 |
+
raise PoleError("Cannot expand %s around 0" % (self))
|
| 1092 |
+
return log(c)
|
| 1093 |
+
|
| 1094 |
+
# STEP 3
|
| 1095 |
+
if c == S.One and e == S.Zero:
|
| 1096 |
+
return (arg0 - S.One).as_leading_term(x, logx=logx)
|
| 1097 |
+
|
| 1098 |
+
# STEP 4
|
| 1099 |
+
res = log(c) - e*log(cdir)
|
| 1100 |
+
logx = log(x) if logx is None else logx
|
| 1101 |
+
res += e*logx
|
| 1102 |
+
|
| 1103 |
+
# STEP 5
|
| 1104 |
+
if c.is_negative and im(z) != 0:
|
| 1105 |
+
from sympy.functions.special.delta_functions import Heaviside
|
| 1106 |
+
for i, term in enumerate(z.lseries(t)):
|
| 1107 |
+
if not term.is_real or i == 5:
|
| 1108 |
+
break
|
| 1109 |
+
if i < 5:
|
| 1110 |
+
coeff, _ = term.as_coeff_exponent(t)
|
| 1111 |
+
res += -2*I*pi*Heaviside(-im(coeff), 0)
|
| 1112 |
+
return res
|
| 1113 |
+
|
| 1114 |
+
|
| 1115 |
+
class LambertW(Function):
|
| 1116 |
+
r"""
|
| 1117 |
+
The Lambert W function $W(z)$ is defined as the inverse
|
| 1118 |
+
function of $w \exp(w)$ [1]_.
|
| 1119 |
+
|
| 1120 |
+
Explanation
|
| 1121 |
+
===========
|
| 1122 |
+
|
| 1123 |
+
In other words, the value of $W(z)$ is such that $z = W(z) \exp(W(z))$
|
| 1124 |
+
for any complex number $z$. The Lambert W function is a multivalued
|
| 1125 |
+
function with infinitely many branches $W_k(z)$, indexed by
|
| 1126 |
+
$k \in \mathbb{Z}$. Each branch gives a different solution $w$
|
| 1127 |
+
of the equation $z = w \exp(w)$.
|
| 1128 |
+
|
| 1129 |
+
The Lambert W function has two partially real branches: the
|
| 1130 |
+
principal branch ($k = 0$) is real for real $z > -1/e$, and the
|
| 1131 |
+
$k = -1$ branch is real for $-1/e < z < 0$. All branches except
|
| 1132 |
+
$k = 0$ have a logarithmic singularity at $z = 0$.
|
| 1133 |
+
|
| 1134 |
+
Examples
|
| 1135 |
+
========
|
| 1136 |
+
|
| 1137 |
+
>>> from sympy import LambertW
|
| 1138 |
+
>>> LambertW(1.2)
|
| 1139 |
+
0.635564016364870
|
| 1140 |
+
>>> LambertW(1.2, -1).n()
|
| 1141 |
+
-1.34747534407696 - 4.41624341514535*I
|
| 1142 |
+
>>> LambertW(-1).is_real
|
| 1143 |
+
False
|
| 1144 |
+
|
| 1145 |
+
References
|
| 1146 |
+
==========
|
| 1147 |
+
|
| 1148 |
+
.. [1] https://en.wikipedia.org/wiki/Lambert_W_function
|
| 1149 |
+
"""
|
| 1150 |
+
_singularities = (-Pow(S.Exp1, -1, evaluate=False), S.ComplexInfinity)
|
| 1151 |
+
|
| 1152 |
+
@classmethod
|
| 1153 |
+
def eval(cls, x, k=None):
|
| 1154 |
+
if k == S.Zero:
|
| 1155 |
+
return cls(x)
|
| 1156 |
+
elif k is None:
|
| 1157 |
+
k = S.Zero
|
| 1158 |
+
|
| 1159 |
+
if k.is_zero:
|
| 1160 |
+
if x.is_zero:
|
| 1161 |
+
return S.Zero
|
| 1162 |
+
if x is S.Exp1:
|
| 1163 |
+
return S.One
|
| 1164 |
+
if x == -1/S.Exp1:
|
| 1165 |
+
return S.NegativeOne
|
| 1166 |
+
if x == -log(2)/2:
|
| 1167 |
+
return -log(2)
|
| 1168 |
+
if x == 2*log(2):
|
| 1169 |
+
return log(2)
|
| 1170 |
+
if x == -pi/2:
|
| 1171 |
+
return I*pi/2
|
| 1172 |
+
if x == exp(1 + S.Exp1):
|
| 1173 |
+
return S.Exp1
|
| 1174 |
+
if x is S.Infinity:
|
| 1175 |
+
return S.Infinity
|
| 1176 |
+
|
| 1177 |
+
if fuzzy_not(k.is_zero):
|
| 1178 |
+
if x.is_zero:
|
| 1179 |
+
return S.NegativeInfinity
|
| 1180 |
+
if k is S.NegativeOne:
|
| 1181 |
+
if x == -pi/2:
|
| 1182 |
+
return -I*pi/2
|
| 1183 |
+
elif x == -1/S.Exp1:
|
| 1184 |
+
return S.NegativeOne
|
| 1185 |
+
elif x == -2*exp(-2):
|
| 1186 |
+
return -Integer(2)
|
| 1187 |
+
|
| 1188 |
+
def fdiff(self, argindex=1):
|
| 1189 |
+
"""
|
| 1190 |
+
Return the first derivative of this function.
|
| 1191 |
+
"""
|
| 1192 |
+
x = self.args[0]
|
| 1193 |
+
|
| 1194 |
+
if len(self.args) == 1:
|
| 1195 |
+
if argindex == 1:
|
| 1196 |
+
return LambertW(x)/(x*(1 + LambertW(x)))
|
| 1197 |
+
else:
|
| 1198 |
+
k = self.args[1]
|
| 1199 |
+
if argindex == 1:
|
| 1200 |
+
return LambertW(x, k)/(x*(1 + LambertW(x, k)))
|
| 1201 |
+
|
| 1202 |
+
raise ArgumentIndexError(self, argindex)
|
| 1203 |
+
|
| 1204 |
+
def _eval_is_extended_real(self):
|
| 1205 |
+
x = self.args[0]
|
| 1206 |
+
if len(self.args) == 1:
|
| 1207 |
+
k = S.Zero
|
| 1208 |
+
else:
|
| 1209 |
+
k = self.args[1]
|
| 1210 |
+
if k.is_zero:
|
| 1211 |
+
if (x + 1/S.Exp1).is_positive:
|
| 1212 |
+
return True
|
| 1213 |
+
elif (x + 1/S.Exp1).is_nonpositive:
|
| 1214 |
+
return False
|
| 1215 |
+
elif (k + 1).is_zero:
|
| 1216 |
+
if x.is_negative and (x + 1/S.Exp1).is_positive:
|
| 1217 |
+
return True
|
| 1218 |
+
elif x.is_nonpositive or (x + 1/S.Exp1).is_nonnegative:
|
| 1219 |
+
return False
|
| 1220 |
+
elif fuzzy_not(k.is_zero) and fuzzy_not((k + 1).is_zero):
|
| 1221 |
+
if x.is_extended_real:
|
| 1222 |
+
return False
|
| 1223 |
+
|
| 1224 |
+
def _eval_is_finite(self):
|
| 1225 |
+
return self.args[0].is_finite
|
| 1226 |
+
|
| 1227 |
+
def _eval_is_algebraic(self):
|
| 1228 |
+
s = self.func(*self.args)
|
| 1229 |
+
if s.func == self.func:
|
| 1230 |
+
if fuzzy_not(self.args[0].is_zero) and self.args[0].is_algebraic:
|
| 1231 |
+
return False
|
| 1232 |
+
else:
|
| 1233 |
+
return s.is_algebraic
|
| 1234 |
+
|
| 1235 |
+
def _eval_as_leading_term(self, x, logx=None, cdir=0):
|
| 1236 |
+
if len(self.args) == 1:
|
| 1237 |
+
arg = self.args[0]
|
| 1238 |
+
arg0 = arg.subs(x, 0).cancel()
|
| 1239 |
+
if not arg0.is_zero:
|
| 1240 |
+
return self.func(arg0)
|
| 1241 |
+
return arg.as_leading_term(x)
|
| 1242 |
+
|
| 1243 |
+
def _eval_nseries(self, x, n, logx, cdir=0):
|
| 1244 |
+
if len(self.args) == 1:
|
| 1245 |
+
from sympy.functions.elementary.integers import ceiling
|
| 1246 |
+
from sympy.series.order import Order
|
| 1247 |
+
arg = self.args[0].nseries(x, n=n, logx=logx)
|
| 1248 |
+
lt = arg.as_leading_term(x, logx=logx)
|
| 1249 |
+
lte = 1
|
| 1250 |
+
if lt.is_Pow:
|
| 1251 |
+
lte = lt.exp
|
| 1252 |
+
if ceiling(n/lte) >= 1:
|
| 1253 |
+
s = Add(*[(-S.One)**(k - 1)*Integer(k)**(k - 2)/
|
| 1254 |
+
factorial(k - 1)*arg**k for k in range(1, ceiling(n/lte))])
|
| 1255 |
+
s = expand_multinomial(s)
|
| 1256 |
+
else:
|
| 1257 |
+
s = S.Zero
|
| 1258 |
+
|
| 1259 |
+
return s + Order(x**n, x)
|
| 1260 |
+
return super()._eval_nseries(x, n, logx)
|
| 1261 |
+
|
| 1262 |
+
def _eval_is_zero(self):
|
| 1263 |
+
x = self.args[0]
|
| 1264 |
+
if len(self.args) == 1:
|
| 1265 |
+
return x.is_zero
|
| 1266 |
+
else:
|
| 1267 |
+
return fuzzy_and([x.is_zero, self.args[1].is_zero])
|
| 1268 |
+
|
| 1269 |
+
|
| 1270 |
+
@cacheit
|
| 1271 |
+
def _log_atan_table():
|
| 1272 |
+
return {
|
| 1273 |
+
# first quadrant only
|
| 1274 |
+
sqrt(3): pi / 3,
|
| 1275 |
+
1: pi / 4,
|
| 1276 |
+
sqrt(5 - 2 * sqrt(5)): pi / 5,
|
| 1277 |
+
sqrt(2) * sqrt(5 - sqrt(5)) / (1 + sqrt(5)): pi / 5,
|
| 1278 |
+
sqrt(5 + 2 * sqrt(5)): pi * Rational(2, 5),
|
| 1279 |
+
sqrt(2) * sqrt(sqrt(5) + 5) / (-1 + sqrt(5)): pi * Rational(2, 5),
|
| 1280 |
+
sqrt(3) / 3: pi / 6,
|
| 1281 |
+
sqrt(2) - 1: pi / 8,
|
| 1282 |
+
sqrt(2 - sqrt(2)) / sqrt(sqrt(2) + 2): pi / 8,
|
| 1283 |
+
sqrt(2) + 1: pi * Rational(3, 8),
|
| 1284 |
+
sqrt(sqrt(2) + 2) / sqrt(2 - sqrt(2)): pi * Rational(3, 8),
|
| 1285 |
+
sqrt(1 - 2 * sqrt(5) / 5): pi / 10,
|
| 1286 |
+
(-sqrt(2) + sqrt(10)) / (2 * sqrt(sqrt(5) + 5)): pi / 10,
|
| 1287 |
+
sqrt(1 + 2 * sqrt(5) / 5): pi * Rational(3, 10),
|
| 1288 |
+
(sqrt(2) + sqrt(10)) / (2 * sqrt(5 - sqrt(5))): pi * Rational(3, 10),
|
| 1289 |
+
2 - sqrt(3): pi / 12,
|
| 1290 |
+
(-1 + sqrt(3)) / (1 + sqrt(3)): pi / 12,
|
| 1291 |
+
2 + sqrt(3): pi * Rational(5, 12),
|
| 1292 |
+
(1 + sqrt(3)) / (-1 + sqrt(3)): pi * Rational(5, 12)
|
| 1293 |
+
}
|
evalkit_tf437/lib/python3.10/site-packages/sympy/functions/elementary/hyperbolic.py
ADDED
|
@@ -0,0 +1,2285 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.core import S, sympify, cacheit
|
| 2 |
+
from sympy.core.add import Add
|
| 3 |
+
from sympy.core.function import Function, ArgumentIndexError
|
| 4 |
+
from sympy.core.logic import fuzzy_or, fuzzy_and, fuzzy_not, FuzzyBool
|
| 5 |
+
from sympy.core.numbers import I, pi, Rational
|
| 6 |
+
from sympy.core.symbol import Dummy
|
| 7 |
+
from sympy.functions.combinatorial.factorials import (binomial, factorial,
|
| 8 |
+
RisingFactorial)
|
| 9 |
+
from sympy.functions.combinatorial.numbers import bernoulli, euler, nC
|
| 10 |
+
from sympy.functions.elementary.complexes import Abs, im, re
|
| 11 |
+
from sympy.functions.elementary.exponential import exp, log, match_real_imag
|
| 12 |
+
from sympy.functions.elementary.integers import floor
|
| 13 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
| 14 |
+
from sympy.functions.elementary.trigonometric import (
|
| 15 |
+
acos, acot, asin, atan, cos, cot, csc, sec, sin, tan,
|
| 16 |
+
_imaginary_unit_as_coefficient)
|
| 17 |
+
from sympy.polys.specialpolys import symmetric_poly
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def _rewrite_hyperbolics_as_exp(expr):
|
| 21 |
+
return expr.xreplace({h: h.rewrite(exp)
|
| 22 |
+
for h in expr.atoms(HyperbolicFunction)})
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
@cacheit
|
| 26 |
+
def _acosh_table():
|
| 27 |
+
return {
|
| 28 |
+
I: log(I*(1 + sqrt(2))),
|
| 29 |
+
-I: log(-I*(1 + sqrt(2))),
|
| 30 |
+
S.Half: pi/3,
|
| 31 |
+
Rational(-1, 2): pi*Rational(2, 3),
|
| 32 |
+
sqrt(2)/2: pi/4,
|
| 33 |
+
-sqrt(2)/2: pi*Rational(3, 4),
|
| 34 |
+
1/sqrt(2): pi/4,
|
| 35 |
+
-1/sqrt(2): pi*Rational(3, 4),
|
| 36 |
+
sqrt(3)/2: pi/6,
|
| 37 |
+
-sqrt(3)/2: pi*Rational(5, 6),
|
| 38 |
+
(sqrt(3) - 1)/sqrt(2**3): pi*Rational(5, 12),
|
| 39 |
+
-(sqrt(3) - 1)/sqrt(2**3): pi*Rational(7, 12),
|
| 40 |
+
sqrt(2 + sqrt(2))/2: pi/8,
|
| 41 |
+
-sqrt(2 + sqrt(2))/2: pi*Rational(7, 8),
|
| 42 |
+
sqrt(2 - sqrt(2))/2: pi*Rational(3, 8),
|
| 43 |
+
-sqrt(2 - sqrt(2))/2: pi*Rational(5, 8),
|
| 44 |
+
(1 + sqrt(3))/(2*sqrt(2)): pi/12,
|
| 45 |
+
-(1 + sqrt(3))/(2*sqrt(2)): pi*Rational(11, 12),
|
| 46 |
+
(sqrt(5) + 1)/4: pi/5,
|
| 47 |
+
-(sqrt(5) + 1)/4: pi*Rational(4, 5)
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
@cacheit
|
| 52 |
+
def _acsch_table():
|
| 53 |
+
return {
|
| 54 |
+
I: -pi / 2,
|
| 55 |
+
I*(sqrt(2) + sqrt(6)): -pi / 12,
|
| 56 |
+
I*(1 + sqrt(5)): -pi / 10,
|
| 57 |
+
I*2 / sqrt(2 - sqrt(2)): -pi / 8,
|
| 58 |
+
I*2: -pi / 6,
|
| 59 |
+
I*sqrt(2 + 2/sqrt(5)): -pi / 5,
|
| 60 |
+
I*sqrt(2): -pi / 4,
|
| 61 |
+
I*(sqrt(5)-1): -3*pi / 10,
|
| 62 |
+
I*2 / sqrt(3): -pi / 3,
|
| 63 |
+
I*2 / sqrt(2 + sqrt(2)): -3*pi / 8,
|
| 64 |
+
I*sqrt(2 - 2/sqrt(5)): -2*pi / 5,
|
| 65 |
+
I*(sqrt(6) - sqrt(2)): -5*pi / 12,
|
| 66 |
+
S(2): -I*log((1+sqrt(5))/2),
|
| 67 |
+
}
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
@cacheit
|
| 71 |
+
def _asech_table():
|
| 72 |
+
return {
|
| 73 |
+
I: - (pi*I / 2) + log(1 + sqrt(2)),
|
| 74 |
+
-I: (pi*I / 2) + log(1 + sqrt(2)),
|
| 75 |
+
(sqrt(6) - sqrt(2)): pi / 12,
|
| 76 |
+
(sqrt(2) - sqrt(6)): 11*pi / 12,
|
| 77 |
+
sqrt(2 - 2/sqrt(5)): pi / 10,
|
| 78 |
+
-sqrt(2 - 2/sqrt(5)): 9*pi / 10,
|
| 79 |
+
2 / sqrt(2 + sqrt(2)): pi / 8,
|
| 80 |
+
-2 / sqrt(2 + sqrt(2)): 7*pi / 8,
|
| 81 |
+
2 / sqrt(3): pi / 6,
|
| 82 |
+
-2 / sqrt(3): 5*pi / 6,
|
| 83 |
+
(sqrt(5) - 1): pi / 5,
|
| 84 |
+
(1 - sqrt(5)): 4*pi / 5,
|
| 85 |
+
sqrt(2): pi / 4,
|
| 86 |
+
-sqrt(2): 3*pi / 4,
|
| 87 |
+
sqrt(2 + 2/sqrt(5)): 3*pi / 10,
|
| 88 |
+
-sqrt(2 + 2/sqrt(5)): 7*pi / 10,
|
| 89 |
+
S(2): pi / 3,
|
| 90 |
+
-S(2): 2*pi / 3,
|
| 91 |
+
sqrt(2*(2 + sqrt(2))): 3*pi / 8,
|
| 92 |
+
-sqrt(2*(2 + sqrt(2))): 5*pi / 8,
|
| 93 |
+
(1 + sqrt(5)): 2*pi / 5,
|
| 94 |
+
(-1 - sqrt(5)): 3*pi / 5,
|
| 95 |
+
(sqrt(6) + sqrt(2)): 5*pi / 12,
|
| 96 |
+
(-sqrt(6) - sqrt(2)): 7*pi / 12,
|
| 97 |
+
I*S.Infinity: -pi*I / 2,
|
| 98 |
+
I*S.NegativeInfinity: pi*I / 2,
|
| 99 |
+
}
|
| 100 |
+
|
| 101 |
+
###############################################################################
|
| 102 |
+
########################### HYPERBOLIC FUNCTIONS ##############################
|
| 103 |
+
###############################################################################
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
class HyperbolicFunction(Function):
|
| 107 |
+
"""
|
| 108 |
+
Base class for hyperbolic functions.
|
| 109 |
+
|
| 110 |
+
See Also
|
| 111 |
+
========
|
| 112 |
+
|
| 113 |
+
sinh, cosh, tanh, coth
|
| 114 |
+
"""
|
| 115 |
+
|
| 116 |
+
unbranched = True
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def _peeloff_ipi(arg):
|
| 120 |
+
r"""
|
| 121 |
+
Split ARG into two parts, a "rest" and a multiple of $I\pi$.
|
| 122 |
+
This assumes ARG to be an ``Add``.
|
| 123 |
+
The multiple of $I\pi$ returned in the second position is always a ``Rational``.
|
| 124 |
+
|
| 125 |
+
Examples
|
| 126 |
+
========
|
| 127 |
+
|
| 128 |
+
>>> from sympy.functions.elementary.hyperbolic import _peeloff_ipi as peel
|
| 129 |
+
>>> from sympy import pi, I
|
| 130 |
+
>>> from sympy.abc import x, y
|
| 131 |
+
>>> peel(x + I*pi/2)
|
| 132 |
+
(x, 1/2)
|
| 133 |
+
>>> peel(x + I*2*pi/3 + I*pi*y)
|
| 134 |
+
(x + I*pi*y + I*pi/6, 1/2)
|
| 135 |
+
"""
|
| 136 |
+
ipi = pi*I
|
| 137 |
+
for a in Add.make_args(arg):
|
| 138 |
+
if a == ipi:
|
| 139 |
+
K = S.One
|
| 140 |
+
break
|
| 141 |
+
elif a.is_Mul:
|
| 142 |
+
K, p = a.as_two_terms()
|
| 143 |
+
if p == ipi and K.is_Rational:
|
| 144 |
+
break
|
| 145 |
+
else:
|
| 146 |
+
return arg, S.Zero
|
| 147 |
+
|
| 148 |
+
m1 = (K % S.Half)
|
| 149 |
+
m2 = K - m1
|
| 150 |
+
return arg - m2*ipi, m2
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
class sinh(HyperbolicFunction):
|
| 154 |
+
r"""
|
| 155 |
+
``sinh(x)`` is the hyperbolic sine of ``x``.
|
| 156 |
+
|
| 157 |
+
The hyperbolic sine function is $\frac{e^x - e^{-x}}{2}$.
|
| 158 |
+
|
| 159 |
+
Examples
|
| 160 |
+
========
|
| 161 |
+
|
| 162 |
+
>>> from sympy import sinh
|
| 163 |
+
>>> from sympy.abc import x
|
| 164 |
+
>>> sinh(x)
|
| 165 |
+
sinh(x)
|
| 166 |
+
|
| 167 |
+
See Also
|
| 168 |
+
========
|
| 169 |
+
|
| 170 |
+
cosh, tanh, asinh
|
| 171 |
+
"""
|
| 172 |
+
|
| 173 |
+
def fdiff(self, argindex=1):
|
| 174 |
+
"""
|
| 175 |
+
Returns the first derivative of this function.
|
| 176 |
+
"""
|
| 177 |
+
if argindex == 1:
|
| 178 |
+
return cosh(self.args[0])
|
| 179 |
+
else:
|
| 180 |
+
raise ArgumentIndexError(self, argindex)
|
| 181 |
+
|
| 182 |
+
def inverse(self, argindex=1):
|
| 183 |
+
"""
|
| 184 |
+
Returns the inverse of this function.
|
| 185 |
+
"""
|
| 186 |
+
return asinh
|
| 187 |
+
|
| 188 |
+
@classmethod
|
| 189 |
+
def eval(cls, arg):
|
| 190 |
+
if arg.is_Number:
|
| 191 |
+
if arg is S.NaN:
|
| 192 |
+
return S.NaN
|
| 193 |
+
elif arg is S.Infinity:
|
| 194 |
+
return S.Infinity
|
| 195 |
+
elif arg is S.NegativeInfinity:
|
| 196 |
+
return S.NegativeInfinity
|
| 197 |
+
elif arg.is_zero:
|
| 198 |
+
return S.Zero
|
| 199 |
+
elif arg.is_negative:
|
| 200 |
+
return -cls(-arg)
|
| 201 |
+
else:
|
| 202 |
+
if arg is S.ComplexInfinity:
|
| 203 |
+
return S.NaN
|
| 204 |
+
|
| 205 |
+
i_coeff = _imaginary_unit_as_coefficient(arg)
|
| 206 |
+
|
| 207 |
+
if i_coeff is not None:
|
| 208 |
+
return I * sin(i_coeff)
|
| 209 |
+
else:
|
| 210 |
+
if arg.could_extract_minus_sign():
|
| 211 |
+
return -cls(-arg)
|
| 212 |
+
|
| 213 |
+
if arg.is_Add:
|
| 214 |
+
x, m = _peeloff_ipi(arg)
|
| 215 |
+
if m:
|
| 216 |
+
m = m*pi*I
|
| 217 |
+
return sinh(m)*cosh(x) + cosh(m)*sinh(x)
|
| 218 |
+
|
| 219 |
+
if arg.is_zero:
|
| 220 |
+
return S.Zero
|
| 221 |
+
|
| 222 |
+
if arg.func == asinh:
|
| 223 |
+
return arg.args[0]
|
| 224 |
+
|
| 225 |
+
if arg.func == acosh:
|
| 226 |
+
x = arg.args[0]
|
| 227 |
+
return sqrt(x - 1) * sqrt(x + 1)
|
| 228 |
+
|
| 229 |
+
if arg.func == atanh:
|
| 230 |
+
x = arg.args[0]
|
| 231 |
+
return x/sqrt(1 - x**2)
|
| 232 |
+
|
| 233 |
+
if arg.func == acoth:
|
| 234 |
+
x = arg.args[0]
|
| 235 |
+
return 1/(sqrt(x - 1) * sqrt(x + 1))
|
| 236 |
+
|
| 237 |
+
@staticmethod
|
| 238 |
+
@cacheit
|
| 239 |
+
def taylor_term(n, x, *previous_terms):
|
| 240 |
+
"""
|
| 241 |
+
Returns the next term in the Taylor series expansion.
|
| 242 |
+
"""
|
| 243 |
+
if n < 0 or n % 2 == 0:
|
| 244 |
+
return S.Zero
|
| 245 |
+
else:
|
| 246 |
+
x = sympify(x)
|
| 247 |
+
|
| 248 |
+
if len(previous_terms) > 2:
|
| 249 |
+
p = previous_terms[-2]
|
| 250 |
+
return p * x**2 / (n*(n - 1))
|
| 251 |
+
else:
|
| 252 |
+
return x**(n) / factorial(n)
|
| 253 |
+
|
| 254 |
+
def _eval_conjugate(self):
|
| 255 |
+
return self.func(self.args[0].conjugate())
|
| 256 |
+
|
| 257 |
+
def as_real_imag(self, deep=True, **hints):
|
| 258 |
+
"""
|
| 259 |
+
Returns this function as a complex coordinate.
|
| 260 |
+
"""
|
| 261 |
+
if self.args[0].is_extended_real:
|
| 262 |
+
if deep:
|
| 263 |
+
hints['complex'] = False
|
| 264 |
+
return (self.expand(deep, **hints), S.Zero)
|
| 265 |
+
else:
|
| 266 |
+
return (self, S.Zero)
|
| 267 |
+
if deep:
|
| 268 |
+
re, im = self.args[0].expand(deep, **hints).as_real_imag()
|
| 269 |
+
else:
|
| 270 |
+
re, im = self.args[0].as_real_imag()
|
| 271 |
+
return (sinh(re)*cos(im), cosh(re)*sin(im))
|
| 272 |
+
|
| 273 |
+
def _eval_expand_complex(self, deep=True, **hints):
|
| 274 |
+
re_part, im_part = self.as_real_imag(deep=deep, **hints)
|
| 275 |
+
return re_part + im_part*I
|
| 276 |
+
|
| 277 |
+
def _eval_expand_trig(self, deep=True, **hints):
|
| 278 |
+
if deep:
|
| 279 |
+
arg = self.args[0].expand(deep, **hints)
|
| 280 |
+
else:
|
| 281 |
+
arg = self.args[0]
|
| 282 |
+
x = None
|
| 283 |
+
if arg.is_Add: # TODO, implement more if deep stuff here
|
| 284 |
+
x, y = arg.as_two_terms()
|
| 285 |
+
else:
|
| 286 |
+
coeff, terms = arg.as_coeff_Mul(rational=True)
|
| 287 |
+
if coeff is not S.One and coeff.is_Integer and terms is not S.One:
|
| 288 |
+
x = terms
|
| 289 |
+
y = (coeff - 1)*x
|
| 290 |
+
if x is not None:
|
| 291 |
+
return (sinh(x)*cosh(y) + sinh(y)*cosh(x)).expand(trig=True)
|
| 292 |
+
return sinh(arg)
|
| 293 |
+
|
| 294 |
+
def _eval_rewrite_as_tractable(self, arg, limitvar=None, **kwargs):
|
| 295 |
+
return (exp(arg) - exp(-arg)) / 2
|
| 296 |
+
|
| 297 |
+
def _eval_rewrite_as_exp(self, arg, **kwargs):
|
| 298 |
+
return (exp(arg) - exp(-arg)) / 2
|
| 299 |
+
|
| 300 |
+
def _eval_rewrite_as_sin(self, arg, **kwargs):
|
| 301 |
+
return -I * sin(I * arg)
|
| 302 |
+
|
| 303 |
+
def _eval_rewrite_as_csc(self, arg, **kwargs):
|
| 304 |
+
return -I / csc(I * arg)
|
| 305 |
+
|
| 306 |
+
def _eval_rewrite_as_cosh(self, arg, **kwargs):
|
| 307 |
+
return -I*cosh(arg + pi*I/2)
|
| 308 |
+
|
| 309 |
+
def _eval_rewrite_as_tanh(self, arg, **kwargs):
|
| 310 |
+
tanh_half = tanh(S.Half*arg)
|
| 311 |
+
return 2*tanh_half/(1 - tanh_half**2)
|
| 312 |
+
|
| 313 |
+
def _eval_rewrite_as_coth(self, arg, **kwargs):
|
| 314 |
+
coth_half = coth(S.Half*arg)
|
| 315 |
+
return 2*coth_half/(coth_half**2 - 1)
|
| 316 |
+
|
| 317 |
+
def _eval_rewrite_as_csch(self, arg, **kwargs):
|
| 318 |
+
return 1 / csch(arg)
|
| 319 |
+
|
| 320 |
+
def _eval_as_leading_term(self, x, logx=None, cdir=0):
|
| 321 |
+
arg = self.args[0].as_leading_term(x, logx=logx, cdir=cdir)
|
| 322 |
+
arg0 = arg.subs(x, 0)
|
| 323 |
+
|
| 324 |
+
if arg0 is S.NaN:
|
| 325 |
+
arg0 = arg.limit(x, 0, dir='-' if cdir.is_negative else '+')
|
| 326 |
+
if arg0.is_zero:
|
| 327 |
+
return arg
|
| 328 |
+
elif arg0.is_finite:
|
| 329 |
+
return self.func(arg0)
|
| 330 |
+
else:
|
| 331 |
+
return self
|
| 332 |
+
|
| 333 |
+
def _eval_is_real(self):
|
| 334 |
+
arg = self.args[0]
|
| 335 |
+
if arg.is_real:
|
| 336 |
+
return True
|
| 337 |
+
|
| 338 |
+
# if `im` is of the form n*pi
|
| 339 |
+
# else, check if it is a number
|
| 340 |
+
re, im = arg.as_real_imag()
|
| 341 |
+
return (im%pi).is_zero
|
| 342 |
+
|
| 343 |
+
def _eval_is_extended_real(self):
|
| 344 |
+
if self.args[0].is_extended_real:
|
| 345 |
+
return True
|
| 346 |
+
|
| 347 |
+
def _eval_is_positive(self):
|
| 348 |
+
if self.args[0].is_extended_real:
|
| 349 |
+
return self.args[0].is_positive
|
| 350 |
+
|
| 351 |
+
def _eval_is_negative(self):
|
| 352 |
+
if self.args[0].is_extended_real:
|
| 353 |
+
return self.args[0].is_negative
|
| 354 |
+
|
| 355 |
+
def _eval_is_finite(self):
|
| 356 |
+
arg = self.args[0]
|
| 357 |
+
return arg.is_finite
|
| 358 |
+
|
| 359 |
+
def _eval_is_zero(self):
|
| 360 |
+
rest, ipi_mult = _peeloff_ipi(self.args[0])
|
| 361 |
+
if rest.is_zero:
|
| 362 |
+
return ipi_mult.is_integer
|
| 363 |
+
|
| 364 |
+
|
| 365 |
+
class cosh(HyperbolicFunction):
|
| 366 |
+
r"""
|
| 367 |
+
``cosh(x)`` is the hyperbolic cosine of ``x``.
|
| 368 |
+
|
| 369 |
+
The hyperbolic cosine function is $\frac{e^x + e^{-x}}{2}$.
|
| 370 |
+
|
| 371 |
+
Examples
|
| 372 |
+
========
|
| 373 |
+
|
| 374 |
+
>>> from sympy import cosh
|
| 375 |
+
>>> from sympy.abc import x
|
| 376 |
+
>>> cosh(x)
|
| 377 |
+
cosh(x)
|
| 378 |
+
|
| 379 |
+
See Also
|
| 380 |
+
========
|
| 381 |
+
|
| 382 |
+
sinh, tanh, acosh
|
| 383 |
+
"""
|
| 384 |
+
|
| 385 |
+
def fdiff(self, argindex=1):
|
| 386 |
+
if argindex == 1:
|
| 387 |
+
return sinh(self.args[0])
|
| 388 |
+
else:
|
| 389 |
+
raise ArgumentIndexError(self, argindex)
|
| 390 |
+
|
| 391 |
+
@classmethod
|
| 392 |
+
def eval(cls, arg):
|
| 393 |
+
from sympy.functions.elementary.trigonometric import cos
|
| 394 |
+
if arg.is_Number:
|
| 395 |
+
if arg is S.NaN:
|
| 396 |
+
return S.NaN
|
| 397 |
+
elif arg is S.Infinity:
|
| 398 |
+
return S.Infinity
|
| 399 |
+
elif arg is S.NegativeInfinity:
|
| 400 |
+
return S.Infinity
|
| 401 |
+
elif arg.is_zero:
|
| 402 |
+
return S.One
|
| 403 |
+
elif arg.is_negative:
|
| 404 |
+
return cls(-arg)
|
| 405 |
+
else:
|
| 406 |
+
if arg is S.ComplexInfinity:
|
| 407 |
+
return S.NaN
|
| 408 |
+
|
| 409 |
+
i_coeff = _imaginary_unit_as_coefficient(arg)
|
| 410 |
+
|
| 411 |
+
if i_coeff is not None:
|
| 412 |
+
return cos(i_coeff)
|
| 413 |
+
else:
|
| 414 |
+
if arg.could_extract_minus_sign():
|
| 415 |
+
return cls(-arg)
|
| 416 |
+
|
| 417 |
+
if arg.is_Add:
|
| 418 |
+
x, m = _peeloff_ipi(arg)
|
| 419 |
+
if m:
|
| 420 |
+
m = m*pi*I
|
| 421 |
+
return cosh(m)*cosh(x) + sinh(m)*sinh(x)
|
| 422 |
+
|
| 423 |
+
if arg.is_zero:
|
| 424 |
+
return S.One
|
| 425 |
+
|
| 426 |
+
if arg.func == asinh:
|
| 427 |
+
return sqrt(1 + arg.args[0]**2)
|
| 428 |
+
|
| 429 |
+
if arg.func == acosh:
|
| 430 |
+
return arg.args[0]
|
| 431 |
+
|
| 432 |
+
if arg.func == atanh:
|
| 433 |
+
return 1/sqrt(1 - arg.args[0]**2)
|
| 434 |
+
|
| 435 |
+
if arg.func == acoth:
|
| 436 |
+
x = arg.args[0]
|
| 437 |
+
return x/(sqrt(x - 1) * sqrt(x + 1))
|
| 438 |
+
|
| 439 |
+
@staticmethod
|
| 440 |
+
@cacheit
|
| 441 |
+
def taylor_term(n, x, *previous_terms):
|
| 442 |
+
if n < 0 or n % 2 == 1:
|
| 443 |
+
return S.Zero
|
| 444 |
+
else:
|
| 445 |
+
x = sympify(x)
|
| 446 |
+
|
| 447 |
+
if len(previous_terms) > 2:
|
| 448 |
+
p = previous_terms[-2]
|
| 449 |
+
return p * x**2 / (n*(n - 1))
|
| 450 |
+
else:
|
| 451 |
+
return x**(n)/factorial(n)
|
| 452 |
+
|
| 453 |
+
def _eval_conjugate(self):
|
| 454 |
+
return self.func(self.args[0].conjugate())
|
| 455 |
+
|
| 456 |
+
def as_real_imag(self, deep=True, **hints):
|
| 457 |
+
if self.args[0].is_extended_real:
|
| 458 |
+
if deep:
|
| 459 |
+
hints['complex'] = False
|
| 460 |
+
return (self.expand(deep, **hints), S.Zero)
|
| 461 |
+
else:
|
| 462 |
+
return (self, S.Zero)
|
| 463 |
+
if deep:
|
| 464 |
+
re, im = self.args[0].expand(deep, **hints).as_real_imag()
|
| 465 |
+
else:
|
| 466 |
+
re, im = self.args[0].as_real_imag()
|
| 467 |
+
|
| 468 |
+
return (cosh(re)*cos(im), sinh(re)*sin(im))
|
| 469 |
+
|
| 470 |
+
def _eval_expand_complex(self, deep=True, **hints):
|
| 471 |
+
re_part, im_part = self.as_real_imag(deep=deep, **hints)
|
| 472 |
+
return re_part + im_part*I
|
| 473 |
+
|
| 474 |
+
def _eval_expand_trig(self, deep=True, **hints):
|
| 475 |
+
if deep:
|
| 476 |
+
arg = self.args[0].expand(deep, **hints)
|
| 477 |
+
else:
|
| 478 |
+
arg = self.args[0]
|
| 479 |
+
x = None
|
| 480 |
+
if arg.is_Add: # TODO, implement more if deep stuff here
|
| 481 |
+
x, y = arg.as_two_terms()
|
| 482 |
+
else:
|
| 483 |
+
coeff, terms = arg.as_coeff_Mul(rational=True)
|
| 484 |
+
if coeff is not S.One and coeff.is_Integer and terms is not S.One:
|
| 485 |
+
x = terms
|
| 486 |
+
y = (coeff - 1)*x
|
| 487 |
+
if x is not None:
|
| 488 |
+
return (cosh(x)*cosh(y) + sinh(x)*sinh(y)).expand(trig=True)
|
| 489 |
+
return cosh(arg)
|
| 490 |
+
|
| 491 |
+
def _eval_rewrite_as_tractable(self, arg, limitvar=None, **kwargs):
|
| 492 |
+
return (exp(arg) + exp(-arg)) / 2
|
| 493 |
+
|
| 494 |
+
def _eval_rewrite_as_exp(self, arg, **kwargs):
|
| 495 |
+
return (exp(arg) + exp(-arg)) / 2
|
| 496 |
+
|
| 497 |
+
def _eval_rewrite_as_cos(self, arg, **kwargs):
|
| 498 |
+
return cos(I * arg, evaluate=False)
|
| 499 |
+
|
| 500 |
+
def _eval_rewrite_as_sec(self, arg, **kwargs):
|
| 501 |
+
return 1 / sec(I * arg, evaluate=False)
|
| 502 |
+
|
| 503 |
+
def _eval_rewrite_as_sinh(self, arg, **kwargs):
|
| 504 |
+
return -I*sinh(arg + pi*I/2, evaluate=False)
|
| 505 |
+
|
| 506 |
+
def _eval_rewrite_as_tanh(self, arg, **kwargs):
|
| 507 |
+
tanh_half = tanh(S.Half*arg)**2
|
| 508 |
+
return (1 + tanh_half)/(1 - tanh_half)
|
| 509 |
+
|
| 510 |
+
def _eval_rewrite_as_coth(self, arg, **kwargs):
|
| 511 |
+
coth_half = coth(S.Half*arg)**2
|
| 512 |
+
return (coth_half + 1)/(coth_half - 1)
|
| 513 |
+
|
| 514 |
+
def _eval_rewrite_as_sech(self, arg, **kwargs):
|
| 515 |
+
return 1 / sech(arg)
|
| 516 |
+
|
| 517 |
+
def _eval_as_leading_term(self, x, logx=None, cdir=0):
|
| 518 |
+
arg = self.args[0].as_leading_term(x, logx=logx, cdir=cdir)
|
| 519 |
+
arg0 = arg.subs(x, 0)
|
| 520 |
+
|
| 521 |
+
if arg0 is S.NaN:
|
| 522 |
+
arg0 = arg.limit(x, 0, dir='-' if cdir.is_negative else '+')
|
| 523 |
+
if arg0.is_zero:
|
| 524 |
+
return S.One
|
| 525 |
+
elif arg0.is_finite:
|
| 526 |
+
return self.func(arg0)
|
| 527 |
+
else:
|
| 528 |
+
return self
|
| 529 |
+
|
| 530 |
+
def _eval_is_real(self):
|
| 531 |
+
arg = self.args[0]
|
| 532 |
+
|
| 533 |
+
# `cosh(x)` is real for real OR purely imaginary `x`
|
| 534 |
+
if arg.is_real or arg.is_imaginary:
|
| 535 |
+
return True
|
| 536 |
+
|
| 537 |
+
# cosh(a+ib) = cos(b)*cosh(a) + i*sin(b)*sinh(a)
|
| 538 |
+
# the imaginary part can be an expression like n*pi
|
| 539 |
+
# if not, check if the imaginary part is a number
|
| 540 |
+
re, im = arg.as_real_imag()
|
| 541 |
+
return (im%pi).is_zero
|
| 542 |
+
|
| 543 |
+
def _eval_is_positive(self):
|
| 544 |
+
# cosh(x+I*y) = cos(y)*cosh(x) + I*sin(y)*sinh(x)
|
| 545 |
+
# cosh(z) is positive iff it is real and the real part is positive.
|
| 546 |
+
# So we need sin(y)*sinh(x) = 0 which gives x=0 or y=n*pi
|
| 547 |
+
# Case 1 (y=n*pi): cosh(z) = (-1)**n * cosh(x) -> positive for n even
|
| 548 |
+
# Case 2 (x=0): cosh(z) = cos(y) -> positive when cos(y) is positive
|
| 549 |
+
z = self.args[0]
|
| 550 |
+
|
| 551 |
+
x, y = z.as_real_imag()
|
| 552 |
+
ymod = y % (2*pi)
|
| 553 |
+
|
| 554 |
+
yzero = ymod.is_zero
|
| 555 |
+
# shortcut if ymod is zero
|
| 556 |
+
if yzero:
|
| 557 |
+
return True
|
| 558 |
+
|
| 559 |
+
xzero = x.is_zero
|
| 560 |
+
# shortcut x is not zero
|
| 561 |
+
if xzero is False:
|
| 562 |
+
return yzero
|
| 563 |
+
|
| 564 |
+
return fuzzy_or([
|
| 565 |
+
# Case 1:
|
| 566 |
+
yzero,
|
| 567 |
+
# Case 2:
|
| 568 |
+
fuzzy_and([
|
| 569 |
+
xzero,
|
| 570 |
+
fuzzy_or([ymod < pi/2, ymod > 3*pi/2])
|
| 571 |
+
])
|
| 572 |
+
])
|
| 573 |
+
|
| 574 |
+
|
| 575 |
+
def _eval_is_nonnegative(self):
|
| 576 |
+
z = self.args[0]
|
| 577 |
+
|
| 578 |
+
x, y = z.as_real_imag()
|
| 579 |
+
ymod = y % (2*pi)
|
| 580 |
+
|
| 581 |
+
yzero = ymod.is_zero
|
| 582 |
+
# shortcut if ymod is zero
|
| 583 |
+
if yzero:
|
| 584 |
+
return True
|
| 585 |
+
|
| 586 |
+
xzero = x.is_zero
|
| 587 |
+
# shortcut x is not zero
|
| 588 |
+
if xzero is False:
|
| 589 |
+
return yzero
|
| 590 |
+
|
| 591 |
+
return fuzzy_or([
|
| 592 |
+
# Case 1:
|
| 593 |
+
yzero,
|
| 594 |
+
# Case 2:
|
| 595 |
+
fuzzy_and([
|
| 596 |
+
xzero,
|
| 597 |
+
fuzzy_or([ymod <= pi/2, ymod >= 3*pi/2])
|
| 598 |
+
])
|
| 599 |
+
])
|
| 600 |
+
|
| 601 |
+
def _eval_is_finite(self):
|
| 602 |
+
arg = self.args[0]
|
| 603 |
+
return arg.is_finite
|
| 604 |
+
|
| 605 |
+
def _eval_is_zero(self):
|
| 606 |
+
rest, ipi_mult = _peeloff_ipi(self.args[0])
|
| 607 |
+
if ipi_mult and rest.is_zero:
|
| 608 |
+
return (ipi_mult - S.Half).is_integer
|
| 609 |
+
|
| 610 |
+
|
| 611 |
+
class tanh(HyperbolicFunction):
|
| 612 |
+
r"""
|
| 613 |
+
``tanh(x)`` is the hyperbolic tangent of ``x``.
|
| 614 |
+
|
| 615 |
+
The hyperbolic tangent function is $\frac{\sinh(x)}{\cosh(x)}$.
|
| 616 |
+
|
| 617 |
+
Examples
|
| 618 |
+
========
|
| 619 |
+
|
| 620 |
+
>>> from sympy import tanh
|
| 621 |
+
>>> from sympy.abc import x
|
| 622 |
+
>>> tanh(x)
|
| 623 |
+
tanh(x)
|
| 624 |
+
|
| 625 |
+
See Also
|
| 626 |
+
========
|
| 627 |
+
|
| 628 |
+
sinh, cosh, atanh
|
| 629 |
+
"""
|
| 630 |
+
|
| 631 |
+
def fdiff(self, argindex=1):
|
| 632 |
+
if argindex == 1:
|
| 633 |
+
return S.One - tanh(self.args[0])**2
|
| 634 |
+
else:
|
| 635 |
+
raise ArgumentIndexError(self, argindex)
|
| 636 |
+
|
| 637 |
+
def inverse(self, argindex=1):
|
| 638 |
+
"""
|
| 639 |
+
Returns the inverse of this function.
|
| 640 |
+
"""
|
| 641 |
+
return atanh
|
| 642 |
+
|
| 643 |
+
@classmethod
|
| 644 |
+
def eval(cls, arg):
|
| 645 |
+
if arg.is_Number:
|
| 646 |
+
if arg is S.NaN:
|
| 647 |
+
return S.NaN
|
| 648 |
+
elif arg is S.Infinity:
|
| 649 |
+
return S.One
|
| 650 |
+
elif arg is S.NegativeInfinity:
|
| 651 |
+
return S.NegativeOne
|
| 652 |
+
elif arg.is_zero:
|
| 653 |
+
return S.Zero
|
| 654 |
+
elif arg.is_negative:
|
| 655 |
+
return -cls(-arg)
|
| 656 |
+
else:
|
| 657 |
+
if arg is S.ComplexInfinity:
|
| 658 |
+
return S.NaN
|
| 659 |
+
|
| 660 |
+
i_coeff = _imaginary_unit_as_coefficient(arg)
|
| 661 |
+
|
| 662 |
+
if i_coeff is not None:
|
| 663 |
+
if i_coeff.could_extract_minus_sign():
|
| 664 |
+
return -I * tan(-i_coeff)
|
| 665 |
+
return I * tan(i_coeff)
|
| 666 |
+
else:
|
| 667 |
+
if arg.could_extract_minus_sign():
|
| 668 |
+
return -cls(-arg)
|
| 669 |
+
|
| 670 |
+
if arg.is_Add:
|
| 671 |
+
x, m = _peeloff_ipi(arg)
|
| 672 |
+
if m:
|
| 673 |
+
tanhm = tanh(m*pi*I)
|
| 674 |
+
if tanhm is S.ComplexInfinity:
|
| 675 |
+
return coth(x)
|
| 676 |
+
else: # tanhm == 0
|
| 677 |
+
return tanh(x)
|
| 678 |
+
|
| 679 |
+
if arg.is_zero:
|
| 680 |
+
return S.Zero
|
| 681 |
+
|
| 682 |
+
if arg.func == asinh:
|
| 683 |
+
x = arg.args[0]
|
| 684 |
+
return x/sqrt(1 + x**2)
|
| 685 |
+
|
| 686 |
+
if arg.func == acosh:
|
| 687 |
+
x = arg.args[0]
|
| 688 |
+
return sqrt(x - 1) * sqrt(x + 1) / x
|
| 689 |
+
|
| 690 |
+
if arg.func == atanh:
|
| 691 |
+
return arg.args[0]
|
| 692 |
+
|
| 693 |
+
if arg.func == acoth:
|
| 694 |
+
return 1/arg.args[0]
|
| 695 |
+
|
| 696 |
+
@staticmethod
|
| 697 |
+
@cacheit
|
| 698 |
+
def taylor_term(n, x, *previous_terms):
|
| 699 |
+
if n < 0 or n % 2 == 0:
|
| 700 |
+
return S.Zero
|
| 701 |
+
else:
|
| 702 |
+
x = sympify(x)
|
| 703 |
+
|
| 704 |
+
a = 2**(n + 1)
|
| 705 |
+
|
| 706 |
+
B = bernoulli(n + 1)
|
| 707 |
+
F = factorial(n + 1)
|
| 708 |
+
|
| 709 |
+
return a*(a - 1) * B/F * x**n
|
| 710 |
+
|
| 711 |
+
def _eval_conjugate(self):
|
| 712 |
+
return self.func(self.args[0].conjugate())
|
| 713 |
+
|
| 714 |
+
def as_real_imag(self, deep=True, **hints):
|
| 715 |
+
if self.args[0].is_extended_real:
|
| 716 |
+
if deep:
|
| 717 |
+
hints['complex'] = False
|
| 718 |
+
return (self.expand(deep, **hints), S.Zero)
|
| 719 |
+
else:
|
| 720 |
+
return (self, S.Zero)
|
| 721 |
+
if deep:
|
| 722 |
+
re, im = self.args[0].expand(deep, **hints).as_real_imag()
|
| 723 |
+
else:
|
| 724 |
+
re, im = self.args[0].as_real_imag()
|
| 725 |
+
denom = sinh(re)**2 + cos(im)**2
|
| 726 |
+
return (sinh(re)*cosh(re)/denom, sin(im)*cos(im)/denom)
|
| 727 |
+
|
| 728 |
+
def _eval_expand_trig(self, **hints):
|
| 729 |
+
arg = self.args[0]
|
| 730 |
+
if arg.is_Add:
|
| 731 |
+
n = len(arg.args)
|
| 732 |
+
TX = [tanh(x, evaluate=False)._eval_expand_trig()
|
| 733 |
+
for x in arg.args]
|
| 734 |
+
p = [0, 0] # [den, num]
|
| 735 |
+
for i in range(n + 1):
|
| 736 |
+
p[i % 2] += symmetric_poly(i, TX)
|
| 737 |
+
return p[1]/p[0]
|
| 738 |
+
elif arg.is_Mul:
|
| 739 |
+
coeff, terms = arg.as_coeff_Mul()
|
| 740 |
+
if coeff.is_Integer and coeff > 1:
|
| 741 |
+
T = tanh(terms)
|
| 742 |
+
n = [nC(range(coeff), k)*T**k for k in range(1, coeff + 1, 2)]
|
| 743 |
+
d = [nC(range(coeff), k)*T**k for k in range(0, coeff + 1, 2)]
|
| 744 |
+
return Add(*n)/Add(*d)
|
| 745 |
+
return tanh(arg)
|
| 746 |
+
|
| 747 |
+
def _eval_rewrite_as_tractable(self, arg, limitvar=None, **kwargs):
|
| 748 |
+
neg_exp, pos_exp = exp(-arg), exp(arg)
|
| 749 |
+
return (pos_exp - neg_exp)/(pos_exp + neg_exp)
|
| 750 |
+
|
| 751 |
+
def _eval_rewrite_as_exp(self, arg, **kwargs):
|
| 752 |
+
neg_exp, pos_exp = exp(-arg), exp(arg)
|
| 753 |
+
return (pos_exp - neg_exp)/(pos_exp + neg_exp)
|
| 754 |
+
|
| 755 |
+
def _eval_rewrite_as_tan(self, arg, **kwargs):
|
| 756 |
+
return -I * tan(I * arg, evaluate=False)
|
| 757 |
+
|
| 758 |
+
def _eval_rewrite_as_cot(self, arg, **kwargs):
|
| 759 |
+
return -I / cot(I * arg, evaluate=False)
|
| 760 |
+
|
| 761 |
+
def _eval_rewrite_as_sinh(self, arg, **kwargs):
|
| 762 |
+
return I*sinh(arg)/sinh(pi*I/2 - arg, evaluate=False)
|
| 763 |
+
|
| 764 |
+
def _eval_rewrite_as_cosh(self, arg, **kwargs):
|
| 765 |
+
return I*cosh(pi*I/2 - arg, evaluate=False)/cosh(arg)
|
| 766 |
+
|
| 767 |
+
def _eval_rewrite_as_coth(self, arg, **kwargs):
|
| 768 |
+
return 1/coth(arg)
|
| 769 |
+
|
| 770 |
+
def _eval_as_leading_term(self, x, logx=None, cdir=0):
|
| 771 |
+
from sympy.series.order import Order
|
| 772 |
+
arg = self.args[0].as_leading_term(x)
|
| 773 |
+
|
| 774 |
+
if x in arg.free_symbols and Order(1, x).contains(arg):
|
| 775 |
+
return arg
|
| 776 |
+
else:
|
| 777 |
+
return self.func(arg)
|
| 778 |
+
|
| 779 |
+
def _eval_is_real(self):
|
| 780 |
+
arg = self.args[0]
|
| 781 |
+
if arg.is_real:
|
| 782 |
+
return True
|
| 783 |
+
|
| 784 |
+
re, im = arg.as_real_imag()
|
| 785 |
+
|
| 786 |
+
# if denom = 0, tanh(arg) = zoo
|
| 787 |
+
if re == 0 and im % pi == pi/2:
|
| 788 |
+
return None
|
| 789 |
+
|
| 790 |
+
# check if im is of the form n*pi/2 to make sin(2*im) = 0
|
| 791 |
+
# if not, im could be a number, return False in that case
|
| 792 |
+
return (im % (pi/2)).is_zero
|
| 793 |
+
|
| 794 |
+
def _eval_is_extended_real(self):
|
| 795 |
+
if self.args[0].is_extended_real:
|
| 796 |
+
return True
|
| 797 |
+
|
| 798 |
+
def _eval_is_positive(self):
|
| 799 |
+
if self.args[0].is_extended_real:
|
| 800 |
+
return self.args[0].is_positive
|
| 801 |
+
|
| 802 |
+
def _eval_is_negative(self):
|
| 803 |
+
if self.args[0].is_extended_real:
|
| 804 |
+
return self.args[0].is_negative
|
| 805 |
+
|
| 806 |
+
def _eval_is_finite(self):
|
| 807 |
+
arg = self.args[0]
|
| 808 |
+
|
| 809 |
+
re, im = arg.as_real_imag()
|
| 810 |
+
denom = cos(im)**2 + sinh(re)**2
|
| 811 |
+
if denom == 0:
|
| 812 |
+
return False
|
| 813 |
+
elif denom.is_number:
|
| 814 |
+
return True
|
| 815 |
+
if arg.is_extended_real:
|
| 816 |
+
return True
|
| 817 |
+
|
| 818 |
+
def _eval_is_zero(self):
|
| 819 |
+
arg = self.args[0]
|
| 820 |
+
if arg.is_zero:
|
| 821 |
+
return True
|
| 822 |
+
|
| 823 |
+
|
| 824 |
+
class coth(HyperbolicFunction):
|
| 825 |
+
r"""
|
| 826 |
+
``coth(x)`` is the hyperbolic cotangent of ``x``.
|
| 827 |
+
|
| 828 |
+
The hyperbolic cotangent function is $\frac{\cosh(x)}{\sinh(x)}$.
|
| 829 |
+
|
| 830 |
+
Examples
|
| 831 |
+
========
|
| 832 |
+
|
| 833 |
+
>>> from sympy import coth
|
| 834 |
+
>>> from sympy.abc import x
|
| 835 |
+
>>> coth(x)
|
| 836 |
+
coth(x)
|
| 837 |
+
|
| 838 |
+
See Also
|
| 839 |
+
========
|
| 840 |
+
|
| 841 |
+
sinh, cosh, acoth
|
| 842 |
+
"""
|
| 843 |
+
|
| 844 |
+
def fdiff(self, argindex=1):
|
| 845 |
+
if argindex == 1:
|
| 846 |
+
return -1/sinh(self.args[0])**2
|
| 847 |
+
else:
|
| 848 |
+
raise ArgumentIndexError(self, argindex)
|
| 849 |
+
|
| 850 |
+
def inverse(self, argindex=1):
|
| 851 |
+
"""
|
| 852 |
+
Returns the inverse of this function.
|
| 853 |
+
"""
|
| 854 |
+
return acoth
|
| 855 |
+
|
| 856 |
+
@classmethod
|
| 857 |
+
def eval(cls, arg):
|
| 858 |
+
if arg.is_Number:
|
| 859 |
+
if arg is S.NaN:
|
| 860 |
+
return S.NaN
|
| 861 |
+
elif arg is S.Infinity:
|
| 862 |
+
return S.One
|
| 863 |
+
elif arg is S.NegativeInfinity:
|
| 864 |
+
return S.NegativeOne
|
| 865 |
+
elif arg.is_zero:
|
| 866 |
+
return S.ComplexInfinity
|
| 867 |
+
elif arg.is_negative:
|
| 868 |
+
return -cls(-arg)
|
| 869 |
+
else:
|
| 870 |
+
if arg is S.ComplexInfinity:
|
| 871 |
+
return S.NaN
|
| 872 |
+
|
| 873 |
+
i_coeff = _imaginary_unit_as_coefficient(arg)
|
| 874 |
+
|
| 875 |
+
if i_coeff is not None:
|
| 876 |
+
if i_coeff.could_extract_minus_sign():
|
| 877 |
+
return I * cot(-i_coeff)
|
| 878 |
+
return -I * cot(i_coeff)
|
| 879 |
+
else:
|
| 880 |
+
if arg.could_extract_minus_sign():
|
| 881 |
+
return -cls(-arg)
|
| 882 |
+
|
| 883 |
+
if arg.is_Add:
|
| 884 |
+
x, m = _peeloff_ipi(arg)
|
| 885 |
+
if m:
|
| 886 |
+
cothm = coth(m*pi*I)
|
| 887 |
+
if cothm is S.ComplexInfinity:
|
| 888 |
+
return coth(x)
|
| 889 |
+
else: # cothm == 0
|
| 890 |
+
return tanh(x)
|
| 891 |
+
|
| 892 |
+
if arg.is_zero:
|
| 893 |
+
return S.ComplexInfinity
|
| 894 |
+
|
| 895 |
+
if arg.func == asinh:
|
| 896 |
+
x = arg.args[0]
|
| 897 |
+
return sqrt(1 + x**2)/x
|
| 898 |
+
|
| 899 |
+
if arg.func == acosh:
|
| 900 |
+
x = arg.args[0]
|
| 901 |
+
return x/(sqrt(x - 1) * sqrt(x + 1))
|
| 902 |
+
|
| 903 |
+
if arg.func == atanh:
|
| 904 |
+
return 1/arg.args[0]
|
| 905 |
+
|
| 906 |
+
if arg.func == acoth:
|
| 907 |
+
return arg.args[0]
|
| 908 |
+
|
| 909 |
+
@staticmethod
|
| 910 |
+
@cacheit
|
| 911 |
+
def taylor_term(n, x, *previous_terms):
|
| 912 |
+
if n == 0:
|
| 913 |
+
return 1 / sympify(x)
|
| 914 |
+
elif n < 0 or n % 2 == 0:
|
| 915 |
+
return S.Zero
|
| 916 |
+
else:
|
| 917 |
+
x = sympify(x)
|
| 918 |
+
|
| 919 |
+
B = bernoulli(n + 1)
|
| 920 |
+
F = factorial(n + 1)
|
| 921 |
+
|
| 922 |
+
return 2**(n + 1) * B/F * x**n
|
| 923 |
+
|
| 924 |
+
def _eval_conjugate(self):
|
| 925 |
+
return self.func(self.args[0].conjugate())
|
| 926 |
+
|
| 927 |
+
def as_real_imag(self, deep=True, **hints):
|
| 928 |
+
from sympy.functions.elementary.trigonometric import (cos, sin)
|
| 929 |
+
if self.args[0].is_extended_real:
|
| 930 |
+
if deep:
|
| 931 |
+
hints['complex'] = False
|
| 932 |
+
return (self.expand(deep, **hints), S.Zero)
|
| 933 |
+
else:
|
| 934 |
+
return (self, S.Zero)
|
| 935 |
+
if deep:
|
| 936 |
+
re, im = self.args[0].expand(deep, **hints).as_real_imag()
|
| 937 |
+
else:
|
| 938 |
+
re, im = self.args[0].as_real_imag()
|
| 939 |
+
denom = sinh(re)**2 + sin(im)**2
|
| 940 |
+
return (sinh(re)*cosh(re)/denom, -sin(im)*cos(im)/denom)
|
| 941 |
+
|
| 942 |
+
def _eval_rewrite_as_tractable(self, arg, limitvar=None, **kwargs):
|
| 943 |
+
neg_exp, pos_exp = exp(-arg), exp(arg)
|
| 944 |
+
return (pos_exp + neg_exp)/(pos_exp - neg_exp)
|
| 945 |
+
|
| 946 |
+
def _eval_rewrite_as_exp(self, arg, **kwargs):
|
| 947 |
+
neg_exp, pos_exp = exp(-arg), exp(arg)
|
| 948 |
+
return (pos_exp + neg_exp)/(pos_exp - neg_exp)
|
| 949 |
+
|
| 950 |
+
def _eval_rewrite_as_sinh(self, arg, **kwargs):
|
| 951 |
+
return -I*sinh(pi*I/2 - arg, evaluate=False)/sinh(arg)
|
| 952 |
+
|
| 953 |
+
def _eval_rewrite_as_cosh(self, arg, **kwargs):
|
| 954 |
+
return -I*cosh(arg)/cosh(pi*I/2 - arg, evaluate=False)
|
| 955 |
+
|
| 956 |
+
def _eval_rewrite_as_tanh(self, arg, **kwargs):
|
| 957 |
+
return 1/tanh(arg)
|
| 958 |
+
|
| 959 |
+
def _eval_is_positive(self):
|
| 960 |
+
if self.args[0].is_extended_real:
|
| 961 |
+
return self.args[0].is_positive
|
| 962 |
+
|
| 963 |
+
def _eval_is_negative(self):
|
| 964 |
+
if self.args[0].is_extended_real:
|
| 965 |
+
return self.args[0].is_negative
|
| 966 |
+
|
| 967 |
+
def _eval_as_leading_term(self, x, logx=None, cdir=0):
|
| 968 |
+
from sympy.series.order import Order
|
| 969 |
+
arg = self.args[0].as_leading_term(x)
|
| 970 |
+
|
| 971 |
+
if x in arg.free_symbols and Order(1, x).contains(arg):
|
| 972 |
+
return 1/arg
|
| 973 |
+
else:
|
| 974 |
+
return self.func(arg)
|
| 975 |
+
|
| 976 |
+
def _eval_expand_trig(self, **hints):
|
| 977 |
+
arg = self.args[0]
|
| 978 |
+
if arg.is_Add:
|
| 979 |
+
CX = [coth(x, evaluate=False)._eval_expand_trig() for x in arg.args]
|
| 980 |
+
p = [[], []]
|
| 981 |
+
n = len(arg.args)
|
| 982 |
+
for i in range(n, -1, -1):
|
| 983 |
+
p[(n - i) % 2].append(symmetric_poly(i, CX))
|
| 984 |
+
return Add(*p[0])/Add(*p[1])
|
| 985 |
+
elif arg.is_Mul:
|
| 986 |
+
coeff, x = arg.as_coeff_Mul(rational=True)
|
| 987 |
+
if coeff.is_Integer and coeff > 1:
|
| 988 |
+
c = coth(x, evaluate=False)
|
| 989 |
+
p = [[], []]
|
| 990 |
+
for i in range(coeff, -1, -1):
|
| 991 |
+
p[(coeff - i) % 2].append(binomial(coeff, i)*c**i)
|
| 992 |
+
return Add(*p[0])/Add(*p[1])
|
| 993 |
+
return coth(arg)
|
| 994 |
+
|
| 995 |
+
|
| 996 |
+
class ReciprocalHyperbolicFunction(HyperbolicFunction):
|
| 997 |
+
"""Base class for reciprocal functions of hyperbolic functions. """
|
| 998 |
+
|
| 999 |
+
#To be defined in class
|
| 1000 |
+
_reciprocal_of = None
|
| 1001 |
+
_is_even: FuzzyBool = None
|
| 1002 |
+
_is_odd: FuzzyBool = None
|
| 1003 |
+
|
| 1004 |
+
@classmethod
|
| 1005 |
+
def eval(cls, arg):
|
| 1006 |
+
if arg.could_extract_minus_sign():
|
| 1007 |
+
if cls._is_even:
|
| 1008 |
+
return cls(-arg)
|
| 1009 |
+
if cls._is_odd:
|
| 1010 |
+
return -cls(-arg)
|
| 1011 |
+
|
| 1012 |
+
t = cls._reciprocal_of.eval(arg)
|
| 1013 |
+
if hasattr(arg, 'inverse') and arg.inverse() == cls:
|
| 1014 |
+
return arg.args[0]
|
| 1015 |
+
return 1/t if t is not None else t
|
| 1016 |
+
|
| 1017 |
+
def _call_reciprocal(self, method_name, *args, **kwargs):
|
| 1018 |
+
# Calls method_name on _reciprocal_of
|
| 1019 |
+
o = self._reciprocal_of(self.args[0])
|
| 1020 |
+
return getattr(o, method_name)(*args, **kwargs)
|
| 1021 |
+
|
| 1022 |
+
def _calculate_reciprocal(self, method_name, *args, **kwargs):
|
| 1023 |
+
# If calling method_name on _reciprocal_of returns a value != None
|
| 1024 |
+
# then return the reciprocal of that value
|
| 1025 |
+
t = self._call_reciprocal(method_name, *args, **kwargs)
|
| 1026 |
+
return 1/t if t is not None else t
|
| 1027 |
+
|
| 1028 |
+
def _rewrite_reciprocal(self, method_name, arg):
|
| 1029 |
+
# Special handling for rewrite functions. If reciprocal rewrite returns
|
| 1030 |
+
# unmodified expression, then return None
|
| 1031 |
+
t = self._call_reciprocal(method_name, arg)
|
| 1032 |
+
if t is not None and t != self._reciprocal_of(arg):
|
| 1033 |
+
return 1/t
|
| 1034 |
+
|
| 1035 |
+
def _eval_rewrite_as_exp(self, arg, **kwargs):
|
| 1036 |
+
return self._rewrite_reciprocal("_eval_rewrite_as_exp", arg)
|
| 1037 |
+
|
| 1038 |
+
def _eval_rewrite_as_tractable(self, arg, limitvar=None, **kwargs):
|
| 1039 |
+
return self._rewrite_reciprocal("_eval_rewrite_as_tractable", arg)
|
| 1040 |
+
|
| 1041 |
+
def _eval_rewrite_as_tanh(self, arg, **kwargs):
|
| 1042 |
+
return self._rewrite_reciprocal("_eval_rewrite_as_tanh", arg)
|
| 1043 |
+
|
| 1044 |
+
def _eval_rewrite_as_coth(self, arg, **kwargs):
|
| 1045 |
+
return self._rewrite_reciprocal("_eval_rewrite_as_coth", arg)
|
| 1046 |
+
|
| 1047 |
+
def as_real_imag(self, deep = True, **hints):
|
| 1048 |
+
return (1 / self._reciprocal_of(self.args[0])).as_real_imag(deep, **hints)
|
| 1049 |
+
|
| 1050 |
+
def _eval_conjugate(self):
|
| 1051 |
+
return self.func(self.args[0].conjugate())
|
| 1052 |
+
|
| 1053 |
+
def _eval_expand_complex(self, deep=True, **hints):
|
| 1054 |
+
re_part, im_part = self.as_real_imag(deep=True, **hints)
|
| 1055 |
+
return re_part + I*im_part
|
| 1056 |
+
|
| 1057 |
+
def _eval_expand_trig(self, **hints):
|
| 1058 |
+
return self._calculate_reciprocal("_eval_expand_trig", **hints)
|
| 1059 |
+
|
| 1060 |
+
def _eval_as_leading_term(self, x, logx=None, cdir=0):
|
| 1061 |
+
return (1/self._reciprocal_of(self.args[0]))._eval_as_leading_term(x)
|
| 1062 |
+
|
| 1063 |
+
def _eval_is_extended_real(self):
|
| 1064 |
+
return self._reciprocal_of(self.args[0]).is_extended_real
|
| 1065 |
+
|
| 1066 |
+
def _eval_is_finite(self):
|
| 1067 |
+
return (1/self._reciprocal_of(self.args[0])).is_finite
|
| 1068 |
+
|
| 1069 |
+
|
| 1070 |
+
class csch(ReciprocalHyperbolicFunction):
|
| 1071 |
+
r"""
|
| 1072 |
+
``csch(x)`` is the hyperbolic cosecant of ``x``.
|
| 1073 |
+
|
| 1074 |
+
The hyperbolic cosecant function is $\frac{2}{e^x - e^{-x}}$
|
| 1075 |
+
|
| 1076 |
+
Examples
|
| 1077 |
+
========
|
| 1078 |
+
|
| 1079 |
+
>>> from sympy import csch
|
| 1080 |
+
>>> from sympy.abc import x
|
| 1081 |
+
>>> csch(x)
|
| 1082 |
+
csch(x)
|
| 1083 |
+
|
| 1084 |
+
See Also
|
| 1085 |
+
========
|
| 1086 |
+
|
| 1087 |
+
sinh, cosh, tanh, sech, asinh, acosh
|
| 1088 |
+
"""
|
| 1089 |
+
|
| 1090 |
+
_reciprocal_of = sinh
|
| 1091 |
+
_is_odd = True
|
| 1092 |
+
|
| 1093 |
+
def fdiff(self, argindex=1):
|
| 1094 |
+
"""
|
| 1095 |
+
Returns the first derivative of this function
|
| 1096 |
+
"""
|
| 1097 |
+
if argindex == 1:
|
| 1098 |
+
return -coth(self.args[0]) * csch(self.args[0])
|
| 1099 |
+
else:
|
| 1100 |
+
raise ArgumentIndexError(self, argindex)
|
| 1101 |
+
|
| 1102 |
+
@staticmethod
|
| 1103 |
+
@cacheit
|
| 1104 |
+
def taylor_term(n, x, *previous_terms):
|
| 1105 |
+
"""
|
| 1106 |
+
Returns the next term in the Taylor series expansion
|
| 1107 |
+
"""
|
| 1108 |
+
if n == 0:
|
| 1109 |
+
return 1/sympify(x)
|
| 1110 |
+
elif n < 0 or n % 2 == 0:
|
| 1111 |
+
return S.Zero
|
| 1112 |
+
else:
|
| 1113 |
+
x = sympify(x)
|
| 1114 |
+
|
| 1115 |
+
B = bernoulli(n + 1)
|
| 1116 |
+
F = factorial(n + 1)
|
| 1117 |
+
|
| 1118 |
+
return 2 * (1 - 2**n) * B/F * x**n
|
| 1119 |
+
|
| 1120 |
+
def _eval_rewrite_as_sin(self, arg, **kwargs):
|
| 1121 |
+
return I / sin(I * arg, evaluate=False)
|
| 1122 |
+
|
| 1123 |
+
def _eval_rewrite_as_csc(self, arg, **kwargs):
|
| 1124 |
+
return I * csc(I * arg, evaluate=False)
|
| 1125 |
+
|
| 1126 |
+
def _eval_rewrite_as_cosh(self, arg, **kwargs):
|
| 1127 |
+
return I / cosh(arg + I * pi / 2, evaluate=False)
|
| 1128 |
+
|
| 1129 |
+
def _eval_rewrite_as_sinh(self, arg, **kwargs):
|
| 1130 |
+
return 1 / sinh(arg)
|
| 1131 |
+
|
| 1132 |
+
def _eval_is_positive(self):
|
| 1133 |
+
if self.args[0].is_extended_real:
|
| 1134 |
+
return self.args[0].is_positive
|
| 1135 |
+
|
| 1136 |
+
def _eval_is_negative(self):
|
| 1137 |
+
if self.args[0].is_extended_real:
|
| 1138 |
+
return self.args[0].is_negative
|
| 1139 |
+
|
| 1140 |
+
|
| 1141 |
+
class sech(ReciprocalHyperbolicFunction):
|
| 1142 |
+
r"""
|
| 1143 |
+
``sech(x)`` is the hyperbolic secant of ``x``.
|
| 1144 |
+
|
| 1145 |
+
The hyperbolic secant function is $\frac{2}{e^x + e^{-x}}$
|
| 1146 |
+
|
| 1147 |
+
Examples
|
| 1148 |
+
========
|
| 1149 |
+
|
| 1150 |
+
>>> from sympy import sech
|
| 1151 |
+
>>> from sympy.abc import x
|
| 1152 |
+
>>> sech(x)
|
| 1153 |
+
sech(x)
|
| 1154 |
+
|
| 1155 |
+
See Also
|
| 1156 |
+
========
|
| 1157 |
+
|
| 1158 |
+
sinh, cosh, tanh, coth, csch, asinh, acosh
|
| 1159 |
+
"""
|
| 1160 |
+
|
| 1161 |
+
_reciprocal_of = cosh
|
| 1162 |
+
_is_even = True
|
| 1163 |
+
|
| 1164 |
+
def fdiff(self, argindex=1):
|
| 1165 |
+
if argindex == 1:
|
| 1166 |
+
return - tanh(self.args[0])*sech(self.args[0])
|
| 1167 |
+
else:
|
| 1168 |
+
raise ArgumentIndexError(self, argindex)
|
| 1169 |
+
|
| 1170 |
+
@staticmethod
|
| 1171 |
+
@cacheit
|
| 1172 |
+
def taylor_term(n, x, *previous_terms):
|
| 1173 |
+
if n < 0 or n % 2 == 1:
|
| 1174 |
+
return S.Zero
|
| 1175 |
+
else:
|
| 1176 |
+
x = sympify(x)
|
| 1177 |
+
return euler(n) / factorial(n) * x**(n)
|
| 1178 |
+
|
| 1179 |
+
def _eval_rewrite_as_cos(self, arg, **kwargs):
|
| 1180 |
+
return 1 / cos(I * arg, evaluate=False)
|
| 1181 |
+
|
| 1182 |
+
def _eval_rewrite_as_sec(self, arg, **kwargs):
|
| 1183 |
+
return sec(I * arg, evaluate=False)
|
| 1184 |
+
|
| 1185 |
+
def _eval_rewrite_as_sinh(self, arg, **kwargs):
|
| 1186 |
+
return I / sinh(arg + I * pi /2, evaluate=False)
|
| 1187 |
+
|
| 1188 |
+
def _eval_rewrite_as_cosh(self, arg, **kwargs):
|
| 1189 |
+
return 1 / cosh(arg)
|
| 1190 |
+
|
| 1191 |
+
def _eval_is_positive(self):
|
| 1192 |
+
if self.args[0].is_extended_real:
|
| 1193 |
+
return True
|
| 1194 |
+
|
| 1195 |
+
|
| 1196 |
+
###############################################################################
|
| 1197 |
+
############################# HYPERBOLIC INVERSES #############################
|
| 1198 |
+
###############################################################################
|
| 1199 |
+
|
| 1200 |
+
class InverseHyperbolicFunction(Function):
|
| 1201 |
+
"""Base class for inverse hyperbolic functions."""
|
| 1202 |
+
|
| 1203 |
+
pass
|
| 1204 |
+
|
| 1205 |
+
|
| 1206 |
+
class asinh(InverseHyperbolicFunction):
|
| 1207 |
+
"""
|
| 1208 |
+
``asinh(x)`` is the inverse hyperbolic sine of ``x``.
|
| 1209 |
+
|
| 1210 |
+
The inverse hyperbolic sine function.
|
| 1211 |
+
|
| 1212 |
+
Examples
|
| 1213 |
+
========
|
| 1214 |
+
|
| 1215 |
+
>>> from sympy import asinh
|
| 1216 |
+
>>> from sympy.abc import x
|
| 1217 |
+
>>> asinh(x).diff(x)
|
| 1218 |
+
1/sqrt(x**2 + 1)
|
| 1219 |
+
>>> asinh(1)
|
| 1220 |
+
log(1 + sqrt(2))
|
| 1221 |
+
|
| 1222 |
+
See Also
|
| 1223 |
+
========
|
| 1224 |
+
|
| 1225 |
+
acosh, atanh, sinh
|
| 1226 |
+
"""
|
| 1227 |
+
|
| 1228 |
+
def fdiff(self, argindex=1):
|
| 1229 |
+
if argindex == 1:
|
| 1230 |
+
return 1/sqrt(self.args[0]**2 + 1)
|
| 1231 |
+
else:
|
| 1232 |
+
raise ArgumentIndexError(self, argindex)
|
| 1233 |
+
|
| 1234 |
+
@classmethod
|
| 1235 |
+
def eval(cls, arg):
|
| 1236 |
+
if arg.is_Number:
|
| 1237 |
+
if arg is S.NaN:
|
| 1238 |
+
return S.NaN
|
| 1239 |
+
elif arg is S.Infinity:
|
| 1240 |
+
return S.Infinity
|
| 1241 |
+
elif arg is S.NegativeInfinity:
|
| 1242 |
+
return S.NegativeInfinity
|
| 1243 |
+
elif arg.is_zero:
|
| 1244 |
+
return S.Zero
|
| 1245 |
+
elif arg is S.One:
|
| 1246 |
+
return log(sqrt(2) + 1)
|
| 1247 |
+
elif arg is S.NegativeOne:
|
| 1248 |
+
return log(sqrt(2) - 1)
|
| 1249 |
+
elif arg.is_negative:
|
| 1250 |
+
return -cls(-arg)
|
| 1251 |
+
else:
|
| 1252 |
+
if arg is S.ComplexInfinity:
|
| 1253 |
+
return S.ComplexInfinity
|
| 1254 |
+
|
| 1255 |
+
if arg.is_zero:
|
| 1256 |
+
return S.Zero
|
| 1257 |
+
|
| 1258 |
+
i_coeff = _imaginary_unit_as_coefficient(arg)
|
| 1259 |
+
|
| 1260 |
+
if i_coeff is not None:
|
| 1261 |
+
return I * asin(i_coeff)
|
| 1262 |
+
else:
|
| 1263 |
+
if arg.could_extract_minus_sign():
|
| 1264 |
+
return -cls(-arg)
|
| 1265 |
+
|
| 1266 |
+
if isinstance(arg, sinh) and arg.args[0].is_number:
|
| 1267 |
+
z = arg.args[0]
|
| 1268 |
+
if z.is_real:
|
| 1269 |
+
return z
|
| 1270 |
+
r, i = match_real_imag(z)
|
| 1271 |
+
if r is not None and i is not None:
|
| 1272 |
+
f = floor((i + pi/2)/pi)
|
| 1273 |
+
m = z - I*pi*f
|
| 1274 |
+
even = f.is_even
|
| 1275 |
+
if even is True:
|
| 1276 |
+
return m
|
| 1277 |
+
elif even is False:
|
| 1278 |
+
return -m
|
| 1279 |
+
|
| 1280 |
+
@staticmethod
|
| 1281 |
+
@cacheit
|
| 1282 |
+
def taylor_term(n, x, *previous_terms):
|
| 1283 |
+
if n < 0 or n % 2 == 0:
|
| 1284 |
+
return S.Zero
|
| 1285 |
+
else:
|
| 1286 |
+
x = sympify(x)
|
| 1287 |
+
if len(previous_terms) >= 2 and n > 2:
|
| 1288 |
+
p = previous_terms[-2]
|
| 1289 |
+
return -p * (n - 2)**2/(n*(n - 1)) * x**2
|
| 1290 |
+
else:
|
| 1291 |
+
k = (n - 1) // 2
|
| 1292 |
+
R = RisingFactorial(S.Half, k)
|
| 1293 |
+
F = factorial(k)
|
| 1294 |
+
return S.NegativeOne**k * R / F * x**n / n
|
| 1295 |
+
|
| 1296 |
+
def _eval_as_leading_term(self, x, logx=None, cdir=0): # asinh
|
| 1297 |
+
arg = self.args[0]
|
| 1298 |
+
x0 = arg.subs(x, 0).cancel()
|
| 1299 |
+
if x0.is_zero:
|
| 1300 |
+
return arg.as_leading_term(x)
|
| 1301 |
+
|
| 1302 |
+
if x0 is S.NaN:
|
| 1303 |
+
expr = self.func(arg.as_leading_term(x))
|
| 1304 |
+
if expr.is_finite:
|
| 1305 |
+
return expr
|
| 1306 |
+
else:
|
| 1307 |
+
return self
|
| 1308 |
+
|
| 1309 |
+
# Handling branch points
|
| 1310 |
+
if x0 in (-I, I, S.ComplexInfinity):
|
| 1311 |
+
return self.rewrite(log)._eval_as_leading_term(x, logx=logx, cdir=cdir)
|
| 1312 |
+
# Handling points lying on branch cuts (-I*oo, -I) U (I, I*oo)
|
| 1313 |
+
if (1 + x0**2).is_negative:
|
| 1314 |
+
ndir = arg.dir(x, cdir if cdir else 1)
|
| 1315 |
+
if re(ndir).is_positive:
|
| 1316 |
+
if im(x0).is_negative:
|
| 1317 |
+
return -self.func(x0) - I*pi
|
| 1318 |
+
elif re(ndir).is_negative:
|
| 1319 |
+
if im(x0).is_positive:
|
| 1320 |
+
return -self.func(x0) + I*pi
|
| 1321 |
+
else:
|
| 1322 |
+
return self.rewrite(log)._eval_as_leading_term(x, logx=logx, cdir=cdir)
|
| 1323 |
+
return self.func(x0)
|
| 1324 |
+
|
| 1325 |
+
def _eval_nseries(self, x, n, logx, cdir=0): # asinh
|
| 1326 |
+
arg = self.args[0]
|
| 1327 |
+
arg0 = arg.subs(x, 0)
|
| 1328 |
+
|
| 1329 |
+
# Handling branch points
|
| 1330 |
+
if arg0 in (I, -I):
|
| 1331 |
+
return self.rewrite(log)._eval_nseries(x, n, logx=logx, cdir=cdir)
|
| 1332 |
+
|
| 1333 |
+
res = Function._eval_nseries(self, x, n=n, logx=logx)
|
| 1334 |
+
if arg0 is S.ComplexInfinity:
|
| 1335 |
+
return res
|
| 1336 |
+
|
| 1337 |
+
# Handling points lying on branch cuts (-I*oo, -I) U (I, I*oo)
|
| 1338 |
+
if (1 + arg0**2).is_negative:
|
| 1339 |
+
ndir = arg.dir(x, cdir if cdir else 1)
|
| 1340 |
+
if re(ndir).is_positive:
|
| 1341 |
+
if im(arg0).is_negative:
|
| 1342 |
+
return -res - I*pi
|
| 1343 |
+
elif re(ndir).is_negative:
|
| 1344 |
+
if im(arg0).is_positive:
|
| 1345 |
+
return -res + I*pi
|
| 1346 |
+
else:
|
| 1347 |
+
return self.rewrite(log)._eval_nseries(x, n, logx=logx, cdir=cdir)
|
| 1348 |
+
return res
|
| 1349 |
+
|
| 1350 |
+
def _eval_rewrite_as_log(self, x, **kwargs):
|
| 1351 |
+
return log(x + sqrt(x**2 + 1))
|
| 1352 |
+
|
| 1353 |
+
_eval_rewrite_as_tractable = _eval_rewrite_as_log
|
| 1354 |
+
|
| 1355 |
+
def _eval_rewrite_as_atanh(self, x, **kwargs):
|
| 1356 |
+
return atanh(x/sqrt(1 + x**2))
|
| 1357 |
+
|
| 1358 |
+
def _eval_rewrite_as_acosh(self, x, **kwargs):
|
| 1359 |
+
ix = I*x
|
| 1360 |
+
return I*(sqrt(1 - ix)/sqrt(ix - 1) * acosh(ix) - pi/2)
|
| 1361 |
+
|
| 1362 |
+
def _eval_rewrite_as_asin(self, x, **kwargs):
|
| 1363 |
+
return -I * asin(I * x, evaluate=False)
|
| 1364 |
+
|
| 1365 |
+
def _eval_rewrite_as_acos(self, x, **kwargs):
|
| 1366 |
+
return I * acos(I * x, evaluate=False) - I*pi/2
|
| 1367 |
+
|
| 1368 |
+
def inverse(self, argindex=1):
|
| 1369 |
+
"""
|
| 1370 |
+
Returns the inverse of this function.
|
| 1371 |
+
"""
|
| 1372 |
+
return sinh
|
| 1373 |
+
|
| 1374 |
+
def _eval_is_zero(self):
|
| 1375 |
+
return self.args[0].is_zero
|
| 1376 |
+
|
| 1377 |
+
def _eval_is_extended_real(self):
|
| 1378 |
+
return self.args[0].is_extended_real
|
| 1379 |
+
|
| 1380 |
+
def _eval_is_finite(self):
|
| 1381 |
+
return self.args[0].is_finite
|
| 1382 |
+
|
| 1383 |
+
|
| 1384 |
+
class acosh(InverseHyperbolicFunction):
|
| 1385 |
+
"""
|
| 1386 |
+
``acosh(x)`` is the inverse hyperbolic cosine of ``x``.
|
| 1387 |
+
|
| 1388 |
+
The inverse hyperbolic cosine function.
|
| 1389 |
+
|
| 1390 |
+
Examples
|
| 1391 |
+
========
|
| 1392 |
+
|
| 1393 |
+
>>> from sympy import acosh
|
| 1394 |
+
>>> from sympy.abc import x
|
| 1395 |
+
>>> acosh(x).diff(x)
|
| 1396 |
+
1/(sqrt(x - 1)*sqrt(x + 1))
|
| 1397 |
+
>>> acosh(1)
|
| 1398 |
+
0
|
| 1399 |
+
|
| 1400 |
+
See Also
|
| 1401 |
+
========
|
| 1402 |
+
|
| 1403 |
+
asinh, atanh, cosh
|
| 1404 |
+
"""
|
| 1405 |
+
|
| 1406 |
+
def fdiff(self, argindex=1):
|
| 1407 |
+
if argindex == 1:
|
| 1408 |
+
arg = self.args[0]
|
| 1409 |
+
return 1/(sqrt(arg - 1)*sqrt(arg + 1))
|
| 1410 |
+
else:
|
| 1411 |
+
raise ArgumentIndexError(self, argindex)
|
| 1412 |
+
|
| 1413 |
+
@classmethod
|
| 1414 |
+
def eval(cls, arg):
|
| 1415 |
+
if arg.is_Number:
|
| 1416 |
+
if arg is S.NaN:
|
| 1417 |
+
return S.NaN
|
| 1418 |
+
elif arg is S.Infinity:
|
| 1419 |
+
return S.Infinity
|
| 1420 |
+
elif arg is S.NegativeInfinity:
|
| 1421 |
+
return S.Infinity
|
| 1422 |
+
elif arg.is_zero:
|
| 1423 |
+
return pi*I / 2
|
| 1424 |
+
elif arg is S.One:
|
| 1425 |
+
return S.Zero
|
| 1426 |
+
elif arg is S.NegativeOne:
|
| 1427 |
+
return pi*I
|
| 1428 |
+
|
| 1429 |
+
if arg.is_number:
|
| 1430 |
+
cst_table = _acosh_table()
|
| 1431 |
+
|
| 1432 |
+
if arg in cst_table:
|
| 1433 |
+
if arg.is_extended_real:
|
| 1434 |
+
return cst_table[arg]*I
|
| 1435 |
+
return cst_table[arg]
|
| 1436 |
+
|
| 1437 |
+
if arg is S.ComplexInfinity:
|
| 1438 |
+
return S.ComplexInfinity
|
| 1439 |
+
if arg == I*S.Infinity:
|
| 1440 |
+
return S.Infinity + I*pi/2
|
| 1441 |
+
if arg == -I*S.Infinity:
|
| 1442 |
+
return S.Infinity - I*pi/2
|
| 1443 |
+
|
| 1444 |
+
if arg.is_zero:
|
| 1445 |
+
return pi*I*S.Half
|
| 1446 |
+
|
| 1447 |
+
if isinstance(arg, cosh) and arg.args[0].is_number:
|
| 1448 |
+
z = arg.args[0]
|
| 1449 |
+
if z.is_real:
|
| 1450 |
+
return Abs(z)
|
| 1451 |
+
r, i = match_real_imag(z)
|
| 1452 |
+
if r is not None and i is not None:
|
| 1453 |
+
f = floor(i/pi)
|
| 1454 |
+
m = z - I*pi*f
|
| 1455 |
+
even = f.is_even
|
| 1456 |
+
if even is True:
|
| 1457 |
+
if r.is_nonnegative:
|
| 1458 |
+
return m
|
| 1459 |
+
elif r.is_negative:
|
| 1460 |
+
return -m
|
| 1461 |
+
elif even is False:
|
| 1462 |
+
m -= I*pi
|
| 1463 |
+
if r.is_nonpositive:
|
| 1464 |
+
return -m
|
| 1465 |
+
elif r.is_positive:
|
| 1466 |
+
return m
|
| 1467 |
+
|
| 1468 |
+
@staticmethod
|
| 1469 |
+
@cacheit
|
| 1470 |
+
def taylor_term(n, x, *previous_terms):
|
| 1471 |
+
if n == 0:
|
| 1472 |
+
return I*pi/2
|
| 1473 |
+
elif n < 0 or n % 2 == 0:
|
| 1474 |
+
return S.Zero
|
| 1475 |
+
else:
|
| 1476 |
+
x = sympify(x)
|
| 1477 |
+
if len(previous_terms) >= 2 and n > 2:
|
| 1478 |
+
p = previous_terms[-2]
|
| 1479 |
+
return p * (n - 2)**2/(n*(n - 1)) * x**2
|
| 1480 |
+
else:
|
| 1481 |
+
k = (n - 1) // 2
|
| 1482 |
+
R = RisingFactorial(S.Half, k)
|
| 1483 |
+
F = factorial(k)
|
| 1484 |
+
return -R / F * I * x**n / n
|
| 1485 |
+
|
| 1486 |
+
def _eval_as_leading_term(self, x, logx=None, cdir=0): # acosh
|
| 1487 |
+
arg = self.args[0]
|
| 1488 |
+
x0 = arg.subs(x, 0).cancel()
|
| 1489 |
+
# Handling branch points
|
| 1490 |
+
if x0 in (-S.One, S.Zero, S.One, S.ComplexInfinity):
|
| 1491 |
+
return self.rewrite(log)._eval_as_leading_term(x, logx=logx, cdir=cdir)
|
| 1492 |
+
|
| 1493 |
+
if x0 is S.NaN:
|
| 1494 |
+
expr = self.func(arg.as_leading_term(x))
|
| 1495 |
+
if expr.is_finite:
|
| 1496 |
+
return expr
|
| 1497 |
+
else:
|
| 1498 |
+
return self
|
| 1499 |
+
|
| 1500 |
+
# Handling points lying on branch cuts (-oo, 1)
|
| 1501 |
+
if (x0 - 1).is_negative:
|
| 1502 |
+
ndir = arg.dir(x, cdir if cdir else 1)
|
| 1503 |
+
if im(ndir).is_negative:
|
| 1504 |
+
if (x0 + 1).is_negative:
|
| 1505 |
+
return self.func(x0) - 2*I*pi
|
| 1506 |
+
return -self.func(x0)
|
| 1507 |
+
elif not im(ndir).is_positive:
|
| 1508 |
+
return self.rewrite(log)._eval_as_leading_term(x, logx=logx, cdir=cdir)
|
| 1509 |
+
return self.func(x0)
|
| 1510 |
+
|
| 1511 |
+
def _eval_nseries(self, x, n, logx, cdir=0): # acosh
|
| 1512 |
+
arg = self.args[0]
|
| 1513 |
+
arg0 = arg.subs(x, 0)
|
| 1514 |
+
|
| 1515 |
+
# Handling branch points
|
| 1516 |
+
if arg0 in (S.One, S.NegativeOne):
|
| 1517 |
+
return self.rewrite(log)._eval_nseries(x, n, logx=logx, cdir=cdir)
|
| 1518 |
+
|
| 1519 |
+
res = Function._eval_nseries(self, x, n=n, logx=logx)
|
| 1520 |
+
if arg0 is S.ComplexInfinity:
|
| 1521 |
+
return res
|
| 1522 |
+
|
| 1523 |
+
# Handling points lying on branch cuts (-oo, 1)
|
| 1524 |
+
if (arg0 - 1).is_negative:
|
| 1525 |
+
ndir = arg.dir(x, cdir if cdir else 1)
|
| 1526 |
+
if im(ndir).is_negative:
|
| 1527 |
+
if (arg0 + 1).is_negative:
|
| 1528 |
+
return res - 2*I*pi
|
| 1529 |
+
return -res
|
| 1530 |
+
elif not im(ndir).is_positive:
|
| 1531 |
+
return self.rewrite(log)._eval_nseries(x, n, logx=logx, cdir=cdir)
|
| 1532 |
+
return res
|
| 1533 |
+
|
| 1534 |
+
def _eval_rewrite_as_log(self, x, **kwargs):
|
| 1535 |
+
return log(x + sqrt(x + 1) * sqrt(x - 1))
|
| 1536 |
+
|
| 1537 |
+
_eval_rewrite_as_tractable = _eval_rewrite_as_log
|
| 1538 |
+
|
| 1539 |
+
def _eval_rewrite_as_acos(self, x, **kwargs):
|
| 1540 |
+
return sqrt(x - 1)/sqrt(1 - x) * acos(x)
|
| 1541 |
+
|
| 1542 |
+
def _eval_rewrite_as_asin(self, x, **kwargs):
|
| 1543 |
+
return sqrt(x - 1)/sqrt(1 - x) * (pi/2 - asin(x))
|
| 1544 |
+
|
| 1545 |
+
def _eval_rewrite_as_asinh(self, x, **kwargs):
|
| 1546 |
+
return sqrt(x - 1)/sqrt(1 - x) * (pi/2 + I*asinh(I*x, evaluate=False))
|
| 1547 |
+
|
| 1548 |
+
def _eval_rewrite_as_atanh(self, x, **kwargs):
|
| 1549 |
+
sxm1 = sqrt(x - 1)
|
| 1550 |
+
s1mx = sqrt(1 - x)
|
| 1551 |
+
sx2m1 = sqrt(x**2 - 1)
|
| 1552 |
+
return (pi/2*sxm1/s1mx*(1 - x * sqrt(1/x**2)) +
|
| 1553 |
+
sxm1*sqrt(x + 1)/sx2m1 * atanh(sx2m1/x))
|
| 1554 |
+
|
| 1555 |
+
def inverse(self, argindex=1):
|
| 1556 |
+
"""
|
| 1557 |
+
Returns the inverse of this function.
|
| 1558 |
+
"""
|
| 1559 |
+
return cosh
|
| 1560 |
+
|
| 1561 |
+
def _eval_is_zero(self):
|
| 1562 |
+
if (self.args[0] - 1).is_zero:
|
| 1563 |
+
return True
|
| 1564 |
+
|
| 1565 |
+
def _eval_is_extended_real(self):
|
| 1566 |
+
return fuzzy_and([self.args[0].is_extended_real, (self.args[0] - 1).is_extended_nonnegative])
|
| 1567 |
+
|
| 1568 |
+
def _eval_is_finite(self):
|
| 1569 |
+
return self.args[0].is_finite
|
| 1570 |
+
|
| 1571 |
+
|
| 1572 |
+
class atanh(InverseHyperbolicFunction):
|
| 1573 |
+
"""
|
| 1574 |
+
``atanh(x)`` is the inverse hyperbolic tangent of ``x``.
|
| 1575 |
+
|
| 1576 |
+
The inverse hyperbolic tangent function.
|
| 1577 |
+
|
| 1578 |
+
Examples
|
| 1579 |
+
========
|
| 1580 |
+
|
| 1581 |
+
>>> from sympy import atanh
|
| 1582 |
+
>>> from sympy.abc import x
|
| 1583 |
+
>>> atanh(x).diff(x)
|
| 1584 |
+
1/(1 - x**2)
|
| 1585 |
+
|
| 1586 |
+
See Also
|
| 1587 |
+
========
|
| 1588 |
+
|
| 1589 |
+
asinh, acosh, tanh
|
| 1590 |
+
"""
|
| 1591 |
+
|
| 1592 |
+
def fdiff(self, argindex=1):
|
| 1593 |
+
if argindex == 1:
|
| 1594 |
+
return 1/(1 - self.args[0]**2)
|
| 1595 |
+
else:
|
| 1596 |
+
raise ArgumentIndexError(self, argindex)
|
| 1597 |
+
|
| 1598 |
+
@classmethod
|
| 1599 |
+
def eval(cls, arg):
|
| 1600 |
+
if arg.is_Number:
|
| 1601 |
+
if arg is S.NaN:
|
| 1602 |
+
return S.NaN
|
| 1603 |
+
elif arg.is_zero:
|
| 1604 |
+
return S.Zero
|
| 1605 |
+
elif arg is S.One:
|
| 1606 |
+
return S.Infinity
|
| 1607 |
+
elif arg is S.NegativeOne:
|
| 1608 |
+
return S.NegativeInfinity
|
| 1609 |
+
elif arg is S.Infinity:
|
| 1610 |
+
return -I * atan(arg)
|
| 1611 |
+
elif arg is S.NegativeInfinity:
|
| 1612 |
+
return I * atan(-arg)
|
| 1613 |
+
elif arg.is_negative:
|
| 1614 |
+
return -cls(-arg)
|
| 1615 |
+
else:
|
| 1616 |
+
if arg is S.ComplexInfinity:
|
| 1617 |
+
from sympy.calculus.accumulationbounds import AccumBounds
|
| 1618 |
+
return I*AccumBounds(-pi/2, pi/2)
|
| 1619 |
+
|
| 1620 |
+
i_coeff = _imaginary_unit_as_coefficient(arg)
|
| 1621 |
+
|
| 1622 |
+
if i_coeff is not None:
|
| 1623 |
+
return I * atan(i_coeff)
|
| 1624 |
+
else:
|
| 1625 |
+
if arg.could_extract_minus_sign():
|
| 1626 |
+
return -cls(-arg)
|
| 1627 |
+
|
| 1628 |
+
if arg.is_zero:
|
| 1629 |
+
return S.Zero
|
| 1630 |
+
|
| 1631 |
+
if isinstance(arg, tanh) and arg.args[0].is_number:
|
| 1632 |
+
z = arg.args[0]
|
| 1633 |
+
if z.is_real:
|
| 1634 |
+
return z
|
| 1635 |
+
r, i = match_real_imag(z)
|
| 1636 |
+
if r is not None and i is not None:
|
| 1637 |
+
f = floor(2*i/pi)
|
| 1638 |
+
even = f.is_even
|
| 1639 |
+
m = z - I*f*pi/2
|
| 1640 |
+
if even is True:
|
| 1641 |
+
return m
|
| 1642 |
+
elif even is False:
|
| 1643 |
+
return m - I*pi/2
|
| 1644 |
+
|
| 1645 |
+
@staticmethod
|
| 1646 |
+
@cacheit
|
| 1647 |
+
def taylor_term(n, x, *previous_terms):
|
| 1648 |
+
if n < 0 or n % 2 == 0:
|
| 1649 |
+
return S.Zero
|
| 1650 |
+
else:
|
| 1651 |
+
x = sympify(x)
|
| 1652 |
+
return x**n / n
|
| 1653 |
+
|
| 1654 |
+
def _eval_as_leading_term(self, x, logx=None, cdir=0): # atanh
|
| 1655 |
+
arg = self.args[0]
|
| 1656 |
+
x0 = arg.subs(x, 0).cancel()
|
| 1657 |
+
if x0.is_zero:
|
| 1658 |
+
return arg.as_leading_term(x)
|
| 1659 |
+
if x0 is S.NaN:
|
| 1660 |
+
expr = self.func(arg.as_leading_term(x))
|
| 1661 |
+
if expr.is_finite:
|
| 1662 |
+
return expr
|
| 1663 |
+
else:
|
| 1664 |
+
return self
|
| 1665 |
+
|
| 1666 |
+
# Handling branch points
|
| 1667 |
+
if x0 in (-S.One, S.One, S.ComplexInfinity):
|
| 1668 |
+
return self.rewrite(log)._eval_as_leading_term(x, logx=logx, cdir=cdir)
|
| 1669 |
+
# Handling points lying on branch cuts (-oo, -1] U [1, oo)
|
| 1670 |
+
if (1 - x0**2).is_negative:
|
| 1671 |
+
ndir = arg.dir(x, cdir if cdir else 1)
|
| 1672 |
+
if im(ndir).is_negative:
|
| 1673 |
+
if x0.is_negative:
|
| 1674 |
+
return self.func(x0) - I*pi
|
| 1675 |
+
elif im(ndir).is_positive:
|
| 1676 |
+
if x0.is_positive:
|
| 1677 |
+
return self.func(x0) + I*pi
|
| 1678 |
+
else:
|
| 1679 |
+
return self.rewrite(log)._eval_as_leading_term(x, logx=logx, cdir=cdir)
|
| 1680 |
+
return self.func(x0)
|
| 1681 |
+
|
| 1682 |
+
def _eval_nseries(self, x, n, logx, cdir=0): # atanh
|
| 1683 |
+
arg = self.args[0]
|
| 1684 |
+
arg0 = arg.subs(x, 0)
|
| 1685 |
+
|
| 1686 |
+
# Handling branch points
|
| 1687 |
+
if arg0 in (S.One, S.NegativeOne):
|
| 1688 |
+
return self.rewrite(log)._eval_nseries(x, n, logx=logx, cdir=cdir)
|
| 1689 |
+
|
| 1690 |
+
res = Function._eval_nseries(self, x, n=n, logx=logx)
|
| 1691 |
+
if arg0 is S.ComplexInfinity:
|
| 1692 |
+
return res
|
| 1693 |
+
|
| 1694 |
+
# Handling points lying on branch cuts (-oo, -1] U [1, oo)
|
| 1695 |
+
if (1 - arg0**2).is_negative:
|
| 1696 |
+
ndir = arg.dir(x, cdir if cdir else 1)
|
| 1697 |
+
if im(ndir).is_negative:
|
| 1698 |
+
if arg0.is_negative:
|
| 1699 |
+
return res - I*pi
|
| 1700 |
+
elif im(ndir).is_positive:
|
| 1701 |
+
if arg0.is_positive:
|
| 1702 |
+
return res + I*pi
|
| 1703 |
+
else:
|
| 1704 |
+
return self.rewrite(log)._eval_nseries(x, n, logx=logx, cdir=cdir)
|
| 1705 |
+
return res
|
| 1706 |
+
|
| 1707 |
+
def _eval_rewrite_as_log(self, x, **kwargs):
|
| 1708 |
+
return (log(1 + x) - log(1 - x)) / 2
|
| 1709 |
+
|
| 1710 |
+
_eval_rewrite_as_tractable = _eval_rewrite_as_log
|
| 1711 |
+
|
| 1712 |
+
def _eval_rewrite_as_asinh(self, x, **kwargs):
|
| 1713 |
+
f = sqrt(1/(x**2 - 1))
|
| 1714 |
+
return (pi*x/(2*sqrt(-x**2)) -
|
| 1715 |
+
sqrt(-x)*sqrt(1 - x**2)/sqrt(x)*f*asinh(f))
|
| 1716 |
+
|
| 1717 |
+
def _eval_is_zero(self):
|
| 1718 |
+
if self.args[0].is_zero:
|
| 1719 |
+
return True
|
| 1720 |
+
|
| 1721 |
+
def _eval_is_extended_real(self):
|
| 1722 |
+
return fuzzy_and([self.args[0].is_extended_real, (1 - self.args[0]).is_nonnegative, (self.args[0] + 1).is_nonnegative])
|
| 1723 |
+
|
| 1724 |
+
def _eval_is_finite(self):
|
| 1725 |
+
return fuzzy_not(fuzzy_or([(self.args[0] - 1).is_zero, (self.args[0] + 1).is_zero]))
|
| 1726 |
+
|
| 1727 |
+
def _eval_is_imaginary(self):
|
| 1728 |
+
return self.args[0].is_imaginary
|
| 1729 |
+
|
| 1730 |
+
def inverse(self, argindex=1):
|
| 1731 |
+
"""
|
| 1732 |
+
Returns the inverse of this function.
|
| 1733 |
+
"""
|
| 1734 |
+
return tanh
|
| 1735 |
+
|
| 1736 |
+
|
| 1737 |
+
class acoth(InverseHyperbolicFunction):
|
| 1738 |
+
"""
|
| 1739 |
+
``acoth(x)`` is the inverse hyperbolic cotangent of ``x``.
|
| 1740 |
+
|
| 1741 |
+
The inverse hyperbolic cotangent function.
|
| 1742 |
+
|
| 1743 |
+
Examples
|
| 1744 |
+
========
|
| 1745 |
+
|
| 1746 |
+
>>> from sympy import acoth
|
| 1747 |
+
>>> from sympy.abc import x
|
| 1748 |
+
>>> acoth(x).diff(x)
|
| 1749 |
+
1/(1 - x**2)
|
| 1750 |
+
|
| 1751 |
+
See Also
|
| 1752 |
+
========
|
| 1753 |
+
|
| 1754 |
+
asinh, acosh, coth
|
| 1755 |
+
"""
|
| 1756 |
+
|
| 1757 |
+
def fdiff(self, argindex=1):
|
| 1758 |
+
if argindex == 1:
|
| 1759 |
+
return 1/(1 - self.args[0]**2)
|
| 1760 |
+
else:
|
| 1761 |
+
raise ArgumentIndexError(self, argindex)
|
| 1762 |
+
|
| 1763 |
+
@classmethod
|
| 1764 |
+
def eval(cls, arg):
|
| 1765 |
+
if arg.is_Number:
|
| 1766 |
+
if arg is S.NaN:
|
| 1767 |
+
return S.NaN
|
| 1768 |
+
elif arg is S.Infinity:
|
| 1769 |
+
return S.Zero
|
| 1770 |
+
elif arg is S.NegativeInfinity:
|
| 1771 |
+
return S.Zero
|
| 1772 |
+
elif arg.is_zero:
|
| 1773 |
+
return pi*I / 2
|
| 1774 |
+
elif arg is S.One:
|
| 1775 |
+
return S.Infinity
|
| 1776 |
+
elif arg is S.NegativeOne:
|
| 1777 |
+
return S.NegativeInfinity
|
| 1778 |
+
elif arg.is_negative:
|
| 1779 |
+
return -cls(-arg)
|
| 1780 |
+
else:
|
| 1781 |
+
if arg is S.ComplexInfinity:
|
| 1782 |
+
return S.Zero
|
| 1783 |
+
|
| 1784 |
+
i_coeff = _imaginary_unit_as_coefficient(arg)
|
| 1785 |
+
|
| 1786 |
+
if i_coeff is not None:
|
| 1787 |
+
return -I * acot(i_coeff)
|
| 1788 |
+
else:
|
| 1789 |
+
if arg.could_extract_minus_sign():
|
| 1790 |
+
return -cls(-arg)
|
| 1791 |
+
|
| 1792 |
+
if arg.is_zero:
|
| 1793 |
+
return pi*I*S.Half
|
| 1794 |
+
|
| 1795 |
+
@staticmethod
|
| 1796 |
+
@cacheit
|
| 1797 |
+
def taylor_term(n, x, *previous_terms):
|
| 1798 |
+
if n == 0:
|
| 1799 |
+
return -I*pi/2
|
| 1800 |
+
elif n < 0 or n % 2 == 0:
|
| 1801 |
+
return S.Zero
|
| 1802 |
+
else:
|
| 1803 |
+
x = sympify(x)
|
| 1804 |
+
return x**n / n
|
| 1805 |
+
|
| 1806 |
+
def _eval_as_leading_term(self, x, logx=None, cdir=0): # acoth
|
| 1807 |
+
arg = self.args[0]
|
| 1808 |
+
x0 = arg.subs(x, 0).cancel()
|
| 1809 |
+
if x0 is S.ComplexInfinity:
|
| 1810 |
+
return (1/arg).as_leading_term(x)
|
| 1811 |
+
if x0 is S.NaN:
|
| 1812 |
+
expr = self.func(arg.as_leading_term(x))
|
| 1813 |
+
if expr.is_finite:
|
| 1814 |
+
return expr
|
| 1815 |
+
else:
|
| 1816 |
+
return self
|
| 1817 |
+
|
| 1818 |
+
# Handling branch points
|
| 1819 |
+
if x0 in (-S.One, S.One, S.Zero):
|
| 1820 |
+
return self.rewrite(log)._eval_as_leading_term(x, logx=logx, cdir=cdir)
|
| 1821 |
+
# Handling points lying on branch cuts [-1, 1]
|
| 1822 |
+
if x0.is_real and (1 - x0**2).is_positive:
|
| 1823 |
+
ndir = arg.dir(x, cdir if cdir else 1)
|
| 1824 |
+
if im(ndir).is_negative:
|
| 1825 |
+
if x0.is_positive:
|
| 1826 |
+
return self.func(x0) + I*pi
|
| 1827 |
+
elif im(ndir).is_positive:
|
| 1828 |
+
if x0.is_negative:
|
| 1829 |
+
return self.func(x0) - I*pi
|
| 1830 |
+
else:
|
| 1831 |
+
return self.rewrite(log)._eval_as_leading_term(x, logx=logx, cdir=cdir)
|
| 1832 |
+
return self.func(x0)
|
| 1833 |
+
|
| 1834 |
+
def _eval_nseries(self, x, n, logx, cdir=0): # acoth
|
| 1835 |
+
arg = self.args[0]
|
| 1836 |
+
arg0 = arg.subs(x, 0)
|
| 1837 |
+
|
| 1838 |
+
# Handling branch points
|
| 1839 |
+
if arg0 in (S.One, S.NegativeOne):
|
| 1840 |
+
return self.rewrite(log)._eval_nseries(x, n, logx=logx, cdir=cdir)
|
| 1841 |
+
|
| 1842 |
+
res = Function._eval_nseries(self, x, n=n, logx=logx)
|
| 1843 |
+
if arg0 is S.ComplexInfinity:
|
| 1844 |
+
return res
|
| 1845 |
+
|
| 1846 |
+
# Handling points lying on branch cuts [-1, 1]
|
| 1847 |
+
if arg0.is_real and (1 - arg0**2).is_positive:
|
| 1848 |
+
ndir = arg.dir(x, cdir if cdir else 1)
|
| 1849 |
+
if im(ndir).is_negative:
|
| 1850 |
+
if arg0.is_positive:
|
| 1851 |
+
return res + I*pi
|
| 1852 |
+
elif im(ndir).is_positive:
|
| 1853 |
+
if arg0.is_negative:
|
| 1854 |
+
return res - I*pi
|
| 1855 |
+
else:
|
| 1856 |
+
return self.rewrite(log)._eval_nseries(x, n, logx=logx, cdir=cdir)
|
| 1857 |
+
return res
|
| 1858 |
+
|
| 1859 |
+
def _eval_rewrite_as_log(self, x, **kwargs):
|
| 1860 |
+
return (log(1 + 1/x) - log(1 - 1/x)) / 2
|
| 1861 |
+
|
| 1862 |
+
_eval_rewrite_as_tractable = _eval_rewrite_as_log
|
| 1863 |
+
|
| 1864 |
+
def _eval_rewrite_as_atanh(self, x, **kwargs):
|
| 1865 |
+
return atanh(1/x)
|
| 1866 |
+
|
| 1867 |
+
def _eval_rewrite_as_asinh(self, x, **kwargs):
|
| 1868 |
+
return (pi*I/2*(sqrt((x - 1)/x)*sqrt(x/(x - 1)) - sqrt(1 + 1/x)*sqrt(x/(x + 1))) +
|
| 1869 |
+
x*sqrt(1/x**2)*asinh(sqrt(1/(x**2 - 1))))
|
| 1870 |
+
|
| 1871 |
+
def inverse(self, argindex=1):
|
| 1872 |
+
"""
|
| 1873 |
+
Returns the inverse of this function.
|
| 1874 |
+
"""
|
| 1875 |
+
return coth
|
| 1876 |
+
|
| 1877 |
+
def _eval_is_extended_real(self):
|
| 1878 |
+
return fuzzy_and([self.args[0].is_extended_real, fuzzy_or([(self.args[0] - 1).is_extended_nonnegative, (self.args[0] + 1).is_extended_nonpositive])])
|
| 1879 |
+
|
| 1880 |
+
def _eval_is_finite(self):
|
| 1881 |
+
return fuzzy_not(fuzzy_or([(self.args[0] - 1).is_zero, (self.args[0] + 1).is_zero]))
|
| 1882 |
+
|
| 1883 |
+
|
| 1884 |
+
class asech(InverseHyperbolicFunction):
|
| 1885 |
+
"""
|
| 1886 |
+
``asech(x)`` is the inverse hyperbolic secant of ``x``.
|
| 1887 |
+
|
| 1888 |
+
The inverse hyperbolic secant function.
|
| 1889 |
+
|
| 1890 |
+
Examples
|
| 1891 |
+
========
|
| 1892 |
+
|
| 1893 |
+
>>> from sympy import asech, sqrt, S
|
| 1894 |
+
>>> from sympy.abc import x
|
| 1895 |
+
>>> asech(x).diff(x)
|
| 1896 |
+
-1/(x*sqrt(1 - x**2))
|
| 1897 |
+
>>> asech(1).diff(x)
|
| 1898 |
+
0
|
| 1899 |
+
>>> asech(1)
|
| 1900 |
+
0
|
| 1901 |
+
>>> asech(S(2))
|
| 1902 |
+
I*pi/3
|
| 1903 |
+
>>> asech(-sqrt(2))
|
| 1904 |
+
3*I*pi/4
|
| 1905 |
+
>>> asech((sqrt(6) - sqrt(2)))
|
| 1906 |
+
I*pi/12
|
| 1907 |
+
|
| 1908 |
+
See Also
|
| 1909 |
+
========
|
| 1910 |
+
|
| 1911 |
+
asinh, atanh, cosh, acoth
|
| 1912 |
+
|
| 1913 |
+
References
|
| 1914 |
+
==========
|
| 1915 |
+
|
| 1916 |
+
.. [1] https://en.wikipedia.org/wiki/Hyperbolic_function
|
| 1917 |
+
.. [2] https://dlmf.nist.gov/4.37
|
| 1918 |
+
.. [3] https://functions.wolfram.com/ElementaryFunctions/ArcSech/
|
| 1919 |
+
|
| 1920 |
+
"""
|
| 1921 |
+
|
| 1922 |
+
def fdiff(self, argindex=1):
|
| 1923 |
+
if argindex == 1:
|
| 1924 |
+
z = self.args[0]
|
| 1925 |
+
return -1/(z*sqrt(1 - z**2))
|
| 1926 |
+
else:
|
| 1927 |
+
raise ArgumentIndexError(self, argindex)
|
| 1928 |
+
|
| 1929 |
+
@classmethod
|
| 1930 |
+
def eval(cls, arg):
|
| 1931 |
+
if arg.is_Number:
|
| 1932 |
+
if arg is S.NaN:
|
| 1933 |
+
return S.NaN
|
| 1934 |
+
elif arg is S.Infinity:
|
| 1935 |
+
return pi*I / 2
|
| 1936 |
+
elif arg is S.NegativeInfinity:
|
| 1937 |
+
return pi*I / 2
|
| 1938 |
+
elif arg.is_zero:
|
| 1939 |
+
return S.Infinity
|
| 1940 |
+
elif arg is S.One:
|
| 1941 |
+
return S.Zero
|
| 1942 |
+
elif arg is S.NegativeOne:
|
| 1943 |
+
return pi*I
|
| 1944 |
+
|
| 1945 |
+
if arg.is_number:
|
| 1946 |
+
cst_table = _asech_table()
|
| 1947 |
+
|
| 1948 |
+
if arg in cst_table:
|
| 1949 |
+
if arg.is_extended_real:
|
| 1950 |
+
return cst_table[arg]*I
|
| 1951 |
+
return cst_table[arg]
|
| 1952 |
+
|
| 1953 |
+
if arg is S.ComplexInfinity:
|
| 1954 |
+
from sympy.calculus.accumulationbounds import AccumBounds
|
| 1955 |
+
return I*AccumBounds(-pi/2, pi/2)
|
| 1956 |
+
|
| 1957 |
+
if arg.is_zero:
|
| 1958 |
+
return S.Infinity
|
| 1959 |
+
|
| 1960 |
+
@staticmethod
|
| 1961 |
+
@cacheit
|
| 1962 |
+
def taylor_term(n, x, *previous_terms):
|
| 1963 |
+
if n == 0:
|
| 1964 |
+
return log(2 / x)
|
| 1965 |
+
elif n < 0 or n % 2 == 1:
|
| 1966 |
+
return S.Zero
|
| 1967 |
+
else:
|
| 1968 |
+
x = sympify(x)
|
| 1969 |
+
if len(previous_terms) > 2 and n > 2:
|
| 1970 |
+
p = previous_terms[-2]
|
| 1971 |
+
return p * ((n - 1)*(n-2)) * x**2/(4 * (n//2)**2)
|
| 1972 |
+
else:
|
| 1973 |
+
k = n // 2
|
| 1974 |
+
R = RisingFactorial(S.Half, k) * n
|
| 1975 |
+
F = factorial(k) * n // 2 * n // 2
|
| 1976 |
+
return -1 * R / F * x**n / 4
|
| 1977 |
+
|
| 1978 |
+
def _eval_as_leading_term(self, x, logx=None, cdir=0): # asech
|
| 1979 |
+
arg = self.args[0]
|
| 1980 |
+
x0 = arg.subs(x, 0).cancel()
|
| 1981 |
+
# Handling branch points
|
| 1982 |
+
if x0 in (-S.One, S.Zero, S.One, S.ComplexInfinity):
|
| 1983 |
+
return self.rewrite(log)._eval_as_leading_term(x, logx=logx, cdir=cdir)
|
| 1984 |
+
|
| 1985 |
+
if x0 is S.NaN:
|
| 1986 |
+
expr = self.func(arg.as_leading_term(x))
|
| 1987 |
+
if expr.is_finite:
|
| 1988 |
+
return expr
|
| 1989 |
+
else:
|
| 1990 |
+
return self
|
| 1991 |
+
|
| 1992 |
+
# Handling points lying on branch cuts (-oo, 0] U (1, oo)
|
| 1993 |
+
if x0.is_negative or (1 - x0).is_negative:
|
| 1994 |
+
ndir = arg.dir(x, cdir if cdir else 1)
|
| 1995 |
+
if im(ndir).is_positive:
|
| 1996 |
+
if x0.is_positive or (x0 + 1).is_negative:
|
| 1997 |
+
return -self.func(x0)
|
| 1998 |
+
return self.func(x0) - 2*I*pi
|
| 1999 |
+
elif not im(ndir).is_negative:
|
| 2000 |
+
return self.rewrite(log)._eval_as_leading_term(x, logx=logx, cdir=cdir)
|
| 2001 |
+
return self.func(x0)
|
| 2002 |
+
|
| 2003 |
+
def _eval_nseries(self, x, n, logx, cdir=0): # asech
|
| 2004 |
+
from sympy.series.order import O
|
| 2005 |
+
arg = self.args[0]
|
| 2006 |
+
arg0 = arg.subs(x, 0)
|
| 2007 |
+
|
| 2008 |
+
# Handling branch points
|
| 2009 |
+
if arg0 is S.One:
|
| 2010 |
+
t = Dummy('t', positive=True)
|
| 2011 |
+
ser = asech(S.One - t**2).rewrite(log).nseries(t, 0, 2*n)
|
| 2012 |
+
arg1 = S.One - self.args[0]
|
| 2013 |
+
f = arg1.as_leading_term(x)
|
| 2014 |
+
g = (arg1 - f)/ f
|
| 2015 |
+
if not g.is_meromorphic(x, 0): # cannot be expanded
|
| 2016 |
+
return O(1) if n == 0 else O(sqrt(x))
|
| 2017 |
+
res1 = sqrt(S.One + g)._eval_nseries(x, n=n, logx=logx)
|
| 2018 |
+
res = (res1.removeO()*sqrt(f)).expand()
|
| 2019 |
+
return ser.removeO().subs(t, res).expand().powsimp() + O(x**n, x)
|
| 2020 |
+
|
| 2021 |
+
if arg0 is S.NegativeOne:
|
| 2022 |
+
t = Dummy('t', positive=True)
|
| 2023 |
+
ser = asech(S.NegativeOne + t**2).rewrite(log).nseries(t, 0, 2*n)
|
| 2024 |
+
arg1 = S.One + self.args[0]
|
| 2025 |
+
f = arg1.as_leading_term(x)
|
| 2026 |
+
g = (arg1 - f)/ f
|
| 2027 |
+
if not g.is_meromorphic(x, 0): # cannot be expanded
|
| 2028 |
+
return O(1) if n == 0 else I*pi + O(sqrt(x))
|
| 2029 |
+
res1 = sqrt(S.One + g)._eval_nseries(x, n=n, logx=logx)
|
| 2030 |
+
res = (res1.removeO()*sqrt(f)).expand()
|
| 2031 |
+
return ser.removeO().subs(t, res).expand().powsimp() + O(x**n, x)
|
| 2032 |
+
|
| 2033 |
+
res = Function._eval_nseries(self, x, n=n, logx=logx)
|
| 2034 |
+
if arg0 is S.ComplexInfinity:
|
| 2035 |
+
return res
|
| 2036 |
+
|
| 2037 |
+
# Handling points lying on branch cuts (-oo, 0] U (1, oo)
|
| 2038 |
+
if arg0.is_negative or (1 - arg0).is_negative:
|
| 2039 |
+
ndir = arg.dir(x, cdir if cdir else 1)
|
| 2040 |
+
if im(ndir).is_positive:
|
| 2041 |
+
if arg0.is_positive or (arg0 + 1).is_negative:
|
| 2042 |
+
return -res
|
| 2043 |
+
return res - 2*I*pi
|
| 2044 |
+
elif not im(ndir).is_negative:
|
| 2045 |
+
return self.rewrite(log)._eval_nseries(x, n, logx=logx, cdir=cdir)
|
| 2046 |
+
return res
|
| 2047 |
+
|
| 2048 |
+
def inverse(self, argindex=1):
|
| 2049 |
+
"""
|
| 2050 |
+
Returns the inverse of this function.
|
| 2051 |
+
"""
|
| 2052 |
+
return sech
|
| 2053 |
+
|
| 2054 |
+
def _eval_rewrite_as_log(self, arg, **kwargs):
|
| 2055 |
+
return log(1/arg + sqrt(1/arg - 1) * sqrt(1/arg + 1))
|
| 2056 |
+
|
| 2057 |
+
_eval_rewrite_as_tractable = _eval_rewrite_as_log
|
| 2058 |
+
|
| 2059 |
+
def _eval_rewrite_as_acosh(self, arg, **kwargs):
|
| 2060 |
+
return acosh(1/arg)
|
| 2061 |
+
|
| 2062 |
+
def _eval_rewrite_as_asinh(self, arg, **kwargs):
|
| 2063 |
+
return sqrt(1/arg - 1)/sqrt(1 - 1/arg)*(I*asinh(I/arg, evaluate=False)
|
| 2064 |
+
+ pi*S.Half)
|
| 2065 |
+
|
| 2066 |
+
def _eval_rewrite_as_atanh(self, x, **kwargs):
|
| 2067 |
+
return (I*pi*(1 - sqrt(x)*sqrt(1/x) - I/2*sqrt(-x)/sqrt(x) - I/2*sqrt(x**2)/sqrt(-x**2))
|
| 2068 |
+
+ sqrt(1/(x + 1))*sqrt(x + 1)*atanh(sqrt(1 - x**2)))
|
| 2069 |
+
|
| 2070 |
+
def _eval_rewrite_as_acsch(self, x, **kwargs):
|
| 2071 |
+
return sqrt(1/x - 1)/sqrt(1 - 1/x)*(pi/2 - I*acsch(I*x, evaluate=False))
|
| 2072 |
+
|
| 2073 |
+
def _eval_is_extended_real(self):
|
| 2074 |
+
return fuzzy_and([self.args[0].is_extended_real, self.args[0].is_nonnegative, (1 - self.args[0]).is_nonnegative])
|
| 2075 |
+
|
| 2076 |
+
def _eval_is_finite(self):
|
| 2077 |
+
return fuzzy_not(self.args[0].is_zero)
|
| 2078 |
+
|
| 2079 |
+
|
| 2080 |
+
class acsch(InverseHyperbolicFunction):
|
| 2081 |
+
"""
|
| 2082 |
+
``acsch(x)`` is the inverse hyperbolic cosecant of ``x``.
|
| 2083 |
+
|
| 2084 |
+
The inverse hyperbolic cosecant function.
|
| 2085 |
+
|
| 2086 |
+
Examples
|
| 2087 |
+
========
|
| 2088 |
+
|
| 2089 |
+
>>> from sympy import acsch, sqrt, I
|
| 2090 |
+
>>> from sympy.abc import x
|
| 2091 |
+
>>> acsch(x).diff(x)
|
| 2092 |
+
-1/(x**2*sqrt(1 + x**(-2)))
|
| 2093 |
+
>>> acsch(1).diff(x)
|
| 2094 |
+
0
|
| 2095 |
+
>>> acsch(1)
|
| 2096 |
+
log(1 + sqrt(2))
|
| 2097 |
+
>>> acsch(I)
|
| 2098 |
+
-I*pi/2
|
| 2099 |
+
>>> acsch(-2*I)
|
| 2100 |
+
I*pi/6
|
| 2101 |
+
>>> acsch(I*(sqrt(6) - sqrt(2)))
|
| 2102 |
+
-5*I*pi/12
|
| 2103 |
+
|
| 2104 |
+
See Also
|
| 2105 |
+
========
|
| 2106 |
+
|
| 2107 |
+
asinh
|
| 2108 |
+
|
| 2109 |
+
References
|
| 2110 |
+
==========
|
| 2111 |
+
|
| 2112 |
+
.. [1] https://en.wikipedia.org/wiki/Hyperbolic_function
|
| 2113 |
+
.. [2] https://dlmf.nist.gov/4.37
|
| 2114 |
+
.. [3] https://functions.wolfram.com/ElementaryFunctions/ArcCsch/
|
| 2115 |
+
|
| 2116 |
+
"""
|
| 2117 |
+
|
| 2118 |
+
def fdiff(self, argindex=1):
|
| 2119 |
+
if argindex == 1:
|
| 2120 |
+
z = self.args[0]
|
| 2121 |
+
return -1/(z**2*sqrt(1 + 1/z**2))
|
| 2122 |
+
else:
|
| 2123 |
+
raise ArgumentIndexError(self, argindex)
|
| 2124 |
+
|
| 2125 |
+
@classmethod
|
| 2126 |
+
def eval(cls, arg):
|
| 2127 |
+
if arg.is_Number:
|
| 2128 |
+
if arg is S.NaN:
|
| 2129 |
+
return S.NaN
|
| 2130 |
+
elif arg is S.Infinity:
|
| 2131 |
+
return S.Zero
|
| 2132 |
+
elif arg is S.NegativeInfinity:
|
| 2133 |
+
return S.Zero
|
| 2134 |
+
elif arg.is_zero:
|
| 2135 |
+
return S.ComplexInfinity
|
| 2136 |
+
elif arg is S.One:
|
| 2137 |
+
return log(1 + sqrt(2))
|
| 2138 |
+
elif arg is S.NegativeOne:
|
| 2139 |
+
return - log(1 + sqrt(2))
|
| 2140 |
+
|
| 2141 |
+
if arg.is_number:
|
| 2142 |
+
cst_table = _acsch_table()
|
| 2143 |
+
|
| 2144 |
+
if arg in cst_table:
|
| 2145 |
+
return cst_table[arg]*I
|
| 2146 |
+
|
| 2147 |
+
if arg is S.ComplexInfinity:
|
| 2148 |
+
return S.Zero
|
| 2149 |
+
|
| 2150 |
+
if arg.is_infinite:
|
| 2151 |
+
return S.Zero
|
| 2152 |
+
|
| 2153 |
+
if arg.is_zero:
|
| 2154 |
+
return S.ComplexInfinity
|
| 2155 |
+
|
| 2156 |
+
if arg.could_extract_minus_sign():
|
| 2157 |
+
return -cls(-arg)
|
| 2158 |
+
|
| 2159 |
+
@staticmethod
|
| 2160 |
+
@cacheit
|
| 2161 |
+
def taylor_term(n, x, *previous_terms):
|
| 2162 |
+
if n == 0:
|
| 2163 |
+
return log(2 / x)
|
| 2164 |
+
elif n < 0 or n % 2 == 1:
|
| 2165 |
+
return S.Zero
|
| 2166 |
+
else:
|
| 2167 |
+
x = sympify(x)
|
| 2168 |
+
if len(previous_terms) > 2 and n > 2:
|
| 2169 |
+
p = previous_terms[-2]
|
| 2170 |
+
return -p * ((n - 1)*(n-2)) * x**2/(4 * (n//2)**2)
|
| 2171 |
+
else:
|
| 2172 |
+
k = n // 2
|
| 2173 |
+
R = RisingFactorial(S.Half, k) * n
|
| 2174 |
+
F = factorial(k) * n // 2 * n // 2
|
| 2175 |
+
return S.NegativeOne**(k +1) * R / F * x**n / 4
|
| 2176 |
+
|
| 2177 |
+
def _eval_as_leading_term(self, x, logx=None, cdir=0): # acsch
|
| 2178 |
+
arg = self.args[0]
|
| 2179 |
+
x0 = arg.subs(x, 0).cancel()
|
| 2180 |
+
# Handling branch points
|
| 2181 |
+
if x0 in (-I, I, S.Zero):
|
| 2182 |
+
return self.rewrite(log)._eval_as_leading_term(x, logx=logx, cdir=cdir)
|
| 2183 |
+
|
| 2184 |
+
if x0 is S.NaN:
|
| 2185 |
+
expr = self.func(arg.as_leading_term(x))
|
| 2186 |
+
if expr.is_finite:
|
| 2187 |
+
return expr
|
| 2188 |
+
else:
|
| 2189 |
+
return self
|
| 2190 |
+
|
| 2191 |
+
if x0 is S.ComplexInfinity:
|
| 2192 |
+
return (1/arg).as_leading_term(x)
|
| 2193 |
+
# Handling points lying on branch cuts (-I, I)
|
| 2194 |
+
if x0.is_imaginary and (1 + x0**2).is_positive:
|
| 2195 |
+
ndir = arg.dir(x, cdir if cdir else 1)
|
| 2196 |
+
if re(ndir).is_positive:
|
| 2197 |
+
if im(x0).is_positive:
|
| 2198 |
+
return -self.func(x0) - I*pi
|
| 2199 |
+
elif re(ndir).is_negative:
|
| 2200 |
+
if im(x0).is_negative:
|
| 2201 |
+
return -self.func(x0) + I*pi
|
| 2202 |
+
else:
|
| 2203 |
+
return self.rewrite(log)._eval_as_leading_term(x, logx=logx, cdir=cdir)
|
| 2204 |
+
return self.func(x0)
|
| 2205 |
+
|
| 2206 |
+
def _eval_nseries(self, x, n, logx, cdir=0): # acsch
|
| 2207 |
+
from sympy.series.order import O
|
| 2208 |
+
arg = self.args[0]
|
| 2209 |
+
arg0 = arg.subs(x, 0)
|
| 2210 |
+
|
| 2211 |
+
# Handling branch points
|
| 2212 |
+
if arg0 is I:
|
| 2213 |
+
t = Dummy('t', positive=True)
|
| 2214 |
+
ser = acsch(I + t**2).rewrite(log).nseries(t, 0, 2*n)
|
| 2215 |
+
arg1 = -I + self.args[0]
|
| 2216 |
+
f = arg1.as_leading_term(x)
|
| 2217 |
+
g = (arg1 - f)/ f
|
| 2218 |
+
if not g.is_meromorphic(x, 0): # cannot be expanded
|
| 2219 |
+
return O(1) if n == 0 else -I*pi/2 + O(sqrt(x))
|
| 2220 |
+
res1 = sqrt(S.One + g)._eval_nseries(x, n=n, logx=logx)
|
| 2221 |
+
res = (res1.removeO()*sqrt(f)).expand()
|
| 2222 |
+
res = ser.removeO().subs(t, res).expand().powsimp() + O(x**n, x)
|
| 2223 |
+
return res
|
| 2224 |
+
|
| 2225 |
+
if arg0 == S.NegativeOne*I:
|
| 2226 |
+
t = Dummy('t', positive=True)
|
| 2227 |
+
ser = acsch(-I + t**2).rewrite(log).nseries(t, 0, 2*n)
|
| 2228 |
+
arg1 = I + self.args[0]
|
| 2229 |
+
f = arg1.as_leading_term(x)
|
| 2230 |
+
g = (arg1 - f)/ f
|
| 2231 |
+
if not g.is_meromorphic(x, 0): # cannot be expanded
|
| 2232 |
+
return O(1) if n == 0 else I*pi/2 + O(sqrt(x))
|
| 2233 |
+
res1 = sqrt(S.One + g)._eval_nseries(x, n=n, logx=logx)
|
| 2234 |
+
res = (res1.removeO()*sqrt(f)).expand()
|
| 2235 |
+
return ser.removeO().subs(t, res).expand().powsimp() + O(x**n, x)
|
| 2236 |
+
|
| 2237 |
+
res = Function._eval_nseries(self, x, n=n, logx=logx)
|
| 2238 |
+
if arg0 is S.ComplexInfinity:
|
| 2239 |
+
return res
|
| 2240 |
+
|
| 2241 |
+
# Handling points lying on branch cuts (-I, I)
|
| 2242 |
+
if arg0.is_imaginary and (1 + arg0**2).is_positive:
|
| 2243 |
+
ndir = self.args[0].dir(x, cdir if cdir else 1)
|
| 2244 |
+
if re(ndir).is_positive:
|
| 2245 |
+
if im(arg0).is_positive:
|
| 2246 |
+
return -res - I*pi
|
| 2247 |
+
elif re(ndir).is_negative:
|
| 2248 |
+
if im(arg0).is_negative:
|
| 2249 |
+
return -res + I*pi
|
| 2250 |
+
else:
|
| 2251 |
+
return self.rewrite(log)._eval_nseries(x, n, logx=logx, cdir=cdir)
|
| 2252 |
+
return res
|
| 2253 |
+
|
| 2254 |
+
def inverse(self, argindex=1):
|
| 2255 |
+
"""
|
| 2256 |
+
Returns the inverse of this function.
|
| 2257 |
+
"""
|
| 2258 |
+
return csch
|
| 2259 |
+
|
| 2260 |
+
def _eval_rewrite_as_log(self, arg, **kwargs):
|
| 2261 |
+
return log(1/arg + sqrt(1/arg**2 + 1))
|
| 2262 |
+
|
| 2263 |
+
_eval_rewrite_as_tractable = _eval_rewrite_as_log
|
| 2264 |
+
|
| 2265 |
+
def _eval_rewrite_as_asinh(self, arg, **kwargs):
|
| 2266 |
+
return asinh(1/arg)
|
| 2267 |
+
|
| 2268 |
+
def _eval_rewrite_as_acosh(self, arg, **kwargs):
|
| 2269 |
+
return I*(sqrt(1 - I/arg)/sqrt(I/arg - 1)*
|
| 2270 |
+
acosh(I/arg, evaluate=False) - pi*S.Half)
|
| 2271 |
+
|
| 2272 |
+
def _eval_rewrite_as_atanh(self, arg, **kwargs):
|
| 2273 |
+
arg2 = arg**2
|
| 2274 |
+
arg2p1 = arg2 + 1
|
| 2275 |
+
return sqrt(-arg2)/arg*(pi*S.Half -
|
| 2276 |
+
sqrt(-arg2p1**2)/arg2p1*atanh(sqrt(arg2p1)))
|
| 2277 |
+
|
| 2278 |
+
def _eval_is_zero(self):
|
| 2279 |
+
return self.args[0].is_infinite
|
| 2280 |
+
|
| 2281 |
+
def _eval_is_extended_real(self):
|
| 2282 |
+
return self.args[0].is_extended_real
|
| 2283 |
+
|
| 2284 |
+
def _eval_is_finite(self):
|
| 2285 |
+
return fuzzy_not(self.args[0].is_zero)
|
evalkit_tf437/lib/python3.10/site-packages/sympy/functions/elementary/integers.py
ADDED
|
@@ -0,0 +1,645 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Tuple as tTuple
|
| 2 |
+
|
| 3 |
+
from sympy.core.basic import Basic
|
| 4 |
+
from sympy.core.expr import Expr
|
| 5 |
+
|
| 6 |
+
from sympy.core import Add, S
|
| 7 |
+
from sympy.core.evalf import get_integer_part, PrecisionExhausted
|
| 8 |
+
from sympy.core.function import Function
|
| 9 |
+
from sympy.core.logic import fuzzy_or
|
| 10 |
+
from sympy.core.numbers import Integer, int_valued
|
| 11 |
+
from sympy.core.relational import Gt, Lt, Ge, Le, Relational, is_eq
|
| 12 |
+
from sympy.core.sympify import _sympify
|
| 13 |
+
from sympy.functions.elementary.complexes import im, re
|
| 14 |
+
from sympy.multipledispatch import dispatch
|
| 15 |
+
|
| 16 |
+
###############################################################################
|
| 17 |
+
######################### FLOOR and CEILING FUNCTIONS #########################
|
| 18 |
+
###############################################################################
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class RoundFunction(Function):
|
| 22 |
+
"""Abstract base class for rounding functions."""
|
| 23 |
+
|
| 24 |
+
args: tTuple[Expr]
|
| 25 |
+
|
| 26 |
+
@classmethod
|
| 27 |
+
def eval(cls, arg):
|
| 28 |
+
v = cls._eval_number(arg)
|
| 29 |
+
if v is not None:
|
| 30 |
+
return v
|
| 31 |
+
|
| 32 |
+
if arg.is_integer or arg.is_finite is False:
|
| 33 |
+
return arg
|
| 34 |
+
if arg.is_imaginary or (S.ImaginaryUnit*arg).is_real:
|
| 35 |
+
i = im(arg)
|
| 36 |
+
if not i.has(S.ImaginaryUnit):
|
| 37 |
+
return cls(i)*S.ImaginaryUnit
|
| 38 |
+
return cls(arg, evaluate=False)
|
| 39 |
+
|
| 40 |
+
# Integral, numerical, symbolic part
|
| 41 |
+
ipart = npart = spart = S.Zero
|
| 42 |
+
|
| 43 |
+
# Extract integral (or complex integral) terms
|
| 44 |
+
intof = lambda x: int(x) if int_valued(x) else (
|
| 45 |
+
x if x.is_integer else None)
|
| 46 |
+
for t in Add.make_args(arg):
|
| 47 |
+
if t.is_imaginary and (i := intof(im(t))) is not None:
|
| 48 |
+
ipart += i*S.ImaginaryUnit
|
| 49 |
+
elif (i := intof(t)) is not None:
|
| 50 |
+
ipart += i
|
| 51 |
+
elif t.is_number:
|
| 52 |
+
npart += t
|
| 53 |
+
else:
|
| 54 |
+
spart += t
|
| 55 |
+
|
| 56 |
+
if not (npart or spart):
|
| 57 |
+
return ipart
|
| 58 |
+
|
| 59 |
+
# Evaluate npart numerically if independent of spart
|
| 60 |
+
if npart and (
|
| 61 |
+
not spart or
|
| 62 |
+
npart.is_real and (spart.is_imaginary or (S.ImaginaryUnit*spart).is_real) or
|
| 63 |
+
npart.is_imaginary and spart.is_real):
|
| 64 |
+
try:
|
| 65 |
+
r, i = get_integer_part(
|
| 66 |
+
npart, cls._dir, {}, return_ints=True)
|
| 67 |
+
ipart += Integer(r) + Integer(i)*S.ImaginaryUnit
|
| 68 |
+
npart = S.Zero
|
| 69 |
+
except (PrecisionExhausted, NotImplementedError):
|
| 70 |
+
pass
|
| 71 |
+
|
| 72 |
+
spart += npart
|
| 73 |
+
if not spart:
|
| 74 |
+
return ipart
|
| 75 |
+
elif spart.is_imaginary or (S.ImaginaryUnit*spart).is_real:
|
| 76 |
+
return ipart + cls(im(spart), evaluate=False)*S.ImaginaryUnit
|
| 77 |
+
elif isinstance(spart, (floor, ceiling)):
|
| 78 |
+
return ipart + spart
|
| 79 |
+
else:
|
| 80 |
+
return ipart + cls(spart, evaluate=False)
|
| 81 |
+
|
| 82 |
+
@classmethod
|
| 83 |
+
def _eval_number(cls, arg):
|
| 84 |
+
raise NotImplementedError()
|
| 85 |
+
|
| 86 |
+
def _eval_is_finite(self):
|
| 87 |
+
return self.args[0].is_finite
|
| 88 |
+
|
| 89 |
+
def _eval_is_real(self):
|
| 90 |
+
return self.args[0].is_real
|
| 91 |
+
|
| 92 |
+
def _eval_is_integer(self):
|
| 93 |
+
return self.args[0].is_real
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
class floor(RoundFunction):
|
| 97 |
+
"""
|
| 98 |
+
Floor is a univariate function which returns the largest integer
|
| 99 |
+
value not greater than its argument. This implementation
|
| 100 |
+
generalizes floor to complex numbers by taking the floor of the
|
| 101 |
+
real and imaginary parts separately.
|
| 102 |
+
|
| 103 |
+
Examples
|
| 104 |
+
========
|
| 105 |
+
|
| 106 |
+
>>> from sympy import floor, E, I, S, Float, Rational
|
| 107 |
+
>>> floor(17)
|
| 108 |
+
17
|
| 109 |
+
>>> floor(Rational(23, 10))
|
| 110 |
+
2
|
| 111 |
+
>>> floor(2*E)
|
| 112 |
+
5
|
| 113 |
+
>>> floor(-Float(0.567))
|
| 114 |
+
-1
|
| 115 |
+
>>> floor(-I/2)
|
| 116 |
+
-I
|
| 117 |
+
>>> floor(S(5)/2 + 5*I/2)
|
| 118 |
+
2 + 2*I
|
| 119 |
+
|
| 120 |
+
See Also
|
| 121 |
+
========
|
| 122 |
+
|
| 123 |
+
sympy.functions.elementary.integers.ceiling
|
| 124 |
+
|
| 125 |
+
References
|
| 126 |
+
==========
|
| 127 |
+
|
| 128 |
+
.. [1] "Concrete mathematics" by Graham, pp. 87
|
| 129 |
+
.. [2] https://mathworld.wolfram.com/FloorFunction.html
|
| 130 |
+
|
| 131 |
+
"""
|
| 132 |
+
_dir = -1
|
| 133 |
+
|
| 134 |
+
@classmethod
|
| 135 |
+
def _eval_number(cls, arg):
|
| 136 |
+
if arg.is_Number:
|
| 137 |
+
return arg.floor()
|
| 138 |
+
elif any(isinstance(i, j)
|
| 139 |
+
for i in (arg, -arg) for j in (floor, ceiling)):
|
| 140 |
+
return arg
|
| 141 |
+
if arg.is_NumberSymbol:
|
| 142 |
+
return arg.approximation_interval(Integer)[0]
|
| 143 |
+
|
| 144 |
+
def _eval_as_leading_term(self, x, logx=None, cdir=0):
|
| 145 |
+
from sympy.calculus.accumulationbounds import AccumBounds
|
| 146 |
+
arg = self.args[0]
|
| 147 |
+
arg0 = arg.subs(x, 0)
|
| 148 |
+
r = self.subs(x, 0)
|
| 149 |
+
if arg0 is S.NaN or isinstance(arg0, AccumBounds):
|
| 150 |
+
arg0 = arg.limit(x, 0, dir='-' if re(cdir).is_negative else '+')
|
| 151 |
+
r = floor(arg0)
|
| 152 |
+
if arg0.is_finite:
|
| 153 |
+
if arg0 == r:
|
| 154 |
+
ndir = arg.dir(x, cdir=cdir if cdir != 0 else 1)
|
| 155 |
+
if ndir.is_negative:
|
| 156 |
+
return r - 1
|
| 157 |
+
elif ndir.is_positive:
|
| 158 |
+
return r
|
| 159 |
+
else:
|
| 160 |
+
raise NotImplementedError("Not sure of sign of %s" % ndir)
|
| 161 |
+
else:
|
| 162 |
+
return r
|
| 163 |
+
return arg.as_leading_term(x, logx=logx, cdir=cdir)
|
| 164 |
+
|
| 165 |
+
def _eval_nseries(self, x, n, logx, cdir=0):
|
| 166 |
+
arg = self.args[0]
|
| 167 |
+
arg0 = arg.subs(x, 0)
|
| 168 |
+
r = self.subs(x, 0)
|
| 169 |
+
if arg0 is S.NaN:
|
| 170 |
+
arg0 = arg.limit(x, 0, dir='-' if re(cdir).is_negative else '+')
|
| 171 |
+
r = floor(arg0)
|
| 172 |
+
if arg0.is_infinite:
|
| 173 |
+
from sympy.calculus.accumulationbounds import AccumBounds
|
| 174 |
+
from sympy.series.order import Order
|
| 175 |
+
s = arg._eval_nseries(x, n, logx, cdir)
|
| 176 |
+
o = Order(1, (x, 0)) if n <= 0 else AccumBounds(-1, 0)
|
| 177 |
+
return s + o
|
| 178 |
+
if arg0 == r:
|
| 179 |
+
ndir = arg.dir(x, cdir=cdir if cdir != 0 else 1)
|
| 180 |
+
if ndir.is_negative:
|
| 181 |
+
return r - 1
|
| 182 |
+
elif ndir.is_positive:
|
| 183 |
+
return r
|
| 184 |
+
else:
|
| 185 |
+
raise NotImplementedError("Not sure of sign of %s" % ndir)
|
| 186 |
+
else:
|
| 187 |
+
return r
|
| 188 |
+
|
| 189 |
+
def _eval_is_negative(self):
|
| 190 |
+
return self.args[0].is_negative
|
| 191 |
+
|
| 192 |
+
def _eval_is_nonnegative(self):
|
| 193 |
+
return self.args[0].is_nonnegative
|
| 194 |
+
|
| 195 |
+
def _eval_rewrite_as_ceiling(self, arg, **kwargs):
|
| 196 |
+
return -ceiling(-arg)
|
| 197 |
+
|
| 198 |
+
def _eval_rewrite_as_frac(self, arg, **kwargs):
|
| 199 |
+
return arg - frac(arg)
|
| 200 |
+
|
| 201 |
+
def __le__(self, other):
|
| 202 |
+
other = S(other)
|
| 203 |
+
if self.args[0].is_real:
|
| 204 |
+
if other.is_integer:
|
| 205 |
+
return self.args[0] < other + 1
|
| 206 |
+
if other.is_number and other.is_real:
|
| 207 |
+
return self.args[0] < ceiling(other)
|
| 208 |
+
if self.args[0] == other and other.is_real:
|
| 209 |
+
return S.true
|
| 210 |
+
if other is S.Infinity and self.is_finite:
|
| 211 |
+
return S.true
|
| 212 |
+
|
| 213 |
+
return Le(self, other, evaluate=False)
|
| 214 |
+
|
| 215 |
+
def __ge__(self, other):
|
| 216 |
+
other = S(other)
|
| 217 |
+
if self.args[0].is_real:
|
| 218 |
+
if other.is_integer:
|
| 219 |
+
return self.args[0] >= other
|
| 220 |
+
if other.is_number and other.is_real:
|
| 221 |
+
return self.args[0] >= ceiling(other)
|
| 222 |
+
if self.args[0] == other and other.is_real:
|
| 223 |
+
return S.false
|
| 224 |
+
if other is S.NegativeInfinity and self.is_finite:
|
| 225 |
+
return S.true
|
| 226 |
+
|
| 227 |
+
return Ge(self, other, evaluate=False)
|
| 228 |
+
|
| 229 |
+
def __gt__(self, other):
|
| 230 |
+
other = S(other)
|
| 231 |
+
if self.args[0].is_real:
|
| 232 |
+
if other.is_integer:
|
| 233 |
+
return self.args[0] >= other + 1
|
| 234 |
+
if other.is_number and other.is_real:
|
| 235 |
+
return self.args[0] >= ceiling(other)
|
| 236 |
+
if self.args[0] == other and other.is_real:
|
| 237 |
+
return S.false
|
| 238 |
+
if other is S.NegativeInfinity and self.is_finite:
|
| 239 |
+
return S.true
|
| 240 |
+
|
| 241 |
+
return Gt(self, other, evaluate=False)
|
| 242 |
+
|
| 243 |
+
def __lt__(self, other):
|
| 244 |
+
other = S(other)
|
| 245 |
+
if self.args[0].is_real:
|
| 246 |
+
if other.is_integer:
|
| 247 |
+
return self.args[0] < other
|
| 248 |
+
if other.is_number and other.is_real:
|
| 249 |
+
return self.args[0] < ceiling(other)
|
| 250 |
+
if self.args[0] == other and other.is_real:
|
| 251 |
+
return S.false
|
| 252 |
+
if other is S.Infinity and self.is_finite:
|
| 253 |
+
return S.true
|
| 254 |
+
|
| 255 |
+
return Lt(self, other, evaluate=False)
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
@dispatch(floor, Expr)
|
| 259 |
+
def _eval_is_eq(lhs, rhs): # noqa:F811
|
| 260 |
+
return is_eq(lhs.rewrite(ceiling), rhs) or \
|
| 261 |
+
is_eq(lhs.rewrite(frac),rhs)
|
| 262 |
+
|
| 263 |
+
|
| 264 |
+
class ceiling(RoundFunction):
|
| 265 |
+
"""
|
| 266 |
+
Ceiling is a univariate function which returns the smallest integer
|
| 267 |
+
value not less than its argument. This implementation
|
| 268 |
+
generalizes ceiling to complex numbers by taking the ceiling of the
|
| 269 |
+
real and imaginary parts separately.
|
| 270 |
+
|
| 271 |
+
Examples
|
| 272 |
+
========
|
| 273 |
+
|
| 274 |
+
>>> from sympy import ceiling, E, I, S, Float, Rational
|
| 275 |
+
>>> ceiling(17)
|
| 276 |
+
17
|
| 277 |
+
>>> ceiling(Rational(23, 10))
|
| 278 |
+
3
|
| 279 |
+
>>> ceiling(2*E)
|
| 280 |
+
6
|
| 281 |
+
>>> ceiling(-Float(0.567))
|
| 282 |
+
0
|
| 283 |
+
>>> ceiling(I/2)
|
| 284 |
+
I
|
| 285 |
+
>>> ceiling(S(5)/2 + 5*I/2)
|
| 286 |
+
3 + 3*I
|
| 287 |
+
|
| 288 |
+
See Also
|
| 289 |
+
========
|
| 290 |
+
|
| 291 |
+
sympy.functions.elementary.integers.floor
|
| 292 |
+
|
| 293 |
+
References
|
| 294 |
+
==========
|
| 295 |
+
|
| 296 |
+
.. [1] "Concrete mathematics" by Graham, pp. 87
|
| 297 |
+
.. [2] https://mathworld.wolfram.com/CeilingFunction.html
|
| 298 |
+
|
| 299 |
+
"""
|
| 300 |
+
_dir = 1
|
| 301 |
+
|
| 302 |
+
@classmethod
|
| 303 |
+
def _eval_number(cls, arg):
|
| 304 |
+
if arg.is_Number:
|
| 305 |
+
return arg.ceiling()
|
| 306 |
+
elif any(isinstance(i, j)
|
| 307 |
+
for i in (arg, -arg) for j in (floor, ceiling)):
|
| 308 |
+
return arg
|
| 309 |
+
if arg.is_NumberSymbol:
|
| 310 |
+
return arg.approximation_interval(Integer)[1]
|
| 311 |
+
|
| 312 |
+
def _eval_as_leading_term(self, x, logx=None, cdir=0):
|
| 313 |
+
from sympy.calculus.accumulationbounds import AccumBounds
|
| 314 |
+
arg = self.args[0]
|
| 315 |
+
arg0 = arg.subs(x, 0)
|
| 316 |
+
r = self.subs(x, 0)
|
| 317 |
+
if arg0 is S.NaN or isinstance(arg0, AccumBounds):
|
| 318 |
+
arg0 = arg.limit(x, 0, dir='-' if re(cdir).is_negative else '+')
|
| 319 |
+
r = ceiling(arg0)
|
| 320 |
+
if arg0.is_finite:
|
| 321 |
+
if arg0 == r:
|
| 322 |
+
ndir = arg.dir(x, cdir=cdir if cdir != 0 else 1)
|
| 323 |
+
if ndir.is_negative:
|
| 324 |
+
return r
|
| 325 |
+
elif ndir.is_positive:
|
| 326 |
+
return r + 1
|
| 327 |
+
else:
|
| 328 |
+
raise NotImplementedError("Not sure of sign of %s" % ndir)
|
| 329 |
+
else:
|
| 330 |
+
return r
|
| 331 |
+
return arg.as_leading_term(x, logx=logx, cdir=cdir)
|
| 332 |
+
|
| 333 |
+
def _eval_nseries(self, x, n, logx, cdir=0):
|
| 334 |
+
arg = self.args[0]
|
| 335 |
+
arg0 = arg.subs(x, 0)
|
| 336 |
+
r = self.subs(x, 0)
|
| 337 |
+
if arg0 is S.NaN:
|
| 338 |
+
arg0 = arg.limit(x, 0, dir='-' if re(cdir).is_negative else '+')
|
| 339 |
+
r = ceiling(arg0)
|
| 340 |
+
if arg0.is_infinite:
|
| 341 |
+
from sympy.calculus.accumulationbounds import AccumBounds
|
| 342 |
+
from sympy.series.order import Order
|
| 343 |
+
s = arg._eval_nseries(x, n, logx, cdir)
|
| 344 |
+
o = Order(1, (x, 0)) if n <= 0 else AccumBounds(0, 1)
|
| 345 |
+
return s + o
|
| 346 |
+
if arg0 == r:
|
| 347 |
+
ndir = arg.dir(x, cdir=cdir if cdir != 0 else 1)
|
| 348 |
+
if ndir.is_negative:
|
| 349 |
+
return r
|
| 350 |
+
elif ndir.is_positive:
|
| 351 |
+
return r + 1
|
| 352 |
+
else:
|
| 353 |
+
raise NotImplementedError("Not sure of sign of %s" % ndir)
|
| 354 |
+
else:
|
| 355 |
+
return r
|
| 356 |
+
|
| 357 |
+
def _eval_rewrite_as_floor(self, arg, **kwargs):
|
| 358 |
+
return -floor(-arg)
|
| 359 |
+
|
| 360 |
+
def _eval_rewrite_as_frac(self, arg, **kwargs):
|
| 361 |
+
return arg + frac(-arg)
|
| 362 |
+
|
| 363 |
+
def _eval_is_positive(self):
|
| 364 |
+
return self.args[0].is_positive
|
| 365 |
+
|
| 366 |
+
def _eval_is_nonpositive(self):
|
| 367 |
+
return self.args[0].is_nonpositive
|
| 368 |
+
|
| 369 |
+
def __lt__(self, other):
|
| 370 |
+
other = S(other)
|
| 371 |
+
if self.args[0].is_real:
|
| 372 |
+
if other.is_integer:
|
| 373 |
+
return self.args[0] <= other - 1
|
| 374 |
+
if other.is_number and other.is_real:
|
| 375 |
+
return self.args[0] <= floor(other)
|
| 376 |
+
if self.args[0] == other and other.is_real:
|
| 377 |
+
return S.false
|
| 378 |
+
if other is S.Infinity and self.is_finite:
|
| 379 |
+
return S.true
|
| 380 |
+
|
| 381 |
+
return Lt(self, other, evaluate=False)
|
| 382 |
+
|
| 383 |
+
def __gt__(self, other):
|
| 384 |
+
other = S(other)
|
| 385 |
+
if self.args[0].is_real:
|
| 386 |
+
if other.is_integer:
|
| 387 |
+
return self.args[0] > other
|
| 388 |
+
if other.is_number and other.is_real:
|
| 389 |
+
return self.args[0] > floor(other)
|
| 390 |
+
if self.args[0] == other and other.is_real:
|
| 391 |
+
return S.false
|
| 392 |
+
if other is S.NegativeInfinity and self.is_finite:
|
| 393 |
+
return S.true
|
| 394 |
+
|
| 395 |
+
return Gt(self, other, evaluate=False)
|
| 396 |
+
|
| 397 |
+
def __ge__(self, other):
|
| 398 |
+
other = S(other)
|
| 399 |
+
if self.args[0].is_real:
|
| 400 |
+
if other.is_integer:
|
| 401 |
+
return self.args[0] > other - 1
|
| 402 |
+
if other.is_number and other.is_real:
|
| 403 |
+
return self.args[0] > floor(other)
|
| 404 |
+
if self.args[0] == other and other.is_real:
|
| 405 |
+
return S.true
|
| 406 |
+
if other is S.NegativeInfinity and self.is_finite:
|
| 407 |
+
return S.true
|
| 408 |
+
|
| 409 |
+
return Ge(self, other, evaluate=False)
|
| 410 |
+
|
| 411 |
+
def __le__(self, other):
|
| 412 |
+
other = S(other)
|
| 413 |
+
if self.args[0].is_real:
|
| 414 |
+
if other.is_integer:
|
| 415 |
+
return self.args[0] <= other
|
| 416 |
+
if other.is_number and other.is_real:
|
| 417 |
+
return self.args[0] <= floor(other)
|
| 418 |
+
if self.args[0] == other and other.is_real:
|
| 419 |
+
return S.false
|
| 420 |
+
if other is S.Infinity and self.is_finite:
|
| 421 |
+
return S.true
|
| 422 |
+
|
| 423 |
+
return Le(self, other, evaluate=False)
|
| 424 |
+
|
| 425 |
+
|
| 426 |
+
@dispatch(ceiling, Basic) # type:ignore
|
| 427 |
+
def _eval_is_eq(lhs, rhs): # noqa:F811
|
| 428 |
+
return is_eq(lhs.rewrite(floor), rhs) or is_eq(lhs.rewrite(frac),rhs)
|
| 429 |
+
|
| 430 |
+
|
| 431 |
+
class frac(Function):
|
| 432 |
+
r"""Represents the fractional part of x
|
| 433 |
+
|
| 434 |
+
For real numbers it is defined [1]_ as
|
| 435 |
+
|
| 436 |
+
.. math::
|
| 437 |
+
x - \left\lfloor{x}\right\rfloor
|
| 438 |
+
|
| 439 |
+
Examples
|
| 440 |
+
========
|
| 441 |
+
|
| 442 |
+
>>> from sympy import Symbol, frac, Rational, floor, I
|
| 443 |
+
>>> frac(Rational(4, 3))
|
| 444 |
+
1/3
|
| 445 |
+
>>> frac(-Rational(4, 3))
|
| 446 |
+
2/3
|
| 447 |
+
|
| 448 |
+
returns zero for integer arguments
|
| 449 |
+
|
| 450 |
+
>>> n = Symbol('n', integer=True)
|
| 451 |
+
>>> frac(n)
|
| 452 |
+
0
|
| 453 |
+
|
| 454 |
+
rewrite as floor
|
| 455 |
+
|
| 456 |
+
>>> x = Symbol('x')
|
| 457 |
+
>>> frac(x).rewrite(floor)
|
| 458 |
+
x - floor(x)
|
| 459 |
+
|
| 460 |
+
for complex arguments
|
| 461 |
+
|
| 462 |
+
>>> r = Symbol('r', real=True)
|
| 463 |
+
>>> t = Symbol('t', real=True)
|
| 464 |
+
>>> frac(t + I*r)
|
| 465 |
+
I*frac(r) + frac(t)
|
| 466 |
+
|
| 467 |
+
See Also
|
| 468 |
+
========
|
| 469 |
+
|
| 470 |
+
sympy.functions.elementary.integers.floor
|
| 471 |
+
sympy.functions.elementary.integers.ceiling
|
| 472 |
+
|
| 473 |
+
References
|
| 474 |
+
===========
|
| 475 |
+
|
| 476 |
+
.. [1] https://en.wikipedia.org/wiki/Fractional_part
|
| 477 |
+
.. [2] https://mathworld.wolfram.com/FractionalPart.html
|
| 478 |
+
|
| 479 |
+
"""
|
| 480 |
+
@classmethod
|
| 481 |
+
def eval(cls, arg):
|
| 482 |
+
from sympy.calculus.accumulationbounds import AccumBounds
|
| 483 |
+
|
| 484 |
+
def _eval(arg):
|
| 485 |
+
if arg in (S.Infinity, S.NegativeInfinity):
|
| 486 |
+
return AccumBounds(0, 1)
|
| 487 |
+
if arg.is_integer:
|
| 488 |
+
return S.Zero
|
| 489 |
+
if arg.is_number:
|
| 490 |
+
if arg is S.NaN:
|
| 491 |
+
return S.NaN
|
| 492 |
+
elif arg is S.ComplexInfinity:
|
| 493 |
+
return S.NaN
|
| 494 |
+
else:
|
| 495 |
+
return arg - floor(arg)
|
| 496 |
+
return cls(arg, evaluate=False)
|
| 497 |
+
|
| 498 |
+
real, imag = S.Zero, S.Zero
|
| 499 |
+
for t in Add.make_args(arg):
|
| 500 |
+
# Two checks are needed for complex arguments
|
| 501 |
+
# see issue-7649 for details
|
| 502 |
+
if t.is_imaginary or (S.ImaginaryUnit*t).is_real:
|
| 503 |
+
i = im(t)
|
| 504 |
+
if not i.has(S.ImaginaryUnit):
|
| 505 |
+
imag += i
|
| 506 |
+
else:
|
| 507 |
+
real += t
|
| 508 |
+
else:
|
| 509 |
+
real += t
|
| 510 |
+
|
| 511 |
+
real = _eval(real)
|
| 512 |
+
imag = _eval(imag)
|
| 513 |
+
return real + S.ImaginaryUnit*imag
|
| 514 |
+
|
| 515 |
+
def _eval_rewrite_as_floor(self, arg, **kwargs):
|
| 516 |
+
return arg - floor(arg)
|
| 517 |
+
|
| 518 |
+
def _eval_rewrite_as_ceiling(self, arg, **kwargs):
|
| 519 |
+
return arg + ceiling(-arg)
|
| 520 |
+
|
| 521 |
+
def _eval_is_finite(self):
|
| 522 |
+
return True
|
| 523 |
+
|
| 524 |
+
def _eval_is_real(self):
|
| 525 |
+
return self.args[0].is_extended_real
|
| 526 |
+
|
| 527 |
+
def _eval_is_imaginary(self):
|
| 528 |
+
return self.args[0].is_imaginary
|
| 529 |
+
|
| 530 |
+
def _eval_is_integer(self):
|
| 531 |
+
return self.args[0].is_integer
|
| 532 |
+
|
| 533 |
+
def _eval_is_zero(self):
|
| 534 |
+
return fuzzy_or([self.args[0].is_zero, self.args[0].is_integer])
|
| 535 |
+
|
| 536 |
+
def _eval_is_negative(self):
|
| 537 |
+
return False
|
| 538 |
+
|
| 539 |
+
def __ge__(self, other):
|
| 540 |
+
if self.is_extended_real:
|
| 541 |
+
other = _sympify(other)
|
| 542 |
+
# Check if other <= 0
|
| 543 |
+
if other.is_extended_nonpositive:
|
| 544 |
+
return S.true
|
| 545 |
+
# Check if other >= 1
|
| 546 |
+
res = self._value_one_or_more(other)
|
| 547 |
+
if res is not None:
|
| 548 |
+
return not(res)
|
| 549 |
+
return Ge(self, other, evaluate=False)
|
| 550 |
+
|
| 551 |
+
def __gt__(self, other):
|
| 552 |
+
if self.is_extended_real:
|
| 553 |
+
other = _sympify(other)
|
| 554 |
+
# Check if other < 0
|
| 555 |
+
res = self._value_one_or_more(other)
|
| 556 |
+
if res is not None:
|
| 557 |
+
return not(res)
|
| 558 |
+
# Check if other >= 1
|
| 559 |
+
if other.is_extended_negative:
|
| 560 |
+
return S.true
|
| 561 |
+
return Gt(self, other, evaluate=False)
|
| 562 |
+
|
| 563 |
+
def __le__(self, other):
|
| 564 |
+
if self.is_extended_real:
|
| 565 |
+
other = _sympify(other)
|
| 566 |
+
# Check if other < 0
|
| 567 |
+
if other.is_extended_negative:
|
| 568 |
+
return S.false
|
| 569 |
+
# Check if other >= 1
|
| 570 |
+
res = self._value_one_or_more(other)
|
| 571 |
+
if res is not None:
|
| 572 |
+
return res
|
| 573 |
+
return Le(self, other, evaluate=False)
|
| 574 |
+
|
| 575 |
+
def __lt__(self, other):
|
| 576 |
+
if self.is_extended_real:
|
| 577 |
+
other = _sympify(other)
|
| 578 |
+
# Check if other <= 0
|
| 579 |
+
if other.is_extended_nonpositive:
|
| 580 |
+
return S.false
|
| 581 |
+
# Check if other >= 1
|
| 582 |
+
res = self._value_one_or_more(other)
|
| 583 |
+
if res is not None:
|
| 584 |
+
return res
|
| 585 |
+
return Lt(self, other, evaluate=False)
|
| 586 |
+
|
| 587 |
+
def _value_one_or_more(self, other):
|
| 588 |
+
if other.is_extended_real:
|
| 589 |
+
if other.is_number:
|
| 590 |
+
res = other >= 1
|
| 591 |
+
if res and not isinstance(res, Relational):
|
| 592 |
+
return S.true
|
| 593 |
+
if other.is_integer and other.is_positive:
|
| 594 |
+
return S.true
|
| 595 |
+
|
| 596 |
+
def _eval_as_leading_term(self, x, logx=None, cdir=0):
|
| 597 |
+
from sympy.calculus.accumulationbounds import AccumBounds
|
| 598 |
+
arg = self.args[0]
|
| 599 |
+
arg0 = arg.subs(x, 0)
|
| 600 |
+
r = self.subs(x, 0)
|
| 601 |
+
|
| 602 |
+
if arg0.is_finite:
|
| 603 |
+
if r.is_zero:
|
| 604 |
+
ndir = arg.dir(x, cdir=cdir)
|
| 605 |
+
if ndir.is_negative:
|
| 606 |
+
return S.One
|
| 607 |
+
return (arg - arg0).as_leading_term(x, logx=logx, cdir=cdir)
|
| 608 |
+
else:
|
| 609 |
+
return r
|
| 610 |
+
elif arg0 in (S.ComplexInfinity, S.Infinity, S.NegativeInfinity):
|
| 611 |
+
return AccumBounds(0, 1)
|
| 612 |
+
return arg.as_leading_term(x, logx=logx, cdir=cdir)
|
| 613 |
+
|
| 614 |
+
def _eval_nseries(self, x, n, logx, cdir=0):
|
| 615 |
+
from sympy.series.order import Order
|
| 616 |
+
arg = self.args[0]
|
| 617 |
+
arg0 = arg.subs(x, 0)
|
| 618 |
+
r = self.subs(x, 0)
|
| 619 |
+
|
| 620 |
+
if arg0.is_infinite:
|
| 621 |
+
from sympy.calculus.accumulationbounds import AccumBounds
|
| 622 |
+
o = Order(1, (x, 0)) if n <= 0 else AccumBounds(0, 1) + Order(x**n, (x, 0))
|
| 623 |
+
return o
|
| 624 |
+
else:
|
| 625 |
+
res = (arg - arg0)._eval_nseries(x, n, logx=logx, cdir=cdir)
|
| 626 |
+
if r.is_zero:
|
| 627 |
+
ndir = arg.dir(x, cdir=cdir)
|
| 628 |
+
res += S.One if ndir.is_negative else S.Zero
|
| 629 |
+
else:
|
| 630 |
+
res += r
|
| 631 |
+
return res
|
| 632 |
+
|
| 633 |
+
|
| 634 |
+
@dispatch(frac, Basic) # type:ignore
|
| 635 |
+
def _eval_is_eq(lhs, rhs): # noqa:F811
|
| 636 |
+
if (lhs.rewrite(floor) == rhs) or \
|
| 637 |
+
(lhs.rewrite(ceiling) == rhs):
|
| 638 |
+
return True
|
| 639 |
+
# Check if other < 0
|
| 640 |
+
if rhs.is_extended_negative:
|
| 641 |
+
return False
|
| 642 |
+
# Check if other >= 1
|
| 643 |
+
res = lhs._value_one_or_more(rhs)
|
| 644 |
+
if res is not None:
|
| 645 |
+
return False
|
evalkit_tf437/lib/python3.10/site-packages/sympy/functions/elementary/miscellaneous.py
ADDED
|
@@ -0,0 +1,915 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.core import Function, S, sympify, NumberKind
|
| 2 |
+
from sympy.utilities.iterables import sift
|
| 3 |
+
from sympy.core.add import Add
|
| 4 |
+
from sympy.core.containers import Tuple
|
| 5 |
+
from sympy.core.operations import LatticeOp, ShortCircuit
|
| 6 |
+
from sympy.core.function import (Application, Lambda,
|
| 7 |
+
ArgumentIndexError)
|
| 8 |
+
from sympy.core.expr import Expr
|
| 9 |
+
from sympy.core.exprtools import factor_terms
|
| 10 |
+
from sympy.core.mod import Mod
|
| 11 |
+
from sympy.core.mul import Mul
|
| 12 |
+
from sympy.core.numbers import Rational
|
| 13 |
+
from sympy.core.power import Pow
|
| 14 |
+
from sympy.core.relational import Eq, Relational
|
| 15 |
+
from sympy.core.singleton import Singleton
|
| 16 |
+
from sympy.core.sorting import ordered
|
| 17 |
+
from sympy.core.symbol import Dummy
|
| 18 |
+
from sympy.core.rules import Transform
|
| 19 |
+
from sympy.core.logic import fuzzy_and, fuzzy_or, _torf
|
| 20 |
+
from sympy.core.traversal import walk
|
| 21 |
+
from sympy.core.numbers import Integer
|
| 22 |
+
from sympy.logic.boolalg import And, Or
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def _minmax_as_Piecewise(op, *args):
|
| 26 |
+
# helper for Min/Max rewrite as Piecewise
|
| 27 |
+
from sympy.functions.elementary.piecewise import Piecewise
|
| 28 |
+
ec = []
|
| 29 |
+
for i, a in enumerate(args):
|
| 30 |
+
c = [Relational(a, args[j], op) for j in range(i + 1, len(args))]
|
| 31 |
+
ec.append((a, And(*c)))
|
| 32 |
+
return Piecewise(*ec)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class IdentityFunction(Lambda, metaclass=Singleton):
|
| 36 |
+
"""
|
| 37 |
+
The identity function
|
| 38 |
+
|
| 39 |
+
Examples
|
| 40 |
+
========
|
| 41 |
+
|
| 42 |
+
>>> from sympy import Id, Symbol
|
| 43 |
+
>>> x = Symbol('x')
|
| 44 |
+
>>> Id(x)
|
| 45 |
+
x
|
| 46 |
+
|
| 47 |
+
"""
|
| 48 |
+
|
| 49 |
+
_symbol = Dummy('x')
|
| 50 |
+
|
| 51 |
+
@property
|
| 52 |
+
def signature(self):
|
| 53 |
+
return Tuple(self._symbol)
|
| 54 |
+
|
| 55 |
+
@property
|
| 56 |
+
def expr(self):
|
| 57 |
+
return self._symbol
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
Id = S.IdentityFunction
|
| 61 |
+
|
| 62 |
+
###############################################################################
|
| 63 |
+
############################# ROOT and SQUARE ROOT FUNCTION ###################
|
| 64 |
+
###############################################################################
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def sqrt(arg, evaluate=None):
|
| 68 |
+
"""Returns the principal square root.
|
| 69 |
+
|
| 70 |
+
Parameters
|
| 71 |
+
==========
|
| 72 |
+
|
| 73 |
+
evaluate : bool, optional
|
| 74 |
+
The parameter determines if the expression should be evaluated.
|
| 75 |
+
If ``None``, its value is taken from
|
| 76 |
+
``global_parameters.evaluate``.
|
| 77 |
+
|
| 78 |
+
Examples
|
| 79 |
+
========
|
| 80 |
+
|
| 81 |
+
>>> from sympy import sqrt, Symbol, S
|
| 82 |
+
>>> x = Symbol('x')
|
| 83 |
+
|
| 84 |
+
>>> sqrt(x)
|
| 85 |
+
sqrt(x)
|
| 86 |
+
|
| 87 |
+
>>> sqrt(x)**2
|
| 88 |
+
x
|
| 89 |
+
|
| 90 |
+
Note that sqrt(x**2) does not simplify to x.
|
| 91 |
+
|
| 92 |
+
>>> sqrt(x**2)
|
| 93 |
+
sqrt(x**2)
|
| 94 |
+
|
| 95 |
+
This is because the two are not equal to each other in general.
|
| 96 |
+
For example, consider x == -1:
|
| 97 |
+
|
| 98 |
+
>>> from sympy import Eq
|
| 99 |
+
>>> Eq(sqrt(x**2), x).subs(x, -1)
|
| 100 |
+
False
|
| 101 |
+
|
| 102 |
+
This is because sqrt computes the principal square root, so the square may
|
| 103 |
+
put the argument in a different branch. This identity does hold if x is
|
| 104 |
+
positive:
|
| 105 |
+
|
| 106 |
+
>>> y = Symbol('y', positive=True)
|
| 107 |
+
>>> sqrt(y**2)
|
| 108 |
+
y
|
| 109 |
+
|
| 110 |
+
You can force this simplification by using the powdenest() function with
|
| 111 |
+
the force option set to True:
|
| 112 |
+
|
| 113 |
+
>>> from sympy import powdenest
|
| 114 |
+
>>> sqrt(x**2)
|
| 115 |
+
sqrt(x**2)
|
| 116 |
+
>>> powdenest(sqrt(x**2), force=True)
|
| 117 |
+
x
|
| 118 |
+
|
| 119 |
+
To get both branches of the square root you can use the rootof function:
|
| 120 |
+
|
| 121 |
+
>>> from sympy import rootof
|
| 122 |
+
|
| 123 |
+
>>> [rootof(x**2-3,i) for i in (0,1)]
|
| 124 |
+
[-sqrt(3), sqrt(3)]
|
| 125 |
+
|
| 126 |
+
Although ``sqrt`` is printed, there is no ``sqrt`` function so looking for
|
| 127 |
+
``sqrt`` in an expression will fail:
|
| 128 |
+
|
| 129 |
+
>>> from sympy.utilities.misc import func_name
|
| 130 |
+
>>> func_name(sqrt(x))
|
| 131 |
+
'Pow'
|
| 132 |
+
>>> sqrt(x).has(sqrt)
|
| 133 |
+
False
|
| 134 |
+
|
| 135 |
+
To find ``sqrt`` look for ``Pow`` with an exponent of ``1/2``:
|
| 136 |
+
|
| 137 |
+
>>> (x + 1/sqrt(x)).find(lambda i: i.is_Pow and abs(i.exp) is S.Half)
|
| 138 |
+
{1/sqrt(x)}
|
| 139 |
+
|
| 140 |
+
See Also
|
| 141 |
+
========
|
| 142 |
+
|
| 143 |
+
sympy.polys.rootoftools.rootof, root, real_root
|
| 144 |
+
|
| 145 |
+
References
|
| 146 |
+
==========
|
| 147 |
+
|
| 148 |
+
.. [1] https://en.wikipedia.org/wiki/Square_root
|
| 149 |
+
.. [2] https://en.wikipedia.org/wiki/Principal_value
|
| 150 |
+
"""
|
| 151 |
+
# arg = sympify(arg) is handled by Pow
|
| 152 |
+
return Pow(arg, S.Half, evaluate=evaluate)
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def cbrt(arg, evaluate=None):
|
| 156 |
+
"""Returns the principal cube root.
|
| 157 |
+
|
| 158 |
+
Parameters
|
| 159 |
+
==========
|
| 160 |
+
|
| 161 |
+
evaluate : bool, optional
|
| 162 |
+
The parameter determines if the expression should be evaluated.
|
| 163 |
+
If ``None``, its value is taken from
|
| 164 |
+
``global_parameters.evaluate``.
|
| 165 |
+
|
| 166 |
+
Examples
|
| 167 |
+
========
|
| 168 |
+
|
| 169 |
+
>>> from sympy import cbrt, Symbol
|
| 170 |
+
>>> x = Symbol('x')
|
| 171 |
+
|
| 172 |
+
>>> cbrt(x)
|
| 173 |
+
x**(1/3)
|
| 174 |
+
|
| 175 |
+
>>> cbrt(x)**3
|
| 176 |
+
x
|
| 177 |
+
|
| 178 |
+
Note that cbrt(x**3) does not simplify to x.
|
| 179 |
+
|
| 180 |
+
>>> cbrt(x**3)
|
| 181 |
+
(x**3)**(1/3)
|
| 182 |
+
|
| 183 |
+
This is because the two are not equal to each other in general.
|
| 184 |
+
For example, consider `x == -1`:
|
| 185 |
+
|
| 186 |
+
>>> from sympy import Eq
|
| 187 |
+
>>> Eq(cbrt(x**3), x).subs(x, -1)
|
| 188 |
+
False
|
| 189 |
+
|
| 190 |
+
This is because cbrt computes the principal cube root, this
|
| 191 |
+
identity does hold if `x` is positive:
|
| 192 |
+
|
| 193 |
+
>>> y = Symbol('y', positive=True)
|
| 194 |
+
>>> cbrt(y**3)
|
| 195 |
+
y
|
| 196 |
+
|
| 197 |
+
See Also
|
| 198 |
+
========
|
| 199 |
+
|
| 200 |
+
sympy.polys.rootoftools.rootof, root, real_root
|
| 201 |
+
|
| 202 |
+
References
|
| 203 |
+
==========
|
| 204 |
+
|
| 205 |
+
.. [1] https://en.wikipedia.org/wiki/Cube_root
|
| 206 |
+
.. [2] https://en.wikipedia.org/wiki/Principal_value
|
| 207 |
+
|
| 208 |
+
"""
|
| 209 |
+
return Pow(arg, Rational(1, 3), evaluate=evaluate)
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
def root(arg, n, k=0, evaluate=None):
|
| 213 |
+
r"""Returns the *k*-th *n*-th root of ``arg``.
|
| 214 |
+
|
| 215 |
+
Parameters
|
| 216 |
+
==========
|
| 217 |
+
|
| 218 |
+
k : int, optional
|
| 219 |
+
Should be an integer in $\{0, 1, ..., n-1\}$.
|
| 220 |
+
Defaults to the principal root if $0$.
|
| 221 |
+
|
| 222 |
+
evaluate : bool, optional
|
| 223 |
+
The parameter determines if the expression should be evaluated.
|
| 224 |
+
If ``None``, its value is taken from
|
| 225 |
+
``global_parameters.evaluate``.
|
| 226 |
+
|
| 227 |
+
Examples
|
| 228 |
+
========
|
| 229 |
+
|
| 230 |
+
>>> from sympy import root, Rational
|
| 231 |
+
>>> from sympy.abc import x, n
|
| 232 |
+
|
| 233 |
+
>>> root(x, 2)
|
| 234 |
+
sqrt(x)
|
| 235 |
+
|
| 236 |
+
>>> root(x, 3)
|
| 237 |
+
x**(1/3)
|
| 238 |
+
|
| 239 |
+
>>> root(x, n)
|
| 240 |
+
x**(1/n)
|
| 241 |
+
|
| 242 |
+
>>> root(x, -Rational(2, 3))
|
| 243 |
+
x**(-3/2)
|
| 244 |
+
|
| 245 |
+
To get the k-th n-th root, specify k:
|
| 246 |
+
|
| 247 |
+
>>> root(-2, 3, 2)
|
| 248 |
+
-(-1)**(2/3)*2**(1/3)
|
| 249 |
+
|
| 250 |
+
To get all n n-th roots you can use the rootof function.
|
| 251 |
+
The following examples show the roots of unity for n
|
| 252 |
+
equal 2, 3 and 4:
|
| 253 |
+
|
| 254 |
+
>>> from sympy import rootof
|
| 255 |
+
|
| 256 |
+
>>> [rootof(x**2 - 1, i) for i in range(2)]
|
| 257 |
+
[-1, 1]
|
| 258 |
+
|
| 259 |
+
>>> [rootof(x**3 - 1,i) for i in range(3)]
|
| 260 |
+
[1, -1/2 - sqrt(3)*I/2, -1/2 + sqrt(3)*I/2]
|
| 261 |
+
|
| 262 |
+
>>> [rootof(x**4 - 1,i) for i in range(4)]
|
| 263 |
+
[-1, 1, -I, I]
|
| 264 |
+
|
| 265 |
+
SymPy, like other symbolic algebra systems, returns the
|
| 266 |
+
complex root of negative numbers. This is the principal
|
| 267 |
+
root and differs from the text-book result that one might
|
| 268 |
+
be expecting. For example, the cube root of -8 does not
|
| 269 |
+
come back as -2:
|
| 270 |
+
|
| 271 |
+
>>> root(-8, 3)
|
| 272 |
+
2*(-1)**(1/3)
|
| 273 |
+
|
| 274 |
+
The real_root function can be used to either make the principal
|
| 275 |
+
result real (or simply to return the real root directly):
|
| 276 |
+
|
| 277 |
+
>>> from sympy import real_root
|
| 278 |
+
>>> real_root(_)
|
| 279 |
+
-2
|
| 280 |
+
>>> real_root(-32, 5)
|
| 281 |
+
-2
|
| 282 |
+
|
| 283 |
+
Alternatively, the n//2-th n-th root of a negative number can be
|
| 284 |
+
computed with root:
|
| 285 |
+
|
| 286 |
+
>>> root(-32, 5, 5//2)
|
| 287 |
+
-2
|
| 288 |
+
|
| 289 |
+
See Also
|
| 290 |
+
========
|
| 291 |
+
|
| 292 |
+
sympy.polys.rootoftools.rootof
|
| 293 |
+
sympy.core.intfunc.integer_nthroot
|
| 294 |
+
sqrt, real_root
|
| 295 |
+
|
| 296 |
+
References
|
| 297 |
+
==========
|
| 298 |
+
|
| 299 |
+
.. [1] https://en.wikipedia.org/wiki/Square_root
|
| 300 |
+
.. [2] https://en.wikipedia.org/wiki/Real_root
|
| 301 |
+
.. [3] https://en.wikipedia.org/wiki/Root_of_unity
|
| 302 |
+
.. [4] https://en.wikipedia.org/wiki/Principal_value
|
| 303 |
+
.. [5] https://mathworld.wolfram.com/CubeRoot.html
|
| 304 |
+
|
| 305 |
+
"""
|
| 306 |
+
n = sympify(n)
|
| 307 |
+
if k:
|
| 308 |
+
return Mul(Pow(arg, S.One/n, evaluate=evaluate), S.NegativeOne**(2*k/n), evaluate=evaluate)
|
| 309 |
+
return Pow(arg, 1/n, evaluate=evaluate)
|
| 310 |
+
|
| 311 |
+
|
| 312 |
+
def real_root(arg, n=None, evaluate=None):
|
| 313 |
+
r"""Return the real *n*'th-root of *arg* if possible.
|
| 314 |
+
|
| 315 |
+
Parameters
|
| 316 |
+
==========
|
| 317 |
+
|
| 318 |
+
n : int or None, optional
|
| 319 |
+
If *n* is ``None``, then all instances of
|
| 320 |
+
$(-n)^{1/\text{odd}}$ will be changed to $-n^{1/\text{odd}}$.
|
| 321 |
+
This will only create a real root of a principal root.
|
| 322 |
+
The presence of other factors may cause the result to not be
|
| 323 |
+
real.
|
| 324 |
+
|
| 325 |
+
evaluate : bool, optional
|
| 326 |
+
The parameter determines if the expression should be evaluated.
|
| 327 |
+
If ``None``, its value is taken from
|
| 328 |
+
``global_parameters.evaluate``.
|
| 329 |
+
|
| 330 |
+
Examples
|
| 331 |
+
========
|
| 332 |
+
|
| 333 |
+
>>> from sympy import root, real_root
|
| 334 |
+
|
| 335 |
+
>>> real_root(-8, 3)
|
| 336 |
+
-2
|
| 337 |
+
>>> root(-8, 3)
|
| 338 |
+
2*(-1)**(1/3)
|
| 339 |
+
>>> real_root(_)
|
| 340 |
+
-2
|
| 341 |
+
|
| 342 |
+
If one creates a non-principal root and applies real_root, the
|
| 343 |
+
result will not be real (so use with caution):
|
| 344 |
+
|
| 345 |
+
>>> root(-8, 3, 2)
|
| 346 |
+
-2*(-1)**(2/3)
|
| 347 |
+
>>> real_root(_)
|
| 348 |
+
-2*(-1)**(2/3)
|
| 349 |
+
|
| 350 |
+
See Also
|
| 351 |
+
========
|
| 352 |
+
|
| 353 |
+
sympy.polys.rootoftools.rootof
|
| 354 |
+
sympy.core.intfunc.integer_nthroot
|
| 355 |
+
root, sqrt
|
| 356 |
+
"""
|
| 357 |
+
from sympy.functions.elementary.complexes import Abs, im, sign
|
| 358 |
+
from sympy.functions.elementary.piecewise import Piecewise
|
| 359 |
+
if n is not None:
|
| 360 |
+
return Piecewise(
|
| 361 |
+
(root(arg, n, evaluate=evaluate), Or(Eq(n, S.One), Eq(n, S.NegativeOne))),
|
| 362 |
+
(Mul(sign(arg), root(Abs(arg), n, evaluate=evaluate), evaluate=evaluate),
|
| 363 |
+
And(Eq(im(arg), S.Zero), Eq(Mod(n, 2), S.One))),
|
| 364 |
+
(root(arg, n, evaluate=evaluate), True))
|
| 365 |
+
rv = sympify(arg)
|
| 366 |
+
n1pow = Transform(lambda x: -(-x.base)**x.exp,
|
| 367 |
+
lambda x:
|
| 368 |
+
x.is_Pow and
|
| 369 |
+
x.base.is_negative and
|
| 370 |
+
x.exp.is_Rational and
|
| 371 |
+
x.exp.p == 1 and x.exp.q % 2)
|
| 372 |
+
return rv.xreplace(n1pow)
|
| 373 |
+
|
| 374 |
+
###############################################################################
|
| 375 |
+
############################# MINIMUM and MAXIMUM #############################
|
| 376 |
+
###############################################################################
|
| 377 |
+
|
| 378 |
+
|
| 379 |
+
class MinMaxBase(Expr, LatticeOp):
|
| 380 |
+
def __new__(cls, *args, **assumptions):
|
| 381 |
+
from sympy.core.parameters import global_parameters
|
| 382 |
+
evaluate = assumptions.pop('evaluate', global_parameters.evaluate)
|
| 383 |
+
args = (sympify(arg) for arg in args)
|
| 384 |
+
|
| 385 |
+
# first standard filter, for cls.zero and cls.identity
|
| 386 |
+
# also reshape Max(a, Max(b, c)) to Max(a, b, c)
|
| 387 |
+
|
| 388 |
+
if evaluate:
|
| 389 |
+
try:
|
| 390 |
+
args = frozenset(cls._new_args_filter(args))
|
| 391 |
+
except ShortCircuit:
|
| 392 |
+
return cls.zero
|
| 393 |
+
# remove redundant args that are easily identified
|
| 394 |
+
args = cls._collapse_arguments(args, **assumptions)
|
| 395 |
+
# find local zeros
|
| 396 |
+
args = cls._find_localzeros(args, **assumptions)
|
| 397 |
+
args = frozenset(args)
|
| 398 |
+
|
| 399 |
+
if not args:
|
| 400 |
+
return cls.identity
|
| 401 |
+
|
| 402 |
+
if len(args) == 1:
|
| 403 |
+
return list(args).pop()
|
| 404 |
+
|
| 405 |
+
# base creation
|
| 406 |
+
obj = Expr.__new__(cls, *ordered(args), **assumptions)
|
| 407 |
+
obj._argset = args
|
| 408 |
+
return obj
|
| 409 |
+
|
| 410 |
+
@classmethod
|
| 411 |
+
def _collapse_arguments(cls, args, **assumptions):
|
| 412 |
+
"""Remove redundant args.
|
| 413 |
+
|
| 414 |
+
Examples
|
| 415 |
+
========
|
| 416 |
+
|
| 417 |
+
>>> from sympy import Min, Max
|
| 418 |
+
>>> from sympy.abc import a, b, c, d, e
|
| 419 |
+
|
| 420 |
+
Any arg in parent that appears in any
|
| 421 |
+
parent-like function in any of the flat args
|
| 422 |
+
of parent can be removed from that sub-arg:
|
| 423 |
+
|
| 424 |
+
>>> Min(a, Max(b, Min(a, c, d)))
|
| 425 |
+
Min(a, Max(b, Min(c, d)))
|
| 426 |
+
|
| 427 |
+
If the arg of parent appears in an opposite-than parent
|
| 428 |
+
function in any of the flat args of parent that function
|
| 429 |
+
can be replaced with the arg:
|
| 430 |
+
|
| 431 |
+
>>> Min(a, Max(b, Min(c, d, Max(a, e))))
|
| 432 |
+
Min(a, Max(b, Min(a, c, d)))
|
| 433 |
+
"""
|
| 434 |
+
if not args:
|
| 435 |
+
return args
|
| 436 |
+
args = list(ordered(args))
|
| 437 |
+
if cls == Min:
|
| 438 |
+
other = Max
|
| 439 |
+
else:
|
| 440 |
+
other = Min
|
| 441 |
+
|
| 442 |
+
# find global comparable max of Max and min of Min if a new
|
| 443 |
+
# value is being introduced in these args at position 0 of
|
| 444 |
+
# the ordered args
|
| 445 |
+
if args[0].is_number:
|
| 446 |
+
sifted = mins, maxs = [], []
|
| 447 |
+
for i in args:
|
| 448 |
+
for v in walk(i, Min, Max):
|
| 449 |
+
if v.args[0].is_comparable:
|
| 450 |
+
sifted[isinstance(v, Max)].append(v)
|
| 451 |
+
small = Min.identity
|
| 452 |
+
for i in mins:
|
| 453 |
+
v = i.args[0]
|
| 454 |
+
if v.is_number and (v < small) == True:
|
| 455 |
+
small = v
|
| 456 |
+
big = Max.identity
|
| 457 |
+
for i in maxs:
|
| 458 |
+
v = i.args[0]
|
| 459 |
+
if v.is_number and (v > big) == True:
|
| 460 |
+
big = v
|
| 461 |
+
# at the point when this function is called from __new__,
|
| 462 |
+
# there may be more than one numeric arg present since
|
| 463 |
+
# local zeros have not been handled yet, so look through
|
| 464 |
+
# more than the first arg
|
| 465 |
+
if cls == Min:
|
| 466 |
+
for arg in args:
|
| 467 |
+
if not arg.is_number:
|
| 468 |
+
break
|
| 469 |
+
if (arg < small) == True:
|
| 470 |
+
small = arg
|
| 471 |
+
elif cls == Max:
|
| 472 |
+
for arg in args:
|
| 473 |
+
if not arg.is_number:
|
| 474 |
+
break
|
| 475 |
+
if (arg > big) == True:
|
| 476 |
+
big = arg
|
| 477 |
+
T = None
|
| 478 |
+
if cls == Min:
|
| 479 |
+
if small != Min.identity:
|
| 480 |
+
other = Max
|
| 481 |
+
T = small
|
| 482 |
+
elif big != Max.identity:
|
| 483 |
+
other = Min
|
| 484 |
+
T = big
|
| 485 |
+
if T is not None:
|
| 486 |
+
# remove numerical redundancy
|
| 487 |
+
for i in range(len(args)):
|
| 488 |
+
a = args[i]
|
| 489 |
+
if isinstance(a, other):
|
| 490 |
+
a0 = a.args[0]
|
| 491 |
+
if ((a0 > T) if other == Max else (a0 < T)) == True:
|
| 492 |
+
args[i] = cls.identity
|
| 493 |
+
|
| 494 |
+
# remove redundant symbolic args
|
| 495 |
+
def do(ai, a):
|
| 496 |
+
if not isinstance(ai, (Min, Max)):
|
| 497 |
+
return ai
|
| 498 |
+
cond = a in ai.args
|
| 499 |
+
if not cond:
|
| 500 |
+
return ai.func(*[do(i, a) for i in ai.args],
|
| 501 |
+
evaluate=False)
|
| 502 |
+
if isinstance(ai, cls):
|
| 503 |
+
return ai.func(*[do(i, a) for i in ai.args if i != a],
|
| 504 |
+
evaluate=False)
|
| 505 |
+
return a
|
| 506 |
+
for i, a in enumerate(args):
|
| 507 |
+
args[i + 1:] = [do(ai, a) for ai in args[i + 1:]]
|
| 508 |
+
|
| 509 |
+
# factor out common elements as for
|
| 510 |
+
# Min(Max(x, y), Max(x, z)) -> Max(x, Min(y, z))
|
| 511 |
+
# and vice versa when swapping Min/Max -- do this only for the
|
| 512 |
+
# easy case where all functions contain something in common;
|
| 513 |
+
# trying to find some optimal subset of args to modify takes
|
| 514 |
+
# too long
|
| 515 |
+
|
| 516 |
+
def factor_minmax(args):
|
| 517 |
+
is_other = lambda arg: isinstance(arg, other)
|
| 518 |
+
other_args, remaining_args = sift(args, is_other, binary=True)
|
| 519 |
+
if not other_args:
|
| 520 |
+
return args
|
| 521 |
+
|
| 522 |
+
# Min(Max(x, y, z), Max(x, y, u, v)) -> {x,y}, ({z}, {u,v})
|
| 523 |
+
arg_sets = [set(arg.args) for arg in other_args]
|
| 524 |
+
common = set.intersection(*arg_sets)
|
| 525 |
+
if not common:
|
| 526 |
+
return args
|
| 527 |
+
|
| 528 |
+
new_other_args = list(common)
|
| 529 |
+
arg_sets_diff = [arg_set - common for arg_set in arg_sets]
|
| 530 |
+
|
| 531 |
+
# If any set is empty after removing common then all can be
|
| 532 |
+
# discarded e.g. Min(Max(a, b, c), Max(a, b)) -> Max(a, b)
|
| 533 |
+
if all(arg_sets_diff):
|
| 534 |
+
other_args_diff = [other(*s, evaluate=False) for s in arg_sets_diff]
|
| 535 |
+
new_other_args.append(cls(*other_args_diff, evaluate=False))
|
| 536 |
+
|
| 537 |
+
other_args_factored = other(*new_other_args, evaluate=False)
|
| 538 |
+
return remaining_args + [other_args_factored]
|
| 539 |
+
|
| 540 |
+
if len(args) > 1:
|
| 541 |
+
args = factor_minmax(args)
|
| 542 |
+
|
| 543 |
+
return args
|
| 544 |
+
|
| 545 |
+
@classmethod
|
| 546 |
+
def _new_args_filter(cls, arg_sequence):
|
| 547 |
+
"""
|
| 548 |
+
Generator filtering args.
|
| 549 |
+
|
| 550 |
+
first standard filter, for cls.zero and cls.identity.
|
| 551 |
+
Also reshape ``Max(a, Max(b, c))`` to ``Max(a, b, c)``,
|
| 552 |
+
and check arguments for comparability
|
| 553 |
+
"""
|
| 554 |
+
for arg in arg_sequence:
|
| 555 |
+
# pre-filter, checking comparability of arguments
|
| 556 |
+
if not isinstance(arg, Expr) or arg.is_extended_real is False or (
|
| 557 |
+
arg.is_number and
|
| 558 |
+
not arg.is_comparable):
|
| 559 |
+
raise ValueError("The argument '%s' is not comparable." % arg)
|
| 560 |
+
|
| 561 |
+
if arg == cls.zero:
|
| 562 |
+
raise ShortCircuit(arg)
|
| 563 |
+
elif arg == cls.identity:
|
| 564 |
+
continue
|
| 565 |
+
elif arg.func == cls:
|
| 566 |
+
yield from arg.args
|
| 567 |
+
else:
|
| 568 |
+
yield arg
|
| 569 |
+
|
| 570 |
+
@classmethod
|
| 571 |
+
def _find_localzeros(cls, values, **options):
|
| 572 |
+
"""
|
| 573 |
+
Sequentially allocate values to localzeros.
|
| 574 |
+
|
| 575 |
+
When a value is identified as being more extreme than another member it
|
| 576 |
+
replaces that member; if this is never true, then the value is simply
|
| 577 |
+
appended to the localzeros.
|
| 578 |
+
"""
|
| 579 |
+
localzeros = set()
|
| 580 |
+
for v in values:
|
| 581 |
+
is_newzero = True
|
| 582 |
+
localzeros_ = list(localzeros)
|
| 583 |
+
for z in localzeros_:
|
| 584 |
+
if id(v) == id(z):
|
| 585 |
+
is_newzero = False
|
| 586 |
+
else:
|
| 587 |
+
con = cls._is_connected(v, z)
|
| 588 |
+
if con:
|
| 589 |
+
is_newzero = False
|
| 590 |
+
if con is True or con == cls:
|
| 591 |
+
localzeros.remove(z)
|
| 592 |
+
localzeros.update([v])
|
| 593 |
+
if is_newzero:
|
| 594 |
+
localzeros.update([v])
|
| 595 |
+
return localzeros
|
| 596 |
+
|
| 597 |
+
@classmethod
|
| 598 |
+
def _is_connected(cls, x, y):
|
| 599 |
+
"""
|
| 600 |
+
Check if x and y are connected somehow.
|
| 601 |
+
"""
|
| 602 |
+
for i in range(2):
|
| 603 |
+
if x == y:
|
| 604 |
+
return True
|
| 605 |
+
t, f = Max, Min
|
| 606 |
+
for op in "><":
|
| 607 |
+
for j in range(2):
|
| 608 |
+
try:
|
| 609 |
+
if op == ">":
|
| 610 |
+
v = x >= y
|
| 611 |
+
else:
|
| 612 |
+
v = x <= y
|
| 613 |
+
except TypeError:
|
| 614 |
+
return False # non-real arg
|
| 615 |
+
if not v.is_Relational:
|
| 616 |
+
return t if v else f
|
| 617 |
+
t, f = f, t
|
| 618 |
+
x, y = y, x
|
| 619 |
+
x, y = y, x # run next pass with reversed order relative to start
|
| 620 |
+
# simplification can be expensive, so be conservative
|
| 621 |
+
# in what is attempted
|
| 622 |
+
x = factor_terms(x - y)
|
| 623 |
+
y = S.Zero
|
| 624 |
+
|
| 625 |
+
return False
|
| 626 |
+
|
| 627 |
+
def _eval_derivative(self, s):
|
| 628 |
+
# f(x).diff(s) -> x.diff(s) * f.fdiff(1)(s)
|
| 629 |
+
i = 0
|
| 630 |
+
l = []
|
| 631 |
+
for a in self.args:
|
| 632 |
+
i += 1
|
| 633 |
+
da = a.diff(s)
|
| 634 |
+
if da.is_zero:
|
| 635 |
+
continue
|
| 636 |
+
try:
|
| 637 |
+
df = self.fdiff(i)
|
| 638 |
+
except ArgumentIndexError:
|
| 639 |
+
df = Function.fdiff(self, i)
|
| 640 |
+
l.append(df * da)
|
| 641 |
+
return Add(*l)
|
| 642 |
+
|
| 643 |
+
def _eval_rewrite_as_Abs(self, *args, **kwargs):
|
| 644 |
+
from sympy.functions.elementary.complexes import Abs
|
| 645 |
+
s = (args[0] + self.func(*args[1:]))/2
|
| 646 |
+
d = abs(args[0] - self.func(*args[1:]))/2
|
| 647 |
+
return (s + d if isinstance(self, Max) else s - d).rewrite(Abs)
|
| 648 |
+
|
| 649 |
+
def evalf(self, n=15, **options):
|
| 650 |
+
return self.func(*[a.evalf(n, **options) for a in self.args])
|
| 651 |
+
|
| 652 |
+
def n(self, *args, **kwargs):
|
| 653 |
+
return self.evalf(*args, **kwargs)
|
| 654 |
+
|
| 655 |
+
_eval_is_algebraic = lambda s: _torf(i.is_algebraic for i in s.args)
|
| 656 |
+
_eval_is_antihermitian = lambda s: _torf(i.is_antihermitian for i in s.args)
|
| 657 |
+
_eval_is_commutative = lambda s: _torf(i.is_commutative for i in s.args)
|
| 658 |
+
_eval_is_complex = lambda s: _torf(i.is_complex for i in s.args)
|
| 659 |
+
_eval_is_composite = lambda s: _torf(i.is_composite for i in s.args)
|
| 660 |
+
_eval_is_even = lambda s: _torf(i.is_even for i in s.args)
|
| 661 |
+
_eval_is_finite = lambda s: _torf(i.is_finite for i in s.args)
|
| 662 |
+
_eval_is_hermitian = lambda s: _torf(i.is_hermitian for i in s.args)
|
| 663 |
+
_eval_is_imaginary = lambda s: _torf(i.is_imaginary for i in s.args)
|
| 664 |
+
_eval_is_infinite = lambda s: _torf(i.is_infinite for i in s.args)
|
| 665 |
+
_eval_is_integer = lambda s: _torf(i.is_integer for i in s.args)
|
| 666 |
+
_eval_is_irrational = lambda s: _torf(i.is_irrational for i in s.args)
|
| 667 |
+
_eval_is_negative = lambda s: _torf(i.is_negative for i in s.args)
|
| 668 |
+
_eval_is_noninteger = lambda s: _torf(i.is_noninteger for i in s.args)
|
| 669 |
+
_eval_is_nonnegative = lambda s: _torf(i.is_nonnegative for i in s.args)
|
| 670 |
+
_eval_is_nonpositive = lambda s: _torf(i.is_nonpositive for i in s.args)
|
| 671 |
+
_eval_is_nonzero = lambda s: _torf(i.is_nonzero for i in s.args)
|
| 672 |
+
_eval_is_odd = lambda s: _torf(i.is_odd for i in s.args)
|
| 673 |
+
_eval_is_polar = lambda s: _torf(i.is_polar for i in s.args)
|
| 674 |
+
_eval_is_positive = lambda s: _torf(i.is_positive for i in s.args)
|
| 675 |
+
_eval_is_prime = lambda s: _torf(i.is_prime for i in s.args)
|
| 676 |
+
_eval_is_rational = lambda s: _torf(i.is_rational for i in s.args)
|
| 677 |
+
_eval_is_real = lambda s: _torf(i.is_real for i in s.args)
|
| 678 |
+
_eval_is_extended_real = lambda s: _torf(i.is_extended_real for i in s.args)
|
| 679 |
+
_eval_is_transcendental = lambda s: _torf(i.is_transcendental for i in s.args)
|
| 680 |
+
_eval_is_zero = lambda s: _torf(i.is_zero for i in s.args)
|
| 681 |
+
|
| 682 |
+
|
| 683 |
+
class Max(MinMaxBase, Application):
|
| 684 |
+
r"""
|
| 685 |
+
Return, if possible, the maximum value of the list.
|
| 686 |
+
|
| 687 |
+
When number of arguments is equal one, then
|
| 688 |
+
return this argument.
|
| 689 |
+
|
| 690 |
+
When number of arguments is equal two, then
|
| 691 |
+
return, if possible, the value from (a, b) that is $\ge$ the other.
|
| 692 |
+
|
| 693 |
+
In common case, when the length of list greater than 2, the task
|
| 694 |
+
is more complicated. Return only the arguments, which are greater
|
| 695 |
+
than others, if it is possible to determine directional relation.
|
| 696 |
+
|
| 697 |
+
If is not possible to determine such a relation, return a partially
|
| 698 |
+
evaluated result.
|
| 699 |
+
|
| 700 |
+
Assumptions are used to make the decision too.
|
| 701 |
+
|
| 702 |
+
Also, only comparable arguments are permitted.
|
| 703 |
+
|
| 704 |
+
It is named ``Max`` and not ``max`` to avoid conflicts
|
| 705 |
+
with the built-in function ``max``.
|
| 706 |
+
|
| 707 |
+
|
| 708 |
+
Examples
|
| 709 |
+
========
|
| 710 |
+
|
| 711 |
+
>>> from sympy import Max, Symbol, oo
|
| 712 |
+
>>> from sympy.abc import x, y, z
|
| 713 |
+
>>> p = Symbol('p', positive=True)
|
| 714 |
+
>>> n = Symbol('n', negative=True)
|
| 715 |
+
|
| 716 |
+
>>> Max(x, -2)
|
| 717 |
+
Max(-2, x)
|
| 718 |
+
>>> Max(x, -2).subs(x, 3)
|
| 719 |
+
3
|
| 720 |
+
>>> Max(p, -2)
|
| 721 |
+
p
|
| 722 |
+
>>> Max(x, y)
|
| 723 |
+
Max(x, y)
|
| 724 |
+
>>> Max(x, y) == Max(y, x)
|
| 725 |
+
True
|
| 726 |
+
>>> Max(x, Max(y, z))
|
| 727 |
+
Max(x, y, z)
|
| 728 |
+
>>> Max(n, 8, p, 7, -oo)
|
| 729 |
+
Max(8, p)
|
| 730 |
+
>>> Max (1, x, oo)
|
| 731 |
+
oo
|
| 732 |
+
|
| 733 |
+
* Algorithm
|
| 734 |
+
|
| 735 |
+
The task can be considered as searching of supremums in the
|
| 736 |
+
directed complete partial orders [1]_.
|
| 737 |
+
|
| 738 |
+
The source values are sequentially allocated by the isolated subsets
|
| 739 |
+
in which supremums are searched and result as Max arguments.
|
| 740 |
+
|
| 741 |
+
If the resulted supremum is single, then it is returned.
|
| 742 |
+
|
| 743 |
+
The isolated subsets are the sets of values which are only the comparable
|
| 744 |
+
with each other in the current set. E.g. natural numbers are comparable with
|
| 745 |
+
each other, but not comparable with the `x` symbol. Another example: the
|
| 746 |
+
symbol `x` with negative assumption is comparable with a natural number.
|
| 747 |
+
|
| 748 |
+
Also there are "least" elements, which are comparable with all others,
|
| 749 |
+
and have a zero property (maximum or minimum for all elements).
|
| 750 |
+
For example, in case of $\infty$, the allocation operation is terminated
|
| 751 |
+
and only this value is returned.
|
| 752 |
+
|
| 753 |
+
Assumption:
|
| 754 |
+
- if $A > B > C$ then $A > C$
|
| 755 |
+
- if $A = B$ then $B$ can be removed
|
| 756 |
+
|
| 757 |
+
References
|
| 758 |
+
==========
|
| 759 |
+
|
| 760 |
+
.. [1] https://en.wikipedia.org/wiki/Directed_complete_partial_order
|
| 761 |
+
.. [2] https://en.wikipedia.org/wiki/Lattice_%28order%29
|
| 762 |
+
|
| 763 |
+
See Also
|
| 764 |
+
========
|
| 765 |
+
|
| 766 |
+
Min : find minimum values
|
| 767 |
+
"""
|
| 768 |
+
zero = S.Infinity
|
| 769 |
+
identity = S.NegativeInfinity
|
| 770 |
+
|
| 771 |
+
def fdiff( self, argindex ):
|
| 772 |
+
from sympy.functions.special.delta_functions import Heaviside
|
| 773 |
+
n = len(self.args)
|
| 774 |
+
if 0 < argindex and argindex <= n:
|
| 775 |
+
argindex -= 1
|
| 776 |
+
if n == 2:
|
| 777 |
+
return Heaviside(self.args[argindex] - self.args[1 - argindex])
|
| 778 |
+
newargs = tuple([self.args[i] for i in range(n) if i != argindex])
|
| 779 |
+
return Heaviside(self.args[argindex] - Max(*newargs))
|
| 780 |
+
else:
|
| 781 |
+
raise ArgumentIndexError(self, argindex)
|
| 782 |
+
|
| 783 |
+
def _eval_rewrite_as_Heaviside(self, *args, **kwargs):
|
| 784 |
+
from sympy.functions.special.delta_functions import Heaviside
|
| 785 |
+
return Add(*[j*Mul(*[Heaviside(j - i) for i in args if i!=j]) \
|
| 786 |
+
for j in args])
|
| 787 |
+
|
| 788 |
+
def _eval_rewrite_as_Piecewise(self, *args, **kwargs):
|
| 789 |
+
return _minmax_as_Piecewise('>=', *args)
|
| 790 |
+
|
| 791 |
+
def _eval_is_positive(self):
|
| 792 |
+
return fuzzy_or(a.is_positive for a in self.args)
|
| 793 |
+
|
| 794 |
+
def _eval_is_nonnegative(self):
|
| 795 |
+
return fuzzy_or(a.is_nonnegative for a in self.args)
|
| 796 |
+
|
| 797 |
+
def _eval_is_negative(self):
|
| 798 |
+
return fuzzy_and(a.is_negative for a in self.args)
|
| 799 |
+
|
| 800 |
+
|
| 801 |
+
class Min(MinMaxBase, Application):
|
| 802 |
+
"""
|
| 803 |
+
Return, if possible, the minimum value of the list.
|
| 804 |
+
It is named ``Min`` and not ``min`` to avoid conflicts
|
| 805 |
+
with the built-in function ``min``.
|
| 806 |
+
|
| 807 |
+
Examples
|
| 808 |
+
========
|
| 809 |
+
|
| 810 |
+
>>> from sympy import Min, Symbol, oo
|
| 811 |
+
>>> from sympy.abc import x, y
|
| 812 |
+
>>> p = Symbol('p', positive=True)
|
| 813 |
+
>>> n = Symbol('n', negative=True)
|
| 814 |
+
|
| 815 |
+
>>> Min(x, -2)
|
| 816 |
+
Min(-2, x)
|
| 817 |
+
>>> Min(x, -2).subs(x, 3)
|
| 818 |
+
-2
|
| 819 |
+
>>> Min(p, -3)
|
| 820 |
+
-3
|
| 821 |
+
>>> Min(x, y)
|
| 822 |
+
Min(x, y)
|
| 823 |
+
>>> Min(n, 8, p, -7, p, oo)
|
| 824 |
+
Min(-7, n)
|
| 825 |
+
|
| 826 |
+
See Also
|
| 827 |
+
========
|
| 828 |
+
|
| 829 |
+
Max : find maximum values
|
| 830 |
+
"""
|
| 831 |
+
zero = S.NegativeInfinity
|
| 832 |
+
identity = S.Infinity
|
| 833 |
+
|
| 834 |
+
def fdiff( self, argindex ):
|
| 835 |
+
from sympy.functions.special.delta_functions import Heaviside
|
| 836 |
+
n = len(self.args)
|
| 837 |
+
if 0 < argindex and argindex <= n:
|
| 838 |
+
argindex -= 1
|
| 839 |
+
if n == 2:
|
| 840 |
+
return Heaviside( self.args[1-argindex] - self.args[argindex] )
|
| 841 |
+
newargs = tuple([ self.args[i] for i in range(n) if i != argindex])
|
| 842 |
+
return Heaviside( Min(*newargs) - self.args[argindex] )
|
| 843 |
+
else:
|
| 844 |
+
raise ArgumentIndexError(self, argindex)
|
| 845 |
+
|
| 846 |
+
def _eval_rewrite_as_Heaviside(self, *args, **kwargs):
|
| 847 |
+
from sympy.functions.special.delta_functions import Heaviside
|
| 848 |
+
return Add(*[j*Mul(*[Heaviside(i-j) for i in args if i!=j]) \
|
| 849 |
+
for j in args])
|
| 850 |
+
|
| 851 |
+
def _eval_rewrite_as_Piecewise(self, *args, **kwargs):
|
| 852 |
+
return _minmax_as_Piecewise('<=', *args)
|
| 853 |
+
|
| 854 |
+
def _eval_is_positive(self):
|
| 855 |
+
return fuzzy_and(a.is_positive for a in self.args)
|
| 856 |
+
|
| 857 |
+
def _eval_is_nonnegative(self):
|
| 858 |
+
return fuzzy_and(a.is_nonnegative for a in self.args)
|
| 859 |
+
|
| 860 |
+
def _eval_is_negative(self):
|
| 861 |
+
return fuzzy_or(a.is_negative for a in self.args)
|
| 862 |
+
|
| 863 |
+
|
| 864 |
+
class Rem(Function):
|
| 865 |
+
"""Returns the remainder when ``p`` is divided by ``q`` where ``p`` is finite
|
| 866 |
+
and ``q`` is not equal to zero. The result, ``p - int(p/q)*q``, has the same sign
|
| 867 |
+
as the divisor.
|
| 868 |
+
|
| 869 |
+
Parameters
|
| 870 |
+
==========
|
| 871 |
+
|
| 872 |
+
p : Expr
|
| 873 |
+
Dividend.
|
| 874 |
+
|
| 875 |
+
q : Expr
|
| 876 |
+
Divisor.
|
| 877 |
+
|
| 878 |
+
Notes
|
| 879 |
+
=====
|
| 880 |
+
|
| 881 |
+
``Rem`` corresponds to the ``%`` operator in C.
|
| 882 |
+
|
| 883 |
+
Examples
|
| 884 |
+
========
|
| 885 |
+
|
| 886 |
+
>>> from sympy.abc import x, y
|
| 887 |
+
>>> from sympy import Rem
|
| 888 |
+
>>> Rem(x**3, y)
|
| 889 |
+
Rem(x**3, y)
|
| 890 |
+
>>> Rem(x**3, y).subs({x: -5, y: 3})
|
| 891 |
+
-2
|
| 892 |
+
|
| 893 |
+
See Also
|
| 894 |
+
========
|
| 895 |
+
|
| 896 |
+
Mod
|
| 897 |
+
"""
|
| 898 |
+
kind = NumberKind
|
| 899 |
+
|
| 900 |
+
@classmethod
|
| 901 |
+
def eval(cls, p, q):
|
| 902 |
+
"""Return the function remainder if both p, q are numbers and q is not
|
| 903 |
+
zero.
|
| 904 |
+
"""
|
| 905 |
+
|
| 906 |
+
if q.is_zero:
|
| 907 |
+
raise ZeroDivisionError("Division by zero")
|
| 908 |
+
if p is S.NaN or q is S.NaN or p.is_finite is False or q.is_finite is False:
|
| 909 |
+
return S.NaN
|
| 910 |
+
if p is S.Zero or p in (q, -q) or (p.is_integer and q == 1):
|
| 911 |
+
return S.Zero
|
| 912 |
+
|
| 913 |
+
if q.is_Number:
|
| 914 |
+
if p.is_Number:
|
| 915 |
+
return p - Integer(p/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2 |
+
from sympy.core.basic import Basic, as_Basic
|
| 3 |
+
from sympy.core.numbers import Rational, NumberSymbol, _illegal
|
| 4 |
+
from sympy.core.parameters import global_parameters
|
| 5 |
+
from sympy.core.relational import (Lt, Gt, Eq, Ne, Relational,
|
| 6 |
+
_canonical, _canonical_coeff)
|
| 7 |
+
from sympy.core.sorting import ordered
|
| 8 |
+
from sympy.functions.elementary.miscellaneous import Max, Min
|
| 9 |
+
from sympy.logic.boolalg import (And, Boolean, distribute_and_over_or, Not,
|
| 10 |
+
true, false, Or, ITE, simplify_logic, to_cnf, distribute_or_over_and)
|
| 11 |
+
from sympy.utilities.iterables import uniq, sift, common_prefix
|
| 12 |
+
from sympy.utilities.misc import filldedent, func_name
|
| 13 |
+
|
| 14 |
+
from itertools import product
|
| 15 |
+
|
| 16 |
+
Undefined = S.NaN # Piecewise()
|
| 17 |
+
|
| 18 |
+
class ExprCondPair(Tuple):
|
| 19 |
+
"""Represents an expression, condition pair."""
|
| 20 |
+
|
| 21 |
+
def __new__(cls, expr, cond):
|
| 22 |
+
expr = as_Basic(expr)
|
| 23 |
+
if cond == True:
|
| 24 |
+
return Tuple.__new__(cls, expr, true)
|
| 25 |
+
elif cond == False:
|
| 26 |
+
return Tuple.__new__(cls, expr, false)
|
| 27 |
+
elif isinstance(cond, Basic) and cond.has(Piecewise):
|
| 28 |
+
cond = piecewise_fold(cond)
|
| 29 |
+
if isinstance(cond, Piecewise):
|
| 30 |
+
cond = cond.rewrite(ITE)
|
| 31 |
+
|
| 32 |
+
if not isinstance(cond, Boolean):
|
| 33 |
+
raise TypeError(filldedent('''
|
| 34 |
+
Second argument must be a Boolean,
|
| 35 |
+
not `%s`''' % func_name(cond)))
|
| 36 |
+
return Tuple.__new__(cls, expr, cond)
|
| 37 |
+
|
| 38 |
+
@property
|
| 39 |
+
def expr(self):
|
| 40 |
+
"""
|
| 41 |
+
Returns the expression of this pair.
|
| 42 |
+
"""
|
| 43 |
+
return self.args[0]
|
| 44 |
+
|
| 45 |
+
@property
|
| 46 |
+
def cond(self):
|
| 47 |
+
"""
|
| 48 |
+
Returns the condition of this pair.
|
| 49 |
+
"""
|
| 50 |
+
return self.args[1]
|
| 51 |
+
|
| 52 |
+
@property
|
| 53 |
+
def is_commutative(self):
|
| 54 |
+
return self.expr.is_commutative
|
| 55 |
+
|
| 56 |
+
def __iter__(self):
|
| 57 |
+
yield self.expr
|
| 58 |
+
yield self.cond
|
| 59 |
+
|
| 60 |
+
def _eval_simplify(self, **kwargs):
|
| 61 |
+
return self.func(*[a.simplify(**kwargs) for a in self.args])
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
class Piecewise(Function):
|
| 65 |
+
"""
|
| 66 |
+
Represents a piecewise function.
|
| 67 |
+
|
| 68 |
+
Usage:
|
| 69 |
+
|
| 70 |
+
Piecewise( (expr,cond), (expr,cond), ... )
|
| 71 |
+
- Each argument is a 2-tuple defining an expression and condition
|
| 72 |
+
- The conds are evaluated in turn returning the first that is True.
|
| 73 |
+
If any of the evaluated conds are not explicitly False,
|
| 74 |
+
e.g. ``x < 1``, the function is returned in symbolic form.
|
| 75 |
+
- If the function is evaluated at a place where all conditions are False,
|
| 76 |
+
nan will be returned.
|
| 77 |
+
- Pairs where the cond is explicitly False, will be removed and no pair
|
| 78 |
+
appearing after a True condition will ever be retained. If a single
|
| 79 |
+
pair with a True condition remains, it will be returned, even when
|
| 80 |
+
evaluation is False.
|
| 81 |
+
|
| 82 |
+
Examples
|
| 83 |
+
========
|
| 84 |
+
|
| 85 |
+
>>> from sympy import Piecewise, log, piecewise_fold
|
| 86 |
+
>>> from sympy.abc import x, y
|
| 87 |
+
>>> f = x**2
|
| 88 |
+
>>> g = log(x)
|
| 89 |
+
>>> p = Piecewise((0, x < -1), (f, x <= 1), (g, True))
|
| 90 |
+
>>> p.subs(x,1)
|
| 91 |
+
1
|
| 92 |
+
>>> p.subs(x,5)
|
| 93 |
+
log(5)
|
| 94 |
+
|
| 95 |
+
Booleans can contain Piecewise elements:
|
| 96 |
+
|
| 97 |
+
>>> cond = (x < y).subs(x, Piecewise((2, x < 0), (3, True))); cond
|
| 98 |
+
Piecewise((2, x < 0), (3, True)) < y
|
| 99 |
+
|
| 100 |
+
The folded version of this results in a Piecewise whose
|
| 101 |
+
expressions are Booleans:
|
| 102 |
+
|
| 103 |
+
>>> folded_cond = piecewise_fold(cond); folded_cond
|
| 104 |
+
Piecewise((2 < y, x < 0), (3 < y, True))
|
| 105 |
+
|
| 106 |
+
When a Boolean containing Piecewise (like cond) or a Piecewise
|
| 107 |
+
with Boolean expressions (like folded_cond) is used as a condition,
|
| 108 |
+
it is converted to an equivalent :class:`~.ITE` object:
|
| 109 |
+
|
| 110 |
+
>>> Piecewise((1, folded_cond))
|
| 111 |
+
Piecewise((1, ITE(x < 0, y > 2, y > 3)))
|
| 112 |
+
|
| 113 |
+
When a condition is an ``ITE``, it will be converted to a simplified
|
| 114 |
+
Boolean expression:
|
| 115 |
+
|
| 116 |
+
>>> piecewise_fold(_)
|
| 117 |
+
Piecewise((1, ((x >= 0) | (y > 2)) & ((y > 3) | (x < 0))))
|
| 118 |
+
|
| 119 |
+
See Also
|
| 120 |
+
========
|
| 121 |
+
|
| 122 |
+
piecewise_fold
|
| 123 |
+
piecewise_exclusive
|
| 124 |
+
ITE
|
| 125 |
+
"""
|
| 126 |
+
|
| 127 |
+
nargs = None
|
| 128 |
+
is_Piecewise = True
|
| 129 |
+
|
| 130 |
+
def __new__(cls, *args, **options):
|
| 131 |
+
if len(args) == 0:
|
| 132 |
+
raise TypeError("At least one (expr, cond) pair expected.")
|
| 133 |
+
# (Try to) sympify args first
|
| 134 |
+
newargs = []
|
| 135 |
+
for ec in args:
|
| 136 |
+
# ec could be a ExprCondPair or a tuple
|
| 137 |
+
pair = ExprCondPair(*getattr(ec, 'args', ec))
|
| 138 |
+
cond = pair.cond
|
| 139 |
+
if cond is false:
|
| 140 |
+
continue
|
| 141 |
+
newargs.append(pair)
|
| 142 |
+
if cond is true:
|
| 143 |
+
break
|
| 144 |
+
|
| 145 |
+
eval = options.pop('evaluate', global_parameters.evaluate)
|
| 146 |
+
if eval:
|
| 147 |
+
r = cls.eval(*newargs)
|
| 148 |
+
if r is not None:
|
| 149 |
+
return r
|
| 150 |
+
elif len(newargs) == 1 and newargs[0].cond == True:
|
| 151 |
+
return newargs[0].expr
|
| 152 |
+
|
| 153 |
+
return Basic.__new__(cls, *newargs, **options)
|
| 154 |
+
|
| 155 |
+
@classmethod
|
| 156 |
+
def eval(cls, *_args):
|
| 157 |
+
"""Either return a modified version of the args or, if no
|
| 158 |
+
modifications were made, return None.
|
| 159 |
+
|
| 160 |
+
Modifications that are made here:
|
| 161 |
+
|
| 162 |
+
1. relationals are made canonical
|
| 163 |
+
2. any False conditions are dropped
|
| 164 |
+
3. any repeat of a previous condition is ignored
|
| 165 |
+
4. any args past one with a true condition are dropped
|
| 166 |
+
|
| 167 |
+
If there are no args left, nan will be returned.
|
| 168 |
+
If there is a single arg with a True condition, its
|
| 169 |
+
corresponding expression will be returned.
|
| 170 |
+
|
| 171 |
+
EXAMPLES
|
| 172 |
+
========
|
| 173 |
+
|
| 174 |
+
>>> from sympy import Piecewise
|
| 175 |
+
>>> from sympy.abc import x
|
| 176 |
+
>>> cond = -x < -1
|
| 177 |
+
>>> args = [(1, cond), (4, cond), (3, False), (2, True), (5, x < 1)]
|
| 178 |
+
>>> Piecewise(*args, evaluate=False)
|
| 179 |
+
Piecewise((1, -x < -1), (4, -x < -1), (2, True))
|
| 180 |
+
>>> Piecewise(*args)
|
| 181 |
+
Piecewise((1, x > 1), (2, True))
|
| 182 |
+
"""
|
| 183 |
+
if not _args:
|
| 184 |
+
return Undefined
|
| 185 |
+
|
| 186 |
+
if len(_args) == 1 and _args[0][-1] == True:
|
| 187 |
+
return _args[0][0]
|
| 188 |
+
|
| 189 |
+
newargs = _piecewise_collapse_arguments(_args)
|
| 190 |
+
|
| 191 |
+
# some conditions may have been redundant
|
| 192 |
+
missing = len(newargs) != len(_args)
|
| 193 |
+
# some conditions may have changed
|
| 194 |
+
same = all(a == b for a, b in zip(newargs, _args))
|
| 195 |
+
# if either change happened we return the expr with the
|
| 196 |
+
# updated args
|
| 197 |
+
if not newargs:
|
| 198 |
+
raise ValueError(filldedent('''
|
| 199 |
+
There are no conditions (or none that
|
| 200 |
+
are not trivially false) to define an
|
| 201 |
+
expression.'''))
|
| 202 |
+
if missing or not same:
|
| 203 |
+
return cls(*newargs)
|
| 204 |
+
|
| 205 |
+
def doit(self, **hints):
|
| 206 |
+
"""
|
| 207 |
+
Evaluate this piecewise function.
|
| 208 |
+
"""
|
| 209 |
+
newargs = []
|
| 210 |
+
for e, c in self.args:
|
| 211 |
+
if hints.get('deep', True):
|
| 212 |
+
if isinstance(e, Basic):
|
| 213 |
+
newe = e.doit(**hints)
|
| 214 |
+
if newe != self:
|
| 215 |
+
e = newe
|
| 216 |
+
if isinstance(c, Basic):
|
| 217 |
+
c = c.doit(**hints)
|
| 218 |
+
newargs.append((e, c))
|
| 219 |
+
return self.func(*newargs)
|
| 220 |
+
|
| 221 |
+
def _eval_simplify(self, **kwargs):
|
| 222 |
+
return piecewise_simplify(self, **kwargs)
|
| 223 |
+
|
| 224 |
+
def _eval_as_leading_term(self, x, logx=None, cdir=0):
|
| 225 |
+
for e, c in self.args:
|
| 226 |
+
if c == True or c.subs(x, 0) == True:
|
| 227 |
+
return e.as_leading_term(x)
|
| 228 |
+
|
| 229 |
+
def _eval_adjoint(self):
|
| 230 |
+
return self.func(*[(e.adjoint(), c) for e, c in self.args])
|
| 231 |
+
|
| 232 |
+
def _eval_conjugate(self):
|
| 233 |
+
return self.func(*[(e.conjugate(), c) for e, c in self.args])
|
| 234 |
+
|
| 235 |
+
def _eval_derivative(self, x):
|
| 236 |
+
return self.func(*[(diff(e, x), c) for e, c in self.args])
|
| 237 |
+
|
| 238 |
+
def _eval_evalf(self, prec):
|
| 239 |
+
return self.func(*[(e._evalf(prec), c) for e, c in self.args])
|
| 240 |
+
|
| 241 |
+
def _eval_is_meromorphic(self, x, a):
|
| 242 |
+
# Conditions often implicitly assume that the argument is real.
|
| 243 |
+
# Hence, there needs to be some check for as_set.
|
| 244 |
+
if not a.is_real:
|
| 245 |
+
return None
|
| 246 |
+
|
| 247 |
+
# Then, scan ExprCondPairs in the given order to find a piece that would contain a,
|
| 248 |
+
# possibly as a boundary point.
|
| 249 |
+
for e, c in self.args:
|
| 250 |
+
cond = c.subs(x, a)
|
| 251 |
+
|
| 252 |
+
if cond.is_Relational:
|
| 253 |
+
return None
|
| 254 |
+
if a in c.as_set().boundary:
|
| 255 |
+
return None
|
| 256 |
+
# Apply expression if a is an interior point of the domain of e.
|
| 257 |
+
if cond:
|
| 258 |
+
return e._eval_is_meromorphic(x, a)
|
| 259 |
+
|
| 260 |
+
def piecewise_integrate(self, x, **kwargs):
|
| 261 |
+
"""Return the Piecewise with each expression being
|
| 262 |
+
replaced with its antiderivative. To obtain a continuous
|
| 263 |
+
antiderivative, use the :func:`~.integrate` function or method.
|
| 264 |
+
|
| 265 |
+
Examples
|
| 266 |
+
========
|
| 267 |
+
|
| 268 |
+
>>> from sympy import Piecewise
|
| 269 |
+
>>> from sympy.abc import x
|
| 270 |
+
>>> p = Piecewise((0, x < 0), (1, x < 1), (2, True))
|
| 271 |
+
>>> p.piecewise_integrate(x)
|
| 272 |
+
Piecewise((0, x < 0), (x, x < 1), (2*x, True))
|
| 273 |
+
|
| 274 |
+
Note that this does not give a continuous function, e.g.
|
| 275 |
+
at x = 1 the 3rd condition applies and the antiderivative
|
| 276 |
+
there is 2*x so the value of the antiderivative is 2:
|
| 277 |
+
|
| 278 |
+
>>> anti = _
|
| 279 |
+
>>> anti.subs(x, 1)
|
| 280 |
+
2
|
| 281 |
+
|
| 282 |
+
The continuous derivative accounts for the integral *up to*
|
| 283 |
+
the point of interest, however:
|
| 284 |
+
|
| 285 |
+
>>> p.integrate(x)
|
| 286 |
+
Piecewise((0, x < 0), (x, x < 1), (2*x - 1, True))
|
| 287 |
+
>>> _.subs(x, 1)
|
| 288 |
+
1
|
| 289 |
+
|
| 290 |
+
See Also
|
| 291 |
+
========
|
| 292 |
+
Piecewise._eval_integral
|
| 293 |
+
"""
|
| 294 |
+
from sympy.integrals import integrate
|
| 295 |
+
return self.func(*[(integrate(e, x, **kwargs), c) for e, c in self.args])
|
| 296 |
+
|
| 297 |
+
def _handle_irel(self, x, handler):
|
| 298 |
+
"""Return either None (if the conditions of self depend only on x) else
|
| 299 |
+
a Piecewise expression whose expressions (handled by the handler that
|
| 300 |
+
was passed) are paired with the governing x-independent relationals,
|
| 301 |
+
e.g. Piecewise((A, a(x) & b(y)), (B, c(x) | c(y)) ->
|
| 302 |
+
Piecewise(
|
| 303 |
+
(handler(Piecewise((A, a(x) & True), (B, c(x) | True)), b(y) & c(y)),
|
| 304 |
+
(handler(Piecewise((A, a(x) & True), (B, c(x) | False)), b(y)),
|
| 305 |
+
(handler(Piecewise((A, a(x) & False), (B, c(x) | True)), c(y)),
|
| 306 |
+
(handler(Piecewise((A, a(x) & False), (B, c(x) | False)), True))
|
| 307 |
+
"""
|
| 308 |
+
# identify governing relationals
|
| 309 |
+
rel = self.atoms(Relational)
|
| 310 |
+
irel = list(ordered([r for r in rel if x not in r.free_symbols
|
| 311 |
+
and r not in (S.true, S.false)]))
|
| 312 |
+
if irel:
|
| 313 |
+
args = {}
|
| 314 |
+
exprinorder = []
|
| 315 |
+
for truth in product((1, 0), repeat=len(irel)):
|
| 316 |
+
reps = dict(zip(irel, truth))
|
| 317 |
+
# only store the true conditions since the false are implied
|
| 318 |
+
# when they appear lower in the Piecewise args
|
| 319 |
+
if 1 not in truth:
|
| 320 |
+
cond = None # flag this one so it doesn't get combined
|
| 321 |
+
else:
|
| 322 |
+
andargs = Tuple(*[i for i in reps if reps[i]])
|
| 323 |
+
free = list(andargs.free_symbols)
|
| 324 |
+
if len(free) == 1:
|
| 325 |
+
from sympy.solvers.inequalities import (
|
| 326 |
+
reduce_inequalities, _solve_inequality)
|
| 327 |
+
try:
|
| 328 |
+
t = reduce_inequalities(andargs, free[0])
|
| 329 |
+
# ValueError when there are potentially
|
| 330 |
+
# nonvanishing imaginary parts
|
| 331 |
+
except (ValueError, NotImplementedError):
|
| 332 |
+
# at least isolate free symbol on left
|
| 333 |
+
t = And(*[_solve_inequality(
|
| 334 |
+
a, free[0], linear=True)
|
| 335 |
+
for a in andargs])
|
| 336 |
+
else:
|
| 337 |
+
t = And(*andargs)
|
| 338 |
+
if t is S.false:
|
| 339 |
+
continue # an impossible combination
|
| 340 |
+
cond = t
|
| 341 |
+
expr = handler(self.xreplace(reps))
|
| 342 |
+
if isinstance(expr, self.func) and len(expr.args) == 1:
|
| 343 |
+
expr, econd = expr.args[0]
|
| 344 |
+
cond = And(econd, True if cond is None else cond)
|
| 345 |
+
# the ec pairs are being collected since all possibilities
|
| 346 |
+
# are being enumerated, but don't put the last one in since
|
| 347 |
+
# its expr might match a previous expression and it
|
| 348 |
+
# must appear last in the args
|
| 349 |
+
if cond is not None:
|
| 350 |
+
args.setdefault(expr, []).append(cond)
|
| 351 |
+
# but since we only store the true conditions we must maintain
|
| 352 |
+
# the order so that the expression with the most true values
|
| 353 |
+
# comes first
|
| 354 |
+
exprinorder.append(expr)
|
| 355 |
+
# convert collected conditions as args of Or
|
| 356 |
+
for k in args:
|
| 357 |
+
args[k] = Or(*args[k])
|
| 358 |
+
# take them in the order obtained
|
| 359 |
+
args = [(e, args[e]) for e in uniq(exprinorder)]
|
| 360 |
+
# add in the last arg
|
| 361 |
+
args.append((expr, True))
|
| 362 |
+
return Piecewise(*args)
|
| 363 |
+
|
| 364 |
+
def _eval_integral(self, x, _first=True, **kwargs):
|
| 365 |
+
"""Return the indefinite integral of the
|
| 366 |
+
Piecewise such that subsequent substitution of x with a
|
| 367 |
+
value will give the value of the integral (not including
|
| 368 |
+
the constant of integration) up to that point. To only
|
| 369 |
+
integrate the individual parts of Piecewise, use the
|
| 370 |
+
``piecewise_integrate`` method.
|
| 371 |
+
|
| 372 |
+
Examples
|
| 373 |
+
========
|
| 374 |
+
|
| 375 |
+
>>> from sympy import Piecewise
|
| 376 |
+
>>> from sympy.abc import x
|
| 377 |
+
>>> p = Piecewise((0, x < 0), (1, x < 1), (2, True))
|
| 378 |
+
>>> p.integrate(x)
|
| 379 |
+
Piecewise((0, x < 0), (x, x < 1), (2*x - 1, True))
|
| 380 |
+
>>> p.piecewise_integrate(x)
|
| 381 |
+
Piecewise((0, x < 0), (x, x < 1), (2*x, True))
|
| 382 |
+
|
| 383 |
+
See Also
|
| 384 |
+
========
|
| 385 |
+
Piecewise.piecewise_integrate
|
| 386 |
+
"""
|
| 387 |
+
from sympy.integrals.integrals import integrate
|
| 388 |
+
|
| 389 |
+
if _first:
|
| 390 |
+
def handler(ipw):
|
| 391 |
+
if isinstance(ipw, self.func):
|
| 392 |
+
return ipw._eval_integral(x, _first=False, **kwargs)
|
| 393 |
+
else:
|
| 394 |
+
return ipw.integrate(x, **kwargs)
|
| 395 |
+
irv = self._handle_irel(x, handler)
|
| 396 |
+
if irv is not None:
|
| 397 |
+
return irv
|
| 398 |
+
|
| 399 |
+
# handle a Piecewise from -oo to oo with and no x-independent relationals
|
| 400 |
+
# -----------------------------------------------------------------------
|
| 401 |
+
ok, abei = self._intervals(x)
|
| 402 |
+
if not ok:
|
| 403 |
+
from sympy.integrals.integrals import Integral
|
| 404 |
+
return Integral(self, x) # unevaluated
|
| 405 |
+
|
| 406 |
+
pieces = [(a, b) for a, b, _, _ in abei]
|
| 407 |
+
oo = S.Infinity
|
| 408 |
+
done = [(-oo, oo, -1)]
|
| 409 |
+
for k, p in enumerate(pieces):
|
| 410 |
+
if p == (-oo, oo):
|
| 411 |
+
# all undone intervals will get this key
|
| 412 |
+
for j, (a, b, i) in enumerate(done):
|
| 413 |
+
if i == -1:
|
| 414 |
+
done[j] = a, b, k
|
| 415 |
+
break # nothing else to consider
|
| 416 |
+
N = len(done) - 1
|
| 417 |
+
for j, (a, b, i) in enumerate(reversed(done)):
|
| 418 |
+
if i == -1:
|
| 419 |
+
j = N - j
|
| 420 |
+
done[j: j + 1] = _clip(p, (a, b), k)
|
| 421 |
+
done = [(a, b, i) for a, b, i in done if a != b]
|
| 422 |
+
|
| 423 |
+
# append an arg if there is a hole so a reference to
|
| 424 |
+
# argument -1 will give Undefined
|
| 425 |
+
if any(i == -1 for (a, b, i) in done):
|
| 426 |
+
abei.append((-oo, oo, Undefined, -1))
|
| 427 |
+
|
| 428 |
+
# return the sum of the intervals
|
| 429 |
+
args = []
|
| 430 |
+
sum = None
|
| 431 |
+
for a, b, i in done:
|
| 432 |
+
anti = integrate(abei[i][-2], x, **kwargs)
|
| 433 |
+
if sum is None:
|
| 434 |
+
sum = anti
|
| 435 |
+
else:
|
| 436 |
+
sum = sum.subs(x, a)
|
| 437 |
+
e = anti._eval_interval(x, a, x)
|
| 438 |
+
if sum.has(*_illegal) or e.has(*_illegal):
|
| 439 |
+
sum = anti
|
| 440 |
+
else:
|
| 441 |
+
sum += e
|
| 442 |
+
# see if we know whether b is contained in original
|
| 443 |
+
# condition
|
| 444 |
+
if b is S.Infinity:
|
| 445 |
+
cond = True
|
| 446 |
+
elif self.args[abei[i][-1]].cond.subs(x, b) == False:
|
| 447 |
+
cond = (x < b)
|
| 448 |
+
else:
|
| 449 |
+
cond = (x <= b)
|
| 450 |
+
args.append((sum, cond))
|
| 451 |
+
return Piecewise(*args)
|
| 452 |
+
|
| 453 |
+
def _eval_interval(self, sym, a, b, _first=True):
|
| 454 |
+
"""Evaluates the function along the sym in a given interval [a, b]"""
|
| 455 |
+
# FIXME: Currently complex intervals are not supported. A possible
|
| 456 |
+
# replacement algorithm, discussed in issue 5227, can be found in the
|
| 457 |
+
# following papers;
|
| 458 |
+
# http://portal.acm.org/citation.cfm?id=281649
|
| 459 |
+
# http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.70.4127&rep=rep1&type=pdf
|
| 460 |
+
|
| 461 |
+
if a is None or b is None:
|
| 462 |
+
# In this case, it is just simple substitution
|
| 463 |
+
return super()._eval_interval(sym, a, b)
|
| 464 |
+
else:
|
| 465 |
+
x, lo, hi = map(as_Basic, (sym, a, b))
|
| 466 |
+
|
| 467 |
+
if _first: # get only x-dependent relationals
|
| 468 |
+
def handler(ipw):
|
| 469 |
+
if isinstance(ipw, self.func):
|
| 470 |
+
return ipw._eval_interval(x, lo, hi, _first=None)
|
| 471 |
+
else:
|
| 472 |
+
return ipw._eval_interval(x, lo, hi)
|
| 473 |
+
irv = self._handle_irel(x, handler)
|
| 474 |
+
if irv is not None:
|
| 475 |
+
return irv
|
| 476 |
+
|
| 477 |
+
if (lo < hi) is S.false or (
|
| 478 |
+
lo is S.Infinity or hi is S.NegativeInfinity):
|
| 479 |
+
rv = self._eval_interval(x, hi, lo, _first=False)
|
| 480 |
+
if isinstance(rv, Piecewise):
|
| 481 |
+
rv = Piecewise(*[(-e, c) for e, c in rv.args])
|
| 482 |
+
else:
|
| 483 |
+
rv = -rv
|
| 484 |
+
return rv
|
| 485 |
+
|
| 486 |
+
if (lo < hi) is S.true or (
|
| 487 |
+
hi is S.Infinity or lo is S.NegativeInfinity):
|
| 488 |
+
pass
|
| 489 |
+
else:
|
| 490 |
+
_a = Dummy('lo')
|
| 491 |
+
_b = Dummy('hi')
|
| 492 |
+
a = lo if lo.is_comparable else _a
|
| 493 |
+
b = hi if hi.is_comparable else _b
|
| 494 |
+
pos = self._eval_interval(x, a, b, _first=False)
|
| 495 |
+
if a == _a and b == _b:
|
| 496 |
+
# it's purely symbolic so just swap lo and hi and
|
| 497 |
+
# change the sign to get the value for when lo > hi
|
| 498 |
+
neg, pos = (-pos.xreplace({_a: hi, _b: lo}),
|
| 499 |
+
pos.xreplace({_a: lo, _b: hi}))
|
| 500 |
+
else:
|
| 501 |
+
# at least one of the bounds was comparable, so allow
|
| 502 |
+
# _eval_interval to use that information when computing
|
| 503 |
+
# the interval with lo and hi reversed
|
| 504 |
+
neg, pos = (-self._eval_interval(x, hi, lo, _first=False),
|
| 505 |
+
pos.xreplace({_a: lo, _b: hi}))
|
| 506 |
+
|
| 507 |
+
# allow simplification based on ordering of lo and hi
|
| 508 |
+
p = Dummy('', positive=True)
|
| 509 |
+
if lo.is_Symbol:
|
| 510 |
+
pos = pos.xreplace({lo: hi - p}).xreplace({p: hi - lo})
|
| 511 |
+
neg = neg.xreplace({lo: hi + p}).xreplace({p: lo - hi})
|
| 512 |
+
elif hi.is_Symbol:
|
| 513 |
+
pos = pos.xreplace({hi: lo + p}).xreplace({p: hi - lo})
|
| 514 |
+
neg = neg.xreplace({hi: lo - p}).xreplace({p: lo - hi})
|
| 515 |
+
# evaluate limits that may have unevaluate Min/Max
|
| 516 |
+
touch = lambda _: _.replace(
|
| 517 |
+
lambda x: isinstance(x, (Min, Max)),
|
| 518 |
+
lambda x: x.func(*x.args))
|
| 519 |
+
neg = touch(neg)
|
| 520 |
+
pos = touch(pos)
|
| 521 |
+
# assemble return expression; make the first condition be Lt
|
| 522 |
+
# b/c then the first expression will look the same whether
|
| 523 |
+
# the lo or hi limit is symbolic
|
| 524 |
+
if a == _a: # the lower limit was symbolic
|
| 525 |
+
rv = Piecewise(
|
| 526 |
+
(pos,
|
| 527 |
+
lo < hi),
|
| 528 |
+
(neg,
|
| 529 |
+
True))
|
| 530 |
+
else:
|
| 531 |
+
rv = Piecewise(
|
| 532 |
+
(neg,
|
| 533 |
+
hi < lo),
|
| 534 |
+
(pos,
|
| 535 |
+
True))
|
| 536 |
+
|
| 537 |
+
if rv == Undefined:
|
| 538 |
+
raise ValueError("Can't integrate across undefined region.")
|
| 539 |
+
if any(isinstance(i, Piecewise) for i in (pos, neg)):
|
| 540 |
+
rv = piecewise_fold(rv)
|
| 541 |
+
return rv
|
| 542 |
+
|
| 543 |
+
# handle a Piecewise with lo <= hi and no x-independent relationals
|
| 544 |
+
# -----------------------------------------------------------------
|
| 545 |
+
ok, abei = self._intervals(x)
|
| 546 |
+
if not ok:
|
| 547 |
+
from sympy.integrals.integrals import Integral
|
| 548 |
+
# not being able to do the interval of f(x) can
|
| 549 |
+
# be stated as not being able to do the integral
|
| 550 |
+
# of f'(x) over the same range
|
| 551 |
+
return Integral(self.diff(x), (x, lo, hi)) # unevaluated
|
| 552 |
+
|
| 553 |
+
pieces = [(a, b) for a, b, _, _ in abei]
|
| 554 |
+
done = [(lo, hi, -1)]
|
| 555 |
+
oo = S.Infinity
|
| 556 |
+
for k, p in enumerate(pieces):
|
| 557 |
+
if p[:2] == (-oo, oo):
|
| 558 |
+
# all undone intervals will get this key
|
| 559 |
+
for j, (a, b, i) in enumerate(done):
|
| 560 |
+
if i == -1:
|
| 561 |
+
done[j] = a, b, k
|
| 562 |
+
break # nothing else to consider
|
| 563 |
+
N = len(done) - 1
|
| 564 |
+
for j, (a, b, i) in enumerate(reversed(done)):
|
| 565 |
+
if i == -1:
|
| 566 |
+
j = N - j
|
| 567 |
+
done[j: j + 1] = _clip(p, (a, b), k)
|
| 568 |
+
done = [(a, b, i) for a, b, i in done if a != b]
|
| 569 |
+
|
| 570 |
+
# return the sum of the intervals
|
| 571 |
+
sum = S.Zero
|
| 572 |
+
upto = None
|
| 573 |
+
for a, b, i in done:
|
| 574 |
+
if i == -1:
|
| 575 |
+
if upto is None:
|
| 576 |
+
return Undefined
|
| 577 |
+
# TODO simplify hi <= upto
|
| 578 |
+
return Piecewise((sum, hi <= upto), (Undefined, True))
|
| 579 |
+
sum += abei[i][-2]._eval_interval(x, a, b)
|
| 580 |
+
upto = b
|
| 581 |
+
return sum
|
| 582 |
+
|
| 583 |
+
def _intervals(self, sym, err_on_Eq=False):
|
| 584 |
+
r"""Return a bool and a message (when bool is False), else a
|
| 585 |
+
list of unique tuples, (a, b, e, i), where a and b
|
| 586 |
+
are the lower and upper bounds in which the expression e of
|
| 587 |
+
argument i in self is defined and $a < b$ (when involving
|
| 588 |
+
numbers) or $a \le b$ when involving symbols.
|
| 589 |
+
|
| 590 |
+
If there are any relationals not involving sym, or any
|
| 591 |
+
relational cannot be solved for sym, the bool will be False
|
| 592 |
+
a message be given as the second return value. The calling
|
| 593 |
+
routine should have removed such relationals before calling
|
| 594 |
+
this routine.
|
| 595 |
+
|
| 596 |
+
The evaluated conditions will be returned as ranges.
|
| 597 |
+
Discontinuous ranges will be returned separately with
|
| 598 |
+
identical expressions. The first condition that evaluates to
|
| 599 |
+
True will be returned as the last tuple with a, b = -oo, oo.
|
| 600 |
+
"""
|
| 601 |
+
from sympy.solvers.inequalities import _solve_inequality
|
| 602 |
+
|
| 603 |
+
assert isinstance(self, Piecewise)
|
| 604 |
+
|
| 605 |
+
def nonsymfail(cond):
|
| 606 |
+
return False, filldedent('''
|
| 607 |
+
A condition not involving
|
| 608 |
+
%s appeared: %s''' % (sym, cond))
|
| 609 |
+
|
| 610 |
+
def _solve_relational(r):
|
| 611 |
+
if sym not in r.free_symbols:
|
| 612 |
+
return nonsymfail(r)
|
| 613 |
+
try:
|
| 614 |
+
rv = _solve_inequality(r, sym)
|
| 615 |
+
except NotImplementedError:
|
| 616 |
+
return False, 'Unable to solve relational %s for %s.' % (r, sym)
|
| 617 |
+
if isinstance(rv, Relational):
|
| 618 |
+
free = rv.args[1].free_symbols
|
| 619 |
+
if rv.args[0] != sym or sym in free:
|
| 620 |
+
return False, 'Unable to solve relational %s for %s.' % (r, sym)
|
| 621 |
+
if rv.rel_op == '==':
|
| 622 |
+
# this equality has been affirmed to have the form
|
| 623 |
+
# Eq(sym, rhs) where rhs is sym-free; it represents
|
| 624 |
+
# a zero-width interval which will be ignored
|
| 625 |
+
# whether it is an isolated condition or contained
|
| 626 |
+
# within an And or an Or
|
| 627 |
+
rv = S.false
|
| 628 |
+
elif rv.rel_op == '!=':
|
| 629 |
+
try:
|
| 630 |
+
rv = Or(sym < rv.rhs, sym > rv.rhs)
|
| 631 |
+
except TypeError:
|
| 632 |
+
# e.g. x != I ==> all real x satisfy
|
| 633 |
+
rv = S.true
|
| 634 |
+
elif rv == (S.NegativeInfinity < sym) & (sym < S.Infinity):
|
| 635 |
+
rv = S.true
|
| 636 |
+
return True, rv
|
| 637 |
+
|
| 638 |
+
args = list(self.args)
|
| 639 |
+
# make self canonical wrt Relationals
|
| 640 |
+
keys = self.atoms(Relational)
|
| 641 |
+
reps = {}
|
| 642 |
+
for r in keys:
|
| 643 |
+
ok, s = _solve_relational(r)
|
| 644 |
+
if ok != True:
|
| 645 |
+
return False, ok
|
| 646 |
+
reps[r] = s
|
| 647 |
+
# process args individually so if any evaluate, their position
|
| 648 |
+
# in the original Piecewise will be known
|
| 649 |
+
args = [i.xreplace(reps) for i in self.args]
|
| 650 |
+
|
| 651 |
+
# precondition args
|
| 652 |
+
expr_cond = []
|
| 653 |
+
default = idefault = None
|
| 654 |
+
for i, (expr, cond) in enumerate(args):
|
| 655 |
+
if cond is S.false:
|
| 656 |
+
continue
|
| 657 |
+
if cond is S.true:
|
| 658 |
+
default = expr
|
| 659 |
+
idefault = i
|
| 660 |
+
break
|
| 661 |
+
if isinstance(cond, Eq):
|
| 662 |
+
# unanticipated condition, but it is here in case a
|
| 663 |
+
# replacement caused an Eq to appear
|
| 664 |
+
if err_on_Eq:
|
| 665 |
+
return False, 'encountered Eq condition: %s' % cond
|
| 666 |
+
continue # zero width interval
|
| 667 |
+
|
| 668 |
+
cond = to_cnf(cond)
|
| 669 |
+
if isinstance(cond, And):
|
| 670 |
+
cond = distribute_or_over_and(cond)
|
| 671 |
+
|
| 672 |
+
if isinstance(cond, Or):
|
| 673 |
+
expr_cond.extend(
|
| 674 |
+
[(i, expr, o) for o in cond.args
|
| 675 |
+
if not isinstance(o, Eq)])
|
| 676 |
+
elif cond is not S.false:
|
| 677 |
+
expr_cond.append((i, expr, cond))
|
| 678 |
+
elif cond is S.true:
|
| 679 |
+
default = expr
|
| 680 |
+
idefault = i
|
| 681 |
+
break
|
| 682 |
+
|
| 683 |
+
# determine intervals represented by conditions
|
| 684 |
+
int_expr = []
|
| 685 |
+
for iarg, expr, cond in expr_cond:
|
| 686 |
+
if isinstance(cond, And):
|
| 687 |
+
lower = S.NegativeInfinity
|
| 688 |
+
upper = S.Infinity
|
| 689 |
+
exclude = []
|
| 690 |
+
for cond2 in cond.args:
|
| 691 |
+
if not isinstance(cond2, Relational):
|
| 692 |
+
return False, 'expecting only Relationals'
|
| 693 |
+
if isinstance(cond2, Eq):
|
| 694 |
+
lower = upper # ignore
|
| 695 |
+
if err_on_Eq:
|
| 696 |
+
return False, 'encountered secondary Eq condition'
|
| 697 |
+
break
|
| 698 |
+
elif isinstance(cond2, Ne):
|
| 699 |
+
l, r = cond2.args
|
| 700 |
+
if l == sym:
|
| 701 |
+
exclude.append(r)
|
| 702 |
+
elif r == sym:
|
| 703 |
+
exclude.append(l)
|
| 704 |
+
else:
|
| 705 |
+
return nonsymfail(cond2)
|
| 706 |
+
continue
|
| 707 |
+
elif cond2.lts == sym:
|
| 708 |
+
upper = Min(cond2.gts, upper)
|
| 709 |
+
elif cond2.gts == sym:
|
| 710 |
+
lower = Max(cond2.lts, lower)
|
| 711 |
+
else:
|
| 712 |
+
return nonsymfail(cond2) # should never get here
|
| 713 |
+
if exclude:
|
| 714 |
+
exclude = list(ordered(exclude))
|
| 715 |
+
newcond = []
|
| 716 |
+
for i, e in enumerate(exclude):
|
| 717 |
+
if e < lower == True or e > upper == True:
|
| 718 |
+
continue
|
| 719 |
+
if not newcond:
|
| 720 |
+
newcond.append((None, lower)) # add a primer
|
| 721 |
+
newcond.append((newcond[-1][1], e))
|
| 722 |
+
newcond.append((newcond[-1][1], upper))
|
| 723 |
+
newcond.pop(0) # remove the primer
|
| 724 |
+
expr_cond.extend([(iarg, expr, And(i[0] < sym, sym < i[1])) for i in newcond])
|
| 725 |
+
continue
|
| 726 |
+
elif isinstance(cond, Relational) and cond.rel_op != '!=':
|
| 727 |
+
lower, upper = cond.lts, cond.gts # part 1: initialize with givens
|
| 728 |
+
if cond.lts == sym: # part 1a: expand the side ...
|
| 729 |
+
lower = S.NegativeInfinity # e.g. x <= 0 ---> -oo <= 0
|
| 730 |
+
elif cond.gts == sym: # part 1a: ... that can be expanded
|
| 731 |
+
upper = S.Infinity # e.g. x >= 0 ---> oo >= 0
|
| 732 |
+
else:
|
| 733 |
+
return nonsymfail(cond)
|
| 734 |
+
else:
|
| 735 |
+
return False, 'unrecognized condition: %s' % cond
|
| 736 |
+
|
| 737 |
+
lower, upper = lower, Max(lower, upper)
|
| 738 |
+
if err_on_Eq and lower == upper:
|
| 739 |
+
return False, 'encountered Eq condition'
|
| 740 |
+
if (lower >= upper) is not S.true:
|
| 741 |
+
int_expr.append((lower, upper, expr, iarg))
|
| 742 |
+
|
| 743 |
+
if default is not None:
|
| 744 |
+
int_expr.append(
|
| 745 |
+
(S.NegativeInfinity, S.Infinity, default, idefault))
|
| 746 |
+
|
| 747 |
+
return True, list(uniq(int_expr))
|
| 748 |
+
|
| 749 |
+
def _eval_nseries(self, x, n, logx, cdir=0):
|
| 750 |
+
args = [(ec.expr._eval_nseries(x, n, logx), ec.cond) for ec in self.args]
|
| 751 |
+
return self.func(*args)
|
| 752 |
+
|
| 753 |
+
def _eval_power(self, s):
|
| 754 |
+
return self.func(*[(e**s, c) for e, c in self.args])
|
| 755 |
+
|
| 756 |
+
def _eval_subs(self, old, new):
|
| 757 |
+
# this is strictly not necessary, but we can keep track
|
| 758 |
+
# of whether True or False conditions arise and be
|
| 759 |
+
# somewhat more efficient by avoiding other substitutions
|
| 760 |
+
# and avoiding invalid conditions that appear after a
|
| 761 |
+
# True condition
|
| 762 |
+
args = list(self.args)
|
| 763 |
+
args_exist = False
|
| 764 |
+
for i, (e, c) in enumerate(args):
|
| 765 |
+
c = c._subs(old, new)
|
| 766 |
+
if c != False:
|
| 767 |
+
args_exist = True
|
| 768 |
+
e = e._subs(old, new)
|
| 769 |
+
args[i] = (e, c)
|
| 770 |
+
if c == True:
|
| 771 |
+
break
|
| 772 |
+
if not args_exist:
|
| 773 |
+
args = ((Undefined, True),)
|
| 774 |
+
return self.func(*args)
|
| 775 |
+
|
| 776 |
+
def _eval_transpose(self):
|
| 777 |
+
return self.func(*[(e.transpose(), c) for e, c in self.args])
|
| 778 |
+
|
| 779 |
+
def _eval_template_is_attr(self, is_attr):
|
| 780 |
+
b = None
|
| 781 |
+
for expr, _ in self.args:
|
| 782 |
+
a = getattr(expr, is_attr)
|
| 783 |
+
if a is None:
|
| 784 |
+
return
|
| 785 |
+
if b is None:
|
| 786 |
+
b = a
|
| 787 |
+
elif b is not a:
|
| 788 |
+
return
|
| 789 |
+
return b
|
| 790 |
+
|
| 791 |
+
_eval_is_finite = lambda self: self._eval_template_is_attr(
|
| 792 |
+
'is_finite')
|
| 793 |
+
_eval_is_complex = lambda self: self._eval_template_is_attr('is_complex')
|
| 794 |
+
_eval_is_even = lambda self: self._eval_template_is_attr('is_even')
|
| 795 |
+
_eval_is_imaginary = lambda self: self._eval_template_is_attr(
|
| 796 |
+
'is_imaginary')
|
| 797 |
+
_eval_is_integer = lambda self: self._eval_template_is_attr('is_integer')
|
| 798 |
+
_eval_is_irrational = lambda self: self._eval_template_is_attr(
|
| 799 |
+
'is_irrational')
|
| 800 |
+
_eval_is_negative = lambda self: self._eval_template_is_attr('is_negative')
|
| 801 |
+
_eval_is_nonnegative = lambda self: self._eval_template_is_attr(
|
| 802 |
+
'is_nonnegative')
|
| 803 |
+
_eval_is_nonpositive = lambda self: self._eval_template_is_attr(
|
| 804 |
+
'is_nonpositive')
|
| 805 |
+
_eval_is_nonzero = lambda self: self._eval_template_is_attr(
|
| 806 |
+
'is_nonzero')
|
| 807 |
+
_eval_is_odd = lambda self: self._eval_template_is_attr('is_odd')
|
| 808 |
+
_eval_is_polar = lambda self: self._eval_template_is_attr('is_polar')
|
| 809 |
+
_eval_is_positive = lambda self: self._eval_template_is_attr('is_positive')
|
| 810 |
+
_eval_is_extended_real = lambda self: self._eval_template_is_attr(
|
| 811 |
+
'is_extended_real')
|
| 812 |
+
_eval_is_extended_positive = lambda self: self._eval_template_is_attr(
|
| 813 |
+
'is_extended_positive')
|
| 814 |
+
_eval_is_extended_negative = lambda self: self._eval_template_is_attr(
|
| 815 |
+
'is_extended_negative')
|
| 816 |
+
_eval_is_extended_nonzero = lambda self: self._eval_template_is_attr(
|
| 817 |
+
'is_extended_nonzero')
|
| 818 |
+
_eval_is_extended_nonpositive = lambda self: self._eval_template_is_attr(
|
| 819 |
+
'is_extended_nonpositive')
|
| 820 |
+
_eval_is_extended_nonnegative = lambda self: self._eval_template_is_attr(
|
| 821 |
+
'is_extended_nonnegative')
|
| 822 |
+
_eval_is_real = lambda self: self._eval_template_is_attr('is_real')
|
| 823 |
+
_eval_is_zero = lambda self: self._eval_template_is_attr(
|
| 824 |
+
'is_zero')
|
| 825 |
+
|
| 826 |
+
@classmethod
|
| 827 |
+
def __eval_cond(cls, cond):
|
| 828 |
+
"""Return the truth value of the condition."""
|
| 829 |
+
if cond == True:
|
| 830 |
+
return True
|
| 831 |
+
if isinstance(cond, Eq):
|
| 832 |
+
try:
|
| 833 |
+
diff = cond.lhs - cond.rhs
|
| 834 |
+
if diff.is_commutative:
|
| 835 |
+
return diff.is_zero
|
| 836 |
+
except TypeError:
|
| 837 |
+
pass
|
| 838 |
+
|
| 839 |
+
def as_expr_set_pairs(self, domain=None):
|
| 840 |
+
"""Return tuples for each argument of self that give
|
| 841 |
+
the expression and the interval in which it is valid
|
| 842 |
+
which is contained within the given domain.
|
| 843 |
+
If a condition cannot be converted to a set, an error
|
| 844 |
+
will be raised. The variable of the conditions is
|
| 845 |
+
assumed to be real; sets of real values are returned.
|
| 846 |
+
|
| 847 |
+
Examples
|
| 848 |
+
========
|
| 849 |
+
|
| 850 |
+
>>> from sympy import Piecewise, Interval
|
| 851 |
+
>>> from sympy.abc import x
|
| 852 |
+
>>> p = Piecewise(
|
| 853 |
+
... (1, x < 2),
|
| 854 |
+
... (2,(x > 0) & (x < 4)),
|
| 855 |
+
... (3, True))
|
| 856 |
+
>>> p.as_expr_set_pairs()
|
| 857 |
+
[(1, Interval.open(-oo, 2)),
|
| 858 |
+
(2, Interval.Ropen(2, 4)),
|
| 859 |
+
(3, Interval(4, oo))]
|
| 860 |
+
>>> p.as_expr_set_pairs(Interval(0, 3))
|
| 861 |
+
[(1, Interval.Ropen(0, 2)),
|
| 862 |
+
(2, Interval(2, 3))]
|
| 863 |
+
"""
|
| 864 |
+
if domain is None:
|
| 865 |
+
domain = S.Reals
|
| 866 |
+
exp_sets = []
|
| 867 |
+
U = domain
|
| 868 |
+
complex = not domain.is_subset(S.Reals)
|
| 869 |
+
cond_free = set()
|
| 870 |
+
for expr, cond in self.args:
|
| 871 |
+
cond_free |= cond.free_symbols
|
| 872 |
+
if len(cond_free) > 1:
|
| 873 |
+
raise NotImplementedError(filldedent('''
|
| 874 |
+
multivariate conditions are not handled.'''))
|
| 875 |
+
if complex:
|
| 876 |
+
for i in cond.atoms(Relational):
|
| 877 |
+
if not isinstance(i, (Eq, Ne)):
|
| 878 |
+
raise ValueError(filldedent('''
|
| 879 |
+
Inequalities in the complex domain are
|
| 880 |
+
not supported. Try the real domain by
|
| 881 |
+
setting domain=S.Reals'''))
|
| 882 |
+
cond_int = U.intersect(cond.as_set())
|
| 883 |
+
U = U - cond_int
|
| 884 |
+
if cond_int != S.EmptySet:
|
| 885 |
+
exp_sets.append((expr, cond_int))
|
| 886 |
+
return exp_sets
|
| 887 |
+
|
| 888 |
+
def _eval_rewrite_as_ITE(self, *args, **kwargs):
|
| 889 |
+
byfree = {}
|
| 890 |
+
args = list(args)
|
| 891 |
+
default = any(c == True for b, c in args)
|
| 892 |
+
for i, (b, c) in enumerate(args):
|
| 893 |
+
if not isinstance(b, Boolean) and b != True:
|
| 894 |
+
raise TypeError(filldedent('''
|
| 895 |
+
Expecting Boolean or bool but got `%s`
|
| 896 |
+
''' % func_name(b)))
|
| 897 |
+
if c == True:
|
| 898 |
+
break
|
| 899 |
+
# loop over independent conditions for this b
|
| 900 |
+
for c in c.args if isinstance(c, Or) else [c]:
|
| 901 |
+
free = c.free_symbols
|
| 902 |
+
x = free.pop()
|
| 903 |
+
try:
|
| 904 |
+
byfree[x] = byfree.setdefault(
|
| 905 |
+
x, S.EmptySet).union(c.as_set())
|
| 906 |
+
except NotImplementedError:
|
| 907 |
+
if not default:
|
| 908 |
+
raise NotImplementedError(filldedent('''
|
| 909 |
+
A method to determine whether a multivariate
|
| 910 |
+
conditional is consistent with a complete coverage
|
| 911 |
+
of all variables has not been implemented so the
|
| 912 |
+
rewrite is being stopped after encountering `%s`.
|
| 913 |
+
This error would not occur if a default expression
|
| 914 |
+
like `(foo, True)` were given.
|
| 915 |
+
''' % c))
|
| 916 |
+
if byfree[x] in (S.UniversalSet, S.Reals):
|
| 917 |
+
# collapse the ith condition to True and break
|
| 918 |
+
args[i] = list(args[i])
|
| 919 |
+
c = args[i][1] = True
|
| 920 |
+
break
|
| 921 |
+
if c == True:
|
| 922 |
+
break
|
| 923 |
+
if c != True:
|
| 924 |
+
raise ValueError(filldedent('''
|
| 925 |
+
Conditions must cover all reals or a final default
|
| 926 |
+
condition `(foo, True)` must be given.
|
| 927 |
+
'''))
|
| 928 |
+
last, _ = args[i] # ignore all past ith arg
|
| 929 |
+
for a, c in reversed(args[:i]):
|
| 930 |
+
last = ITE(c, a, last)
|
| 931 |
+
return _canonical(last)
|
| 932 |
+
|
| 933 |
+
def _eval_rewrite_as_KroneckerDelta(self, *args, **kwargs):
|
| 934 |
+
from sympy.functions.special.tensor_functions import KroneckerDelta
|
| 935 |
+
|
| 936 |
+
rules = {
|
| 937 |
+
And: [False, False],
|
| 938 |
+
Or: [True, True],
|
| 939 |
+
Not: [True, False],
|
| 940 |
+
Eq: [None, None],
|
| 941 |
+
Ne: [None, None]
|
| 942 |
+
}
|
| 943 |
+
|
| 944 |
+
class UnrecognizedCondition(Exception):
|
| 945 |
+
pass
|
| 946 |
+
|
| 947 |
+
def rewrite(cond):
|
| 948 |
+
if isinstance(cond, Eq):
|
| 949 |
+
return KroneckerDelta(*cond.args)
|
| 950 |
+
if isinstance(cond, Ne):
|
| 951 |
+
return 1 - KroneckerDelta(*cond.args)
|
| 952 |
+
|
| 953 |
+
cls, args = type(cond), cond.args
|
| 954 |
+
if cls not in rules:
|
| 955 |
+
raise UnrecognizedCondition(cls)
|
| 956 |
+
|
| 957 |
+
b1, b2 = rules[cls]
|
| 958 |
+
k = Mul(*[1 - rewrite(c) for c in args]) if b1 else Mul(*[rewrite(c) for c in args])
|
| 959 |
+
|
| 960 |
+
if b2:
|
| 961 |
+
return 1 - k
|
| 962 |
+
return k
|
| 963 |
+
|
| 964 |
+
conditions = []
|
| 965 |
+
true_value = None
|
| 966 |
+
for value, cond in args:
|
| 967 |
+
if type(cond) in rules:
|
| 968 |
+
conditions.append((value, cond))
|
| 969 |
+
elif cond is S.true:
|
| 970 |
+
if true_value is None:
|
| 971 |
+
true_value = value
|
| 972 |
+
else:
|
| 973 |
+
return
|
| 974 |
+
|
| 975 |
+
if true_value is not None:
|
| 976 |
+
result = true_value
|
| 977 |
+
|
| 978 |
+
for value, cond in conditions[::-1]:
|
| 979 |
+
try:
|
| 980 |
+
k = rewrite(cond)
|
| 981 |
+
result = k * value + (1 - k) * result
|
| 982 |
+
except UnrecognizedCondition:
|
| 983 |
+
return
|
| 984 |
+
|
| 985 |
+
return result
|
| 986 |
+
|
| 987 |
+
|
| 988 |
+
def piecewise_fold(expr, evaluate=True):
|
| 989 |
+
"""
|
| 990 |
+
Takes an expression containing a piecewise function and returns the
|
| 991 |
+
expression in piecewise form. In addition, any ITE conditions are
|
| 992 |
+
rewritten in negation normal form and simplified.
|
| 993 |
+
|
| 994 |
+
The final Piecewise is evaluated (default) but if the raw form
|
| 995 |
+
is desired, send ``evaluate=False``; if trivial evaluation is
|
| 996 |
+
desired, send ``evaluate=None`` and duplicate conditions and
|
| 997 |
+
processing of True and False will be handled.
|
| 998 |
+
|
| 999 |
+
Examples
|
| 1000 |
+
========
|
| 1001 |
+
|
| 1002 |
+
>>> from sympy import Piecewise, piecewise_fold, S
|
| 1003 |
+
>>> from sympy.abc import x
|
| 1004 |
+
>>> p = Piecewise((x, x < 1), (1, S(1) <= x))
|
| 1005 |
+
>>> piecewise_fold(x*p)
|
| 1006 |
+
Piecewise((x**2, x < 1), (x, True))
|
| 1007 |
+
|
| 1008 |
+
See Also
|
| 1009 |
+
========
|
| 1010 |
+
|
| 1011 |
+
Piecewise
|
| 1012 |
+
piecewise_exclusive
|
| 1013 |
+
"""
|
| 1014 |
+
if not isinstance(expr, Basic) or not expr.has(Piecewise):
|
| 1015 |
+
return expr
|
| 1016 |
+
|
| 1017 |
+
new_args = []
|
| 1018 |
+
if isinstance(expr, (ExprCondPair, Piecewise)):
|
| 1019 |
+
for e, c in expr.args:
|
| 1020 |
+
if not isinstance(e, Piecewise):
|
| 1021 |
+
e = piecewise_fold(e)
|
| 1022 |
+
# we don't keep Piecewise in condition because
|
| 1023 |
+
# it has to be checked to see that it's complete
|
| 1024 |
+
# and we convert it to ITE at that time
|
| 1025 |
+
assert not c.has(Piecewise) # pragma: no cover
|
| 1026 |
+
if isinstance(c, ITE):
|
| 1027 |
+
c = c.to_nnf()
|
| 1028 |
+
c = simplify_logic(c, form='cnf')
|
| 1029 |
+
if isinstance(e, Piecewise):
|
| 1030 |
+
new_args.extend([(piecewise_fold(ei), And(ci, c))
|
| 1031 |
+
for ei, ci in e.args])
|
| 1032 |
+
else:
|
| 1033 |
+
new_args.append((e, c))
|
| 1034 |
+
else:
|
| 1035 |
+
# Given
|
| 1036 |
+
# P1 = Piecewise((e11, c1), (e12, c2), A)
|
| 1037 |
+
# P2 = Piecewise((e21, c1), (e22, c2), B)
|
| 1038 |
+
# ...
|
| 1039 |
+
# the folding of f(P1, P2) is trivially
|
| 1040 |
+
# Piecewise(
|
| 1041 |
+
# (f(e11, e21), c1),
|
| 1042 |
+
# (f(e12, e22), c2),
|
| 1043 |
+
# (f(Piecewise(A), Piecewise(B)), True))
|
| 1044 |
+
# Certain objects end up rewriting themselves as thus, so
|
| 1045 |
+
# we do that grouping before the more generic folding.
|
| 1046 |
+
# The following applies this idea when f = Add or f = Mul
|
| 1047 |
+
# (and the expression is commutative).
|
| 1048 |
+
if expr.is_Add or expr.is_Mul and expr.is_commutative:
|
| 1049 |
+
p, args = sift(expr.args, lambda x: x.is_Piecewise, binary=True)
|
| 1050 |
+
pc = sift(p, lambda x: tuple([c for e,c in x.args]))
|
| 1051 |
+
for c in list(ordered(pc)):
|
| 1052 |
+
if len(pc[c]) > 1:
|
| 1053 |
+
pargs = [list(i.args) for i in pc[c]]
|
| 1054 |
+
# the first one is the same; there may be more
|
| 1055 |
+
com = common_prefix(*[
|
| 1056 |
+
[i.cond for i in j] for j in pargs])
|
| 1057 |
+
n = len(com)
|
| 1058 |
+
collected = []
|
| 1059 |
+
for i in range(n):
|
| 1060 |
+
collected.append((
|
| 1061 |
+
expr.func(*[ai[i].expr for ai in pargs]),
|
| 1062 |
+
com[i]))
|
| 1063 |
+
remains = []
|
| 1064 |
+
for a in pargs:
|
| 1065 |
+
if n == len(a): # no more args
|
| 1066 |
+
continue
|
| 1067 |
+
if a[n].cond == True: # no longer Piecewise
|
| 1068 |
+
remains.append(a[n].expr)
|
| 1069 |
+
else: # restore the remaining Piecewise
|
| 1070 |
+
remains.append(
|
| 1071 |
+
Piecewise(*a[n:], evaluate=False))
|
| 1072 |
+
if remains:
|
| 1073 |
+
collected.append((expr.func(*remains), True))
|
| 1074 |
+
args.append(Piecewise(*collected, evaluate=False))
|
| 1075 |
+
continue
|
| 1076 |
+
args.extend(pc[c])
|
| 1077 |
+
else:
|
| 1078 |
+
args = expr.args
|
| 1079 |
+
# fold
|
| 1080 |
+
folded = list(map(piecewise_fold, args))
|
| 1081 |
+
for ec in product(*[
|
| 1082 |
+
(i.args if isinstance(i, Piecewise) else
|
| 1083 |
+
[(i, true)]) for i in folded]):
|
| 1084 |
+
e, c = zip(*ec)
|
| 1085 |
+
new_args.append((expr.func(*e), And(*c)))
|
| 1086 |
+
|
| 1087 |
+
if evaluate is None:
|
| 1088 |
+
# don't return duplicate conditions, otherwise don't evaluate
|
| 1089 |
+
new_args = list(reversed([(e, c) for c, e in {
|
| 1090 |
+
c: e for e, c in reversed(new_args)}.items()]))
|
| 1091 |
+
rv = Piecewise(*new_args, evaluate=evaluate)
|
| 1092 |
+
if evaluate is None and len(rv.args) == 1 and rv.args[0].cond == True:
|
| 1093 |
+
return rv.args[0].expr
|
| 1094 |
+
if any(s.expr.has(Piecewise) for p in rv.atoms(Piecewise) for s in p.args):
|
| 1095 |
+
return piecewise_fold(rv)
|
| 1096 |
+
return rv
|
| 1097 |
+
|
| 1098 |
+
|
| 1099 |
+
def _clip(A, B, k):
|
| 1100 |
+
"""Return interval B as intervals that are covered by A (keyed
|
| 1101 |
+
to k) and all other intervals of B not covered by A keyed to -1.
|
| 1102 |
+
|
| 1103 |
+
The reference point of each interval is the rhs; if the lhs is
|
| 1104 |
+
greater than the rhs then an interval of zero width interval will
|
| 1105 |
+
result, e.g. (4, 1) is treated like (1, 1).
|
| 1106 |
+
|
| 1107 |
+
Examples
|
| 1108 |
+
========
|
| 1109 |
+
|
| 1110 |
+
>>> from sympy.functions.elementary.piecewise import _clip
|
| 1111 |
+
>>> from sympy import Tuple
|
| 1112 |
+
>>> A = Tuple(1, 3)
|
| 1113 |
+
>>> B = Tuple(2, 4)
|
| 1114 |
+
>>> _clip(A, B, 0)
|
| 1115 |
+
[(2, 3, 0), (3, 4, -1)]
|
| 1116 |
+
|
| 1117 |
+
Interpretation: interval portion (2, 3) of interval (2, 4) is
|
| 1118 |
+
covered by interval (1, 3) and is keyed to 0 as requested;
|
| 1119 |
+
interval (3, 4) was not covered by (1, 3) and is keyed to -1.
|
| 1120 |
+
"""
|
| 1121 |
+
a, b = B
|
| 1122 |
+
c, d = A
|
| 1123 |
+
c, d = Min(Max(c, a), b), Min(Max(d, a), b)
|
| 1124 |
+
a, b = Min(a, b), b
|
| 1125 |
+
p = []
|
| 1126 |
+
if a != c:
|
| 1127 |
+
p.append((a, c, -1))
|
| 1128 |
+
else:
|
| 1129 |
+
pass
|
| 1130 |
+
if c != d:
|
| 1131 |
+
p.append((c, d, k))
|
| 1132 |
+
else:
|
| 1133 |
+
pass
|
| 1134 |
+
if b != d:
|
| 1135 |
+
if d == c and p and p[-1][-1] == -1:
|
| 1136 |
+
p[-1] = p[-1][0], b, -1
|
| 1137 |
+
else:
|
| 1138 |
+
p.append((d, b, -1))
|
| 1139 |
+
else:
|
| 1140 |
+
pass
|
| 1141 |
+
|
| 1142 |
+
return p
|
| 1143 |
+
|
| 1144 |
+
|
| 1145 |
+
def piecewise_simplify_arguments(expr, **kwargs):
|
| 1146 |
+
from sympy.simplify.simplify import simplify
|
| 1147 |
+
|
| 1148 |
+
# simplify conditions
|
| 1149 |
+
f1 = expr.args[0].cond.free_symbols
|
| 1150 |
+
args = None
|
| 1151 |
+
if len(f1) == 1 and not expr.atoms(Eq):
|
| 1152 |
+
x = f1.pop()
|
| 1153 |
+
# this won't return intervals involving Eq
|
| 1154 |
+
# and it won't handle symbols treated as
|
| 1155 |
+
# booleans
|
| 1156 |
+
ok, abe_ = expr._intervals(x, err_on_Eq=True)
|
| 1157 |
+
def include(c, x, a):
|
| 1158 |
+
"return True if c.subs(x, a) is True, else False"
|
| 1159 |
+
try:
|
| 1160 |
+
return c.subs(x, a) == True
|
| 1161 |
+
except TypeError:
|
| 1162 |
+
return False
|
| 1163 |
+
if ok:
|
| 1164 |
+
args = []
|
| 1165 |
+
covered = S.EmptySet
|
| 1166 |
+
from sympy.sets.sets import Interval
|
| 1167 |
+
for a, b, e, i in abe_:
|
| 1168 |
+
c = expr.args[i].cond
|
| 1169 |
+
incl_a = include(c, x, a)
|
| 1170 |
+
incl_b = include(c, x, b)
|
| 1171 |
+
iv = Interval(a, b, not incl_a, not incl_b)
|
| 1172 |
+
cset = iv - covered
|
| 1173 |
+
if not cset:
|
| 1174 |
+
continue
|
| 1175 |
+
try:
|
| 1176 |
+
a = cset.inf
|
| 1177 |
+
except NotImplementedError:
|
| 1178 |
+
pass # continue with the given `a`
|
| 1179 |
+
else:
|
| 1180 |
+
incl_a = include(c, x, a)
|
| 1181 |
+
if incl_a and incl_b:
|
| 1182 |
+
if a.is_infinite and b.is_infinite:
|
| 1183 |
+
c = S.true
|
| 1184 |
+
elif b.is_infinite:
|
| 1185 |
+
c = (x > a) if a in covered else (x >= a)
|
| 1186 |
+
elif a.is_infinite:
|
| 1187 |
+
c = (x <= b)
|
| 1188 |
+
elif a in covered:
|
| 1189 |
+
c = And(a < x, x <= b)
|
| 1190 |
+
else:
|
| 1191 |
+
c = And(a <= x, x <= b)
|
| 1192 |
+
elif incl_a:
|
| 1193 |
+
if a.is_infinite:
|
| 1194 |
+
c = (x < b)
|
| 1195 |
+
elif a in covered:
|
| 1196 |
+
c = And(a < x, x < b)
|
| 1197 |
+
else:
|
| 1198 |
+
c = And(a <= x, x < b)
|
| 1199 |
+
elif incl_b:
|
| 1200 |
+
if b.is_infinite:
|
| 1201 |
+
c = (x > a)
|
| 1202 |
+
else:
|
| 1203 |
+
c = And(a < x, x <= b)
|
| 1204 |
+
else:
|
| 1205 |
+
if a in covered:
|
| 1206 |
+
c = (x < b)
|
| 1207 |
+
else:
|
| 1208 |
+
c = And(a < x, x < b)
|
| 1209 |
+
covered |= iv
|
| 1210 |
+
if a is S.NegativeInfinity and incl_a:
|
| 1211 |
+
covered |= {S.NegativeInfinity}
|
| 1212 |
+
if b is S.Infinity and incl_b:
|
| 1213 |
+
covered |= {S.Infinity}
|
| 1214 |
+
args.append((e, c))
|
| 1215 |
+
if not S.Reals.is_subset(covered):
|
| 1216 |
+
args.append((Undefined, True))
|
| 1217 |
+
if args is None:
|
| 1218 |
+
args = list(expr.args)
|
| 1219 |
+
for i in range(len(args)):
|
| 1220 |
+
e, c = args[i]
|
| 1221 |
+
if isinstance(c, Basic):
|
| 1222 |
+
c = simplify(c, **kwargs)
|
| 1223 |
+
args[i] = (e, c)
|
| 1224 |
+
|
| 1225 |
+
# simplify expressions
|
| 1226 |
+
doit = kwargs.pop('doit', None)
|
| 1227 |
+
for i in range(len(args)):
|
| 1228 |
+
e, c = args[i]
|
| 1229 |
+
if isinstance(e, Basic):
|
| 1230 |
+
# Skip doit to avoid growth at every call for some integrals
|
| 1231 |
+
# and sums, see sympy/sympy#17165
|
| 1232 |
+
newe = simplify(e, doit=False, **kwargs)
|
| 1233 |
+
if newe != e:
|
| 1234 |
+
e = newe
|
| 1235 |
+
args[i] = (e, c)
|
| 1236 |
+
|
| 1237 |
+
# restore kwargs flag
|
| 1238 |
+
if doit is not None:
|
| 1239 |
+
kwargs['doit'] = doit
|
| 1240 |
+
|
| 1241 |
+
return Piecewise(*args)
|
| 1242 |
+
|
| 1243 |
+
|
| 1244 |
+
def _piecewise_collapse_arguments(_args):
|
| 1245 |
+
newargs = [] # the unevaluated conditions
|
| 1246 |
+
current_cond = set() # the conditions up to a given e, c pair
|
| 1247 |
+
for expr, cond in _args:
|
| 1248 |
+
cond = cond.replace(
|
| 1249 |
+
lambda _: _.is_Relational, _canonical_coeff)
|
| 1250 |
+
# Check here if expr is a Piecewise and collapse if one of
|
| 1251 |
+
# the conds in expr matches cond. This allows the collapsing
|
| 1252 |
+
# of Piecewise((Piecewise((x,x<0)),x<0)) to Piecewise((x,x<0)).
|
| 1253 |
+
# This is important when using piecewise_fold to simplify
|
| 1254 |
+
# multiple Piecewise instances having the same conds.
|
| 1255 |
+
# Eventually, this code should be able to collapse Piecewise's
|
| 1256 |
+
# having different intervals, but this will probably require
|
| 1257 |
+
# using the new assumptions.
|
| 1258 |
+
if isinstance(expr, Piecewise):
|
| 1259 |
+
unmatching = []
|
| 1260 |
+
for i, (e, c) in enumerate(expr.args):
|
| 1261 |
+
if c in current_cond:
|
| 1262 |
+
# this would already have triggered
|
| 1263 |
+
continue
|
| 1264 |
+
if c == cond:
|
| 1265 |
+
if c != True:
|
| 1266 |
+
# nothing past this condition will ever
|
| 1267 |
+
# trigger and only those args before this
|
| 1268 |
+
# that didn't match a previous condition
|
| 1269 |
+
# could possibly trigger
|
| 1270 |
+
if unmatching:
|
| 1271 |
+
expr = Piecewise(*(
|
| 1272 |
+
unmatching + [(e, c)]))
|
| 1273 |
+
else:
|
| 1274 |
+
expr = e
|
| 1275 |
+
break
|
| 1276 |
+
else:
|
| 1277 |
+
unmatching.append((e, c))
|
| 1278 |
+
|
| 1279 |
+
# check for condition repeats
|
| 1280 |
+
got = False
|
| 1281 |
+
# -- if an And contains a condition that was
|
| 1282 |
+
# already encountered, then the And will be
|
| 1283 |
+
# False: if the previous condition was False
|
| 1284 |
+
# then the And will be False and if the previous
|
| 1285 |
+
# condition is True then then we wouldn't get to
|
| 1286 |
+
# this point. In either case, we can skip this condition.
|
| 1287 |
+
for i in ([cond] +
|
| 1288 |
+
(list(cond.args) if isinstance(cond, And) else
|
| 1289 |
+
[])):
|
| 1290 |
+
if i in current_cond:
|
| 1291 |
+
got = True
|
| 1292 |
+
break
|
| 1293 |
+
if got:
|
| 1294 |
+
continue
|
| 1295 |
+
|
| 1296 |
+
# -- if not(c) is already in current_cond then c is
|
| 1297 |
+
# a redundant condition in an And. This does not
|
| 1298 |
+
# apply to Or, however: (e1, c), (e2, Or(~c, d))
|
| 1299 |
+
# is not (e1, c), (e2, d) because if c and d are
|
| 1300 |
+
# both False this would give no results when the
|
| 1301 |
+
# true answer should be (e2, True)
|
| 1302 |
+
if isinstance(cond, And):
|
| 1303 |
+
nonredundant = []
|
| 1304 |
+
for c in cond.args:
|
| 1305 |
+
if isinstance(c, Relational):
|
| 1306 |
+
if c.negated.canonical in current_cond:
|
| 1307 |
+
continue
|
| 1308 |
+
# if a strict inequality appears after
|
| 1309 |
+
# a non-strict one, then the condition is
|
| 1310 |
+
# redundant
|
| 1311 |
+
if isinstance(c, (Lt, Gt)) and (
|
| 1312 |
+
c.weak in current_cond):
|
| 1313 |
+
cond = False
|
| 1314 |
+
break
|
| 1315 |
+
nonredundant.append(c)
|
| 1316 |
+
else:
|
| 1317 |
+
cond = cond.func(*nonredundant)
|
| 1318 |
+
elif isinstance(cond, Relational):
|
| 1319 |
+
if cond.negated.canonical in current_cond:
|
| 1320 |
+
cond = S.true
|
| 1321 |
+
|
| 1322 |
+
current_cond.add(cond)
|
| 1323 |
+
|
| 1324 |
+
# collect successive e,c pairs when exprs or cond match
|
| 1325 |
+
if newargs:
|
| 1326 |
+
if newargs[-1].expr == expr:
|
| 1327 |
+
orcond = Or(cond, newargs[-1].cond)
|
| 1328 |
+
if isinstance(orcond, (And, Or)):
|
| 1329 |
+
orcond = distribute_and_over_or(orcond)
|
| 1330 |
+
newargs[-1] = ExprCondPair(expr, orcond)
|
| 1331 |
+
continue
|
| 1332 |
+
elif newargs[-1].cond == cond:
|
| 1333 |
+
continue
|
| 1334 |
+
newargs.append(ExprCondPair(expr, cond))
|
| 1335 |
+
return newargs
|
| 1336 |
+
|
| 1337 |
+
|
| 1338 |
+
_blessed = lambda e: getattr(e.lhs, '_diff_wrt', False) and (
|
| 1339 |
+
getattr(e.rhs, '_diff_wrt', None) or
|
| 1340 |
+
isinstance(e.rhs, (Rational, NumberSymbol)))
|
| 1341 |
+
|
| 1342 |
+
|
| 1343 |
+
def piecewise_simplify(expr, **kwargs):
|
| 1344 |
+
expr = piecewise_simplify_arguments(expr, **kwargs)
|
| 1345 |
+
if not isinstance(expr, Piecewise):
|
| 1346 |
+
return expr
|
| 1347 |
+
args = list(expr.args)
|
| 1348 |
+
|
| 1349 |
+
args = _piecewise_simplify_eq_and(args)
|
| 1350 |
+
args = _piecewise_simplify_equal_to_next_segment(args)
|
| 1351 |
+
return Piecewise(*args)
|
| 1352 |
+
|
| 1353 |
+
|
| 1354 |
+
def _piecewise_simplify_equal_to_next_segment(args):
|
| 1355 |
+
"""
|
| 1356 |
+
See if expressions valid for an Equal expression happens to evaluate
|
| 1357 |
+
to the same function as in the next piecewise segment, see:
|
| 1358 |
+
https://github.com/sympy/sympy/issues/8458
|
| 1359 |
+
"""
|
| 1360 |
+
prevexpr = None
|
| 1361 |
+
for i, (expr, cond) in reversed(list(enumerate(args))):
|
| 1362 |
+
if prevexpr is not None:
|
| 1363 |
+
if isinstance(cond, And):
|
| 1364 |
+
eqs, other = sift(cond.args,
|
| 1365 |
+
lambda i: isinstance(i, Eq), binary=True)
|
| 1366 |
+
elif isinstance(cond, Eq):
|
| 1367 |
+
eqs, other = [cond], []
|
| 1368 |
+
else:
|
| 1369 |
+
eqs = other = []
|
| 1370 |
+
_prevexpr = prevexpr
|
| 1371 |
+
_expr = expr
|
| 1372 |
+
if eqs and not other:
|
| 1373 |
+
eqs = list(ordered(eqs))
|
| 1374 |
+
for e in eqs:
|
| 1375 |
+
# allow 2 args to collapse into 1 for any e
|
| 1376 |
+
# otherwise limit simplification to only simple-arg
|
| 1377 |
+
# Eq instances
|
| 1378 |
+
if len(args) == 2 or _blessed(e):
|
| 1379 |
+
_prevexpr = _prevexpr.subs(*e.args)
|
| 1380 |
+
_expr = _expr.subs(*e.args)
|
| 1381 |
+
# Did it evaluate to the same?
|
| 1382 |
+
if _prevexpr == _expr:
|
| 1383 |
+
# Set the expression for the Not equal section to the same
|
| 1384 |
+
# as the next. These will be merged when creating the new
|
| 1385 |
+
# Piecewise
|
| 1386 |
+
args[i] = args[i].func(args[i + 1][0], cond)
|
| 1387 |
+
else:
|
| 1388 |
+
# Update the expression that we compare against
|
| 1389 |
+
prevexpr = expr
|
| 1390 |
+
else:
|
| 1391 |
+
prevexpr = expr
|
| 1392 |
+
return args
|
| 1393 |
+
|
| 1394 |
+
|
| 1395 |
+
def _piecewise_simplify_eq_and(args):
|
| 1396 |
+
"""
|
| 1397 |
+
Try to simplify conditions and the expression for
|
| 1398 |
+
equalities that are part of the condition, e.g.
|
| 1399 |
+
Piecewise((n, And(Eq(n,0), Eq(n + m, 0))), (1, True))
|
| 1400 |
+
-> Piecewise((0, And(Eq(n, 0), Eq(m, 0))), (1, True))
|
| 1401 |
+
"""
|
| 1402 |
+
for i, (expr, cond) in enumerate(args):
|
| 1403 |
+
if isinstance(cond, And):
|
| 1404 |
+
eqs, other = sift(cond.args,
|
| 1405 |
+
lambda i: isinstance(i, Eq), binary=True)
|
| 1406 |
+
elif isinstance(cond, Eq):
|
| 1407 |
+
eqs, other = [cond], []
|
| 1408 |
+
else:
|
| 1409 |
+
eqs = other = []
|
| 1410 |
+
if eqs:
|
| 1411 |
+
eqs = list(ordered(eqs))
|
| 1412 |
+
for j, e in enumerate(eqs):
|
| 1413 |
+
# these blessed lhs objects behave like Symbols
|
| 1414 |
+
# and the rhs are simple replacements for the "symbols"
|
| 1415 |
+
if _blessed(e):
|
| 1416 |
+
expr = expr.subs(*e.args)
|
| 1417 |
+
eqs[j + 1:] = [ei.subs(*e.args) for ei in eqs[j + 1:]]
|
| 1418 |
+
other = [ei.subs(*e.args) for ei in other]
|
| 1419 |
+
cond = And(*(eqs + other))
|
| 1420 |
+
args[i] = args[i].func(expr, cond)
|
| 1421 |
+
return args
|
| 1422 |
+
|
| 1423 |
+
|
| 1424 |
+
def piecewise_exclusive(expr, *, skip_nan=False, deep=True):
|
| 1425 |
+
"""
|
| 1426 |
+
Rewrite :class:`Piecewise` with mutually exclusive conditions.
|
| 1427 |
+
|
| 1428 |
+
Explanation
|
| 1429 |
+
===========
|
| 1430 |
+
|
| 1431 |
+
SymPy represents the conditions of a :class:`Piecewise` in an
|
| 1432 |
+
"if-elif"-fashion, allowing more than one condition to be simultaneously
|
| 1433 |
+
True. The interpretation is that the first condition that is True is the
|
| 1434 |
+
case that holds. While this is a useful representation computationally it
|
| 1435 |
+
is not how a piecewise formula is typically shown in a mathematical text.
|
| 1436 |
+
The :func:`piecewise_exclusive` function can be used to rewrite any
|
| 1437 |
+
:class:`Piecewise` with more typical mutually exclusive conditions.
|
| 1438 |
+
|
| 1439 |
+
Note that further manipulation of the resulting :class:`Piecewise`, e.g.
|
| 1440 |
+
simplifying it, will most likely make it non-exclusive. Hence, this is
|
| 1441 |
+
primarily a function to be used in conjunction with printing the Piecewise
|
| 1442 |
+
or if one would like to reorder the expression-condition pairs.
|
| 1443 |
+
|
| 1444 |
+
If it is not possible to determine that all possibilities are covered by
|
| 1445 |
+
the different cases of the :class:`Piecewise` then a final
|
| 1446 |
+
:class:`~sympy.core.numbers.NaN` case will be included explicitly. This
|
| 1447 |
+
can be prevented by passing ``skip_nan=True``.
|
| 1448 |
+
|
| 1449 |
+
Examples
|
| 1450 |
+
========
|
| 1451 |
+
|
| 1452 |
+
>>> from sympy import piecewise_exclusive, Symbol, Piecewise, S
|
| 1453 |
+
>>> x = Symbol('x', real=True)
|
| 1454 |
+
>>> p = Piecewise((0, x < 0), (S.Half, x <= 0), (1, True))
|
| 1455 |
+
>>> piecewise_exclusive(p)
|
| 1456 |
+
Piecewise((0, x < 0), (1/2, Eq(x, 0)), (1, x > 0))
|
| 1457 |
+
>>> piecewise_exclusive(Piecewise((2, x > 1)))
|
| 1458 |
+
Piecewise((2, x > 1), (nan, x <= 1))
|
| 1459 |
+
>>> piecewise_exclusive(Piecewise((2, x > 1)), skip_nan=True)
|
| 1460 |
+
Piecewise((2, x > 1))
|
| 1461 |
+
|
| 1462 |
+
Parameters
|
| 1463 |
+
==========
|
| 1464 |
+
|
| 1465 |
+
expr: a SymPy expression.
|
| 1466 |
+
Any :class:`Piecewise` in the expression will be rewritten.
|
| 1467 |
+
skip_nan: ``bool`` (default ``False``)
|
| 1468 |
+
If ``skip_nan`` is set to ``True`` then a final
|
| 1469 |
+
:class:`~sympy.core.numbers.NaN` case will not be included.
|
| 1470 |
+
deep: ``bool`` (default ``True``)
|
| 1471 |
+
If ``deep`` is ``True`` then :func:`piecewise_exclusive` will rewrite
|
| 1472 |
+
any :class:`Piecewise` subexpressions in ``expr`` rather than just
|
| 1473 |
+
rewriting ``expr`` itself.
|
| 1474 |
+
|
| 1475 |
+
Returns
|
| 1476 |
+
=======
|
| 1477 |
+
|
| 1478 |
+
An expression equivalent to ``expr`` but where all :class:`Piecewise` have
|
| 1479 |
+
been rewritten with mutually exclusive conditions.
|
| 1480 |
+
|
| 1481 |
+
See Also
|
| 1482 |
+
========
|
| 1483 |
+
|
| 1484 |
+
Piecewise
|
| 1485 |
+
piecewise_fold
|
| 1486 |
+
"""
|
| 1487 |
+
|
| 1488 |
+
def make_exclusive(*pwargs):
|
| 1489 |
+
|
| 1490 |
+
cumcond = false
|
| 1491 |
+
newargs = []
|
| 1492 |
+
|
| 1493 |
+
# Handle the first n-1 cases
|
| 1494 |
+
for expr_i, cond_i in pwargs[:-1]:
|
| 1495 |
+
cancond = And(cond_i, Not(cumcond)).simplify()
|
| 1496 |
+
cumcond = Or(cond_i, cumcond).simplify()
|
| 1497 |
+
newargs.append((expr_i, cancond))
|
| 1498 |
+
|
| 1499 |
+
# For the nth case defer simplification of cumcond
|
| 1500 |
+
expr_n, cond_n = pwargs[-1]
|
| 1501 |
+
cancond_n = And(cond_n, Not(cumcond)).simplify()
|
| 1502 |
+
newargs.append((expr_n, cancond_n))
|
| 1503 |
+
|
| 1504 |
+
if not skip_nan:
|
| 1505 |
+
cumcond = Or(cond_n, cumcond).simplify()
|
| 1506 |
+
if cumcond is not true:
|
| 1507 |
+
newargs.append((Undefined, Not(cumcond).simplify()))
|
| 1508 |
+
|
| 1509 |
+
return Piecewise(*newargs, evaluate=False)
|
| 1510 |
+
|
| 1511 |
+
if deep:
|
| 1512 |
+
return expr.replace(Piecewise, make_exclusive)
|
| 1513 |
+
elif isinstance(expr, Piecewise):
|
| 1514 |
+
return make_exclusive(*expr.args)
|
| 1515 |
+
else:
|
| 1516 |
+
return expr
|
evalkit_tf437/lib/python3.10/site-packages/sympy/functions/elementary/tests/__init__.py
ADDED
|
File without changes
|
evalkit_tf437/lib/python3.10/site-packages/sympy/functions/elementary/tests/__pycache__/test_integers.cpython-310.pyc
ADDED
|
Binary file (18.5 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/sympy/functions/elementary/tests/__pycache__/test_interface.cpython-310.pyc
ADDED
|
Binary file (3.1 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/sympy/functions/elementary/tests/test_complexes.py
ADDED
|
@@ -0,0 +1,1028 @@
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.core.expr import Expr
|
| 2 |
+
from sympy.core.function import (Derivative, Function, Lambda, expand)
|
| 3 |
+
from sympy.core.numbers import (E, I, Rational, comp, nan, oo, pi, zoo)
|
| 4 |
+
from sympy.core.relational import Eq
|
| 5 |
+
from sympy.core.singleton import S
|
| 6 |
+
from sympy.core.symbol import (Symbol, symbols)
|
| 7 |
+
from sympy.functions.elementary.complexes import (Abs, adjoint, arg, conjugate, im, re, sign, transpose)
|
| 8 |
+
from sympy.functions.elementary.exponential import (exp, exp_polar, log)
|
| 9 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
| 10 |
+
from sympy.functions.elementary.piecewise import Piecewise
|
| 11 |
+
from sympy.functions.elementary.trigonometric import (acos, atan, atan2, cos, sin)
|
| 12 |
+
from sympy.functions.elementary.hyperbolic import sinh
|
| 13 |
+
from sympy.functions.special.delta_functions import (DiracDelta, Heaviside)
|
| 14 |
+
from sympy.integrals.integrals import Integral
|
| 15 |
+
from sympy.matrices.dense import Matrix
|
| 16 |
+
from sympy.matrices.expressions.funcmatrix import FunctionMatrix
|
| 17 |
+
from sympy.matrices.expressions.matexpr import MatrixSymbol
|
| 18 |
+
from sympy.matrices.immutable import (ImmutableMatrix, ImmutableSparseMatrix)
|
| 19 |
+
from sympy.matrices import SparseMatrix
|
| 20 |
+
from sympy.sets.sets import Interval
|
| 21 |
+
from sympy.core.expr import unchanged
|
| 22 |
+
from sympy.core.function import ArgumentIndexError
|
| 23 |
+
from sympy.testing.pytest import XFAIL, raises, _both_exp_pow
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def N_equals(a, b):
|
| 27 |
+
"""Check whether two complex numbers are numerically close"""
|
| 28 |
+
return comp(a.n(), b.n(), 1.e-6)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def test_re():
|
| 32 |
+
x, y = symbols('x,y')
|
| 33 |
+
a, b = symbols('a,b', real=True)
|
| 34 |
+
|
| 35 |
+
r = Symbol('r', real=True)
|
| 36 |
+
i = Symbol('i', imaginary=True)
|
| 37 |
+
|
| 38 |
+
assert re(nan) is nan
|
| 39 |
+
|
| 40 |
+
assert re(oo) is oo
|
| 41 |
+
assert re(-oo) is -oo
|
| 42 |
+
|
| 43 |
+
assert re(0) == 0
|
| 44 |
+
|
| 45 |
+
assert re(1) == 1
|
| 46 |
+
assert re(-1) == -1
|
| 47 |
+
|
| 48 |
+
assert re(E) == E
|
| 49 |
+
assert re(-E) == -E
|
| 50 |
+
|
| 51 |
+
assert unchanged(re, x)
|
| 52 |
+
assert re(x*I) == -im(x)
|
| 53 |
+
assert re(r*I) == 0
|
| 54 |
+
assert re(r) == r
|
| 55 |
+
assert re(i*I) == I * i
|
| 56 |
+
assert re(i) == 0
|
| 57 |
+
|
| 58 |
+
assert re(x + y) == re(x) + re(y)
|
| 59 |
+
assert re(x + r) == re(x) + r
|
| 60 |
+
|
| 61 |
+
assert re(re(x)) == re(x)
|
| 62 |
+
|
| 63 |
+
assert re(2 + I) == 2
|
| 64 |
+
assert re(x + I) == re(x)
|
| 65 |
+
|
| 66 |
+
assert re(x + y*I) == re(x) - im(y)
|
| 67 |
+
assert re(x + r*I) == re(x)
|
| 68 |
+
|
| 69 |
+
assert re(log(2*I)) == log(2)
|
| 70 |
+
|
| 71 |
+
assert re((2 + I)**2).expand(complex=True) == 3
|
| 72 |
+
|
| 73 |
+
assert re(conjugate(x)) == re(x)
|
| 74 |
+
assert conjugate(re(x)) == re(x)
|
| 75 |
+
|
| 76 |
+
assert re(x).as_real_imag() == (re(x), 0)
|
| 77 |
+
|
| 78 |
+
assert re(i*r*x).diff(r) == re(i*x)
|
| 79 |
+
assert re(i*r*x).diff(i) == I*r*im(x)
|
| 80 |
+
|
| 81 |
+
assert re(
|
| 82 |
+
sqrt(a + b*I)) == (a**2 + b**2)**Rational(1, 4)*cos(atan2(b, a)/2)
|
| 83 |
+
assert re(a * (2 + b*I)) == 2*a
|
| 84 |
+
|
| 85 |
+
assert re((1 + sqrt(a + b*I))/2) == \
|
| 86 |
+
(a**2 + b**2)**Rational(1, 4)*cos(atan2(b, a)/2)/2 + S.Half
|
| 87 |
+
|
| 88 |
+
assert re(x).rewrite(im) == x - S.ImaginaryUnit*im(x)
|
| 89 |
+
assert (x + re(y)).rewrite(re, im) == x + y - S.ImaginaryUnit*im(y)
|
| 90 |
+
|
| 91 |
+
a = Symbol('a', algebraic=True)
|
| 92 |
+
t = Symbol('t', transcendental=True)
|
| 93 |
+
x = Symbol('x')
|
| 94 |
+
assert re(a).is_algebraic
|
| 95 |
+
assert re(x).is_algebraic is None
|
| 96 |
+
assert re(t).is_algebraic is False
|
| 97 |
+
|
| 98 |
+
assert re(S.ComplexInfinity) is S.NaN
|
| 99 |
+
|
| 100 |
+
n, m, l = symbols('n m l')
|
| 101 |
+
A = MatrixSymbol('A',n,m)
|
| 102 |
+
assert re(A) == (S.Half) * (A + conjugate(A))
|
| 103 |
+
|
| 104 |
+
A = Matrix([[1 + 4*I,2],[0, -3*I]])
|
| 105 |
+
assert re(A) == Matrix([[1, 2],[0, 0]])
|
| 106 |
+
|
| 107 |
+
A = ImmutableMatrix([[1 + 3*I, 3-2*I],[0, 2*I]])
|
| 108 |
+
assert re(A) == ImmutableMatrix([[1, 3],[0, 0]])
|
| 109 |
+
|
| 110 |
+
X = SparseMatrix([[2*j + i*I for i in range(5)] for j in range(5)])
|
| 111 |
+
assert re(X) - Matrix([[0, 0, 0, 0, 0],
|
| 112 |
+
[2, 2, 2, 2, 2],
|
| 113 |
+
[4, 4, 4, 4, 4],
|
| 114 |
+
[6, 6, 6, 6, 6],
|
| 115 |
+
[8, 8, 8, 8, 8]]) == Matrix.zeros(5)
|
| 116 |
+
|
| 117 |
+
assert im(X) - Matrix([[0, 1, 2, 3, 4],
|
| 118 |
+
[0, 1, 2, 3, 4],
|
| 119 |
+
[0, 1, 2, 3, 4],
|
| 120 |
+
[0, 1, 2, 3, 4],
|
| 121 |
+
[0, 1, 2, 3, 4]]) == Matrix.zeros(5)
|
| 122 |
+
|
| 123 |
+
X = FunctionMatrix(3, 3, Lambda((n, m), n + m*I))
|
| 124 |
+
assert re(X) == Matrix([[0, 0, 0], [1, 1, 1], [2, 2, 2]])
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def test_im():
|
| 128 |
+
x, y = symbols('x,y')
|
| 129 |
+
a, b = symbols('a,b', real=True)
|
| 130 |
+
|
| 131 |
+
r = Symbol('r', real=True)
|
| 132 |
+
i = Symbol('i', imaginary=True)
|
| 133 |
+
|
| 134 |
+
assert im(nan) is nan
|
| 135 |
+
|
| 136 |
+
assert im(oo*I) is oo
|
| 137 |
+
assert im(-oo*I) is -oo
|
| 138 |
+
|
| 139 |
+
assert im(0) == 0
|
| 140 |
+
|
| 141 |
+
assert im(1) == 0
|
| 142 |
+
assert im(-1) == 0
|
| 143 |
+
|
| 144 |
+
assert im(E*I) == E
|
| 145 |
+
assert im(-E*I) == -E
|
| 146 |
+
|
| 147 |
+
assert unchanged(im, x)
|
| 148 |
+
assert im(x*I) == re(x)
|
| 149 |
+
assert im(r*I) == r
|
| 150 |
+
assert im(r) == 0
|
| 151 |
+
assert im(i*I) == 0
|
| 152 |
+
assert im(i) == -I * i
|
| 153 |
+
|
| 154 |
+
assert im(x + y) == im(x) + im(y)
|
| 155 |
+
assert im(x + r) == im(x)
|
| 156 |
+
assert im(x + r*I) == im(x) + r
|
| 157 |
+
|
| 158 |
+
assert im(im(x)*I) == im(x)
|
| 159 |
+
|
| 160 |
+
assert im(2 + I) == 1
|
| 161 |
+
assert im(x + I) == im(x) + 1
|
| 162 |
+
|
| 163 |
+
assert im(x + y*I) == im(x) + re(y)
|
| 164 |
+
assert im(x + r*I) == im(x) + r
|
| 165 |
+
|
| 166 |
+
assert im(log(2*I)) == pi/2
|
| 167 |
+
|
| 168 |
+
assert im((2 + I)**2).expand(complex=True) == 4
|
| 169 |
+
|
| 170 |
+
assert im(conjugate(x)) == -im(x)
|
| 171 |
+
assert conjugate(im(x)) == im(x)
|
| 172 |
+
|
| 173 |
+
assert im(x).as_real_imag() == (im(x), 0)
|
| 174 |
+
|
| 175 |
+
assert im(i*r*x).diff(r) == im(i*x)
|
| 176 |
+
assert im(i*r*x).diff(i) == -I * re(r*x)
|
| 177 |
+
|
| 178 |
+
assert im(
|
| 179 |
+
sqrt(a + b*I)) == (a**2 + b**2)**Rational(1, 4)*sin(atan2(b, a)/2)
|
| 180 |
+
assert im(a * (2 + b*I)) == a*b
|
| 181 |
+
|
| 182 |
+
assert im((1 + sqrt(a + b*I))/2) == \
|
| 183 |
+
(a**2 + b**2)**Rational(1, 4)*sin(atan2(b, a)/2)/2
|
| 184 |
+
|
| 185 |
+
assert im(x).rewrite(re) == -S.ImaginaryUnit * (x - re(x))
|
| 186 |
+
assert (x + im(y)).rewrite(im, re) == x - S.ImaginaryUnit * (y - re(y))
|
| 187 |
+
|
| 188 |
+
a = Symbol('a', algebraic=True)
|
| 189 |
+
t = Symbol('t', transcendental=True)
|
| 190 |
+
x = Symbol('x')
|
| 191 |
+
assert re(a).is_algebraic
|
| 192 |
+
assert re(x).is_algebraic is None
|
| 193 |
+
assert re(t).is_algebraic is False
|
| 194 |
+
|
| 195 |
+
assert im(S.ComplexInfinity) is S.NaN
|
| 196 |
+
|
| 197 |
+
n, m, l = symbols('n m l')
|
| 198 |
+
A = MatrixSymbol('A',n,m)
|
| 199 |
+
|
| 200 |
+
assert im(A) == (S.One/(2*I)) * (A - conjugate(A))
|
| 201 |
+
|
| 202 |
+
A = Matrix([[1 + 4*I, 2],[0, -3*I]])
|
| 203 |
+
assert im(A) == Matrix([[4, 0],[0, -3]])
|
| 204 |
+
|
| 205 |
+
A = ImmutableMatrix([[1 + 3*I, 3-2*I],[0, 2*I]])
|
| 206 |
+
assert im(A) == ImmutableMatrix([[3, -2],[0, 2]])
|
| 207 |
+
|
| 208 |
+
X = ImmutableSparseMatrix(
|
| 209 |
+
[[i*I + i for i in range(5)] for i in range(5)])
|
| 210 |
+
Y = SparseMatrix([list(range(5)) for i in range(5)])
|
| 211 |
+
assert im(X).as_immutable() == Y
|
| 212 |
+
|
| 213 |
+
X = FunctionMatrix(3, 3, Lambda((n, m), n + m*I))
|
| 214 |
+
assert im(X) == Matrix([[0, 1, 2], [0, 1, 2], [0, 1, 2]])
|
| 215 |
+
|
| 216 |
+
def test_sign():
|
| 217 |
+
assert sign(1.2) == 1
|
| 218 |
+
assert sign(-1.2) == -1
|
| 219 |
+
assert sign(3*I) == I
|
| 220 |
+
assert sign(-3*I) == -I
|
| 221 |
+
assert sign(0) == 0
|
| 222 |
+
assert sign(0, evaluate=False).doit() == 0
|
| 223 |
+
assert sign(oo, evaluate=False).doit() == 1
|
| 224 |
+
assert sign(nan) is nan
|
| 225 |
+
assert sign(2 + 2*I).doit() == sqrt(2)*(2 + 2*I)/4
|
| 226 |
+
assert sign(2 + 3*I).simplify() == sign(2 + 3*I)
|
| 227 |
+
assert sign(2 + 2*I).simplify() == sign(1 + I)
|
| 228 |
+
assert sign(im(sqrt(1 - sqrt(3)))) == 1
|
| 229 |
+
assert sign(sqrt(1 - sqrt(3))) == I
|
| 230 |
+
|
| 231 |
+
x = Symbol('x')
|
| 232 |
+
assert sign(x).is_finite is True
|
| 233 |
+
assert sign(x).is_complex is True
|
| 234 |
+
assert sign(x).is_imaginary is None
|
| 235 |
+
assert sign(x).is_integer is None
|
| 236 |
+
assert sign(x).is_real is None
|
| 237 |
+
assert sign(x).is_zero is None
|
| 238 |
+
assert sign(x).doit() == sign(x)
|
| 239 |
+
assert sign(1.2*x) == sign(x)
|
| 240 |
+
assert sign(2*x) == sign(x)
|
| 241 |
+
assert sign(I*x) == I*sign(x)
|
| 242 |
+
assert sign(-2*I*x) == -I*sign(x)
|
| 243 |
+
assert sign(conjugate(x)) == conjugate(sign(x))
|
| 244 |
+
|
| 245 |
+
p = Symbol('p', positive=True)
|
| 246 |
+
n = Symbol('n', negative=True)
|
| 247 |
+
m = Symbol('m', negative=True)
|
| 248 |
+
assert sign(2*p*x) == sign(x)
|
| 249 |
+
assert sign(n*x) == -sign(x)
|
| 250 |
+
assert sign(n*m*x) == sign(x)
|
| 251 |
+
|
| 252 |
+
x = Symbol('x', imaginary=True)
|
| 253 |
+
assert sign(x).is_imaginary is True
|
| 254 |
+
assert sign(x).is_integer is False
|
| 255 |
+
assert sign(x).is_real is False
|
| 256 |
+
assert sign(x).is_zero is False
|
| 257 |
+
assert sign(x).diff(x) == 2*DiracDelta(-I*x)
|
| 258 |
+
assert sign(x).doit() == x / Abs(x)
|
| 259 |
+
assert conjugate(sign(x)) == -sign(x)
|
| 260 |
+
|
| 261 |
+
x = Symbol('x', real=True)
|
| 262 |
+
assert sign(x).is_imaginary is False
|
| 263 |
+
assert sign(x).is_integer is True
|
| 264 |
+
assert sign(x).is_real is True
|
| 265 |
+
assert sign(x).is_zero is None
|
| 266 |
+
assert sign(x).diff(x) == 2*DiracDelta(x)
|
| 267 |
+
assert sign(x).doit() == sign(x)
|
| 268 |
+
assert conjugate(sign(x)) == sign(x)
|
| 269 |
+
|
| 270 |
+
x = Symbol('x', nonzero=True)
|
| 271 |
+
assert sign(x).is_imaginary is False
|
| 272 |
+
assert sign(x).is_integer is True
|
| 273 |
+
assert sign(x).is_real is True
|
| 274 |
+
assert sign(x).is_zero is False
|
| 275 |
+
assert sign(x).doit() == x / Abs(x)
|
| 276 |
+
assert sign(Abs(x)) == 1
|
| 277 |
+
assert Abs(sign(x)) == 1
|
| 278 |
+
|
| 279 |
+
x = Symbol('x', positive=True)
|
| 280 |
+
assert sign(x).is_imaginary is False
|
| 281 |
+
assert sign(x).is_integer is True
|
| 282 |
+
assert sign(x).is_real is True
|
| 283 |
+
assert sign(x).is_zero is False
|
| 284 |
+
assert sign(x).doit() == x / Abs(x)
|
| 285 |
+
assert sign(Abs(x)) == 1
|
| 286 |
+
assert Abs(sign(x)) == 1
|
| 287 |
+
|
| 288 |
+
x = 0
|
| 289 |
+
assert sign(x).is_imaginary is False
|
| 290 |
+
assert sign(x).is_integer is True
|
| 291 |
+
assert sign(x).is_real is True
|
| 292 |
+
assert sign(x).is_zero is True
|
| 293 |
+
assert sign(x).doit() == 0
|
| 294 |
+
assert sign(Abs(x)) == 0
|
| 295 |
+
assert Abs(sign(x)) == 0
|
| 296 |
+
|
| 297 |
+
nz = Symbol('nz', nonzero=True, integer=True)
|
| 298 |
+
assert sign(nz).is_imaginary is False
|
| 299 |
+
assert sign(nz).is_integer is True
|
| 300 |
+
assert sign(nz).is_real is True
|
| 301 |
+
assert sign(nz).is_zero is False
|
| 302 |
+
assert sign(nz)**2 == 1
|
| 303 |
+
assert (sign(nz)**3).args == (sign(nz), 3)
|
| 304 |
+
|
| 305 |
+
assert sign(Symbol('x', nonnegative=True)).is_nonnegative
|
| 306 |
+
assert sign(Symbol('x', nonnegative=True)).is_nonpositive is None
|
| 307 |
+
assert sign(Symbol('x', nonpositive=True)).is_nonnegative is None
|
| 308 |
+
assert sign(Symbol('x', nonpositive=True)).is_nonpositive
|
| 309 |
+
assert sign(Symbol('x', real=True)).is_nonnegative is None
|
| 310 |
+
assert sign(Symbol('x', real=True)).is_nonpositive is None
|
| 311 |
+
assert sign(Symbol('x', real=True, zero=False)).is_nonpositive is None
|
| 312 |
+
|
| 313 |
+
x, y = Symbol('x', real=True), Symbol('y')
|
| 314 |
+
f = Function('f')
|
| 315 |
+
assert sign(x).rewrite(Piecewise) == \
|
| 316 |
+
Piecewise((1, x > 0), (-1, x < 0), (0, True))
|
| 317 |
+
assert sign(y).rewrite(Piecewise) == sign(y)
|
| 318 |
+
assert sign(x).rewrite(Heaviside) == 2*Heaviside(x, H0=S(1)/2) - 1
|
| 319 |
+
assert sign(y).rewrite(Heaviside) == sign(y)
|
| 320 |
+
assert sign(y).rewrite(Abs) == Piecewise((0, Eq(y, 0)), (y/Abs(y), True))
|
| 321 |
+
assert sign(f(y)).rewrite(Abs) == Piecewise((0, Eq(f(y), 0)), (f(y)/Abs(f(y)), True))
|
| 322 |
+
|
| 323 |
+
# evaluate what can be evaluated
|
| 324 |
+
assert sign(exp_polar(I*pi)*pi) is S.NegativeOne
|
| 325 |
+
|
| 326 |
+
eq = -sqrt(10 + 6*sqrt(3)) + sqrt(1 + sqrt(3)) + sqrt(3 + 3*sqrt(3))
|
| 327 |
+
# if there is a fast way to know when and when you cannot prove an
|
| 328 |
+
# expression like this is zero then the equality to zero is ok
|
| 329 |
+
assert sign(eq).func is sign or sign(eq) == 0
|
| 330 |
+
# but sometimes it's hard to do this so it's better not to load
|
| 331 |
+
# abs down with tests that will be very slow
|
| 332 |
+
q = 1 + sqrt(2) - 2*sqrt(3) + 1331*sqrt(6)
|
| 333 |
+
p = expand(q**3)**Rational(1, 3)
|
| 334 |
+
d = p - q
|
| 335 |
+
assert sign(d).func is sign or sign(d) == 0
|
| 336 |
+
|
| 337 |
+
|
| 338 |
+
def test_as_real_imag():
|
| 339 |
+
n = pi**1000
|
| 340 |
+
# the special code for working out the real
|
| 341 |
+
# and complex parts of a power with Integer exponent
|
| 342 |
+
# should not run if there is no imaginary part, hence
|
| 343 |
+
# this should not hang
|
| 344 |
+
assert n.as_real_imag() == (n, 0)
|
| 345 |
+
|
| 346 |
+
# issue 6261
|
| 347 |
+
x = Symbol('x')
|
| 348 |
+
assert sqrt(x).as_real_imag() == \
|
| 349 |
+
((re(x)**2 + im(x)**2)**Rational(1, 4)*cos(atan2(im(x), re(x))/2),
|
| 350 |
+
(re(x)**2 + im(x)**2)**Rational(1, 4)*sin(atan2(im(x), re(x))/2))
|
| 351 |
+
|
| 352 |
+
# issue 3853
|
| 353 |
+
a, b = symbols('a,b', real=True)
|
| 354 |
+
assert ((1 + sqrt(a + b*I))/2).as_real_imag() == \
|
| 355 |
+
(
|
| 356 |
+
(a**2 + b**2)**Rational(
|
| 357 |
+
1, 4)*cos(atan2(b, a)/2)/2 + S.Half,
|
| 358 |
+
(a**2 + b**2)**Rational(1, 4)*sin(atan2(b, a)/2)/2)
|
| 359 |
+
|
| 360 |
+
assert sqrt(a**2).as_real_imag() == (sqrt(a**2), 0)
|
| 361 |
+
i = symbols('i', imaginary=True)
|
| 362 |
+
assert sqrt(i**2).as_real_imag() == (0, abs(i))
|
| 363 |
+
|
| 364 |
+
assert ((1 + I)/(1 - I)).as_real_imag() == (0, 1)
|
| 365 |
+
assert ((1 + I)**3/(1 - I)).as_real_imag() == (-2, 0)
|
| 366 |
+
|
| 367 |
+
|
| 368 |
+
@XFAIL
|
| 369 |
+
def test_sign_issue_3068():
|
| 370 |
+
n = pi**1000
|
| 371 |
+
i = int(n)
|
| 372 |
+
x = Symbol('x')
|
| 373 |
+
assert (n - i).round() == 1 # doesn't hang
|
| 374 |
+
assert sign(n - i) == 1
|
| 375 |
+
# perhaps it's not possible to get the sign right when
|
| 376 |
+
# only 1 digit is being requested for this situation;
|
| 377 |
+
# 2 digits works
|
| 378 |
+
assert (n - x).n(1, subs={x: i}) > 0
|
| 379 |
+
assert (n - x).n(2, subs={x: i}) > 0
|
| 380 |
+
|
| 381 |
+
|
| 382 |
+
def test_Abs():
|
| 383 |
+
raises(TypeError, lambda: Abs(Interval(2, 3))) # issue 8717
|
| 384 |
+
|
| 385 |
+
x, y = symbols('x,y')
|
| 386 |
+
assert sign(sign(x)) == sign(x)
|
| 387 |
+
assert sign(x*y).func is sign
|
| 388 |
+
assert Abs(0) == 0
|
| 389 |
+
assert Abs(1) == 1
|
| 390 |
+
assert Abs(-1) == 1
|
| 391 |
+
assert Abs(I) == 1
|
| 392 |
+
assert Abs(-I) == 1
|
| 393 |
+
assert Abs(nan) is nan
|
| 394 |
+
assert Abs(zoo) is oo
|
| 395 |
+
assert Abs(I * pi) == pi
|
| 396 |
+
assert Abs(-I * pi) == pi
|
| 397 |
+
assert Abs(I * x) == Abs(x)
|
| 398 |
+
assert Abs(-I * x) == Abs(x)
|
| 399 |
+
assert Abs(-2*x) == 2*Abs(x)
|
| 400 |
+
assert Abs(-2.0*x) == 2.0*Abs(x)
|
| 401 |
+
assert Abs(2*pi*x*y) == 2*pi*Abs(x*y)
|
| 402 |
+
assert Abs(conjugate(x)) == Abs(x)
|
| 403 |
+
assert conjugate(Abs(x)) == Abs(x)
|
| 404 |
+
assert Abs(x).expand(complex=True) == sqrt(re(x)**2 + im(x)**2)
|
| 405 |
+
|
| 406 |
+
a = Symbol('a', positive=True)
|
| 407 |
+
assert Abs(2*pi*x*a) == 2*pi*a*Abs(x)
|
| 408 |
+
assert Abs(2*pi*I*x*a) == 2*pi*a*Abs(x)
|
| 409 |
+
|
| 410 |
+
x = Symbol('x', real=True)
|
| 411 |
+
n = Symbol('n', integer=True)
|
| 412 |
+
assert Abs((-1)**n) == 1
|
| 413 |
+
assert x**(2*n) == Abs(x)**(2*n)
|
| 414 |
+
assert Abs(x).diff(x) == sign(x)
|
| 415 |
+
assert abs(x) == Abs(x) # Python built-in
|
| 416 |
+
assert Abs(x)**3 == x**2*Abs(x)
|
| 417 |
+
assert Abs(x)**4 == x**4
|
| 418 |
+
assert (
|
| 419 |
+
Abs(x)**(3*n)).args == (Abs(x), 3*n) # leave symbolic odd unchanged
|
| 420 |
+
assert (1/Abs(x)).args == (Abs(x), -1)
|
| 421 |
+
assert 1/Abs(x)**3 == 1/(x**2*Abs(x))
|
| 422 |
+
assert Abs(x)**-3 == Abs(x)/(x**4)
|
| 423 |
+
assert Abs(x**3) == x**2*Abs(x)
|
| 424 |
+
assert Abs(I**I) == exp(-pi/2)
|
| 425 |
+
assert Abs((4 + 5*I)**(6 + 7*I)) == 68921*exp(-7*atan(Rational(5, 4)))
|
| 426 |
+
y = Symbol('y', real=True)
|
| 427 |
+
assert Abs(I**y) == 1
|
| 428 |
+
y = Symbol('y')
|
| 429 |
+
assert Abs(I**y) == exp(-pi*im(y)/2)
|
| 430 |
+
|
| 431 |
+
x = Symbol('x', imaginary=True)
|
| 432 |
+
assert Abs(x).diff(x) == -sign(x)
|
| 433 |
+
|
| 434 |
+
eq = -sqrt(10 + 6*sqrt(3)) + sqrt(1 + sqrt(3)) + sqrt(3 + 3*sqrt(3))
|
| 435 |
+
# if there is a fast way to know when you can and when you cannot prove an
|
| 436 |
+
# expression like this is zero then the equality to zero is ok
|
| 437 |
+
assert abs(eq).func is Abs or abs(eq) == 0
|
| 438 |
+
# but sometimes it's hard to do this so it's better not to load
|
| 439 |
+
# abs down with tests that will be very slow
|
| 440 |
+
q = 1 + sqrt(2) - 2*sqrt(3) + 1331*sqrt(6)
|
| 441 |
+
p = expand(q**3)**Rational(1, 3)
|
| 442 |
+
d = p - q
|
| 443 |
+
assert abs(d).func is Abs or abs(d) == 0
|
| 444 |
+
|
| 445 |
+
assert Abs(4*exp(pi*I/4)) == 4
|
| 446 |
+
assert Abs(3**(2 + I)) == 9
|
| 447 |
+
assert Abs((-3)**(1 - I)) == 3*exp(pi)
|
| 448 |
+
|
| 449 |
+
assert Abs(oo) is oo
|
| 450 |
+
assert Abs(-oo) is oo
|
| 451 |
+
assert Abs(oo + I) is oo
|
| 452 |
+
assert Abs(oo + I*oo) is oo
|
| 453 |
+
|
| 454 |
+
a = Symbol('a', algebraic=True)
|
| 455 |
+
t = Symbol('t', transcendental=True)
|
| 456 |
+
x = Symbol('x')
|
| 457 |
+
assert re(a).is_algebraic
|
| 458 |
+
assert re(x).is_algebraic is None
|
| 459 |
+
assert re(t).is_algebraic is False
|
| 460 |
+
assert Abs(x).fdiff() == sign(x)
|
| 461 |
+
raises(ArgumentIndexError, lambda: Abs(x).fdiff(2))
|
| 462 |
+
|
| 463 |
+
# doesn't have recursion error
|
| 464 |
+
arg = sqrt(acos(1 - I)*acos(1 + I))
|
| 465 |
+
assert abs(arg) == arg
|
| 466 |
+
|
| 467 |
+
# special handling to put Abs in denom
|
| 468 |
+
assert abs(1/x) == 1/Abs(x)
|
| 469 |
+
e = abs(2/x**2)
|
| 470 |
+
assert e.is_Mul and e == 2/Abs(x**2)
|
| 471 |
+
assert unchanged(Abs, y/x)
|
| 472 |
+
assert unchanged(Abs, x/(x + 1))
|
| 473 |
+
assert unchanged(Abs, x*y)
|
| 474 |
+
p = Symbol('p', positive=True)
|
| 475 |
+
assert abs(x/p) == abs(x)/p
|
| 476 |
+
|
| 477 |
+
# coverage
|
| 478 |
+
assert unchanged(Abs, Symbol('x', real=True)**y)
|
| 479 |
+
# issue 19627
|
| 480 |
+
f = Function('f', positive=True)
|
| 481 |
+
assert sqrt(f(x)**2) == f(x)
|
| 482 |
+
# issue 21625
|
| 483 |
+
assert unchanged(Abs, S("im(acos(-i + acosh(-g + i)))"))
|
| 484 |
+
|
| 485 |
+
|
| 486 |
+
def test_Abs_rewrite():
|
| 487 |
+
x = Symbol('x', real=True)
|
| 488 |
+
a = Abs(x).rewrite(Heaviside).expand()
|
| 489 |
+
assert a == x*Heaviside(x) - x*Heaviside(-x)
|
| 490 |
+
for i in [-2, -1, 0, 1, 2]:
|
| 491 |
+
assert a.subs(x, i) == abs(i)
|
| 492 |
+
y = Symbol('y')
|
| 493 |
+
assert Abs(y).rewrite(Heaviside) == Abs(y)
|
| 494 |
+
|
| 495 |
+
x, y = Symbol('x', real=True), Symbol('y')
|
| 496 |
+
assert Abs(x).rewrite(Piecewise) == Piecewise((x, x >= 0), (-x, True))
|
| 497 |
+
assert Abs(y).rewrite(Piecewise) == Abs(y)
|
| 498 |
+
assert Abs(y).rewrite(sign) == y/sign(y)
|
| 499 |
+
|
| 500 |
+
i = Symbol('i', imaginary=True)
|
| 501 |
+
assert abs(i).rewrite(Piecewise) == Piecewise((I*i, I*i >= 0), (-I*i, True))
|
| 502 |
+
|
| 503 |
+
|
| 504 |
+
assert Abs(y).rewrite(conjugate) == sqrt(y*conjugate(y))
|
| 505 |
+
assert Abs(i).rewrite(conjugate) == sqrt(-i**2) # == -I*i
|
| 506 |
+
|
| 507 |
+
y = Symbol('y', extended_real=True)
|
| 508 |
+
assert (Abs(exp(-I*x)-exp(-I*y))**2).rewrite(conjugate) == \
|
| 509 |
+
-exp(I*x)*exp(-I*y) + 2 - exp(-I*x)*exp(I*y)
|
| 510 |
+
|
| 511 |
+
|
| 512 |
+
def test_Abs_real():
|
| 513 |
+
# test some properties of abs that only apply
|
| 514 |
+
# to real numbers
|
| 515 |
+
x = Symbol('x', complex=True)
|
| 516 |
+
assert sqrt(x**2) != Abs(x)
|
| 517 |
+
assert Abs(x**2) != x**2
|
| 518 |
+
|
| 519 |
+
x = Symbol('x', real=True)
|
| 520 |
+
assert sqrt(x**2) == Abs(x)
|
| 521 |
+
assert Abs(x**2) == x**2
|
| 522 |
+
|
| 523 |
+
# if the symbol is zero, the following will still apply
|
| 524 |
+
nn = Symbol('nn', nonnegative=True, real=True)
|
| 525 |
+
np = Symbol('np', nonpositive=True, real=True)
|
| 526 |
+
assert Abs(nn) == nn
|
| 527 |
+
assert Abs(np) == -np
|
| 528 |
+
|
| 529 |
+
|
| 530 |
+
def test_Abs_properties():
|
| 531 |
+
x = Symbol('x')
|
| 532 |
+
assert Abs(x).is_real is None
|
| 533 |
+
assert Abs(x).is_extended_real is True
|
| 534 |
+
assert Abs(x).is_rational is None
|
| 535 |
+
assert Abs(x).is_positive is None
|
| 536 |
+
assert Abs(x).is_nonnegative is None
|
| 537 |
+
assert Abs(x).is_extended_positive is None
|
| 538 |
+
assert Abs(x).is_extended_nonnegative is True
|
| 539 |
+
|
| 540 |
+
f = Symbol('x', finite=True)
|
| 541 |
+
assert Abs(f).is_real is True
|
| 542 |
+
assert Abs(f).is_extended_real is True
|
| 543 |
+
assert Abs(f).is_rational is None
|
| 544 |
+
assert Abs(f).is_positive is None
|
| 545 |
+
assert Abs(f).is_nonnegative is True
|
| 546 |
+
assert Abs(f).is_extended_positive is None
|
| 547 |
+
assert Abs(f).is_extended_nonnegative is True
|
| 548 |
+
|
| 549 |
+
z = Symbol('z', complex=True, zero=False)
|
| 550 |
+
assert Abs(z).is_real is True # since complex implies finite
|
| 551 |
+
assert Abs(z).is_extended_real is True
|
| 552 |
+
assert Abs(z).is_rational is None
|
| 553 |
+
assert Abs(z).is_positive is True
|
| 554 |
+
assert Abs(z).is_extended_positive is True
|
| 555 |
+
assert Abs(z).is_zero is False
|
| 556 |
+
|
| 557 |
+
p = Symbol('p', positive=True)
|
| 558 |
+
assert Abs(p).is_real is True
|
| 559 |
+
assert Abs(p).is_extended_real is True
|
| 560 |
+
assert Abs(p).is_rational is None
|
| 561 |
+
assert Abs(p).is_positive is True
|
| 562 |
+
assert Abs(p).is_zero is False
|
| 563 |
+
|
| 564 |
+
q = Symbol('q', rational=True)
|
| 565 |
+
assert Abs(q).is_real is True
|
| 566 |
+
assert Abs(q).is_rational is True
|
| 567 |
+
assert Abs(q).is_integer is None
|
| 568 |
+
assert Abs(q).is_positive is None
|
| 569 |
+
assert Abs(q).is_nonnegative is True
|
| 570 |
+
|
| 571 |
+
i = Symbol('i', integer=True)
|
| 572 |
+
assert Abs(i).is_real is True
|
| 573 |
+
assert Abs(i).is_integer is True
|
| 574 |
+
assert Abs(i).is_positive is None
|
| 575 |
+
assert Abs(i).is_nonnegative is True
|
| 576 |
+
|
| 577 |
+
e = Symbol('n', even=True)
|
| 578 |
+
ne = Symbol('ne', real=True, even=False)
|
| 579 |
+
assert Abs(e).is_even is True
|
| 580 |
+
assert Abs(ne).is_even is False
|
| 581 |
+
assert Abs(i).is_even is None
|
| 582 |
+
|
| 583 |
+
o = Symbol('n', odd=True)
|
| 584 |
+
no = Symbol('no', real=True, odd=False)
|
| 585 |
+
assert Abs(o).is_odd is True
|
| 586 |
+
assert Abs(no).is_odd is False
|
| 587 |
+
assert Abs(i).is_odd is None
|
| 588 |
+
|
| 589 |
+
|
| 590 |
+
def test_abs():
|
| 591 |
+
# this tests that abs calls Abs; don't rename to
|
| 592 |
+
# test_Abs since that test is already above
|
| 593 |
+
a = Symbol('a', positive=True)
|
| 594 |
+
assert abs(I*(1 + a)**2) == (1 + a)**2
|
| 595 |
+
|
| 596 |
+
|
| 597 |
+
def test_arg():
|
| 598 |
+
assert arg(0) is nan
|
| 599 |
+
assert arg(1) == 0
|
| 600 |
+
assert arg(-1) == pi
|
| 601 |
+
assert arg(I) == pi/2
|
| 602 |
+
assert arg(-I) == -pi/2
|
| 603 |
+
assert arg(1 + I) == pi/4
|
| 604 |
+
assert arg(-1 + I) == pi*Rational(3, 4)
|
| 605 |
+
assert arg(1 - I) == -pi/4
|
| 606 |
+
assert arg(exp_polar(4*pi*I)) == 4*pi
|
| 607 |
+
assert arg(exp_polar(-7*pi*I)) == -7*pi
|
| 608 |
+
assert arg(exp_polar(5 - 3*pi*I/4)) == pi*Rational(-3, 4)
|
| 609 |
+
|
| 610 |
+
assert arg(exp(I*pi/7)) == pi/7 # issue 17300
|
| 611 |
+
assert arg(exp(16*I)) == 16 - 6*pi
|
| 612 |
+
assert arg(exp(13*I*pi/12)) == -11*pi/12
|
| 613 |
+
assert arg(exp(123 - 5*I)) == -5 + 2*pi
|
| 614 |
+
assert arg(exp(sin(1 + 3*I))) == -2*pi + cos(1)*sinh(3)
|
| 615 |
+
r = Symbol('r', real=True)
|
| 616 |
+
assert arg(exp(r - 2*I)) == -2
|
| 617 |
+
|
| 618 |
+
f = Function('f')
|
| 619 |
+
assert not arg(f(0) + I*f(1)).atoms(re)
|
| 620 |
+
|
| 621 |
+
# check nesting
|
| 622 |
+
x = Symbol('x')
|
| 623 |
+
assert arg(arg(arg(x))) is not S.NaN
|
| 624 |
+
assert arg(arg(arg(arg(x)))) is S.NaN
|
| 625 |
+
r = Symbol('r', extended_real=True)
|
| 626 |
+
assert arg(arg(r)) is not S.NaN
|
| 627 |
+
assert arg(arg(arg(r))) is S.NaN
|
| 628 |
+
|
| 629 |
+
p = Function('p', extended_positive=True)
|
| 630 |
+
assert arg(p(x)) == 0
|
| 631 |
+
assert arg((3 + I)*p(x)) == arg(3 + I)
|
| 632 |
+
|
| 633 |
+
p = Symbol('p', positive=True)
|
| 634 |
+
assert arg(p) == 0
|
| 635 |
+
assert arg(p*I) == pi/2
|
| 636 |
+
|
| 637 |
+
n = Symbol('n', negative=True)
|
| 638 |
+
assert arg(n) == pi
|
| 639 |
+
assert arg(n*I) == -pi/2
|
| 640 |
+
|
| 641 |
+
x = Symbol('x')
|
| 642 |
+
assert conjugate(arg(x)) == arg(x)
|
| 643 |
+
|
| 644 |
+
e = p + I*p**2
|
| 645 |
+
assert arg(e) == arg(1 + p*I)
|
| 646 |
+
# make sure sign doesn't swap
|
| 647 |
+
e = -2*p + 4*I*p**2
|
| 648 |
+
assert arg(e) == arg(-1 + 2*p*I)
|
| 649 |
+
# make sure sign isn't lost
|
| 650 |
+
x = symbols('x', real=True) # could be zero
|
| 651 |
+
e = x + I*x
|
| 652 |
+
assert arg(e) == arg(x*(1 + I))
|
| 653 |
+
assert arg(e/p) == arg(x*(1 + I))
|
| 654 |
+
e = p*cos(p) + I*log(p)*exp(p)
|
| 655 |
+
assert arg(e).args[0] == e
|
| 656 |
+
# keep it simple -- let the user do more advanced cancellation
|
| 657 |
+
e = (p + 1) + I*(p**2 - 1)
|
| 658 |
+
assert arg(e).args[0] == e
|
| 659 |
+
|
| 660 |
+
f = Function('f')
|
| 661 |
+
e = 2*x*(f(0) - 1) - 2*x*f(0)
|
| 662 |
+
assert arg(e) == arg(-2*x)
|
| 663 |
+
assert arg(f(0)).func == arg and arg(f(0)).args == (f(0),)
|
| 664 |
+
|
| 665 |
+
|
| 666 |
+
def test_arg_rewrite():
|
| 667 |
+
assert arg(1 + I) == atan2(1, 1)
|
| 668 |
+
|
| 669 |
+
x = Symbol('x', real=True)
|
| 670 |
+
y = Symbol('y', real=True)
|
| 671 |
+
assert arg(x + I*y).rewrite(atan2) == atan2(y, x)
|
| 672 |
+
|
| 673 |
+
|
| 674 |
+
def test_adjoint():
|
| 675 |
+
a = Symbol('a', antihermitian=True)
|
| 676 |
+
b = Symbol('b', hermitian=True)
|
| 677 |
+
assert adjoint(a) == -a
|
| 678 |
+
assert adjoint(I*a) == I*a
|
| 679 |
+
assert adjoint(b) == b
|
| 680 |
+
assert adjoint(I*b) == -I*b
|
| 681 |
+
assert adjoint(a*b) == -b*a
|
| 682 |
+
assert adjoint(I*a*b) == I*b*a
|
| 683 |
+
|
| 684 |
+
x, y = symbols('x y')
|
| 685 |
+
assert adjoint(adjoint(x)) == x
|
| 686 |
+
assert adjoint(x + y) == adjoint(x) + adjoint(y)
|
| 687 |
+
assert adjoint(x - y) == adjoint(x) - adjoint(y)
|
| 688 |
+
assert adjoint(x * y) == adjoint(x) * adjoint(y)
|
| 689 |
+
assert adjoint(x / y) == adjoint(x) / adjoint(y)
|
| 690 |
+
assert adjoint(-x) == -adjoint(x)
|
| 691 |
+
|
| 692 |
+
x, y = symbols('x y', commutative=False)
|
| 693 |
+
assert adjoint(adjoint(x)) == x
|
| 694 |
+
assert adjoint(x + y) == adjoint(x) + adjoint(y)
|
| 695 |
+
assert adjoint(x - y) == adjoint(x) - adjoint(y)
|
| 696 |
+
assert adjoint(x * y) == adjoint(y) * adjoint(x)
|
| 697 |
+
assert adjoint(x / y) == 1 / adjoint(y) * adjoint(x)
|
| 698 |
+
assert adjoint(-x) == -adjoint(x)
|
| 699 |
+
|
| 700 |
+
|
| 701 |
+
def test_conjugate():
|
| 702 |
+
a = Symbol('a', real=True)
|
| 703 |
+
b = Symbol('b', imaginary=True)
|
| 704 |
+
assert conjugate(a) == a
|
| 705 |
+
assert conjugate(I*a) == -I*a
|
| 706 |
+
assert conjugate(b) == -b
|
| 707 |
+
assert conjugate(I*b) == I*b
|
| 708 |
+
assert conjugate(a*b) == -a*b
|
| 709 |
+
assert conjugate(I*a*b) == I*a*b
|
| 710 |
+
|
| 711 |
+
x, y = symbols('x y')
|
| 712 |
+
assert conjugate(conjugate(x)) == x
|
| 713 |
+
assert conjugate(x).inverse() == conjugate
|
| 714 |
+
assert conjugate(x + y) == conjugate(x) + conjugate(y)
|
| 715 |
+
assert conjugate(x - y) == conjugate(x) - conjugate(y)
|
| 716 |
+
assert conjugate(x * y) == conjugate(x) * conjugate(y)
|
| 717 |
+
assert conjugate(x / y) == conjugate(x) / conjugate(y)
|
| 718 |
+
assert conjugate(-x) == -conjugate(x)
|
| 719 |
+
|
| 720 |
+
a = Symbol('a', algebraic=True)
|
| 721 |
+
t = Symbol('t', transcendental=True)
|
| 722 |
+
assert re(a).is_algebraic
|
| 723 |
+
assert re(x).is_algebraic is None
|
| 724 |
+
assert re(t).is_algebraic is False
|
| 725 |
+
|
| 726 |
+
|
| 727 |
+
def test_conjugate_transpose():
|
| 728 |
+
x = Symbol('x')
|
| 729 |
+
assert conjugate(transpose(x)) == adjoint(x)
|
| 730 |
+
assert transpose(conjugate(x)) == adjoint(x)
|
| 731 |
+
assert adjoint(transpose(x)) == conjugate(x)
|
| 732 |
+
assert transpose(adjoint(x)) == conjugate(x)
|
| 733 |
+
assert adjoint(conjugate(x)) == transpose(x)
|
| 734 |
+
assert conjugate(adjoint(x)) == transpose(x)
|
| 735 |
+
|
| 736 |
+
class Symmetric(Expr):
|
| 737 |
+
def _eval_adjoint(self):
|
| 738 |
+
return None
|
| 739 |
+
|
| 740 |
+
def _eval_conjugate(self):
|
| 741 |
+
return None
|
| 742 |
+
|
| 743 |
+
def _eval_transpose(self):
|
| 744 |
+
return self
|
| 745 |
+
x = Symmetric()
|
| 746 |
+
assert conjugate(x) == adjoint(x)
|
| 747 |
+
assert transpose(x) == x
|
| 748 |
+
|
| 749 |
+
|
| 750 |
+
def test_transpose():
|
| 751 |
+
a = Symbol('a', complex=True)
|
| 752 |
+
assert transpose(a) == a
|
| 753 |
+
assert transpose(I*a) == I*a
|
| 754 |
+
|
| 755 |
+
x, y = symbols('x y')
|
| 756 |
+
assert transpose(transpose(x)) == x
|
| 757 |
+
assert transpose(x + y) == transpose(x) + transpose(y)
|
| 758 |
+
assert transpose(x - y) == transpose(x) - transpose(y)
|
| 759 |
+
assert transpose(x * y) == transpose(x) * transpose(y)
|
| 760 |
+
assert transpose(x / y) == transpose(x) / transpose(y)
|
| 761 |
+
assert transpose(-x) == -transpose(x)
|
| 762 |
+
|
| 763 |
+
x, y = symbols('x y', commutative=False)
|
| 764 |
+
assert transpose(transpose(x)) == x
|
| 765 |
+
assert transpose(x + y) == transpose(x) + transpose(y)
|
| 766 |
+
assert transpose(x - y) == transpose(x) - transpose(y)
|
| 767 |
+
assert transpose(x * y) == transpose(y) * transpose(x)
|
| 768 |
+
assert transpose(x / y) == 1 / transpose(y) * transpose(x)
|
| 769 |
+
assert transpose(-x) == -transpose(x)
|
| 770 |
+
|
| 771 |
+
|
| 772 |
+
@_both_exp_pow
|
| 773 |
+
def test_polarify():
|
| 774 |
+
from sympy.functions.elementary.complexes import (polar_lift, polarify)
|
| 775 |
+
x = Symbol('x')
|
| 776 |
+
z = Symbol('z', polar=True)
|
| 777 |
+
f = Function('f')
|
| 778 |
+
ES = {}
|
| 779 |
+
|
| 780 |
+
assert polarify(-1) == (polar_lift(-1), ES)
|
| 781 |
+
assert polarify(1 + I) == (polar_lift(1 + I), ES)
|
| 782 |
+
|
| 783 |
+
assert polarify(exp(x), subs=False) == exp(x)
|
| 784 |
+
assert polarify(1 + x, subs=False) == 1 + x
|
| 785 |
+
assert polarify(f(I) + x, subs=False) == f(polar_lift(I)) + x
|
| 786 |
+
|
| 787 |
+
assert polarify(x, lift=True) == polar_lift(x)
|
| 788 |
+
assert polarify(z, lift=True) == z
|
| 789 |
+
assert polarify(f(x), lift=True) == f(polar_lift(x))
|
| 790 |
+
assert polarify(1 + x, lift=True) == polar_lift(1 + x)
|
| 791 |
+
assert polarify(1 + f(x), lift=True) == polar_lift(1 + f(polar_lift(x)))
|
| 792 |
+
|
| 793 |
+
newex, subs = polarify(f(x) + z)
|
| 794 |
+
assert newex.subs(subs) == f(x) + z
|
| 795 |
+
|
| 796 |
+
mu = Symbol("mu")
|
| 797 |
+
sigma = Symbol("sigma", positive=True)
|
| 798 |
+
|
| 799 |
+
# Make sure polarify(lift=True) doesn't try to lift the integration
|
| 800 |
+
# variable
|
| 801 |
+
assert polarify(
|
| 802 |
+
Integral(sqrt(2)*x*exp(-(-mu + x)**2/(2*sigma**2))/(2*sqrt(pi)*sigma),
|
| 803 |
+
(x, -oo, oo)), lift=True) == Integral(sqrt(2)*(sigma*exp_polar(0))**exp_polar(I*pi)*
|
| 804 |
+
exp((sigma*exp_polar(0))**(2*exp_polar(I*pi))*exp_polar(I*pi)*polar_lift(-mu + x)**
|
| 805 |
+
(2*exp_polar(0))/2)*exp_polar(0)*polar_lift(x)/(2*sqrt(pi)), (x, -oo, oo))
|
| 806 |
+
|
| 807 |
+
|
| 808 |
+
def test_unpolarify():
|
| 809 |
+
from sympy.functions.elementary.complexes import (polar_lift, principal_branch, unpolarify)
|
| 810 |
+
from sympy.core.relational import Ne
|
| 811 |
+
from sympy.functions.elementary.hyperbolic import tanh
|
| 812 |
+
from sympy.functions.special.error_functions import erf
|
| 813 |
+
from sympy.functions.special.gamma_functions import (gamma, uppergamma)
|
| 814 |
+
from sympy.abc import x
|
| 815 |
+
p = exp_polar(7*I) + 1
|
| 816 |
+
u = exp(7*I) + 1
|
| 817 |
+
|
| 818 |
+
assert unpolarify(1) == 1
|
| 819 |
+
assert unpolarify(p) == u
|
| 820 |
+
assert unpolarify(p**2) == u**2
|
| 821 |
+
assert unpolarify(p**x) == p**x
|
| 822 |
+
assert unpolarify(p*x) == u*x
|
| 823 |
+
assert unpolarify(p + x) == u + x
|
| 824 |
+
assert unpolarify(sqrt(sin(p))) == sqrt(sin(u))
|
| 825 |
+
|
| 826 |
+
# Test reduction to principal branch 2*pi.
|
| 827 |
+
t = principal_branch(x, 2*pi)
|
| 828 |
+
assert unpolarify(t) == x
|
| 829 |
+
assert unpolarify(sqrt(t)) == sqrt(t)
|
| 830 |
+
|
| 831 |
+
# Test exponents_only.
|
| 832 |
+
assert unpolarify(p**p, exponents_only=True) == p**u
|
| 833 |
+
assert unpolarify(uppergamma(x, p**p)) == uppergamma(x, p**u)
|
| 834 |
+
|
| 835 |
+
# Test functions.
|
| 836 |
+
assert unpolarify(sin(p)) == sin(u)
|
| 837 |
+
assert unpolarify(tanh(p)) == tanh(u)
|
| 838 |
+
assert unpolarify(gamma(p)) == gamma(u)
|
| 839 |
+
assert unpolarify(erf(p)) == erf(u)
|
| 840 |
+
assert unpolarify(uppergamma(x, p)) == uppergamma(x, p)
|
| 841 |
+
|
| 842 |
+
assert unpolarify(uppergamma(sin(p), sin(p + exp_polar(0)))) == \
|
| 843 |
+
uppergamma(sin(u), sin(u + 1))
|
| 844 |
+
assert unpolarify(uppergamma(polar_lift(0), 2*exp_polar(0))) == \
|
| 845 |
+
uppergamma(0, 2)
|
| 846 |
+
|
| 847 |
+
assert unpolarify(Eq(p, 0)) == Eq(u, 0)
|
| 848 |
+
assert unpolarify(Ne(p, 0)) == Ne(u, 0)
|
| 849 |
+
assert unpolarify(polar_lift(x) > 0) == (x > 0)
|
| 850 |
+
|
| 851 |
+
# Test bools
|
| 852 |
+
assert unpolarify(True) is True
|
| 853 |
+
|
| 854 |
+
|
| 855 |
+
def test_issue_4035():
|
| 856 |
+
x = Symbol('x')
|
| 857 |
+
assert Abs(x).expand(trig=True) == Abs(x)
|
| 858 |
+
assert sign(x).expand(trig=True) == sign(x)
|
| 859 |
+
assert arg(x).expand(trig=True) == arg(x)
|
| 860 |
+
|
| 861 |
+
|
| 862 |
+
def test_issue_3206():
|
| 863 |
+
x = Symbol('x')
|
| 864 |
+
assert Abs(Abs(x)) == Abs(x)
|
| 865 |
+
|
| 866 |
+
|
| 867 |
+
def test_issue_4754_derivative_conjugate():
|
| 868 |
+
x = Symbol('x', real=True)
|
| 869 |
+
y = Symbol('y', imaginary=True)
|
| 870 |
+
f = Function('f')
|
| 871 |
+
assert (f(x).conjugate()).diff(x) == (f(x).diff(x)).conjugate()
|
| 872 |
+
assert (f(y).conjugate()).diff(y) == -(f(y).diff(y)).conjugate()
|
| 873 |
+
|
| 874 |
+
|
| 875 |
+
def test_derivatives_issue_4757():
|
| 876 |
+
x = Symbol('x', real=True)
|
| 877 |
+
y = Symbol('y', imaginary=True)
|
| 878 |
+
f = Function('f')
|
| 879 |
+
assert re(f(x)).diff(x) == re(f(x).diff(x))
|
| 880 |
+
assert im(f(x)).diff(x) == im(f(x).diff(x))
|
| 881 |
+
assert re(f(y)).diff(y) == -I*im(f(y).diff(y))
|
| 882 |
+
assert im(f(y)).diff(y) == -I*re(f(y).diff(y))
|
| 883 |
+
assert Abs(f(x)).diff(x).subs(f(x), 1 + I*x).doit() == x/sqrt(1 + x**2)
|
| 884 |
+
assert arg(f(x)).diff(x).subs(f(x), 1 + I*x**2).doit() == 2*x/(1 + x**4)
|
| 885 |
+
assert Abs(f(y)).diff(y).subs(f(y), 1 + y).doit() == -y/sqrt(1 - y**2)
|
| 886 |
+
assert arg(f(y)).diff(y).subs(f(y), I + y**2).doit() == 2*y/(1 + y**4)
|
| 887 |
+
|
| 888 |
+
|
| 889 |
+
def test_issue_11413():
|
| 890 |
+
from sympy.simplify.simplify import simplify
|
| 891 |
+
v0 = Symbol('v0')
|
| 892 |
+
v1 = Symbol('v1')
|
| 893 |
+
v2 = Symbol('v2')
|
| 894 |
+
V = Matrix([[v0],[v1],[v2]])
|
| 895 |
+
U = V.normalized()
|
| 896 |
+
assert U == Matrix([
|
| 897 |
+
[v0/sqrt(Abs(v0)**2 + Abs(v1)**2 + Abs(v2)**2)],
|
| 898 |
+
[v1/sqrt(Abs(v0)**2 + Abs(v1)**2 + Abs(v2)**2)],
|
| 899 |
+
[v2/sqrt(Abs(v0)**2 + Abs(v1)**2 + Abs(v2)**2)]])
|
| 900 |
+
U.norm = sqrt(v0**2/(v0**2 + v1**2 + v2**2) + v1**2/(v0**2 + v1**2 + v2**2) + v2**2/(v0**2 + v1**2 + v2**2))
|
| 901 |
+
assert simplify(U.norm) == 1
|
| 902 |
+
|
| 903 |
+
|
| 904 |
+
def test_periodic_argument():
|
| 905 |
+
from sympy.functions.elementary.complexes import (periodic_argument, polar_lift, principal_branch, unbranched_argument)
|
| 906 |
+
x = Symbol('x')
|
| 907 |
+
p = Symbol('p', positive=True)
|
| 908 |
+
|
| 909 |
+
assert unbranched_argument(2 + I) == periodic_argument(2 + I, oo)
|
| 910 |
+
assert unbranched_argument(1 + x) == periodic_argument(1 + x, oo)
|
| 911 |
+
assert N_equals(unbranched_argument((1 + I)**2), pi/2)
|
| 912 |
+
assert N_equals(unbranched_argument((1 - I)**2), -pi/2)
|
| 913 |
+
assert N_equals(periodic_argument((1 + I)**2, 3*pi), pi/2)
|
| 914 |
+
assert N_equals(periodic_argument((1 - I)**2, 3*pi), -pi/2)
|
| 915 |
+
|
| 916 |
+
assert unbranched_argument(principal_branch(x, pi)) == \
|
| 917 |
+
periodic_argument(x, pi)
|
| 918 |
+
|
| 919 |
+
assert unbranched_argument(polar_lift(2 + I)) == unbranched_argument(2 + I)
|
| 920 |
+
assert periodic_argument(polar_lift(2 + I), 2*pi) == \
|
| 921 |
+
periodic_argument(2 + I, 2*pi)
|
| 922 |
+
assert periodic_argument(polar_lift(2 + I), 3*pi) == \
|
| 923 |
+
periodic_argument(2 + I, 3*pi)
|
| 924 |
+
assert periodic_argument(polar_lift(2 + I), pi) == \
|
| 925 |
+
periodic_argument(polar_lift(2 + I), pi)
|
| 926 |
+
|
| 927 |
+
assert unbranched_argument(polar_lift(1 + I)) == pi/4
|
| 928 |
+
assert periodic_argument(2*p, p) == periodic_argument(p, p)
|
| 929 |
+
assert periodic_argument(pi*p, p) == periodic_argument(p, p)
|
| 930 |
+
|
| 931 |
+
assert Abs(polar_lift(1 + I)) == Abs(1 + I)
|
| 932 |
+
|
| 933 |
+
|
| 934 |
+
@XFAIL
|
| 935 |
+
def test_principal_branch_fail():
|
| 936 |
+
# TODO XXX why does abs(x)._eval_evalf() not fall back to global evalf?
|
| 937 |
+
from sympy.functions.elementary.complexes import principal_branch
|
| 938 |
+
assert N_equals(principal_branch((1 + I)**2, pi/2), 0)
|
| 939 |
+
|
| 940 |
+
|
| 941 |
+
def test_principal_branch():
|
| 942 |
+
from sympy.functions.elementary.complexes import (polar_lift, principal_branch)
|
| 943 |
+
p = Symbol('p', positive=True)
|
| 944 |
+
x = Symbol('x')
|
| 945 |
+
neg = Symbol('x', negative=True)
|
| 946 |
+
|
| 947 |
+
assert principal_branch(polar_lift(x), p) == principal_branch(x, p)
|
| 948 |
+
assert principal_branch(polar_lift(2 + I), p) == principal_branch(2 + I, p)
|
| 949 |
+
assert principal_branch(2*x, p) == 2*principal_branch(x, p)
|
| 950 |
+
assert principal_branch(1, pi) == exp_polar(0)
|
| 951 |
+
assert principal_branch(-1, 2*pi) == exp_polar(I*pi)
|
| 952 |
+
assert principal_branch(-1, pi) == exp_polar(0)
|
| 953 |
+
assert principal_branch(exp_polar(3*pi*I)*x, 2*pi) == \
|
| 954 |
+
principal_branch(exp_polar(I*pi)*x, 2*pi)
|
| 955 |
+
assert principal_branch(neg*exp_polar(pi*I), 2*pi) == neg*exp_polar(-I*pi)
|
| 956 |
+
# related to issue #14692
|
| 957 |
+
assert principal_branch(exp_polar(-I*pi/2)/polar_lift(neg), 2*pi) == \
|
| 958 |
+
exp_polar(-I*pi/2)/neg
|
| 959 |
+
|
| 960 |
+
assert N_equals(principal_branch((1 + I)**2, 2*pi), 2*I)
|
| 961 |
+
assert N_equals(principal_branch((1 + I)**2, 3*pi), 2*I)
|
| 962 |
+
assert N_equals(principal_branch((1 + I)**2, 1*pi), 2*I)
|
| 963 |
+
|
| 964 |
+
# test argument sanitization
|
| 965 |
+
assert principal_branch(x, I).func is principal_branch
|
| 966 |
+
assert principal_branch(x, -4).func is principal_branch
|
| 967 |
+
assert principal_branch(x, -oo).func is principal_branch
|
| 968 |
+
assert principal_branch(x, zoo).func is principal_branch
|
| 969 |
+
|
| 970 |
+
|
| 971 |
+
@XFAIL
|
| 972 |
+
def test_issue_6167_6151():
|
| 973 |
+
n = pi**1000
|
| 974 |
+
i = int(n)
|
| 975 |
+
assert sign(n - i) == 1
|
| 976 |
+
assert abs(n - i) == n - i
|
| 977 |
+
x = Symbol('x')
|
| 978 |
+
eps = pi**-1500
|
| 979 |
+
big = pi**1000
|
| 980 |
+
one = cos(x)**2 + sin(x)**2
|
| 981 |
+
e = big*one - big + eps
|
| 982 |
+
from sympy.simplify.simplify import simplify
|
| 983 |
+
assert sign(simplify(e)) == 1
|
| 984 |
+
for xi in (111, 11, 1, Rational(1, 10)):
|
| 985 |
+
assert sign(e.subs(x, xi)) == 1
|
| 986 |
+
|
| 987 |
+
|
| 988 |
+
def test_issue_14216():
|
| 989 |
+
from sympy.functions.elementary.complexes import unpolarify
|
| 990 |
+
A = MatrixSymbol("A", 2, 2)
|
| 991 |
+
assert unpolarify(A[0, 0]) == A[0, 0]
|
| 992 |
+
assert unpolarify(A[0, 0]*A[1, 0]) == A[0, 0]*A[1, 0]
|
| 993 |
+
|
| 994 |
+
|
| 995 |
+
def test_issue_14238():
|
| 996 |
+
# doesn't cause recursion error
|
| 997 |
+
r = Symbol('r', real=True)
|
| 998 |
+
assert Abs(r + Piecewise((0, r > 0), (1 - r, True)))
|
| 999 |
+
|
| 1000 |
+
|
| 1001 |
+
def test_issue_22189():
|
| 1002 |
+
x = Symbol('x')
|
| 1003 |
+
for a in (sqrt(7 - 2*x) - 2, 1 - x):
|
| 1004 |
+
assert Abs(a) - Abs(-a) == 0, a
|
| 1005 |
+
|
| 1006 |
+
|
| 1007 |
+
def test_zero_assumptions():
|
| 1008 |
+
nr = Symbol('nonreal', real=False, finite=True)
|
| 1009 |
+
ni = Symbol('nonimaginary', imaginary=False)
|
| 1010 |
+
# imaginary implies not zero
|
| 1011 |
+
nzni = Symbol('nonzerononimaginary', zero=False, imaginary=False)
|
| 1012 |
+
|
| 1013 |
+
assert re(nr).is_zero is None
|
| 1014 |
+
assert im(nr).is_zero is False
|
| 1015 |
+
|
| 1016 |
+
assert re(ni).is_zero is None
|
| 1017 |
+
assert im(ni).is_zero is None
|
| 1018 |
+
|
| 1019 |
+
assert re(nzni).is_zero is False
|
| 1020 |
+
assert im(nzni).is_zero is None
|
| 1021 |
+
|
| 1022 |
+
|
| 1023 |
+
@_both_exp_pow
|
| 1024 |
+
def test_issue_15893():
|
| 1025 |
+
f = Function('f', real=True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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.assumptions.refine import refine
|
| 2 |
+
from sympy.calculus.accumulationbounds import AccumBounds
|
| 3 |
+
from sympy.concrete.products import Product
|
| 4 |
+
from sympy.concrete.summations import Sum
|
| 5 |
+
from sympy.core.function import expand_log
|
| 6 |
+
from sympy.core.numbers import (E, Float, I, Rational, nan, oo, pi, zoo)
|
| 7 |
+
from sympy.core.power import Pow
|
| 8 |
+
from sympy.core.singleton import S
|
| 9 |
+
from sympy.core.symbol import (Symbol, symbols)
|
| 10 |
+
from sympy.functions.elementary.complexes import (adjoint, conjugate, re, sign, transpose)
|
| 11 |
+
from sympy.functions.elementary.exponential import (LambertW, exp, exp_polar, log)
|
| 12 |
+
from sympy.functions.elementary.hyperbolic import (cosh, sinh, tanh)
|
| 13 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
| 14 |
+
from sympy.functions.elementary.trigonometric import (cos, sin, tan)
|
| 15 |
+
from sympy.matrices.expressions.matexpr import MatrixSymbol
|
| 16 |
+
from sympy.polys.polytools import gcd
|
| 17 |
+
from sympy.series.order import O
|
| 18 |
+
from sympy.simplify.simplify import simplify
|
| 19 |
+
from sympy.core.parameters import global_parameters
|
| 20 |
+
from sympy.functions.elementary.exponential import match_real_imag
|
| 21 |
+
from sympy.abc import x, y, z
|
| 22 |
+
from sympy.core.expr import unchanged
|
| 23 |
+
from sympy.core.function import ArgumentIndexError
|
| 24 |
+
from sympy.testing.pytest import raises, XFAIL, _both_exp_pow
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
@_both_exp_pow
|
| 28 |
+
def test_exp_values():
|
| 29 |
+
if global_parameters.exp_is_pow:
|
| 30 |
+
assert type(exp(x)) is Pow
|
| 31 |
+
else:
|
| 32 |
+
assert type(exp(x)) is exp
|
| 33 |
+
|
| 34 |
+
k = Symbol('k', integer=True)
|
| 35 |
+
|
| 36 |
+
assert exp(nan) is nan
|
| 37 |
+
|
| 38 |
+
assert exp(oo) is oo
|
| 39 |
+
assert exp(-oo) == 0
|
| 40 |
+
|
| 41 |
+
assert exp(0) == 1
|
| 42 |
+
assert exp(1) == E
|
| 43 |
+
assert exp(-1 + x).as_base_exp() == (S.Exp1, x - 1)
|
| 44 |
+
assert exp(1 + x).as_base_exp() == (S.Exp1, x + 1)
|
| 45 |
+
|
| 46 |
+
assert exp(pi*I/2) == I
|
| 47 |
+
assert exp(pi*I) == -1
|
| 48 |
+
assert exp(pi*I*Rational(3, 2)) == -I
|
| 49 |
+
assert exp(2*pi*I) == 1
|
| 50 |
+
|
| 51 |
+
assert refine(exp(pi*I*2*k)) == 1
|
| 52 |
+
assert refine(exp(pi*I*2*(k + S.Half))) == -1
|
| 53 |
+
assert refine(exp(pi*I*2*(k + Rational(1, 4)))) == I
|
| 54 |
+
assert refine(exp(pi*I*2*(k + Rational(3, 4)))) == -I
|
| 55 |
+
|
| 56 |
+
assert exp(log(x)) == x
|
| 57 |
+
assert exp(2*log(x)) == x**2
|
| 58 |
+
assert exp(pi*log(x)) == x**pi
|
| 59 |
+
|
| 60 |
+
assert exp(17*log(x) + E*log(y)) == x**17 * y**E
|
| 61 |
+
|
| 62 |
+
assert exp(x*log(x)) != x**x
|
| 63 |
+
assert exp(sin(x)*log(x)) != x
|
| 64 |
+
|
| 65 |
+
assert exp(3*log(x) + oo*x) == exp(oo*x) * x**3
|
| 66 |
+
assert exp(4*log(x)*log(y) + 3*log(x)) == x**3 * exp(4*log(x)*log(y))
|
| 67 |
+
|
| 68 |
+
assert exp(-oo, evaluate=False).is_finite is True
|
| 69 |
+
assert exp(oo, evaluate=False).is_finite is False
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
@_both_exp_pow
|
| 73 |
+
def test_exp_period():
|
| 74 |
+
assert exp(I*pi*Rational(9, 4)) == exp(I*pi/4)
|
| 75 |
+
assert exp(I*pi*Rational(46, 18)) == exp(I*pi*Rational(5, 9))
|
| 76 |
+
assert exp(I*pi*Rational(25, 7)) == exp(I*pi*Rational(-3, 7))
|
| 77 |
+
assert exp(I*pi*Rational(-19, 3)) == exp(-I*pi/3)
|
| 78 |
+
assert exp(I*pi*Rational(37, 8)) - exp(I*pi*Rational(-11, 8)) == 0
|
| 79 |
+
assert exp(I*pi*Rational(-5, 3)) / exp(I*pi*Rational(11, 5)) * exp(I*pi*Rational(148, 15)) == 1
|
| 80 |
+
|
| 81 |
+
assert exp(2 - I*pi*Rational(17, 5)) == exp(2 + I*pi*Rational(3, 5))
|
| 82 |
+
assert exp(log(3) + I*pi*Rational(29, 9)) == 3 * exp(I*pi*Rational(-7, 9))
|
| 83 |
+
|
| 84 |
+
n = Symbol('n', integer=True)
|
| 85 |
+
e = Symbol('e', even=True)
|
| 86 |
+
assert exp(e*I*pi) == 1
|
| 87 |
+
assert exp((e + 1)*I*pi) == -1
|
| 88 |
+
assert exp((1 + 4*n)*I*pi/2) == I
|
| 89 |
+
assert exp((-1 + 4*n)*I*pi/2) == -I
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
@_both_exp_pow
|
| 93 |
+
def test_exp_log():
|
| 94 |
+
x = Symbol("x", real=True)
|
| 95 |
+
assert log(exp(x)) == x
|
| 96 |
+
assert exp(log(x)) == x
|
| 97 |
+
|
| 98 |
+
if not global_parameters.exp_is_pow:
|
| 99 |
+
assert log(x).inverse() == exp
|
| 100 |
+
assert exp(x).inverse() == log
|
| 101 |
+
|
| 102 |
+
y = Symbol("y", polar=True)
|
| 103 |
+
assert log(exp_polar(z)) == z
|
| 104 |
+
assert exp(log(y)) == y
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
@_both_exp_pow
|
| 108 |
+
def test_exp_expand():
|
| 109 |
+
e = exp(log(Rational(2))*(1 + x) - log(Rational(2))*x)
|
| 110 |
+
assert e.expand() == 2
|
| 111 |
+
assert exp(x + y) != exp(x)*exp(y)
|
| 112 |
+
assert exp(x + y).expand() == exp(x)*exp(y)
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
@_both_exp_pow
|
| 116 |
+
def test_exp__as_base_exp():
|
| 117 |
+
assert exp(x).as_base_exp() == (E, x)
|
| 118 |
+
assert exp(2*x).as_base_exp() == (E, 2*x)
|
| 119 |
+
assert exp(x*y).as_base_exp() == (E, x*y)
|
| 120 |
+
assert exp(-x).as_base_exp() == (E, -x)
|
| 121 |
+
|
| 122 |
+
# Pow( *expr.as_base_exp() ) == expr invariant should hold
|
| 123 |
+
assert E**x == exp(x)
|
| 124 |
+
assert E**(2*x) == exp(2*x)
|
| 125 |
+
assert E**(x*y) == exp(x*y)
|
| 126 |
+
|
| 127 |
+
assert exp(x).base is S.Exp1
|
| 128 |
+
assert exp(x).exp == x
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
@_both_exp_pow
|
| 132 |
+
def test_exp_infinity():
|
| 133 |
+
assert exp(I*y) != nan
|
| 134 |
+
assert refine(exp(I*oo)) is nan
|
| 135 |
+
assert refine(exp(-I*oo)) is nan
|
| 136 |
+
assert exp(y*I*oo) != nan
|
| 137 |
+
assert exp(zoo) is nan
|
| 138 |
+
x = Symbol('x', extended_real=True, finite=False)
|
| 139 |
+
assert exp(x).is_complex is None
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
@_both_exp_pow
|
| 143 |
+
def test_exp_subs():
|
| 144 |
+
x = Symbol('x')
|
| 145 |
+
e = (exp(3*log(x), evaluate=False)) # evaluates to x**3
|
| 146 |
+
assert e.subs(x**3, y**3) == e
|
| 147 |
+
assert e.subs(x**2, 5) == e
|
| 148 |
+
assert (x**3).subs(x**2, y) != y**Rational(3, 2)
|
| 149 |
+
assert exp(exp(x) + exp(x**2)).subs(exp(exp(x)), y) == y * exp(exp(x**2))
|
| 150 |
+
assert exp(x).subs(E, y) == y**x
|
| 151 |
+
x = symbols('x', real=True)
|
| 152 |
+
assert exp(5*x).subs(exp(7*x), y) == y**Rational(5, 7)
|
| 153 |
+
assert exp(2*x + 7).subs(exp(3*x), y) == y**Rational(2, 3) * exp(7)
|
| 154 |
+
x = symbols('x', positive=True)
|
| 155 |
+
assert exp(3*log(x)).subs(x**2, y) == y**Rational(3, 2)
|
| 156 |
+
# differentiate between E and exp
|
| 157 |
+
assert exp(exp(x + E)).subs(exp, 3) == 3**(3**(x + E))
|
| 158 |
+
assert exp(exp(x + E)).subs(exp, sin) == sin(sin(x + E))
|
| 159 |
+
assert exp(exp(x + E)).subs(E, 3) == 3**(3**(x + 3))
|
| 160 |
+
assert exp(3).subs(E, sin) == sin(3)
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def test_exp_adjoint():
|
| 164 |
+
assert adjoint(exp(x)) == exp(adjoint(x))
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
def test_exp_conjugate():
|
| 168 |
+
assert conjugate(exp(x)) == exp(conjugate(x))
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
@_both_exp_pow
|
| 172 |
+
def test_exp_transpose():
|
| 173 |
+
assert transpose(exp(x)) == exp(transpose(x))
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
@_both_exp_pow
|
| 177 |
+
def test_exp_rewrite():
|
| 178 |
+
assert exp(x).rewrite(sin) == sinh(x) + cosh(x)
|
| 179 |
+
assert exp(x*I).rewrite(cos) == cos(x) + I*sin(x)
|
| 180 |
+
assert exp(1).rewrite(cos) == sinh(1) + cosh(1)
|
| 181 |
+
assert exp(1).rewrite(sin) == sinh(1) + cosh(1)
|
| 182 |
+
assert exp(1).rewrite(sin) == sinh(1) + cosh(1)
|
| 183 |
+
assert exp(x).rewrite(tanh) == (1 + tanh(x/2))/(1 - tanh(x/2))
|
| 184 |
+
assert exp(pi*I/4).rewrite(sqrt) == sqrt(2)/2 + sqrt(2)*I/2
|
| 185 |
+
assert exp(pi*I/3).rewrite(sqrt) == S.Half + sqrt(3)*I/2
|
| 186 |
+
if not global_parameters.exp_is_pow:
|
| 187 |
+
assert exp(x*log(y)).rewrite(Pow) == y**x
|
| 188 |
+
assert exp(log(x)*log(y)).rewrite(Pow) in [x**log(y), y**log(x)]
|
| 189 |
+
assert exp(log(log(x))*y).rewrite(Pow) == log(x)**y
|
| 190 |
+
|
| 191 |
+
n = Symbol('n', integer=True)
|
| 192 |
+
|
| 193 |
+
assert Sum((exp(pi*I/2)/2)**n, (n, 0, oo)).rewrite(sqrt).doit() == Rational(4, 5) + I*2/5
|
| 194 |
+
assert Sum((exp(pi*I/4)/2)**n, (n, 0, oo)).rewrite(sqrt).doit() == 1/(1 - sqrt(2)*(1 + I)/4)
|
| 195 |
+
assert (Sum((exp(pi*I/3)/2)**n, (n, 0, oo)).rewrite(sqrt).doit().cancel()
|
| 196 |
+
== 4*I/(sqrt(3) + 3*I))
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
@_both_exp_pow
|
| 200 |
+
def test_exp_leading_term():
|
| 201 |
+
assert exp(x).as_leading_term(x) == 1
|
| 202 |
+
assert exp(2 + x).as_leading_term(x) == exp(2)
|
| 203 |
+
assert exp((2*x + 3) / (x+1)).as_leading_term(x) == exp(3)
|
| 204 |
+
|
| 205 |
+
# The following tests are commented, since now SymPy returns the
|
| 206 |
+
# original function when the leading term in the series expansion does
|
| 207 |
+
# not exist.
|
| 208 |
+
# raises(NotImplementedError, lambda: exp(1/x).as_leading_term(x))
|
| 209 |
+
# raises(NotImplementedError, lambda: exp((x + 1) / x**2).as_leading_term(x))
|
| 210 |
+
# raises(NotImplementedError, lambda: exp(x + 1/x).as_leading_term(x))
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
@_both_exp_pow
|
| 214 |
+
def test_exp_taylor_term():
|
| 215 |
+
x = symbols('x')
|
| 216 |
+
assert exp(x).taylor_term(1, x) == x
|
| 217 |
+
assert exp(x).taylor_term(3, x) == x**3/6
|
| 218 |
+
assert exp(x).taylor_term(4, x) == x**4/24
|
| 219 |
+
assert exp(x).taylor_term(-1, x) is S.Zero
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
def test_exp_MatrixSymbol():
|
| 223 |
+
A = MatrixSymbol("A", 2, 2)
|
| 224 |
+
assert exp(A).has(exp)
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
def test_exp_fdiff():
|
| 228 |
+
x = Symbol('x')
|
| 229 |
+
raises(ArgumentIndexError, lambda: exp(x).fdiff(2))
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
def test_log_values():
|
| 233 |
+
assert log(nan) is nan
|
| 234 |
+
|
| 235 |
+
assert log(oo) is oo
|
| 236 |
+
assert log(-oo) is oo
|
| 237 |
+
|
| 238 |
+
assert log(zoo) is zoo
|
| 239 |
+
assert log(-zoo) is zoo
|
| 240 |
+
|
| 241 |
+
assert log(0) is zoo
|
| 242 |
+
|
| 243 |
+
assert log(1) == 0
|
| 244 |
+
assert log(-1) == I*pi
|
| 245 |
+
|
| 246 |
+
assert log(E) == 1
|
| 247 |
+
assert log(-E).expand() == 1 + I*pi
|
| 248 |
+
|
| 249 |
+
assert unchanged(log, pi)
|
| 250 |
+
assert log(-pi).expand() == log(pi) + I*pi
|
| 251 |
+
|
| 252 |
+
assert unchanged(log, 17)
|
| 253 |
+
assert log(-17) == log(17) + I*pi
|
| 254 |
+
|
| 255 |
+
assert log(I) == I*pi/2
|
| 256 |
+
assert log(-I) == -I*pi/2
|
| 257 |
+
|
| 258 |
+
assert log(17*I) == I*pi/2 + log(17)
|
| 259 |
+
assert log(-17*I).expand() == -I*pi/2 + log(17)
|
| 260 |
+
|
| 261 |
+
assert log(oo*I) is oo
|
| 262 |
+
assert log(-oo*I) is oo
|
| 263 |
+
assert log(0, 2) is zoo
|
| 264 |
+
assert log(0, 5) is zoo
|
| 265 |
+
|
| 266 |
+
assert exp(-log(3))**(-1) == 3
|
| 267 |
+
|
| 268 |
+
assert log(S.Half) == -log(2)
|
| 269 |
+
assert log(2*3).func is log
|
| 270 |
+
assert log(2*3**2).func is log
|
| 271 |
+
|
| 272 |
+
|
| 273 |
+
def test_match_real_imag():
|
| 274 |
+
x, y = symbols('x,y', real=True)
|
| 275 |
+
i = Symbol('i', imaginary=True)
|
| 276 |
+
assert match_real_imag(S.One) == (1, 0)
|
| 277 |
+
assert match_real_imag(I) == (0, 1)
|
| 278 |
+
assert match_real_imag(3 - 5*I) == (3, -5)
|
| 279 |
+
assert match_real_imag(-sqrt(3) + S.Half*I) == (-sqrt(3), S.Half)
|
| 280 |
+
assert match_real_imag(x + y*I) == (x, y)
|
| 281 |
+
assert match_real_imag(x*I + y*I) == (0, x + y)
|
| 282 |
+
assert match_real_imag((x + y)*I) == (0, x + y)
|
| 283 |
+
assert match_real_imag(Rational(-2, 3)*i*I) == (None, None)
|
| 284 |
+
assert match_real_imag(1 - 2*i) == (None, None)
|
| 285 |
+
assert match_real_imag(sqrt(2)*(3 - 5*I)) == (None, None)
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
def test_log_exact():
|
| 289 |
+
# check for pi/2, pi/3, pi/4, pi/6, pi/8, pi/12; pi/5, pi/10:
|
| 290 |
+
for n in range(-23, 24):
|
| 291 |
+
if gcd(n, 24) != 1:
|
| 292 |
+
assert log(exp(n*I*pi/24).rewrite(sqrt)) == n*I*pi/24
|
| 293 |
+
for n in range(-9, 10):
|
| 294 |
+
assert log(exp(n*I*pi/10).rewrite(sqrt)) == n*I*pi/10
|
| 295 |
+
|
| 296 |
+
assert log(S.Half - I*sqrt(3)/2) == -I*pi/3
|
| 297 |
+
assert log(Rational(-1, 2) + I*sqrt(3)/2) == I*pi*Rational(2, 3)
|
| 298 |
+
assert log(-sqrt(2)/2 - I*sqrt(2)/2) == -I*pi*Rational(3, 4)
|
| 299 |
+
assert log(-sqrt(3)/2 - I*S.Half) == -I*pi*Rational(5, 6)
|
| 300 |
+
|
| 301 |
+
assert log(Rational(-1, 4) + sqrt(5)/4 - I*sqrt(sqrt(5)/8 + Rational(5, 8))) == -I*pi*Rational(2, 5)
|
| 302 |
+
assert log(sqrt(Rational(5, 8) - sqrt(5)/8) + I*(Rational(1, 4) + sqrt(5)/4)) == I*pi*Rational(3, 10)
|
| 303 |
+
assert log(-sqrt(sqrt(2)/4 + S.Half) + I*sqrt(S.Half - sqrt(2)/4)) == I*pi*Rational(7, 8)
|
| 304 |
+
assert log(-sqrt(6)/4 - sqrt(2)/4 + I*(-sqrt(6)/4 + sqrt(2)/4)) == -I*pi*Rational(11, 12)
|
| 305 |
+
|
| 306 |
+
assert log(-1 + I*sqrt(3)) == log(2) + I*pi*Rational(2, 3)
|
| 307 |
+
assert log(5 + 5*I) == log(5*sqrt(2)) + I*pi/4
|
| 308 |
+
assert log(sqrt(-12)) == log(2*sqrt(3)) + I*pi/2
|
| 309 |
+
assert log(-sqrt(6) + sqrt(2) - I*sqrt(6) - I*sqrt(2)) == log(4) - I*pi*Rational(7, 12)
|
| 310 |
+
assert log(-sqrt(6-3*sqrt(2)) - I*sqrt(6+3*sqrt(2))) == log(2*sqrt(3)) - I*pi*Rational(5, 8)
|
| 311 |
+
assert log(1 + I*sqrt(2-sqrt(2))/sqrt(2+sqrt(2))) == log(2/sqrt(sqrt(2) + 2)) + I*pi/8
|
| 312 |
+
assert log(cos(pi*Rational(7, 12)) + I*sin(pi*Rational(7, 12))) == I*pi*Rational(7, 12)
|
| 313 |
+
assert log(cos(pi*Rational(6, 5)) + I*sin(pi*Rational(6, 5))) == I*pi*Rational(-4, 5)
|
| 314 |
+
|
| 315 |
+
assert log(5*(1 + I)/sqrt(2)) == log(5) + I*pi/4
|
| 316 |
+
assert log(sqrt(2)*(-sqrt(3) + 1 - sqrt(3)*I - I)) == log(4) - I*pi*Rational(7, 12)
|
| 317 |
+
assert log(-sqrt(2)*(1 - I*sqrt(3))) == log(2*sqrt(2)) + I*pi*Rational(2, 3)
|
| 318 |
+
assert log(sqrt(3)*I*(-sqrt(6 - 3*sqrt(2)) - I*sqrt(3*sqrt(2) + 6))) == log(6) - I*pi/8
|
| 319 |
+
|
| 320 |
+
zero = (1 + sqrt(2))**2 - 3 - 2*sqrt(2)
|
| 321 |
+
assert log(zero - I*sqrt(3)) == log(sqrt(3)) - I*pi/2
|
| 322 |
+
assert unchanged(log, zero + I*zero) or log(zero + zero*I) is zoo
|
| 323 |
+
|
| 324 |
+
# bail quickly if no obvious simplification is possible:
|
| 325 |
+
assert unchanged(log, (sqrt(2)-1/sqrt(sqrt(3)+I))**1000)
|
| 326 |
+
# beware of non-real coefficients
|
| 327 |
+
assert unchanged(log, sqrt(2-sqrt(5))*(1 + I))
|
| 328 |
+
|
| 329 |
+
|
| 330 |
+
def test_log_base():
|
| 331 |
+
assert log(1, 2) == 0
|
| 332 |
+
assert log(2, 2) == 1
|
| 333 |
+
assert log(3, 2) == log(3)/log(2)
|
| 334 |
+
assert log(6, 2) == 1 + log(3)/log(2)
|
| 335 |
+
assert log(6, 3) == 1 + log(2)/log(3)
|
| 336 |
+
assert log(2**3, 2) == 3
|
| 337 |
+
assert log(3**3, 3) == 3
|
| 338 |
+
assert log(5, 1) is zoo
|
| 339 |
+
assert log(1, 1) is nan
|
| 340 |
+
assert log(Rational(2, 3), 10) == log(Rational(2, 3))/log(10)
|
| 341 |
+
assert log(Rational(2, 3), Rational(1, 3)) == -log(2)/log(3) + 1
|
| 342 |
+
assert log(Rational(2, 3), Rational(2, 5)) == \
|
| 343 |
+
log(Rational(2, 3))/log(Rational(2, 5))
|
| 344 |
+
# issue 17148
|
| 345 |
+
assert log(Rational(8, 3), 2) == -log(3)/log(2) + 3
|
| 346 |
+
|
| 347 |
+
|
| 348 |
+
def test_log_symbolic():
|
| 349 |
+
assert log(x, exp(1)) == log(x)
|
| 350 |
+
assert log(exp(x)) != x
|
| 351 |
+
|
| 352 |
+
assert log(x, exp(1)) == log(x)
|
| 353 |
+
assert log(x*y) != log(x) + log(y)
|
| 354 |
+
assert log(x/y).expand() != log(x) - log(y)
|
| 355 |
+
assert log(x/y).expand(force=True) == log(x) - log(y)
|
| 356 |
+
assert log(x**y).expand() != y*log(x)
|
| 357 |
+
assert log(x**y).expand(force=True) == y*log(x)
|
| 358 |
+
|
| 359 |
+
assert log(x, 2) == log(x)/log(2)
|
| 360 |
+
assert log(E, 2) == 1/log(2)
|
| 361 |
+
|
| 362 |
+
p, q = symbols('p,q', positive=True)
|
| 363 |
+
r = Symbol('r', real=True)
|
| 364 |
+
|
| 365 |
+
assert log(p**2) != 2*log(p)
|
| 366 |
+
assert log(p**2).expand() == 2*log(p)
|
| 367 |
+
assert log(x**2).expand() != 2*log(x)
|
| 368 |
+
assert log(p**q) != q*log(p)
|
| 369 |
+
assert log(exp(p)) == p
|
| 370 |
+
assert log(p*q) != log(p) + log(q)
|
| 371 |
+
assert log(p*q).expand() == log(p) + log(q)
|
| 372 |
+
|
| 373 |
+
assert log(-sqrt(3)) == log(sqrt(3)) + I*pi
|
| 374 |
+
assert log(-exp(p)) != p + I*pi
|
| 375 |
+
assert log(-exp(x)).expand() != x + I*pi
|
| 376 |
+
assert log(-exp(r)).expand() == r + I*pi
|
| 377 |
+
|
| 378 |
+
assert log(x**y) != y*log(x)
|
| 379 |
+
|
| 380 |
+
assert (log(x**-5)**-1).expand() != -1/log(x)/5
|
| 381 |
+
assert (log(p**-5)**-1).expand() == -1/log(p)/5
|
| 382 |
+
assert log(-x).func is log and log(-x).args[0] == -x
|
| 383 |
+
assert log(-p).func is log and log(-p).args[0] == -p
|
| 384 |
+
|
| 385 |
+
|
| 386 |
+
def test_log_exp():
|
| 387 |
+
assert log(exp(4*I*pi)) == 0 # exp evaluates
|
| 388 |
+
assert log(exp(-5*I*pi)) == I*pi # exp evaluates
|
| 389 |
+
assert log(exp(I*pi*Rational(19, 4))) == I*pi*Rational(3, 4)
|
| 390 |
+
assert log(exp(I*pi*Rational(25, 7))) == I*pi*Rational(-3, 7)
|
| 391 |
+
assert log(exp(-5*I)) == -5*I + 2*I*pi
|
| 392 |
+
|
| 393 |
+
|
| 394 |
+
@_both_exp_pow
|
| 395 |
+
def test_exp_assumptions():
|
| 396 |
+
r = Symbol('r', real=True)
|
| 397 |
+
i = Symbol('i', imaginary=True)
|
| 398 |
+
for e in exp, exp_polar:
|
| 399 |
+
assert e(x).is_real is None
|
| 400 |
+
assert e(x).is_imaginary is None
|
| 401 |
+
assert e(i).is_real is None
|
| 402 |
+
assert e(i).is_imaginary is None
|
| 403 |
+
assert e(r).is_real is True
|
| 404 |
+
assert e(r).is_imaginary is False
|
| 405 |
+
assert e(re(x)).is_extended_real is True
|
| 406 |
+
assert e(re(x)).is_imaginary is False
|
| 407 |
+
|
| 408 |
+
assert Pow(E, I*pi, evaluate=False).is_imaginary == False
|
| 409 |
+
assert Pow(E, 2*I*pi, evaluate=False).is_imaginary == False
|
| 410 |
+
assert Pow(E, I*pi/2, evaluate=False).is_imaginary == True
|
| 411 |
+
assert Pow(E, I*pi/3, evaluate=False).is_imaginary is None
|
| 412 |
+
|
| 413 |
+
assert exp(0, evaluate=False).is_algebraic
|
| 414 |
+
|
| 415 |
+
a = Symbol('a', algebraic=True)
|
| 416 |
+
an = Symbol('an', algebraic=True, nonzero=True)
|
| 417 |
+
r = Symbol('r', rational=True)
|
| 418 |
+
rn = Symbol('rn', rational=True, nonzero=True)
|
| 419 |
+
assert exp(a).is_algebraic is None
|
| 420 |
+
assert exp(an).is_algebraic is False
|
| 421 |
+
assert exp(pi*r).is_algebraic is None
|
| 422 |
+
assert exp(pi*rn).is_algebraic is False
|
| 423 |
+
|
| 424 |
+
assert exp(0, evaluate=False).is_algebraic is True
|
| 425 |
+
assert exp(I*pi/3, evaluate=False).is_algebraic is True
|
| 426 |
+
assert exp(I*pi*r, evaluate=False).is_algebraic is True
|
| 427 |
+
|
| 428 |
+
|
| 429 |
+
@_both_exp_pow
|
| 430 |
+
def test_exp_AccumBounds():
|
| 431 |
+
assert exp(AccumBounds(1, 2)) == AccumBounds(E, E**2)
|
| 432 |
+
|
| 433 |
+
|
| 434 |
+
def test_log_assumptions():
|
| 435 |
+
p = symbols('p', positive=True)
|
| 436 |
+
n = symbols('n', negative=True)
|
| 437 |
+
z = symbols('z', zero=True)
|
| 438 |
+
x = symbols('x', infinite=True, extended_positive=True)
|
| 439 |
+
|
| 440 |
+
assert log(z).is_positive is False
|
| 441 |
+
assert log(x).is_extended_positive is True
|
| 442 |
+
assert log(2) > 0
|
| 443 |
+
assert log(1, evaluate=False).is_zero
|
| 444 |
+
assert log(1 + z).is_zero
|
| 445 |
+
assert log(p).is_zero is None
|
| 446 |
+
assert log(n).is_zero is False
|
| 447 |
+
assert log(0.5).is_negative is True
|
| 448 |
+
assert log(exp(p) + 1).is_positive
|
| 449 |
+
|
| 450 |
+
assert log(1, evaluate=False).is_algebraic
|
| 451 |
+
assert log(42, evaluate=False).is_algebraic is False
|
| 452 |
+
|
| 453 |
+
assert log(1 + z).is_rational
|
| 454 |
+
|
| 455 |
+
|
| 456 |
+
def test_log_hashing():
|
| 457 |
+
assert x != log(log(x))
|
| 458 |
+
assert hash(x) != hash(log(log(x)))
|
| 459 |
+
assert log(x) != log(log(log(x)))
|
| 460 |
+
|
| 461 |
+
e = 1/log(log(x) + log(log(x)))
|
| 462 |
+
assert e.base.func is log
|
| 463 |
+
e = 1/log(log(x) + log(log(log(x))))
|
| 464 |
+
assert e.base.func is log
|
| 465 |
+
|
| 466 |
+
e = log(log(x))
|
| 467 |
+
assert e.func is log
|
| 468 |
+
assert x.func is not log
|
| 469 |
+
assert hash(log(log(x))) != hash(x)
|
| 470 |
+
assert e != x
|
| 471 |
+
|
| 472 |
+
|
| 473 |
+
def test_log_sign():
|
| 474 |
+
assert sign(log(2)) == 1
|
| 475 |
+
|
| 476 |
+
|
| 477 |
+
def test_log_expand_complex():
|
| 478 |
+
assert log(1 + I).expand(complex=True) == log(2)/2 + I*pi/4
|
| 479 |
+
assert log(1 - sqrt(2)).expand(complex=True) == log(sqrt(2) - 1) + I*pi
|
| 480 |
+
|
| 481 |
+
|
| 482 |
+
def test_log_apply_evalf():
|
| 483 |
+
value = (log(3)/log(2) - 1).evalf()
|
| 484 |
+
assert value.epsilon_eq(Float("0.58496250072115618145373"))
|
| 485 |
+
|
| 486 |
+
|
| 487 |
+
def test_log_leading_term():
|
| 488 |
+
p = Symbol('p')
|
| 489 |
+
|
| 490 |
+
# Test for STEP 3
|
| 491 |
+
assert log(1 + x + x**2).as_leading_term(x, cdir=1) == x
|
| 492 |
+
# Test for STEP 4
|
| 493 |
+
assert log(2*x).as_leading_term(x, cdir=1) == log(x) + log(2)
|
| 494 |
+
assert log(2*x).as_leading_term(x, cdir=-1) == log(x) + log(2)
|
| 495 |
+
assert log(-2*x).as_leading_term(x, cdir=1, logx=p) == p + log(2) + I*pi
|
| 496 |
+
assert log(-2*x).as_leading_term(x, cdir=-1, logx=p) == p + log(2) - I*pi
|
| 497 |
+
# Test for STEP 5
|
| 498 |
+
assert log(-2*x + (3 - I)*x**2).as_leading_term(x, cdir=1) == log(x) + log(2) - I*pi
|
| 499 |
+
assert log(-2*x + (3 - I)*x**2).as_leading_term(x, cdir=-1) == log(x) + log(2) - I*pi
|
| 500 |
+
assert log(2*x + (3 - I)*x**2).as_leading_term(x, cdir=1) == log(x) + log(2)
|
| 501 |
+
assert log(2*x + (3 - I)*x**2).as_leading_term(x, cdir=-1) == log(x) + log(2) - 2*I*pi
|
| 502 |
+
assert log(-1 + x - I*x**2 + I*x**3).as_leading_term(x, cdir=1) == -I*pi
|
| 503 |
+
assert log(-1 + x - I*x**2 + I*x**3).as_leading_term(x, cdir=-1) == -I*pi
|
| 504 |
+
assert log(-1/(1 - x)).as_leading_term(x, cdir=1) == I*pi
|
| 505 |
+
assert log(-1/(1 - x)).as_leading_term(x, cdir=-1) == I*pi
|
| 506 |
+
|
| 507 |
+
|
| 508 |
+
def test_log_nseries():
|
| 509 |
+
p = Symbol('p')
|
| 510 |
+
assert log(1/x)._eval_nseries(x, 4, logx=-p, cdir=1) == p
|
| 511 |
+
assert log(1/x)._eval_nseries(x, 4, logx=-p, cdir=-1) == p + 2*I*pi
|
| 512 |
+
assert log(x - 1)._eval_nseries(x, 4, None, I) == I*pi - x - x**2/2 - x**3/3 + O(x**4)
|
| 513 |
+
assert log(x - 1)._eval_nseries(x, 4, None, -I) == -I*pi - x - x**2/2 - x**3/3 + O(x**4)
|
| 514 |
+
assert log(I*x + I*x**3 - 1)._eval_nseries(x, 3, None, 1) == I*pi - I*x + x**2/2 + O(x**3)
|
| 515 |
+
assert log(I*x + I*x**3 - 1)._eval_nseries(x, 3, None, -1) == -I*pi - I*x + x**2/2 + O(x**3)
|
| 516 |
+
assert log(I*x**2 + I*x**3 - 1)._eval_nseries(x, 3, None, 1) == I*pi - I*x**2 + O(x**3)
|
| 517 |
+
assert log(I*x**2 + I*x**3 - 1)._eval_nseries(x, 3, None, -1) == I*pi - I*x**2 + O(x**3)
|
| 518 |
+
assert log(2*x + (3 - I)*x**2)._eval_nseries(x, 3, None, 1) == log(2) + log(x) + \
|
| 519 |
+
x*(S(3)/2 - I/2) + x**2*(-1 + 3*I/4) + O(x**3)
|
| 520 |
+
assert log(2*x + (3 - I)*x**2)._eval_nseries(x, 3, None, -1) == -2*I*pi + log(2) + \
|
| 521 |
+
log(x) - x*(-S(3)/2 + I/2) + x**2*(-1 + 3*I/4) + O(x**3)
|
| 522 |
+
assert log(-2*x + (3 - I)*x**2)._eval_nseries(x, 3, None, 1) == -I*pi + log(2) + log(x) + \
|
| 523 |
+
x*(-S(3)/2 + I/2) + x**2*(-1 + 3*I/4) + O(x**3)
|
| 524 |
+
assert log(-2*x + (3 - I)*x**2)._eval_nseries(x, 3, None, -1) == -I*pi + log(2) + log(x) - \
|
| 525 |
+
x*(S(3)/2 - I/2) + x**2*(-1 + 3*I/4) + O(x**3)
|
| 526 |
+
assert log(sqrt(-I*x**2 - 3)*sqrt(-I*x**2 - 1) - 2)._eval_nseries(x, 3, None, 1) == -I*pi + \
|
| 527 |
+
log(sqrt(3) + 2) + I*x**2*(-2 + 4*sqrt(3)/3) + O(x**3)
|
| 528 |
+
assert log(-1/(1 - x))._eval_nseries(x, 3, None, 1) == I*pi + x + x**2/2 + O(x**3)
|
| 529 |
+
assert log(-1/(1 - x))._eval_nseries(x, 3, None, -1) == I*pi + x + x**2/2 + O(x**3)
|
| 530 |
+
|
| 531 |
+
|
| 532 |
+
def test_log_series():
|
| 533 |
+
# Note Series at infinities other than oo/-oo were introduced as a part of
|
| 534 |
+
# pull request 23798. Refer https://github.com/sympy/sympy/pull/23798 for
|
| 535 |
+
# more information.
|
| 536 |
+
expr1 = log(1 + x)
|
| 537 |
+
expr2 = log(x + sqrt(x**2 + 1))
|
| 538 |
+
|
| 539 |
+
assert expr1.series(x, x0=I*oo, n=4) == 1/(3*x**3) - 1/(2*x**2) + 1/x + \
|
| 540 |
+
I*pi/2 - log(I/x) + O(x**(-4), (x, oo*I))
|
| 541 |
+
assert expr1.series(x, x0=-I*oo, n=4) == 1/(3*x**3) - 1/(2*x**2) + 1/x - \
|
| 542 |
+
I*pi/2 - log(-I/x) + O(x**(-4), (x, -oo*I))
|
| 543 |
+
assert expr2.series(x, x0=I*oo, n=4) == 1/(4*x**2) + I*pi/2 + log(2) - \
|
| 544 |
+
log(I/x) + O(x**(-4), (x, oo*I))
|
| 545 |
+
assert expr2.series(x, x0=-I*oo, n=4) == -1/(4*x**2) - I*pi/2 - log(2) + \
|
| 546 |
+
log(-I/x) + O(x**(-4), (x, -oo*I))
|
| 547 |
+
|
| 548 |
+
|
| 549 |
+
def test_log_expand():
|
| 550 |
+
w = Symbol("w", positive=True)
|
| 551 |
+
e = log(w**(log(5)/log(3)))
|
| 552 |
+
assert e.expand() == log(5)/log(3) * log(w)
|
| 553 |
+
x, y, z = symbols('x,y,z', positive=True)
|
| 554 |
+
assert log(x*(y + z)).expand(mul=False) == log(x) + log(y + z)
|
| 555 |
+
assert log(log(x**2)*log(y*z)).expand() in [log(2*log(x)*log(y) +
|
| 556 |
+
2*log(x)*log(z)), log(log(x)*log(z) + log(y)*log(x)) + log(2),
|
| 557 |
+
log((log(y) + log(z))*log(x)) + log(2)]
|
| 558 |
+
assert log(x**log(x**2)).expand(deep=False) == log(x)*log(x**2)
|
| 559 |
+
assert log(x**log(x**2)).expand() == 2*log(x)**2
|
| 560 |
+
x, y = symbols('x,y')
|
| 561 |
+
assert log(x*y).expand(force=True) == log(x) + log(y)
|
| 562 |
+
assert log(x**y).expand(force=True) == y*log(x)
|
| 563 |
+
assert log(exp(x)).expand(force=True) == x
|
| 564 |
+
|
| 565 |
+
# there's generally no need to expand out logs since this requires
|
| 566 |
+
# factoring and if simplification is sought, it's cheaper to put
|
| 567 |
+
# logs together than it is to take them apart.
|
| 568 |
+
assert log(2*3**2).expand() != 2*log(3) + log(2)
|
| 569 |
+
|
| 570 |
+
|
| 571 |
+
@XFAIL
|
| 572 |
+
def test_log_expand_fail():
|
| 573 |
+
x, y, z = symbols('x,y,z', positive=True)
|
| 574 |
+
assert (log(x*(y + z))*(x + y)).expand(mul=True, log=True) == y*log(
|
| 575 |
+
x) + y*log(y + z) + z*log(x) + z*log(y + z)
|
| 576 |
+
|
| 577 |
+
|
| 578 |
+
def test_log_simplify():
|
| 579 |
+
x = Symbol("x", positive=True)
|
| 580 |
+
assert log(x**2).expand() == 2*log(x)
|
| 581 |
+
assert expand_log(log(x**(2 + log(2)))) == (2 + log(2))*log(x)
|
| 582 |
+
|
| 583 |
+
z = Symbol('z')
|
| 584 |
+
assert log(sqrt(z)).expand() == log(z)/2
|
| 585 |
+
assert expand_log(log(z**(log(2) - 1))) == (log(2) - 1)*log(z)
|
| 586 |
+
assert log(z**(-1)).expand() != -log(z)
|
| 587 |
+
assert log(z**(x/(x+1))).expand() == x*log(z)/(x + 1)
|
| 588 |
+
|
| 589 |
+
|
| 590 |
+
def test_log_AccumBounds():
|
| 591 |
+
assert log(AccumBounds(1, E)) == AccumBounds(0, 1)
|
| 592 |
+
assert log(AccumBounds(0, E)) == AccumBounds(-oo, 1)
|
| 593 |
+
assert log(AccumBounds(-1, E)) == S.NaN
|
| 594 |
+
assert log(AccumBounds(0, oo)) == AccumBounds(-oo, oo)
|
| 595 |
+
assert log(AccumBounds(-oo, 0)) == S.NaN
|
| 596 |
+
assert log(AccumBounds(-oo, oo)) == S.NaN
|
| 597 |
+
|
| 598 |
+
|
| 599 |
+
@_both_exp_pow
|
| 600 |
+
def test_lambertw():
|
| 601 |
+
k = Symbol('k')
|
| 602 |
+
|
| 603 |
+
assert LambertW(x, 0) == LambertW(x)
|
| 604 |
+
assert LambertW(x, 0, evaluate=False) != LambertW(x)
|
| 605 |
+
assert LambertW(0) == 0
|
| 606 |
+
assert LambertW(E) == 1
|
| 607 |
+
assert LambertW(-1/E) == -1
|
| 608 |
+
assert LambertW(-log(2)/2) == -log(2)
|
| 609 |
+
assert LambertW(oo) is oo
|
| 610 |
+
assert LambertW(0, 1) is -oo
|
| 611 |
+
assert LambertW(0, 42) is -oo
|
| 612 |
+
assert LambertW(-pi/2, -1) == -I*pi/2
|
| 613 |
+
assert LambertW(-1/E, -1) == -1
|
| 614 |
+
assert LambertW(-2*exp(-2), -1) == -2
|
| 615 |
+
assert LambertW(2*log(2)) == log(2)
|
| 616 |
+
assert LambertW(-pi/2) == I*pi/2
|
| 617 |
+
assert LambertW(exp(1 + E)) == E
|
| 618 |
+
|
| 619 |
+
assert LambertW(x**2).diff(x) == 2*LambertW(x**2)/x/(1 + LambertW(x**2))
|
| 620 |
+
assert LambertW(x, k).diff(x) == LambertW(x, k)/x/(1 + LambertW(x, k))
|
| 621 |
+
|
| 622 |
+
assert LambertW(sqrt(2)).evalf(30).epsilon_eq(
|
| 623 |
+
Float("0.701338383413663009202120278965", 30), 1e-29)
|
| 624 |
+
assert re(LambertW(2, -1)).evalf().epsilon_eq(Float("-0.834310366631110"))
|
| 625 |
+
|
| 626 |
+
assert LambertW(-1).is_real is False # issue 5215
|
| 627 |
+
assert LambertW(2, evaluate=False).is_real
|
| 628 |
+
p = Symbol('p', positive=True)
|
| 629 |
+
assert LambertW(p, evaluate=False).is_real
|
| 630 |
+
assert LambertW(p - 1, evaluate=False).is_real is None
|
| 631 |
+
assert LambertW(-p - 2/S.Exp1, evaluate=False).is_real is False
|
| 632 |
+
assert LambertW(S.Half, -1, evaluate=False).is_real is False
|
| 633 |
+
assert LambertW(Rational(-1, 10), -1, evaluate=False).is_real
|
| 634 |
+
assert LambertW(-10, -1, evaluate=False).is_real is False
|
| 635 |
+
assert LambertW(-2, 2, evaluate=False).is_real is False
|
| 636 |
+
|
| 637 |
+
assert LambertW(0, evaluate=False).is_algebraic
|
| 638 |
+
na = Symbol('na', nonzero=True, algebraic=True)
|
| 639 |
+
assert LambertW(na).is_algebraic is False
|
| 640 |
+
assert LambertW(p).is_zero is False
|
| 641 |
+
n = Symbol('n', negative=True)
|
| 642 |
+
assert LambertW(n).is_zero is False
|
| 643 |
+
|
| 644 |
+
|
| 645 |
+
def test_issue_5673():
|
| 646 |
+
e = LambertW(-1)
|
| 647 |
+
assert e.is_comparable is False
|
| 648 |
+
assert e.is_positive is not True
|
| 649 |
+
e2 = 1 - 1/(1 - exp(-1000))
|
| 650 |
+
assert e2.is_positive is not True
|
| 651 |
+
e3 = -2 + exp(exp(LambertW(log(2)))*LambertW(log(2)))
|
| 652 |
+
assert e3.is_nonzero is not True
|
| 653 |
+
|
| 654 |
+
|
| 655 |
+
def test_log_fdiff():
|
| 656 |
+
x = Symbol('x')
|
| 657 |
+
raises(ArgumentIndexError, lambda: log(x).fdiff(2))
|
| 658 |
+
|
| 659 |
+
|
| 660 |
+
def test_log_taylor_term():
|
| 661 |
+
x = symbols('x')
|
| 662 |
+
assert log(x).taylor_term(0, x) == x
|
| 663 |
+
assert log(x).taylor_term(1, x) == -x**2/2
|
| 664 |
+
assert log(x).taylor_term(4, x) == x**5/5
|
| 665 |
+
assert log(x).taylor_term(-1, x) is S.Zero
|
| 666 |
+
|
| 667 |
+
|
| 668 |
+
def test_exp_expand_NC():
|
| 669 |
+
A, B, C = symbols('A,B,C', commutative=False)
|
| 670 |
+
|
| 671 |
+
assert exp(A + B).expand() == exp(A + B)
|
| 672 |
+
assert exp(A + B + C).expand() == exp(A + B + C)
|
| 673 |
+
assert exp(x + y).expand() == exp(x)*exp(y)
|
| 674 |
+
assert exp(x + y + z).expand() == exp(x)*exp(y)*exp(z)
|
| 675 |
+
|
| 676 |
+
|
| 677 |
+
@_both_exp_pow
|
| 678 |
+
def test_as_numer_denom():
|
| 679 |
+
n = symbols('n', negative=True)
|
| 680 |
+
assert exp(x).as_numer_denom() == (exp(x), 1)
|
| 681 |
+
assert exp(-x).as_numer_denom() == (1, exp(x))
|
| 682 |
+
assert exp(-2*x).as_numer_denom() == (1, exp(2*x))
|
| 683 |
+
assert exp(-2).as_numer_denom() == (1, exp(2))
|
| 684 |
+
assert exp(n).as_numer_denom() == (1, exp(-n))
|
| 685 |
+
assert exp(-n).as_numer_denom() == (exp(-n), 1)
|
| 686 |
+
assert exp(-I*x).as_numer_denom() == (1, exp(I*x))
|
| 687 |
+
assert exp(-I*n).as_numer_denom() == (1, exp(I*n))
|
| 688 |
+
assert exp(-n).as_numer_denom() == (exp(-n), 1)
|
| 689 |
+
# Check noncommutativity
|
| 690 |
+
a = symbols('a', commutative=False)
|
| 691 |
+
assert exp(-a).as_numer_denom() == (exp(-a), 1)
|
| 692 |
+
|
| 693 |
+
|
| 694 |
+
@_both_exp_pow
|
| 695 |
+
def test_polar():
|
| 696 |
+
x, y = symbols('x y', polar=True)
|
| 697 |
+
|
| 698 |
+
assert abs(exp_polar(I*4)) == 1
|
| 699 |
+
assert abs(exp_polar(0)) == 1
|
| 700 |
+
assert abs(exp_polar(2 + 3*I)) == exp(2)
|
| 701 |
+
assert exp_polar(I*10).n() == exp_polar(I*10)
|
| 702 |
+
|
| 703 |
+
assert log(exp_polar(z)) == z
|
| 704 |
+
assert log(x*y).expand() == log(x) + log(y)
|
| 705 |
+
assert log(x**z).expand() == z*log(x)
|
| 706 |
+
|
| 707 |
+
assert exp_polar(3).exp == 3
|
| 708 |
+
|
| 709 |
+
# Compare exp(1.0*pi*I).
|
| 710 |
+
assert (exp_polar(1.0*pi*I).n(n=5)).as_real_imag()[1] >= 0
|
| 711 |
+
|
| 712 |
+
assert exp_polar(0).is_rational is True # issue 8008
|
| 713 |
+
|
| 714 |
+
|
| 715 |
+
def test_exp_summation():
|
| 716 |
+
w = symbols("w")
|
| 717 |
+
m, n, i, j = symbols("m n i j")
|
| 718 |
+
expr = exp(Sum(w*i, (i, 0, n), (j, 0, m)))
|
| 719 |
+
assert expr.expand() == Product(exp(w*i), (i, 0, n), (j, 0, m))
|
| 720 |
+
|
| 721 |
+
|
| 722 |
+
def test_log_product():
|
| 723 |
+
from sympy.abc import n, m
|
| 724 |
+
|
| 725 |
+
i, j = symbols('i,j', positive=True, integer=True)
|
| 726 |
+
x, y = symbols('x,y', positive=True)
|
| 727 |
+
z = symbols('z', real=True)
|
| 728 |
+
w = symbols('w')
|
| 729 |
+
|
| 730 |
+
expr = log(Product(x**i, (i, 1, n)))
|
| 731 |
+
assert simplify(expr) == expr
|
| 732 |
+
assert expr.expand() == Sum(i*log(x), (i, 1, n))
|
| 733 |
+
expr = log(Product(x**i*y**j, (i, 1, n), (j, 1, m)))
|
| 734 |
+
assert simplify(expr) == expr
|
| 735 |
+
assert expr.expand() == Sum(i*log(x) + j*log(y), (i, 1, n), (j, 1, m))
|
| 736 |
+
|
| 737 |
+
expr = log(Product(-2, (n, 0, 4)))
|
| 738 |
+
assert simplify(expr) == expr
|
| 739 |
+
assert expr.expand() == expr
|
| 740 |
+
assert expr.expand(force=True) == Sum(log(-2), (n, 0, 4))
|
| 741 |
+
|
| 742 |
+
expr = log(Product(exp(z*i), (i, 0, n)))
|
| 743 |
+
assert expr.expand() == Sum(z*i, (i, 0, n))
|
| 744 |
+
|
| 745 |
+
expr = log(Product(exp(w*i), (i, 0, n)))
|
| 746 |
+
assert expr.expand() == expr
|
| 747 |
+
assert expr.expand(force=True) == Sum(w*i, (i, 0, n))
|
| 748 |
+
|
| 749 |
+
expr = log(Product(i**2*abs(j), (i, 1, n), (j, 1, m)))
|
| 750 |
+
assert expr.expand() == Sum(2*log(i) + log(j), (i, 1, n), (j, 1, m))
|
| 751 |
+
|
| 752 |
+
|
| 753 |
+
@XFAIL
|
| 754 |
+
def test_log_product_simplify_to_sum():
|
| 755 |
+
from sympy.abc import n, m
|
| 756 |
+
i, j = symbols('i,j', positive=True, integer=True)
|
| 757 |
+
x, y = symbols('x,y', positive=True)
|
| 758 |
+
assert simplify(log(Product(x**i, (i, 1, n)))) == Sum(i*log(x), (i, 1, n))
|
| 759 |
+
assert simplify(log(Product(x**i*y**j, (i, 1, n), (j, 1, m)))) == \
|
| 760 |
+
Sum(i*log(x) + j*log(y), (i, 1, n), (j, 1, m))
|
| 761 |
+
|
| 762 |
+
|
| 763 |
+
def test_issue_8866():
|
| 764 |
+
assert simplify(log(x, 10, evaluate=False)) == simplify(log(x, 10))
|
| 765 |
+
assert expand_log(log(x, 10, evaluate=False)) == expand_log(log(x, 10))
|
| 766 |
+
|
| 767 |
+
y = Symbol('y', positive=True)
|
| 768 |
+
l1 = log(exp(y), exp(10))
|
| 769 |
+
b1 = log(exp(y), exp(5))
|
| 770 |
+
l2 = log(exp(y), exp(10), evaluate=False)
|
| 771 |
+
b2 = log(exp(y), exp(5), evaluate=False)
|
| 772 |
+
assert simplify(log(l1, b1)) == simplify(log(l2, b2))
|
| 773 |
+
assert expand_log(log(l1, b1)) == expand_log(log(l2, b2))
|
| 774 |
+
|
| 775 |
+
|
| 776 |
+
def test_log_expand_factor():
|
| 777 |
+
assert (log(18)/log(3) - 2).expand(factor=True) == log(2)/log(3)
|
| 778 |
+
assert (log(12)/log(2)).expand(factor=True) == log(3)/log(2) + 2
|
| 779 |
+
assert (log(15)/log(3)).expand(factor=True) == 1 + log(5)/log(3)
|
| 780 |
+
assert (log(2)/(-log(12) + log(24))).expand(factor=True) == 1
|
| 781 |
+
|
| 782 |
+
assert expand_log(log(12), factor=True) == log(3) + 2*log(2)
|
| 783 |
+
assert expand_log(log(21)/log(7), factor=False) == log(3)/log(7) + 1
|
| 784 |
+
assert expand_log(log(45)/log(5) + log(20), factor=False) == \
|
| 785 |
+
1 + 2*log(3)/log(5) + log(20)
|
| 786 |
+
assert expand_log(log(45)/log(5) + log(26), factor=True) == \
|
| 787 |
+
log(2) + log(13) + (log(5) + 2*log(3))/log(5)
|
| 788 |
+
|
| 789 |
+
|
| 790 |
+
def test_issue_9116():
|
| 791 |
+
n = Symbol('n', positive=True, integer=True)
|
| 792 |
+
assert log(n).is_nonnegative is True
|
| 793 |
+
|
| 794 |
+
|
| 795 |
+
def test_issue_18473():
|
| 796 |
+
assert exp(x*log(cos(1/x))).as_leading_term(x) == S.NaN
|
| 797 |
+
assert exp(x*log(tan(1/x))).as_leading_term(x) == S.NaN
|
| 798 |
+
assert log(cos(1/x)).as_leading_term(x) == S.NaN
|
| 799 |
+
assert log(tan(1/x)).as_leading_term(x) == S.NaN
|
| 800 |
+
assert log(cos(1/x) + 2).as_leading_term(x) == AccumBounds(0, log(3))
|
| 801 |
+
assert exp(x*log(cos(1/x) + 2)).as_leading_term(x) == 1
|
| 802 |
+
assert log(cos(1/x) - 2).as_leading_term(x) == S.NaN
|
| 803 |
+
assert exp(x*log(cos(1/x) - 2)).as_leading_term(x) == S.NaN
|
| 804 |
+
assert log(cos(1/x) + 1).as_leading_term(x) == AccumBounds(-oo, log(2))
|
| 805 |
+
assert exp(x*log(cos(1/x) + 1)).as_leading_term(x) == AccumBounds(0, 1)
|
| 806 |
+
assert log(sin(1/x)**2).as_leading_term(x) == AccumBounds(-oo, 0)
|
| 807 |
+
assert exp(x*log(sin(1/x)**2)).as_leading_term(x) == AccumBounds(0, 1)
|
| 808 |
+
assert log(tan(1/x)**2).as_leading_term(x) == AccumBounds(-oo, oo)
|
| 809 |
+
assert exp(2*x*(log(tan(1/x)**2))).as_leading_term(x) == AccumBounds(0, oo)
|
evalkit_tf437/lib/python3.10/site-packages/sympy/functions/elementary/tests/test_hyperbolic.py
ADDED
|
@@ -0,0 +1,1542 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.calculus.accumulationbounds import AccumBounds
|
| 2 |
+
from sympy.core.function import (expand_mul, expand_trig)
|
| 3 |
+
from sympy.core.numbers import (E, I, Integer, Rational, nan, oo, pi, zoo)
|
| 4 |
+
from sympy.core.singleton import S
|
| 5 |
+
from sympy.core.symbol import (Symbol, symbols)
|
| 6 |
+
from sympy.functions.elementary.complexes import (im, re)
|
| 7 |
+
from sympy.functions.elementary.exponential import (exp, log)
|
| 8 |
+
from sympy.functions.elementary.hyperbolic import (acosh, acoth, acsch, asech, asinh, atanh, cosh, coth, csch, sech, sinh, tanh)
|
| 9 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
| 10 |
+
from sympy.functions.elementary.trigonometric import (acos, asin, cos, cot, sec, sin, tan)
|
| 11 |
+
from sympy.series.order import O
|
| 12 |
+
|
| 13 |
+
from sympy.core.expr import unchanged
|
| 14 |
+
from sympy.core.function import ArgumentIndexError, PoleError
|
| 15 |
+
from sympy.testing.pytest import raises
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def test_sinh():
|
| 19 |
+
x, y = symbols('x,y')
|
| 20 |
+
|
| 21 |
+
k = Symbol('k', integer=True)
|
| 22 |
+
|
| 23 |
+
assert sinh(nan) is nan
|
| 24 |
+
assert sinh(zoo) is nan
|
| 25 |
+
|
| 26 |
+
assert sinh(oo) is oo
|
| 27 |
+
assert sinh(-oo) is -oo
|
| 28 |
+
|
| 29 |
+
assert sinh(0) == 0
|
| 30 |
+
|
| 31 |
+
assert unchanged(sinh, 1)
|
| 32 |
+
assert sinh(-1) == -sinh(1)
|
| 33 |
+
|
| 34 |
+
assert unchanged(sinh, x)
|
| 35 |
+
assert sinh(-x) == -sinh(x)
|
| 36 |
+
|
| 37 |
+
assert unchanged(sinh, pi)
|
| 38 |
+
assert sinh(-pi) == -sinh(pi)
|
| 39 |
+
|
| 40 |
+
assert unchanged(sinh, 2**1024 * E)
|
| 41 |
+
assert sinh(-2**1024 * E) == -sinh(2**1024 * E)
|
| 42 |
+
|
| 43 |
+
assert sinh(pi*I) == 0
|
| 44 |
+
assert sinh(-pi*I) == 0
|
| 45 |
+
assert sinh(2*pi*I) == 0
|
| 46 |
+
assert sinh(-2*pi*I) == 0
|
| 47 |
+
assert sinh(-3*10**73*pi*I) == 0
|
| 48 |
+
assert sinh(7*10**103*pi*I) == 0
|
| 49 |
+
|
| 50 |
+
assert sinh(pi*I/2) == I
|
| 51 |
+
assert sinh(-pi*I/2) == -I
|
| 52 |
+
assert sinh(pi*I*Rational(5, 2)) == I
|
| 53 |
+
assert sinh(pi*I*Rational(7, 2)) == -I
|
| 54 |
+
|
| 55 |
+
assert sinh(pi*I/3) == S.Half*sqrt(3)*I
|
| 56 |
+
assert sinh(pi*I*Rational(-2, 3)) == Rational(-1, 2)*sqrt(3)*I
|
| 57 |
+
|
| 58 |
+
assert sinh(pi*I/4) == S.Half*sqrt(2)*I
|
| 59 |
+
assert sinh(-pi*I/4) == Rational(-1, 2)*sqrt(2)*I
|
| 60 |
+
assert sinh(pi*I*Rational(17, 4)) == S.Half*sqrt(2)*I
|
| 61 |
+
assert sinh(pi*I*Rational(-3, 4)) == Rational(-1, 2)*sqrt(2)*I
|
| 62 |
+
|
| 63 |
+
assert sinh(pi*I/6) == S.Half*I
|
| 64 |
+
assert sinh(-pi*I/6) == Rational(-1, 2)*I
|
| 65 |
+
assert sinh(pi*I*Rational(7, 6)) == Rational(-1, 2)*I
|
| 66 |
+
assert sinh(pi*I*Rational(-5, 6)) == Rational(-1, 2)*I
|
| 67 |
+
|
| 68 |
+
assert sinh(pi*I/105) == sin(pi/105)*I
|
| 69 |
+
assert sinh(-pi*I/105) == -sin(pi/105)*I
|
| 70 |
+
|
| 71 |
+
assert unchanged(sinh, 2 + 3*I)
|
| 72 |
+
|
| 73 |
+
assert sinh(x*I) == sin(x)*I
|
| 74 |
+
|
| 75 |
+
assert sinh(k*pi*I) == 0
|
| 76 |
+
assert sinh(17*k*pi*I) == 0
|
| 77 |
+
|
| 78 |
+
assert sinh(k*pi*I/2) == sin(k*pi/2)*I
|
| 79 |
+
|
| 80 |
+
assert sinh(x).as_real_imag(deep=False) == (cos(im(x))*sinh(re(x)),
|
| 81 |
+
sin(im(x))*cosh(re(x)))
|
| 82 |
+
x = Symbol('x', extended_real=True)
|
| 83 |
+
assert sinh(x).as_real_imag(deep=False) == (sinh(x), 0)
|
| 84 |
+
|
| 85 |
+
x = Symbol('x', real=True)
|
| 86 |
+
assert sinh(I*x).is_finite is True
|
| 87 |
+
assert sinh(x).is_real is True
|
| 88 |
+
assert sinh(I).is_real is False
|
| 89 |
+
p = Symbol('p', positive=True)
|
| 90 |
+
assert sinh(p).is_zero is False
|
| 91 |
+
assert sinh(0, evaluate=False).is_zero is True
|
| 92 |
+
assert sinh(2*pi*I, evaluate=False).is_zero is True
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def test_sinh_series():
|
| 96 |
+
x = Symbol('x')
|
| 97 |
+
assert sinh(x).series(x, 0, 10) == \
|
| 98 |
+
x + x**3/6 + x**5/120 + x**7/5040 + x**9/362880 + O(x**10)
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def test_sinh_fdiff():
|
| 102 |
+
x = Symbol('x')
|
| 103 |
+
raises(ArgumentIndexError, lambda: sinh(x).fdiff(2))
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def test_cosh():
|
| 107 |
+
x, y = symbols('x,y')
|
| 108 |
+
|
| 109 |
+
k = Symbol('k', integer=True)
|
| 110 |
+
|
| 111 |
+
assert cosh(nan) is nan
|
| 112 |
+
assert cosh(zoo) is nan
|
| 113 |
+
|
| 114 |
+
assert cosh(oo) is oo
|
| 115 |
+
assert cosh(-oo) is oo
|
| 116 |
+
|
| 117 |
+
assert cosh(0) == 1
|
| 118 |
+
|
| 119 |
+
assert unchanged(cosh, 1)
|
| 120 |
+
assert cosh(-1) == cosh(1)
|
| 121 |
+
|
| 122 |
+
assert unchanged(cosh, x)
|
| 123 |
+
assert cosh(-x) == cosh(x)
|
| 124 |
+
|
| 125 |
+
assert cosh(pi*I) == cos(pi)
|
| 126 |
+
assert cosh(-pi*I) == cos(pi)
|
| 127 |
+
|
| 128 |
+
assert unchanged(cosh, 2**1024 * E)
|
| 129 |
+
assert cosh(-2**1024 * E) == cosh(2**1024 * E)
|
| 130 |
+
|
| 131 |
+
assert cosh(pi*I/2) == 0
|
| 132 |
+
assert cosh(-pi*I/2) == 0
|
| 133 |
+
assert cosh((-3*10**73 + 1)*pi*I/2) == 0
|
| 134 |
+
assert cosh((7*10**103 + 1)*pi*I/2) == 0
|
| 135 |
+
|
| 136 |
+
assert cosh(pi*I) == -1
|
| 137 |
+
assert cosh(-pi*I) == -1
|
| 138 |
+
assert cosh(5*pi*I) == -1
|
| 139 |
+
assert cosh(8*pi*I) == 1
|
| 140 |
+
|
| 141 |
+
assert cosh(pi*I/3) == S.Half
|
| 142 |
+
assert cosh(pi*I*Rational(-2, 3)) == Rational(-1, 2)
|
| 143 |
+
|
| 144 |
+
assert cosh(pi*I/4) == S.Half*sqrt(2)
|
| 145 |
+
assert cosh(-pi*I/4) == S.Half*sqrt(2)
|
| 146 |
+
assert cosh(pi*I*Rational(11, 4)) == Rational(-1, 2)*sqrt(2)
|
| 147 |
+
assert cosh(pi*I*Rational(-3, 4)) == Rational(-1, 2)*sqrt(2)
|
| 148 |
+
|
| 149 |
+
assert cosh(pi*I/6) == S.Half*sqrt(3)
|
| 150 |
+
assert cosh(-pi*I/6) == S.Half*sqrt(3)
|
| 151 |
+
assert cosh(pi*I*Rational(7, 6)) == Rational(-1, 2)*sqrt(3)
|
| 152 |
+
assert cosh(pi*I*Rational(-5, 6)) == Rational(-1, 2)*sqrt(3)
|
| 153 |
+
|
| 154 |
+
assert cosh(pi*I/105) == cos(pi/105)
|
| 155 |
+
assert cosh(-pi*I/105) == cos(pi/105)
|
| 156 |
+
|
| 157 |
+
assert unchanged(cosh, 2 + 3*I)
|
| 158 |
+
|
| 159 |
+
assert cosh(x*I) == cos(x)
|
| 160 |
+
|
| 161 |
+
assert cosh(k*pi*I) == cos(k*pi)
|
| 162 |
+
assert cosh(17*k*pi*I) == cos(17*k*pi)
|
| 163 |
+
|
| 164 |
+
assert unchanged(cosh, k*pi)
|
| 165 |
+
|
| 166 |
+
assert cosh(x).as_real_imag(deep=False) == (cos(im(x))*cosh(re(x)),
|
| 167 |
+
sin(im(x))*sinh(re(x)))
|
| 168 |
+
x = Symbol('x', extended_real=True)
|
| 169 |
+
assert cosh(x).as_real_imag(deep=False) == (cosh(x), 0)
|
| 170 |
+
|
| 171 |
+
x = Symbol('x', real=True)
|
| 172 |
+
assert cosh(I*x).is_finite is True
|
| 173 |
+
assert cosh(I*x).is_real is True
|
| 174 |
+
assert cosh(I*2 + 1).is_real is False
|
| 175 |
+
assert cosh(5*I*S.Pi/2, evaluate=False).is_zero is True
|
| 176 |
+
assert cosh(x).is_zero is False
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
def test_cosh_series():
|
| 180 |
+
x = Symbol('x')
|
| 181 |
+
assert cosh(x).series(x, 0, 10) == \
|
| 182 |
+
1 + x**2/2 + x**4/24 + x**6/720 + x**8/40320 + O(x**10)
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
def test_cosh_fdiff():
|
| 186 |
+
x = Symbol('x')
|
| 187 |
+
raises(ArgumentIndexError, lambda: cosh(x).fdiff(2))
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
def test_tanh():
|
| 191 |
+
x, y = symbols('x,y')
|
| 192 |
+
|
| 193 |
+
k = Symbol('k', integer=True)
|
| 194 |
+
|
| 195 |
+
assert tanh(nan) is nan
|
| 196 |
+
assert tanh(zoo) is nan
|
| 197 |
+
|
| 198 |
+
assert tanh(oo) == 1
|
| 199 |
+
assert tanh(-oo) == -1
|
| 200 |
+
|
| 201 |
+
assert tanh(0) == 0
|
| 202 |
+
|
| 203 |
+
assert unchanged(tanh, 1)
|
| 204 |
+
assert tanh(-1) == -tanh(1)
|
| 205 |
+
|
| 206 |
+
assert unchanged(tanh, x)
|
| 207 |
+
assert tanh(-x) == -tanh(x)
|
| 208 |
+
|
| 209 |
+
assert unchanged(tanh, pi)
|
| 210 |
+
assert tanh(-pi) == -tanh(pi)
|
| 211 |
+
|
| 212 |
+
assert unchanged(tanh, 2**1024 * E)
|
| 213 |
+
assert tanh(-2**1024 * E) == -tanh(2**1024 * E)
|
| 214 |
+
|
| 215 |
+
assert tanh(pi*I) == 0
|
| 216 |
+
assert tanh(-pi*I) == 0
|
| 217 |
+
assert tanh(2*pi*I) == 0
|
| 218 |
+
assert tanh(-2*pi*I) == 0
|
| 219 |
+
assert tanh(-3*10**73*pi*I) == 0
|
| 220 |
+
assert tanh(7*10**103*pi*I) == 0
|
| 221 |
+
|
| 222 |
+
assert tanh(pi*I/2) is zoo
|
| 223 |
+
assert tanh(-pi*I/2) is zoo
|
| 224 |
+
assert tanh(pi*I*Rational(5, 2)) is zoo
|
| 225 |
+
assert tanh(pi*I*Rational(7, 2)) is zoo
|
| 226 |
+
|
| 227 |
+
assert tanh(pi*I/3) == sqrt(3)*I
|
| 228 |
+
assert tanh(pi*I*Rational(-2, 3)) == sqrt(3)*I
|
| 229 |
+
|
| 230 |
+
assert tanh(pi*I/4) == I
|
| 231 |
+
assert tanh(-pi*I/4) == -I
|
| 232 |
+
assert tanh(pi*I*Rational(17, 4)) == I
|
| 233 |
+
assert tanh(pi*I*Rational(-3, 4)) == I
|
| 234 |
+
|
| 235 |
+
assert tanh(pi*I/6) == I/sqrt(3)
|
| 236 |
+
assert tanh(-pi*I/6) == -I/sqrt(3)
|
| 237 |
+
assert tanh(pi*I*Rational(7, 6)) == I/sqrt(3)
|
| 238 |
+
assert tanh(pi*I*Rational(-5, 6)) == I/sqrt(3)
|
| 239 |
+
|
| 240 |
+
assert tanh(pi*I/105) == tan(pi/105)*I
|
| 241 |
+
assert tanh(-pi*I/105) == -tan(pi/105)*I
|
| 242 |
+
|
| 243 |
+
assert unchanged(tanh, 2 + 3*I)
|
| 244 |
+
|
| 245 |
+
assert tanh(x*I) == tan(x)*I
|
| 246 |
+
|
| 247 |
+
assert tanh(k*pi*I) == 0
|
| 248 |
+
assert tanh(17*k*pi*I) == 0
|
| 249 |
+
|
| 250 |
+
assert tanh(k*pi*I/2) == tan(k*pi/2)*I
|
| 251 |
+
|
| 252 |
+
assert tanh(x).as_real_imag(deep=False) == (sinh(re(x))*cosh(re(x))/(cos(im(x))**2
|
| 253 |
+
+ sinh(re(x))**2),
|
| 254 |
+
sin(im(x))*cos(im(x))/(cos(im(x))**2 + sinh(re(x))**2))
|
| 255 |
+
x = Symbol('x', extended_real=True)
|
| 256 |
+
assert tanh(x).as_real_imag(deep=False) == (tanh(x), 0)
|
| 257 |
+
assert tanh(I*pi/3 + 1).is_real is False
|
| 258 |
+
assert tanh(x).is_real is True
|
| 259 |
+
assert tanh(I*pi*x/2).is_real is None
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
def test_tanh_series():
|
| 263 |
+
x = Symbol('x')
|
| 264 |
+
assert tanh(x).series(x, 0, 10) == \
|
| 265 |
+
x - x**3/3 + 2*x**5/15 - 17*x**7/315 + 62*x**9/2835 + O(x**10)
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
def test_tanh_fdiff():
|
| 269 |
+
x = Symbol('x')
|
| 270 |
+
raises(ArgumentIndexError, lambda: tanh(x).fdiff(2))
|
| 271 |
+
|
| 272 |
+
|
| 273 |
+
def test_coth():
|
| 274 |
+
x, y = symbols('x,y')
|
| 275 |
+
|
| 276 |
+
k = Symbol('k', integer=True)
|
| 277 |
+
|
| 278 |
+
assert coth(nan) is nan
|
| 279 |
+
assert coth(zoo) is nan
|
| 280 |
+
|
| 281 |
+
assert coth(oo) == 1
|
| 282 |
+
assert coth(-oo) == -1
|
| 283 |
+
|
| 284 |
+
assert coth(0) is zoo
|
| 285 |
+
assert unchanged(coth, 1)
|
| 286 |
+
assert coth(-1) == -coth(1)
|
| 287 |
+
|
| 288 |
+
assert unchanged(coth, x)
|
| 289 |
+
assert coth(-x) == -coth(x)
|
| 290 |
+
|
| 291 |
+
assert coth(pi*I) == -I*cot(pi)
|
| 292 |
+
assert coth(-pi*I) == cot(pi)*I
|
| 293 |
+
|
| 294 |
+
assert unchanged(coth, 2**1024 * E)
|
| 295 |
+
assert coth(-2**1024 * E) == -coth(2**1024 * E)
|
| 296 |
+
|
| 297 |
+
assert coth(pi*I) == -I*cot(pi)
|
| 298 |
+
assert coth(-pi*I) == I*cot(pi)
|
| 299 |
+
assert coth(2*pi*I) == -I*cot(2*pi)
|
| 300 |
+
assert coth(-2*pi*I) == I*cot(2*pi)
|
| 301 |
+
assert coth(-3*10**73*pi*I) == I*cot(3*10**73*pi)
|
| 302 |
+
assert coth(7*10**103*pi*I) == -I*cot(7*10**103*pi)
|
| 303 |
+
|
| 304 |
+
assert coth(pi*I/2) == 0
|
| 305 |
+
assert coth(-pi*I/2) == 0
|
| 306 |
+
assert coth(pi*I*Rational(5, 2)) == 0
|
| 307 |
+
assert coth(pi*I*Rational(7, 2)) == 0
|
| 308 |
+
|
| 309 |
+
assert coth(pi*I/3) == -I/sqrt(3)
|
| 310 |
+
assert coth(pi*I*Rational(-2, 3)) == -I/sqrt(3)
|
| 311 |
+
|
| 312 |
+
assert coth(pi*I/4) == -I
|
| 313 |
+
assert coth(-pi*I/4) == I
|
| 314 |
+
assert coth(pi*I*Rational(17, 4)) == -I
|
| 315 |
+
assert coth(pi*I*Rational(-3, 4)) == -I
|
| 316 |
+
|
| 317 |
+
assert coth(pi*I/6) == -sqrt(3)*I
|
| 318 |
+
assert coth(-pi*I/6) == sqrt(3)*I
|
| 319 |
+
assert coth(pi*I*Rational(7, 6)) == -sqrt(3)*I
|
| 320 |
+
assert coth(pi*I*Rational(-5, 6)) == -sqrt(3)*I
|
| 321 |
+
|
| 322 |
+
assert coth(pi*I/105) == -cot(pi/105)*I
|
| 323 |
+
assert coth(-pi*I/105) == cot(pi/105)*I
|
| 324 |
+
|
| 325 |
+
assert unchanged(coth, 2 + 3*I)
|
| 326 |
+
|
| 327 |
+
assert coth(x*I) == -cot(x)*I
|
| 328 |
+
|
| 329 |
+
assert coth(k*pi*I) == -cot(k*pi)*I
|
| 330 |
+
assert coth(17*k*pi*I) == -cot(17*k*pi)*I
|
| 331 |
+
|
| 332 |
+
assert coth(k*pi*I) == -cot(k*pi)*I
|
| 333 |
+
|
| 334 |
+
assert coth(log(tan(2))) == coth(log(-tan(2)))
|
| 335 |
+
assert coth(1 + I*pi/2) == tanh(1)
|
| 336 |
+
|
| 337 |
+
assert coth(x).as_real_imag(deep=False) == (sinh(re(x))*cosh(re(x))/(sin(im(x))**2
|
| 338 |
+
+ sinh(re(x))**2),
|
| 339 |
+
-sin(im(x))*cos(im(x))/(sin(im(x))**2 + sinh(re(x))**2))
|
| 340 |
+
x = Symbol('x', extended_real=True)
|
| 341 |
+
assert coth(x).as_real_imag(deep=False) == (coth(x), 0)
|
| 342 |
+
|
| 343 |
+
assert expand_trig(coth(2*x)) == (coth(x)**2 + 1)/(2*coth(x))
|
| 344 |
+
assert expand_trig(coth(3*x)) == (coth(x)**3 + 3*coth(x))/(1 + 3*coth(x)**2)
|
| 345 |
+
|
| 346 |
+
assert expand_trig(coth(x + y)) == (1 + coth(x)*coth(y))/(coth(x) + coth(y))
|
| 347 |
+
|
| 348 |
+
|
| 349 |
+
def test_coth_series():
|
| 350 |
+
x = Symbol('x')
|
| 351 |
+
assert coth(x).series(x, 0, 8) == \
|
| 352 |
+
1/x + x/3 - x**3/45 + 2*x**5/945 - x**7/4725 + O(x**8)
|
| 353 |
+
|
| 354 |
+
|
| 355 |
+
def test_coth_fdiff():
|
| 356 |
+
x = Symbol('x')
|
| 357 |
+
raises(ArgumentIndexError, lambda: coth(x).fdiff(2))
|
| 358 |
+
|
| 359 |
+
|
| 360 |
+
def test_csch():
|
| 361 |
+
x, y = symbols('x,y')
|
| 362 |
+
|
| 363 |
+
k = Symbol('k', integer=True)
|
| 364 |
+
n = Symbol('n', positive=True)
|
| 365 |
+
|
| 366 |
+
assert csch(nan) is nan
|
| 367 |
+
assert csch(zoo) is nan
|
| 368 |
+
|
| 369 |
+
assert csch(oo) == 0
|
| 370 |
+
assert csch(-oo) == 0
|
| 371 |
+
|
| 372 |
+
assert csch(0) is zoo
|
| 373 |
+
|
| 374 |
+
assert csch(-1) == -csch(1)
|
| 375 |
+
|
| 376 |
+
assert csch(-x) == -csch(x)
|
| 377 |
+
assert csch(-pi) == -csch(pi)
|
| 378 |
+
assert csch(-2**1024 * E) == -csch(2**1024 * E)
|
| 379 |
+
|
| 380 |
+
assert csch(pi*I) is zoo
|
| 381 |
+
assert csch(-pi*I) is zoo
|
| 382 |
+
assert csch(2*pi*I) is zoo
|
| 383 |
+
assert csch(-2*pi*I) is zoo
|
| 384 |
+
assert csch(-3*10**73*pi*I) is zoo
|
| 385 |
+
assert csch(7*10**103*pi*I) is zoo
|
| 386 |
+
|
| 387 |
+
assert csch(pi*I/2) == -I
|
| 388 |
+
assert csch(-pi*I/2) == I
|
| 389 |
+
assert csch(pi*I*Rational(5, 2)) == -I
|
| 390 |
+
assert csch(pi*I*Rational(7, 2)) == I
|
| 391 |
+
|
| 392 |
+
assert csch(pi*I/3) == -2/sqrt(3)*I
|
| 393 |
+
assert csch(pi*I*Rational(-2, 3)) == 2/sqrt(3)*I
|
| 394 |
+
|
| 395 |
+
assert csch(pi*I/4) == -sqrt(2)*I
|
| 396 |
+
assert csch(-pi*I/4) == sqrt(2)*I
|
| 397 |
+
assert csch(pi*I*Rational(7, 4)) == sqrt(2)*I
|
| 398 |
+
assert csch(pi*I*Rational(-3, 4)) == sqrt(2)*I
|
| 399 |
+
|
| 400 |
+
assert csch(pi*I/6) == -2*I
|
| 401 |
+
assert csch(-pi*I/6) == 2*I
|
| 402 |
+
assert csch(pi*I*Rational(7, 6)) == 2*I
|
| 403 |
+
assert csch(pi*I*Rational(-7, 6)) == -2*I
|
| 404 |
+
assert csch(pi*I*Rational(-5, 6)) == 2*I
|
| 405 |
+
|
| 406 |
+
assert csch(pi*I/105) == -1/sin(pi/105)*I
|
| 407 |
+
assert csch(-pi*I/105) == 1/sin(pi/105)*I
|
| 408 |
+
|
| 409 |
+
assert csch(x*I) == -1/sin(x)*I
|
| 410 |
+
|
| 411 |
+
assert csch(k*pi*I) is zoo
|
| 412 |
+
assert csch(17*k*pi*I) is zoo
|
| 413 |
+
|
| 414 |
+
assert csch(k*pi*I/2) == -1/sin(k*pi/2)*I
|
| 415 |
+
|
| 416 |
+
assert csch(n).is_real is True
|
| 417 |
+
|
| 418 |
+
assert expand_trig(csch(x + y)) == 1/(sinh(x)*cosh(y) + cosh(x)*sinh(y))
|
| 419 |
+
|
| 420 |
+
|
| 421 |
+
def test_csch_series():
|
| 422 |
+
x = Symbol('x')
|
| 423 |
+
assert csch(x).series(x, 0, 10) == \
|
| 424 |
+
1/ x - x/6 + 7*x**3/360 - 31*x**5/15120 + 127*x**7/604800 \
|
| 425 |
+
- 73*x**9/3421440 + O(x**10)
|
| 426 |
+
|
| 427 |
+
|
| 428 |
+
def test_csch_fdiff():
|
| 429 |
+
x = Symbol('x')
|
| 430 |
+
raises(ArgumentIndexError, lambda: csch(x).fdiff(2))
|
| 431 |
+
|
| 432 |
+
|
| 433 |
+
def test_sech():
|
| 434 |
+
x, y = symbols('x, y')
|
| 435 |
+
|
| 436 |
+
k = Symbol('k', integer=True)
|
| 437 |
+
n = Symbol('n', positive=True)
|
| 438 |
+
|
| 439 |
+
assert sech(nan) is nan
|
| 440 |
+
assert sech(zoo) is nan
|
| 441 |
+
|
| 442 |
+
assert sech(oo) == 0
|
| 443 |
+
assert sech(-oo) == 0
|
| 444 |
+
|
| 445 |
+
assert sech(0) == 1
|
| 446 |
+
|
| 447 |
+
assert sech(-1) == sech(1)
|
| 448 |
+
assert sech(-x) == sech(x)
|
| 449 |
+
|
| 450 |
+
assert sech(pi*I) == sec(pi)
|
| 451 |
+
|
| 452 |
+
assert sech(-pi*I) == sec(pi)
|
| 453 |
+
assert sech(-2**1024 * E) == sech(2**1024 * E)
|
| 454 |
+
|
| 455 |
+
assert sech(pi*I/2) is zoo
|
| 456 |
+
assert sech(-pi*I/2) is zoo
|
| 457 |
+
assert sech((-3*10**73 + 1)*pi*I/2) is zoo
|
| 458 |
+
assert sech((7*10**103 + 1)*pi*I/2) is zoo
|
| 459 |
+
|
| 460 |
+
assert sech(pi*I) == -1
|
| 461 |
+
assert sech(-pi*I) == -1
|
| 462 |
+
assert sech(5*pi*I) == -1
|
| 463 |
+
assert sech(8*pi*I) == 1
|
| 464 |
+
|
| 465 |
+
assert sech(pi*I/3) == 2
|
| 466 |
+
assert sech(pi*I*Rational(-2, 3)) == -2
|
| 467 |
+
|
| 468 |
+
assert sech(pi*I/4) == sqrt(2)
|
| 469 |
+
assert sech(-pi*I/4) == sqrt(2)
|
| 470 |
+
assert sech(pi*I*Rational(5, 4)) == -sqrt(2)
|
| 471 |
+
assert sech(pi*I*Rational(-5, 4)) == -sqrt(2)
|
| 472 |
+
|
| 473 |
+
assert sech(pi*I/6) == 2/sqrt(3)
|
| 474 |
+
assert sech(-pi*I/6) == 2/sqrt(3)
|
| 475 |
+
assert sech(pi*I*Rational(7, 6)) == -2/sqrt(3)
|
| 476 |
+
assert sech(pi*I*Rational(-5, 6)) == -2/sqrt(3)
|
| 477 |
+
|
| 478 |
+
assert sech(pi*I/105) == 1/cos(pi/105)
|
| 479 |
+
assert sech(-pi*I/105) == 1/cos(pi/105)
|
| 480 |
+
|
| 481 |
+
assert sech(x*I) == 1/cos(x)
|
| 482 |
+
|
| 483 |
+
assert sech(k*pi*I) == 1/cos(k*pi)
|
| 484 |
+
assert sech(17*k*pi*I) == 1/cos(17*k*pi)
|
| 485 |
+
|
| 486 |
+
assert sech(n).is_real is True
|
| 487 |
+
|
| 488 |
+
assert expand_trig(sech(x + y)) == 1/(cosh(x)*cosh(y) + sinh(x)*sinh(y))
|
| 489 |
+
|
| 490 |
+
|
| 491 |
+
def test_sech_series():
|
| 492 |
+
x = Symbol('x')
|
| 493 |
+
assert sech(x).series(x, 0, 10) == \
|
| 494 |
+
1 - x**2/2 + 5*x**4/24 - 61*x**6/720 + 277*x**8/8064 + O(x**10)
|
| 495 |
+
|
| 496 |
+
|
| 497 |
+
def test_sech_fdiff():
|
| 498 |
+
x = Symbol('x')
|
| 499 |
+
raises(ArgumentIndexError, lambda: sech(x).fdiff(2))
|
| 500 |
+
|
| 501 |
+
|
| 502 |
+
def test_asinh():
|
| 503 |
+
x, y = symbols('x,y')
|
| 504 |
+
assert unchanged(asinh, x)
|
| 505 |
+
assert asinh(-x) == -asinh(x)
|
| 506 |
+
|
| 507 |
+
# at specific points
|
| 508 |
+
assert asinh(nan) is nan
|
| 509 |
+
assert asinh( 0) == 0
|
| 510 |
+
assert asinh(+1) == log(sqrt(2) + 1)
|
| 511 |
+
|
| 512 |
+
assert asinh(-1) == log(sqrt(2) - 1)
|
| 513 |
+
assert asinh(I) == pi*I/2
|
| 514 |
+
assert asinh(-I) == -pi*I/2
|
| 515 |
+
assert asinh(I/2) == pi*I/6
|
| 516 |
+
assert asinh(-I/2) == -pi*I/6
|
| 517 |
+
|
| 518 |
+
# at infinites
|
| 519 |
+
assert asinh(oo) is oo
|
| 520 |
+
assert asinh(-oo) is -oo
|
| 521 |
+
|
| 522 |
+
assert asinh(I*oo) is oo
|
| 523 |
+
assert asinh(-I *oo) is -oo
|
| 524 |
+
|
| 525 |
+
assert asinh(zoo) is zoo
|
| 526 |
+
|
| 527 |
+
# properties
|
| 528 |
+
assert asinh(I *(sqrt(3) - 1)/(2**Rational(3, 2))) == pi*I/12
|
| 529 |
+
assert asinh(-I *(sqrt(3) - 1)/(2**Rational(3, 2))) == -pi*I/12
|
| 530 |
+
|
| 531 |
+
assert asinh(I*(sqrt(5) - 1)/4) == pi*I/10
|
| 532 |
+
assert asinh(-I*(sqrt(5) - 1)/4) == -pi*I/10
|
| 533 |
+
|
| 534 |
+
assert asinh(I*(sqrt(5) + 1)/4) == pi*I*Rational(3, 10)
|
| 535 |
+
assert asinh(-I*(sqrt(5) + 1)/4) == pi*I*Rational(-3, 10)
|
| 536 |
+
|
| 537 |
+
# reality
|
| 538 |
+
assert asinh(S(2)).is_real is True
|
| 539 |
+
assert asinh(S(2)).is_finite is True
|
| 540 |
+
assert asinh(S(-2)).is_real is True
|
| 541 |
+
assert asinh(S(oo)).is_extended_real is True
|
| 542 |
+
assert asinh(-S(oo)).is_real is False
|
| 543 |
+
assert (asinh(2) - oo) == -oo
|
| 544 |
+
assert asinh(symbols('y', real=True)).is_real is True
|
| 545 |
+
|
| 546 |
+
# Symmetry
|
| 547 |
+
assert asinh(Rational(-1, 2)) == -asinh(S.Half)
|
| 548 |
+
|
| 549 |
+
# inverse composition
|
| 550 |
+
assert unchanged(asinh, sinh(Symbol('v1')))
|
| 551 |
+
|
| 552 |
+
assert asinh(sinh(0, evaluate=False)) == 0
|
| 553 |
+
assert asinh(sinh(-3, evaluate=False)) == -3
|
| 554 |
+
assert asinh(sinh(2, evaluate=False)) == 2
|
| 555 |
+
assert asinh(sinh(I, evaluate=False)) == I
|
| 556 |
+
assert asinh(sinh(-I, evaluate=False)) == -I
|
| 557 |
+
assert asinh(sinh(5*I, evaluate=False)) == -2*I*pi + 5*I
|
| 558 |
+
assert asinh(sinh(15 + 11*I)) == 15 - 4*I*pi + 11*I
|
| 559 |
+
assert asinh(sinh(-73 + 97*I)) == 73 - 97*I + 31*I*pi
|
| 560 |
+
assert asinh(sinh(-7 - 23*I)) == 7 - 7*I*pi + 23*I
|
| 561 |
+
assert asinh(sinh(13 - 3*I)) == -13 - I*pi + 3*I
|
| 562 |
+
p = Symbol('p', positive=True)
|
| 563 |
+
assert asinh(p).is_zero is False
|
| 564 |
+
assert asinh(sinh(0, evaluate=False), evaluate=False).is_zero is True
|
| 565 |
+
|
| 566 |
+
|
| 567 |
+
def test_asinh_rewrite():
|
| 568 |
+
x = Symbol('x')
|
| 569 |
+
assert asinh(x).rewrite(log) == log(x + sqrt(x**2 + 1))
|
| 570 |
+
assert asinh(x).rewrite(atanh) == atanh(x/sqrt(1 + x**2))
|
| 571 |
+
assert asinh(x).rewrite(asin) == -I*asin(I*x, evaluate=False)
|
| 572 |
+
assert asinh(x*(1 + I)).rewrite(asin) == -I*asin(I*x*(1+I))
|
| 573 |
+
assert asinh(x).rewrite(acos) == I*acos(I*x, evaluate=False) - I*pi/2
|
| 574 |
+
|
| 575 |
+
|
| 576 |
+
def test_asinh_leading_term():
|
| 577 |
+
x = Symbol('x')
|
| 578 |
+
assert asinh(x).as_leading_term(x, cdir=1) == x
|
| 579 |
+
# Tests concerning branch points
|
| 580 |
+
assert asinh(x + I).as_leading_term(x, cdir=1) == I*pi/2
|
| 581 |
+
assert asinh(x - I).as_leading_term(x, cdir=1) == -I*pi/2
|
| 582 |
+
assert asinh(1/x).as_leading_term(x, cdir=1) == -log(x) + log(2)
|
| 583 |
+
assert asinh(1/x).as_leading_term(x, cdir=-1) == log(x) - log(2) - I*pi
|
| 584 |
+
# Tests concerning points lying on branch cuts
|
| 585 |
+
assert asinh(x + 2*I).as_leading_term(x, cdir=1) == I*asin(2)
|
| 586 |
+
assert asinh(x + 2*I).as_leading_term(x, cdir=-1) == -I*asin(2) + I*pi
|
| 587 |
+
assert asinh(x - 2*I).as_leading_term(x, cdir=1) == -I*pi + I*asin(2)
|
| 588 |
+
assert asinh(x - 2*I).as_leading_term(x, cdir=-1) == -I*asin(2)
|
| 589 |
+
# Tests concerning re(ndir) == 0
|
| 590 |
+
assert asinh(2*I + I*x - x**2).as_leading_term(x, cdir=1) == log(2 - sqrt(3)) + I*pi/2
|
| 591 |
+
assert asinh(2*I + I*x - x**2).as_leading_term(x, cdir=-1) == log(2 - sqrt(3)) + I*pi/2
|
| 592 |
+
|
| 593 |
+
|
| 594 |
+
def test_asinh_series():
|
| 595 |
+
x = Symbol('x')
|
| 596 |
+
assert asinh(x).series(x, 0, 8) == \
|
| 597 |
+
x - x**3/6 + 3*x**5/40 - 5*x**7/112 + O(x**8)
|
| 598 |
+
t5 = asinh(x).taylor_term(5, x)
|
| 599 |
+
assert t5 == 3*x**5/40
|
| 600 |
+
assert asinh(x).taylor_term(7, x, t5, 0) == -5*x**7/112
|
| 601 |
+
|
| 602 |
+
|
| 603 |
+
def test_asinh_nseries():
|
| 604 |
+
x = Symbol('x')
|
| 605 |
+
# Tests concerning branch points
|
| 606 |
+
assert asinh(x + I)._eval_nseries(x, 4, None) == I*pi/2 + \
|
| 607 |
+
sqrt(x)*(1 - I) + x**(S(3)/2)*(S(1)/12 + I/12) + x**(S(5)/2)*(-S(3)/160 + 3*I/160) + \
|
| 608 |
+
x**(S(7)/2)*(-S(5)/896 - 5*I/896) + O(x**4)
|
| 609 |
+
assert asinh(x - I)._eval_nseries(x, 4, None) == -I*pi/2 + \
|
| 610 |
+
sqrt(x)*(1 + I) + x**(S(3)/2)*(S(1)/12 - I/12) + x**(S(5)/2)*(-S(3)/160 - 3*I/160) + \
|
| 611 |
+
x**(S(7)/2)*(-S(5)/896 + 5*I/896) + O(x**4)
|
| 612 |
+
# Tests concerning points lying on branch cuts
|
| 613 |
+
assert asinh(x + 2*I)._eval_nseries(x, 4, None, cdir=1) == I*asin(2) - \
|
| 614 |
+
sqrt(3)*I*x/3 + sqrt(3)*x**2/9 + sqrt(3)*I*x**3/18 + O(x**4)
|
| 615 |
+
assert asinh(x + 2*I)._eval_nseries(x, 4, None, cdir=-1) == I*pi - I*asin(2) + \
|
| 616 |
+
sqrt(3)*I*x/3 - sqrt(3)*x**2/9 - sqrt(3)*I*x**3/18 + O(x**4)
|
| 617 |
+
assert asinh(x - 2*I)._eval_nseries(x, 4, None, cdir=1) == I*asin(2) - I*pi + \
|
| 618 |
+
sqrt(3)*I*x/3 + sqrt(3)*x**2/9 - sqrt(3)*I*x**3/18 + O(x**4)
|
| 619 |
+
assert asinh(x - 2*I)._eval_nseries(x, 4, None, cdir=-1) == -I*asin(2) - \
|
| 620 |
+
sqrt(3)*I*x/3 - sqrt(3)*x**2/9 + sqrt(3)*I*x**3/18 + O(x**4)
|
| 621 |
+
# Tests concerning re(ndir) == 0
|
| 622 |
+
assert asinh(2*I + I*x - x**2)._eval_nseries(x, 4, None) == I*pi/2 + log(2 - sqrt(3)) - \
|
| 623 |
+
sqrt(3)*x/3 + x**2*(sqrt(3)/9 - sqrt(3)*I/3) + x**3*(-sqrt(3)/18 + 2*sqrt(3)*I/9) + O(x**4)
|
| 624 |
+
|
| 625 |
+
|
| 626 |
+
def test_asinh_fdiff():
|
| 627 |
+
x = Symbol('x')
|
| 628 |
+
raises(ArgumentIndexError, lambda: asinh(x).fdiff(2))
|
| 629 |
+
|
| 630 |
+
|
| 631 |
+
def test_acosh():
|
| 632 |
+
x = Symbol('x')
|
| 633 |
+
|
| 634 |
+
assert unchanged(acosh, -x)
|
| 635 |
+
|
| 636 |
+
#at specific points
|
| 637 |
+
assert acosh(1) == 0
|
| 638 |
+
assert acosh(-1) == pi*I
|
| 639 |
+
assert acosh(0) == I*pi/2
|
| 640 |
+
assert acosh(S.Half) == I*pi/3
|
| 641 |
+
assert acosh(Rational(-1, 2)) == pi*I*Rational(2, 3)
|
| 642 |
+
assert acosh(nan) is nan
|
| 643 |
+
|
| 644 |
+
# at infinites
|
| 645 |
+
assert acosh(oo) is oo
|
| 646 |
+
assert acosh(-oo) is oo
|
| 647 |
+
|
| 648 |
+
assert acosh(I*oo) == oo + I*pi/2
|
| 649 |
+
assert acosh(-I*oo) == oo - I*pi/2
|
| 650 |
+
|
| 651 |
+
assert acosh(zoo) is zoo
|
| 652 |
+
|
| 653 |
+
assert acosh(I) == log(I*(1 + sqrt(2)))
|
| 654 |
+
assert acosh(-I) == log(-I*(1 + sqrt(2)))
|
| 655 |
+
assert acosh((sqrt(3) - 1)/(2*sqrt(2))) == pi*I*Rational(5, 12)
|
| 656 |
+
assert acosh(-(sqrt(3) - 1)/(2*sqrt(2))) == pi*I*Rational(7, 12)
|
| 657 |
+
assert acosh(sqrt(2)/2) == I*pi/4
|
| 658 |
+
assert acosh(-sqrt(2)/2) == I*pi*Rational(3, 4)
|
| 659 |
+
assert acosh(sqrt(3)/2) == I*pi/6
|
| 660 |
+
assert acosh(-sqrt(3)/2) == I*pi*Rational(5, 6)
|
| 661 |
+
assert acosh(sqrt(2 + sqrt(2))/2) == I*pi/8
|
| 662 |
+
assert acosh(-sqrt(2 + sqrt(2))/2) == I*pi*Rational(7, 8)
|
| 663 |
+
assert acosh(sqrt(2 - sqrt(2))/2) == I*pi*Rational(3, 8)
|
| 664 |
+
assert acosh(-sqrt(2 - sqrt(2))/2) == I*pi*Rational(5, 8)
|
| 665 |
+
assert acosh((1 + sqrt(3))/(2*sqrt(2))) == I*pi/12
|
| 666 |
+
assert acosh(-(1 + sqrt(3))/(2*sqrt(2))) == I*pi*Rational(11, 12)
|
| 667 |
+
assert acosh((sqrt(5) + 1)/4) == I*pi/5
|
| 668 |
+
assert acosh(-(sqrt(5) + 1)/4) == I*pi*Rational(4, 5)
|
| 669 |
+
|
| 670 |
+
assert str(acosh(5*I).n(6)) == '2.31244 + 1.5708*I'
|
| 671 |
+
assert str(acosh(-5*I).n(6)) == '2.31244 - 1.5708*I'
|
| 672 |
+
|
| 673 |
+
# inverse composition
|
| 674 |
+
assert unchanged(acosh, Symbol('v1'))
|
| 675 |
+
|
| 676 |
+
assert acosh(cosh(-3, evaluate=False)) == 3
|
| 677 |
+
assert acosh(cosh(3, evaluate=False)) == 3
|
| 678 |
+
assert acosh(cosh(0, evaluate=False)) == 0
|
| 679 |
+
assert acosh(cosh(I, evaluate=False)) == I
|
| 680 |
+
assert acosh(cosh(-I, evaluate=False)) == I
|
| 681 |
+
assert acosh(cosh(7*I, evaluate=False)) == -2*I*pi + 7*I
|
| 682 |
+
assert acosh(cosh(1 + I)) == 1 + I
|
| 683 |
+
assert acosh(cosh(3 - 3*I)) == 3 - 3*I
|
| 684 |
+
assert acosh(cosh(-3 + 2*I)) == 3 - 2*I
|
| 685 |
+
assert acosh(cosh(-5 - 17*I)) == 5 - 6*I*pi + 17*I
|
| 686 |
+
assert acosh(cosh(-21 + 11*I)) == 21 - 11*I + 4*I*pi
|
| 687 |
+
assert acosh(cosh(cosh(1) + I)) == cosh(1) + I
|
| 688 |
+
assert acosh(1, evaluate=False).is_zero is True
|
| 689 |
+
|
| 690 |
+
# Reality
|
| 691 |
+
assert acosh(S(2)).is_real is True
|
| 692 |
+
assert acosh(S(2)).is_extended_real is True
|
| 693 |
+
assert acosh(oo).is_extended_real is True
|
| 694 |
+
assert acosh(S(2)).is_finite is True
|
| 695 |
+
assert acosh(S(1) / 5).is_real is False
|
| 696 |
+
assert (acosh(2) - oo) == -oo
|
| 697 |
+
assert acosh(symbols('y', real=True)).is_real is None
|
| 698 |
+
|
| 699 |
+
|
| 700 |
+
def test_acosh_rewrite():
|
| 701 |
+
x = Symbol('x')
|
| 702 |
+
assert acosh(x).rewrite(log) == log(x + sqrt(x - 1)*sqrt(x + 1))
|
| 703 |
+
assert acosh(x).rewrite(asin) == sqrt(x - 1)*(-asin(x) + pi/2)/sqrt(1 - x)
|
| 704 |
+
assert acosh(x).rewrite(asinh) == sqrt(x - 1)*(I*asinh(I*x, evaluate=False) + pi/2)/sqrt(1 - x)
|
| 705 |
+
assert acosh(x).rewrite(atanh) == \
|
| 706 |
+
(sqrt(x - 1)*sqrt(x + 1)*atanh(sqrt(x**2 - 1)/x)/sqrt(x**2 - 1) +
|
| 707 |
+
pi*sqrt(x - 1)*(-x*sqrt(x**(-2)) + 1)/(2*sqrt(1 - x)))
|
| 708 |
+
x = Symbol('x', positive=True)
|
| 709 |
+
assert acosh(x).rewrite(atanh) == \
|
| 710 |
+
sqrt(x - 1)*sqrt(x + 1)*atanh(sqrt(x**2 - 1)/x)/sqrt(x**2 - 1)
|
| 711 |
+
|
| 712 |
+
|
| 713 |
+
def test_acosh_leading_term():
|
| 714 |
+
x = Symbol('x')
|
| 715 |
+
# Tests concerning branch points
|
| 716 |
+
assert acosh(x).as_leading_term(x) == I*pi/2
|
| 717 |
+
assert acosh(x + 1).as_leading_term(x) == sqrt(2)*sqrt(x)
|
| 718 |
+
assert acosh(x - 1).as_leading_term(x) == I*pi
|
| 719 |
+
assert acosh(1/x).as_leading_term(x, cdir=1) == -log(x) + log(2)
|
| 720 |
+
assert acosh(1/x).as_leading_term(x, cdir=-1) == -log(x) + log(2) + 2*I*pi
|
| 721 |
+
# Tests concerning points lying on branch cuts
|
| 722 |
+
assert acosh(I*x - 2).as_leading_term(x, cdir=1) == acosh(-2)
|
| 723 |
+
assert acosh(-I*x - 2).as_leading_term(x, cdir=1) == -2*I*pi + acosh(-2)
|
| 724 |
+
assert acosh(x**2 - I*x + S(1)/3).as_leading_term(x, cdir=1) == -acosh(S(1)/3)
|
| 725 |
+
assert acosh(x**2 - I*x + S(1)/3).as_leading_term(x, cdir=-1) == acosh(S(1)/3)
|
| 726 |
+
assert acosh(1/(I*x - 3)).as_leading_term(x, cdir=1) == -acosh(-S(1)/3)
|
| 727 |
+
assert acosh(1/(I*x - 3)).as_leading_term(x, cdir=-1) == acosh(-S(1)/3)
|
| 728 |
+
# Tests concerning im(ndir) == 0
|
| 729 |
+
assert acosh(-I*x**2 + x - 2).as_leading_term(x, cdir=1) == log(sqrt(3) + 2) - I*pi
|
| 730 |
+
assert acosh(-I*x**2 + x - 2).as_leading_term(x, cdir=-1) == log(sqrt(3) + 2) - I*pi
|
| 731 |
+
|
| 732 |
+
|
| 733 |
+
def test_acosh_series():
|
| 734 |
+
x = Symbol('x')
|
| 735 |
+
assert acosh(x).series(x, 0, 8) == \
|
| 736 |
+
-I*x + pi*I/2 - I*x**3/6 - 3*I*x**5/40 - 5*I*x**7/112 + O(x**8)
|
| 737 |
+
t5 = acosh(x).taylor_term(5, x)
|
| 738 |
+
assert t5 == - 3*I*x**5/40
|
| 739 |
+
assert acosh(x).taylor_term(7, x, t5, 0) == - 5*I*x**7/112
|
| 740 |
+
|
| 741 |
+
|
| 742 |
+
def test_acosh_nseries():
|
| 743 |
+
x = Symbol('x')
|
| 744 |
+
# Tests concerning branch points
|
| 745 |
+
assert acosh(x + 1)._eval_nseries(x, 4, None) == sqrt(2)*sqrt(x) - \
|
| 746 |
+
sqrt(2)*x**(S(3)/2)/12 + 3*sqrt(2)*x**(S(5)/2)/160 - 5*sqrt(2)*x**(S(7)/2)/896 + O(x**4)
|
| 747 |
+
# Tests concerning points lying on branch cuts
|
| 748 |
+
assert acosh(x - 1)._eval_nseries(x, 4, None) == I*pi - \
|
| 749 |
+
sqrt(2)*I*sqrt(x) - sqrt(2)*I*x**(S(3)/2)/12 - 3*sqrt(2)*I*x**(S(5)/2)/160 - \
|
| 750 |
+
5*sqrt(2)*I*x**(S(7)/2)/896 + O(x**4)
|
| 751 |
+
assert acosh(I*x - 2)._eval_nseries(x, 4, None, cdir=1) == acosh(-2) - \
|
| 752 |
+
sqrt(3)*I*x/3 + sqrt(3)*x**2/9 + sqrt(3)*I*x**3/18 + O(x**4)
|
| 753 |
+
assert acosh(-I*x - 2)._eval_nseries(x, 4, None, cdir=1) == acosh(-2) - \
|
| 754 |
+
2*I*pi + sqrt(3)*I*x/3 + sqrt(3)*x**2/9 - sqrt(3)*I*x**3/18 + O(x**4)
|
| 755 |
+
assert acosh(1/(I*x - 3))._eval_nseries(x, 4, None, cdir=1) == -acosh(-S(1)/3) + \
|
| 756 |
+
sqrt(2)*x/12 + 17*sqrt(2)*I*x**2/576 - 443*sqrt(2)*x**3/41472 + O(x**4)
|
| 757 |
+
assert acosh(1/(I*x - 3))._eval_nseries(x, 4, None, cdir=-1) == acosh(-S(1)/3) - \
|
| 758 |
+
sqrt(2)*x/12 - 17*sqrt(2)*I*x**2/576 + 443*sqrt(2)*x**3/41472 + O(x**4)
|
| 759 |
+
# Tests concerning im(ndir) == 0
|
| 760 |
+
assert acosh(-I*x**2 + x - 2)._eval_nseries(x, 4, None) == -I*pi + log(sqrt(3) + 2) - \
|
| 761 |
+
sqrt(3)*x/3 + x**2*(-sqrt(3)/9 + sqrt(3)*I/3) + x**3*(-sqrt(3)/18 + 2*sqrt(3)*I/9) + O(x**4)
|
| 762 |
+
|
| 763 |
+
|
| 764 |
+
def test_acosh_fdiff():
|
| 765 |
+
x = Symbol('x')
|
| 766 |
+
raises(ArgumentIndexError, lambda: acosh(x).fdiff(2))
|
| 767 |
+
|
| 768 |
+
|
| 769 |
+
def test_asech():
|
| 770 |
+
x = Symbol('x')
|
| 771 |
+
|
| 772 |
+
assert unchanged(asech, -x)
|
| 773 |
+
|
| 774 |
+
# values at fixed points
|
| 775 |
+
assert asech(1) == 0
|
| 776 |
+
assert asech(-1) == pi*I
|
| 777 |
+
assert asech(0) is oo
|
| 778 |
+
assert asech(2) == I*pi/3
|
| 779 |
+
assert asech(-2) == 2*I*pi / 3
|
| 780 |
+
assert asech(nan) is nan
|
| 781 |
+
|
| 782 |
+
# at infinites
|
| 783 |
+
assert asech(oo) == I*pi/2
|
| 784 |
+
assert asech(-oo) == I*pi/2
|
| 785 |
+
assert asech(zoo) == I*AccumBounds(-pi/2, pi/2)
|
| 786 |
+
|
| 787 |
+
assert asech(I) == log(1 + sqrt(2)) - I*pi/2
|
| 788 |
+
assert asech(-I) == log(1 + sqrt(2)) + I*pi/2
|
| 789 |
+
assert asech(sqrt(2) - sqrt(6)) == 11*I*pi / 12
|
| 790 |
+
assert asech(sqrt(2 - 2/sqrt(5))) == I*pi / 10
|
| 791 |
+
assert asech(-sqrt(2 - 2/sqrt(5))) == 9*I*pi / 10
|
| 792 |
+
assert asech(2 / sqrt(2 + sqrt(2))) == I*pi / 8
|
| 793 |
+
assert asech(-2 / sqrt(2 + sqrt(2))) == 7*I*pi / 8
|
| 794 |
+
assert asech(sqrt(5) - 1) == I*pi / 5
|
| 795 |
+
assert asech(1 - sqrt(5)) == 4*I*pi / 5
|
| 796 |
+
assert asech(-sqrt(2*(2 + sqrt(2)))) == 5*I*pi / 8
|
| 797 |
+
|
| 798 |
+
# properties
|
| 799 |
+
# asech(x) == acosh(1/x)
|
| 800 |
+
assert asech(sqrt(2)) == acosh(1/sqrt(2))
|
| 801 |
+
assert asech(2/sqrt(3)) == acosh(sqrt(3)/2)
|
| 802 |
+
assert asech(2/sqrt(2 + sqrt(2))) == acosh(sqrt(2 + sqrt(2))/2)
|
| 803 |
+
assert asech(2) == acosh(S.Half)
|
| 804 |
+
|
| 805 |
+
# reality
|
| 806 |
+
assert asech(S(2)).is_real is False
|
| 807 |
+
assert asech(-S(1) / 3).is_real is False
|
| 808 |
+
assert asech(S(2) / 3).is_finite is True
|
| 809 |
+
assert asech(S(0)).is_real is False
|
| 810 |
+
assert asech(S(0)).is_extended_real is True
|
| 811 |
+
assert asech(symbols('y', real=True)).is_real is None
|
| 812 |
+
|
| 813 |
+
# asech(x) == I*acos(1/x)
|
| 814 |
+
# (Note: the exact formula is asech(x) == +/- I*acos(1/x))
|
| 815 |
+
assert asech(-sqrt(2)) == I*acos(-1/sqrt(2))
|
| 816 |
+
assert asech(-2/sqrt(3)) == I*acos(-sqrt(3)/2)
|
| 817 |
+
assert asech(-S(2)) == I*acos(Rational(-1, 2))
|
| 818 |
+
assert asech(-2/sqrt(2)) == I*acos(-sqrt(2)/2)
|
| 819 |
+
|
| 820 |
+
# sech(asech(x)) / x == 1
|
| 821 |
+
assert expand_mul(sech(asech(sqrt(6) - sqrt(2))) / (sqrt(6) - sqrt(2))) == 1
|
| 822 |
+
assert expand_mul(sech(asech(sqrt(6) + sqrt(2))) / (sqrt(6) + sqrt(2))) == 1
|
| 823 |
+
assert (sech(asech(sqrt(2 + 2/sqrt(5)))) / (sqrt(2 + 2/sqrt(5)))).simplify() == 1
|
| 824 |
+
assert (sech(asech(-sqrt(2 + 2/sqrt(5)))) / (-sqrt(2 + 2/sqrt(5)))).simplify() == 1
|
| 825 |
+
assert (sech(asech(sqrt(2*(2 + sqrt(2))))) / (sqrt(2*(2 + sqrt(2))))).simplify() == 1
|
| 826 |
+
assert expand_mul(sech(asech(1 + sqrt(5))) / (1 + sqrt(5))) == 1
|
| 827 |
+
assert expand_mul(sech(asech(-1 - sqrt(5))) / (-1 - sqrt(5))) == 1
|
| 828 |
+
assert expand_mul(sech(asech(-sqrt(6) - sqrt(2))) / (-sqrt(6) - sqrt(2))) == 1
|
| 829 |
+
|
| 830 |
+
# numerical evaluation
|
| 831 |
+
assert str(asech(5*I).n(6)) == '0.19869 - 1.5708*I'
|
| 832 |
+
assert str(asech(-5*I).n(6)) == '0.19869 + 1.5708*I'
|
| 833 |
+
|
| 834 |
+
|
| 835 |
+
def test_asech_leading_term():
|
| 836 |
+
x = Symbol('x')
|
| 837 |
+
# Tests concerning branch points
|
| 838 |
+
assert asech(x).as_leading_term(x, cdir=1) == -log(x) + log(2)
|
| 839 |
+
assert asech(x).as_leading_term(x, cdir=-1) == -log(x) + log(2) + 2*I*pi
|
| 840 |
+
assert asech(x + 1).as_leading_term(x, cdir=1) == sqrt(2)*I*sqrt(x)
|
| 841 |
+
assert asech(1/x).as_leading_term(x, cdir=1) == I*pi/2
|
| 842 |
+
# Tests concerning points lying on branch cuts
|
| 843 |
+
assert asech(x - 1).as_leading_term(x, cdir=1) == I*pi
|
| 844 |
+
assert asech(I*x + 3).as_leading_term(x, cdir=1) == -asech(3)
|
| 845 |
+
assert asech(-I*x + 3).as_leading_term(x, cdir=1) == asech(3)
|
| 846 |
+
assert asech(I*x - 3).as_leading_term(x, cdir=1) == -asech(-3)
|
| 847 |
+
assert asech(-I*x - 3).as_leading_term(x, cdir=1) == asech(-3)
|
| 848 |
+
assert asech(I*x - S(1)/3).as_leading_term(x, cdir=1) == -2*I*pi + asech(-S(1)/3)
|
| 849 |
+
assert asech(I*x - S(1)/3).as_leading_term(x, cdir=-1) == asech(-S(1)/3)
|
| 850 |
+
# Tests concerning im(ndir) == 0
|
| 851 |
+
assert asech(-I*x**2 + x - 3).as_leading_term(x, cdir=1) == log(-S(1)/3 + 2*sqrt(2)*I/3)
|
| 852 |
+
assert asech(-I*x**2 + x - 3).as_leading_term(x, cdir=-1) == log(-S(1)/3 + 2*sqrt(2)*I/3)
|
| 853 |
+
|
| 854 |
+
|
| 855 |
+
def test_asech_series():
|
| 856 |
+
x = Symbol('x')
|
| 857 |
+
assert asech(x).series(x, 0, 9, cdir=1) == log(2) - log(x) - x**2/4 - 3*x**4/32 \
|
| 858 |
+
- 5*x**6/96 - 35*x**8/1024 + O(x**9)
|
| 859 |
+
assert asech(x).series(x, 0, 9, cdir=-1) == I*pi + log(2) - log(-x) - x**2/4 - \
|
| 860 |
+
3*x**4/32 - 5*x**6/96 - 35*x**8/1024 + O(x**9)
|
| 861 |
+
t6 = asech(x).taylor_term(6, x)
|
| 862 |
+
assert t6 == -5*x**6/96
|
| 863 |
+
assert asech(x).taylor_term(8, x, t6, 0) == -35*x**8/1024
|
| 864 |
+
|
| 865 |
+
|
| 866 |
+
def test_asech_nseries():
|
| 867 |
+
x = Symbol('x')
|
| 868 |
+
# Tests concerning branch points
|
| 869 |
+
assert asech(x + 1)._eval_nseries(x, 4, None) == sqrt(2)*sqrt(-x) + 5*sqrt(2)*(-x)**(S(3)/2)/12 + \
|
| 870 |
+
43*sqrt(2)*(-x)**(S(5)/2)/160 + 177*sqrt(2)*(-x)**(S(7)/2)/896 + O(x**4)
|
| 871 |
+
# Tests concerning points lying on branch cuts
|
| 872 |
+
assert asech(x - 1)._eval_nseries(x, 4, None) == I*pi + sqrt(2)*sqrt(x) + \
|
| 873 |
+
5*sqrt(2)*x**(S(3)/2)/12 + 43*sqrt(2)*x**(S(5)/2)/160 + 177*sqrt(2)*x**(S(7)/2)/896 + O(x**4)
|
| 874 |
+
assert asech(I*x + 3)._eval_nseries(x, 4, None) == -asech(3) + sqrt(2)*x/12 - \
|
| 875 |
+
17*sqrt(2)*I*x**2/576 - 443*sqrt(2)*x**3/41472 + O(x**4)
|
| 876 |
+
assert asech(-I*x + 3)._eval_nseries(x, 4, None) == asech(3) + sqrt(2)*x/12 + \
|
| 877 |
+
17*sqrt(2)*I*x**2/576 - 443*sqrt(2)*x**3/41472 + O(x**4)
|
| 878 |
+
assert asech(I*x - 3)._eval_nseries(x, 4, None) == -asech(-3) - sqrt(2)*x/12 - \
|
| 879 |
+
17*sqrt(2)*I*x**2/576 + 443*sqrt(2)*x**3/41472 + O(x**4)
|
| 880 |
+
assert asech(-I*x - 3)._eval_nseries(x, 4, None) == asech(-3) - sqrt(2)*x/12 + \
|
| 881 |
+
17*sqrt(2)*I*x**2/576 + 443*sqrt(2)*x**3/41472 + O(x**4)
|
| 882 |
+
# Tests concerning im(ndir) == 0
|
| 883 |
+
assert asech(-I*x**2 + x - 2)._eval_nseries(x, 3, None) == 2*I*pi/3 + sqrt(3)*I*x/6 + \
|
| 884 |
+
x**2*(sqrt(3)/6 + 7*sqrt(3)*I/72) + O(x**3)
|
| 885 |
+
|
| 886 |
+
|
| 887 |
+
def test_asech_rewrite():
|
| 888 |
+
x = Symbol('x')
|
| 889 |
+
assert asech(x).rewrite(log) == log(1/x + sqrt(1/x - 1) * sqrt(1/x + 1))
|
| 890 |
+
assert asech(x).rewrite(acosh) == acosh(1/x)
|
| 891 |
+
assert asech(x).rewrite(asinh) == sqrt(-1 + 1/x)*(I*asinh(I/x, evaluate=False) + pi/2)/sqrt(1 - 1/x)
|
| 892 |
+
assert asech(x).rewrite(atanh) == \
|
| 893 |
+
sqrt(x + 1)*sqrt(1/(x + 1))*atanh(sqrt(1 - x**2)) + I*pi*(-sqrt(x)*sqrt(1/x) + 1 - I*sqrt(x**2)/(2*sqrt(-x**2)) - I*sqrt(-x)/(2*sqrt(x)))
|
| 894 |
+
|
| 895 |
+
|
| 896 |
+
def test_asech_fdiff():
|
| 897 |
+
x = Symbol('x')
|
| 898 |
+
raises(ArgumentIndexError, lambda: asech(x).fdiff(2))
|
| 899 |
+
|
| 900 |
+
|
| 901 |
+
def test_acsch():
|
| 902 |
+
x = Symbol('x')
|
| 903 |
+
|
| 904 |
+
assert unchanged(acsch, x)
|
| 905 |
+
assert acsch(-x) == -acsch(x)
|
| 906 |
+
|
| 907 |
+
# values at fixed points
|
| 908 |
+
assert acsch(1) == log(1 + sqrt(2))
|
| 909 |
+
assert acsch(-1) == - log(1 + sqrt(2))
|
| 910 |
+
assert acsch(0) is zoo
|
| 911 |
+
assert acsch(2) == log((1+sqrt(5))/2)
|
| 912 |
+
assert acsch(-2) == - log((1+sqrt(5))/2)
|
| 913 |
+
|
| 914 |
+
assert acsch(I) == - I*pi/2
|
| 915 |
+
assert acsch(-I) == I*pi/2
|
| 916 |
+
assert acsch(-I*(sqrt(6) + sqrt(2))) == I*pi / 12
|
| 917 |
+
assert acsch(I*(sqrt(2) + sqrt(6))) == -I*pi / 12
|
| 918 |
+
assert acsch(-I*(1 + sqrt(5))) == I*pi / 10
|
| 919 |
+
assert acsch(I*(1 + sqrt(5))) == -I*pi / 10
|
| 920 |
+
assert acsch(-I*2 / sqrt(2 - sqrt(2))) == I*pi / 8
|
| 921 |
+
assert acsch(I*2 / sqrt(2 - sqrt(2))) == -I*pi / 8
|
| 922 |
+
assert acsch(-I*2) == I*pi / 6
|
| 923 |
+
assert acsch(I*2) == -I*pi / 6
|
| 924 |
+
assert acsch(-I*sqrt(2 + 2/sqrt(5))) == I*pi / 5
|
| 925 |
+
assert acsch(I*sqrt(2 + 2/sqrt(5))) == -I*pi / 5
|
| 926 |
+
assert acsch(-I*sqrt(2)) == I*pi / 4
|
| 927 |
+
assert acsch(I*sqrt(2)) == -I*pi / 4
|
| 928 |
+
assert acsch(-I*(sqrt(5)-1)) == 3*I*pi / 10
|
| 929 |
+
assert acsch(I*(sqrt(5)-1)) == -3*I*pi / 10
|
| 930 |
+
assert acsch(-I*2 / sqrt(3)) == I*pi / 3
|
| 931 |
+
assert acsch(I*2 / sqrt(3)) == -I*pi / 3
|
| 932 |
+
assert acsch(-I*2 / sqrt(2 + sqrt(2))) == 3*I*pi / 8
|
| 933 |
+
assert acsch(I*2 / sqrt(2 + sqrt(2))) == -3*I*pi / 8
|
| 934 |
+
assert acsch(-I*sqrt(2 - 2/sqrt(5))) == 2*I*pi / 5
|
| 935 |
+
assert acsch(I*sqrt(2 - 2/sqrt(5))) == -2*I*pi / 5
|
| 936 |
+
assert acsch(-I*(sqrt(6) - sqrt(2))) == 5*I*pi / 12
|
| 937 |
+
assert acsch(I*(sqrt(6) - sqrt(2))) == -5*I*pi / 12
|
| 938 |
+
assert acsch(nan) is nan
|
| 939 |
+
|
| 940 |
+
# properties
|
| 941 |
+
# acsch(x) == asinh(1/x)
|
| 942 |
+
assert acsch(-I*sqrt(2)) == asinh(I/sqrt(2))
|
| 943 |
+
assert acsch(-I*2 / sqrt(3)) == asinh(I*sqrt(3) / 2)
|
| 944 |
+
|
| 945 |
+
# reality
|
| 946 |
+
assert acsch(S(2)).is_real is True
|
| 947 |
+
assert acsch(S(2)).is_finite is True
|
| 948 |
+
assert acsch(S(-2)).is_real is True
|
| 949 |
+
assert acsch(S(oo)).is_extended_real is True
|
| 950 |
+
assert acsch(-S(oo)).is_real is True
|
| 951 |
+
assert (acsch(2) - oo) == -oo
|
| 952 |
+
assert acsch(symbols('y', extended_real=True)).is_extended_real is True
|
| 953 |
+
|
| 954 |
+
# acsch(x) == -I*asin(I/x)
|
| 955 |
+
assert acsch(-I*sqrt(2)) == -I*asin(-1/sqrt(2))
|
| 956 |
+
assert acsch(-I*2 / sqrt(3)) == -I*asin(-sqrt(3)/2)
|
| 957 |
+
|
| 958 |
+
# csch(acsch(x)) / x == 1
|
| 959 |
+
assert expand_mul(csch(acsch(-I*(sqrt(6) + sqrt(2)))) / (-I*(sqrt(6) + sqrt(2)))) == 1
|
| 960 |
+
assert expand_mul(csch(acsch(I*(1 + sqrt(5)))) / (I*(1 + sqrt(5)))) == 1
|
| 961 |
+
assert (csch(acsch(I*sqrt(2 - 2/sqrt(5)))) / (I*sqrt(2 - 2/sqrt(5)))).simplify() == 1
|
| 962 |
+
assert (csch(acsch(-I*sqrt(2 - 2/sqrt(5)))) / (-I*sqrt(2 - 2/sqrt(5)))).simplify() == 1
|
| 963 |
+
|
| 964 |
+
# numerical evaluation
|
| 965 |
+
assert str(acsch(5*I+1).n(6)) == '0.0391819 - 0.193363*I'
|
| 966 |
+
assert str(acsch(-5*I+1).n(6)) == '0.0391819 + 0.193363*I'
|
| 967 |
+
|
| 968 |
+
|
| 969 |
+
def test_acsch_infinities():
|
| 970 |
+
assert acsch(oo) == 0
|
| 971 |
+
assert acsch(-oo) == 0
|
| 972 |
+
assert acsch(zoo) == 0
|
| 973 |
+
|
| 974 |
+
|
| 975 |
+
def test_acsch_leading_term():
|
| 976 |
+
x = Symbol('x')
|
| 977 |
+
assert acsch(1/x).as_leading_term(x) == x
|
| 978 |
+
# Tests concerning branch points
|
| 979 |
+
assert acsch(x + I).as_leading_term(x) == -I*pi/2
|
| 980 |
+
assert acsch(x - I).as_leading_term(x) == I*pi/2
|
| 981 |
+
# Tests concerning points lying on branch cuts
|
| 982 |
+
assert acsch(x).as_leading_term(x, cdir=1) == -log(x) + log(2)
|
| 983 |
+
assert acsch(x).as_leading_term(x, cdir=-1) == log(x) - log(2) - I*pi
|
| 984 |
+
assert acsch(x + I/2).as_leading_term(x, cdir=1) == -I*pi - acsch(I/2)
|
| 985 |
+
assert acsch(x + I/2).as_leading_term(x, cdir=-1) == acsch(I/2)
|
| 986 |
+
assert acsch(x - I/2).as_leading_term(x, cdir=1) == -acsch(I/2)
|
| 987 |
+
assert acsch(x - I/2).as_leading_term(x, cdir=-1) == acsch(I/2) + I*pi
|
| 988 |
+
# Tests concerning re(ndir) == 0
|
| 989 |
+
assert acsch(I/2 + I*x - x**2).as_leading_term(x, cdir=1) == log(2 - sqrt(3)) - I*pi/2
|
| 990 |
+
assert acsch(I/2 + I*x - x**2).as_leading_term(x, cdir=-1) == log(2 - sqrt(3)) - I*pi/2
|
| 991 |
+
|
| 992 |
+
|
| 993 |
+
def test_acsch_series():
|
| 994 |
+
x = Symbol('x')
|
| 995 |
+
assert acsch(x).series(x, 0, 9) == log(2) - log(x) + x**2/4 - 3*x**4/32 \
|
| 996 |
+
+ 5*x**6/96 - 35*x**8/1024 + O(x**9)
|
| 997 |
+
t4 = acsch(x).taylor_term(4, x)
|
| 998 |
+
assert t4 == -3*x**4/32
|
| 999 |
+
assert acsch(x).taylor_term(6, x, t4, 0) == 5*x**6/96
|
| 1000 |
+
|
| 1001 |
+
|
| 1002 |
+
def test_acsch_nseries():
|
| 1003 |
+
x = Symbol('x')
|
| 1004 |
+
# Tests concerning branch points
|
| 1005 |
+
assert acsch(x + I)._eval_nseries(x, 4, None) == -I*pi/2 + I*sqrt(x) + \
|
| 1006 |
+
sqrt(x) + 5*I*x**(S(3)/2)/12 - 5*x**(S(3)/2)/12 - 43*I*x**(S(5)/2)/160 - \
|
| 1007 |
+
43*x**(S(5)/2)/160 - 177*I*x**(S(7)/2)/896 + 177*x**(S(7)/2)/896 + O(x**4)
|
| 1008 |
+
assert acsch(x - I)._eval_nseries(x, 4, None) == I*pi/2 - I*sqrt(x) + \
|
| 1009 |
+
sqrt(x) - 5*I*x**(S(3)/2)/12 - 5*x**(S(3)/2)/12 + 43*I*x**(S(5)/2)/160 - \
|
| 1010 |
+
43*x**(S(5)/2)/160 + 177*I*x**(S(7)/2)/896 + 177*x**(S(7)/2)/896 + O(x**4)
|
| 1011 |
+
# Tests concerning points lying on branch cuts
|
| 1012 |
+
assert acsch(x + I/2)._eval_nseries(x, 4, None, cdir=1) == -acsch(I/2) - \
|
| 1013 |
+
I*pi + 4*sqrt(3)*I*x/3 - 8*sqrt(3)*x**2/9 - 16*sqrt(3)*I*x**3/9 + O(x**4)
|
| 1014 |
+
assert acsch(x + I/2)._eval_nseries(x, 4, None, cdir=-1) == acsch(I/2) - \
|
| 1015 |
+
4*sqrt(3)*I*x/3 + 8*sqrt(3)*x**2/9 + 16*sqrt(3)*I*x**3/9 + O(x**4)
|
| 1016 |
+
assert acsch(x - I/2)._eval_nseries(x, 4, None, cdir=1) == -acsch(I/2) - \
|
| 1017 |
+
4*sqrt(3)*I*x/3 - 8*sqrt(3)*x**2/9 + 16*sqrt(3)*I*x**3/9 + O(x**4)
|
| 1018 |
+
assert acsch(x - I/2)._eval_nseries(x, 4, None, cdir=-1) == I*pi + \
|
| 1019 |
+
acsch(I/2) + 4*sqrt(3)*I*x/3 + 8*sqrt(3)*x**2/9 - 16*sqrt(3)*I*x**3/9 + O(x**4)
|
| 1020 |
+
# TODO: Tests concerning re(ndir) == 0
|
| 1021 |
+
assert acsch(I/2 + I*x - x**2)._eval_nseries(x, 4, None) == -I*pi/2 + \
|
| 1022 |
+
log(2 - sqrt(3)) + 4*sqrt(3)*x/3 + x**2*(-8*sqrt(3)/9 + 4*sqrt(3)*I/3) + \
|
| 1023 |
+
x**3*(16*sqrt(3)/9 - 16*sqrt(3)*I/9) + O(x**4)
|
| 1024 |
+
|
| 1025 |
+
|
| 1026 |
+
def test_acsch_rewrite():
|
| 1027 |
+
x = Symbol('x')
|
| 1028 |
+
assert acsch(x).rewrite(log) == log(1/x + sqrt(1/x**2 + 1))
|
| 1029 |
+
assert acsch(x).rewrite(asinh) == asinh(1/x)
|
| 1030 |
+
assert acsch(x).rewrite(atanh) == (sqrt(-x**2)*(-sqrt(-(x**2 + 1)**2)
|
| 1031 |
+
*atanh(sqrt(x**2 + 1))/(x**2 + 1)
|
| 1032 |
+
+ pi/2)/x)
|
| 1033 |
+
|
| 1034 |
+
|
| 1035 |
+
def test_acsch_fdiff():
|
| 1036 |
+
x = Symbol('x')
|
| 1037 |
+
raises(ArgumentIndexError, lambda: acsch(x).fdiff(2))
|
| 1038 |
+
|
| 1039 |
+
|
| 1040 |
+
def test_atanh():
|
| 1041 |
+
x = Symbol('x')
|
| 1042 |
+
|
| 1043 |
+
# at specific points
|
| 1044 |
+
assert atanh(0) == 0
|
| 1045 |
+
assert atanh(I) == I*pi/4
|
| 1046 |
+
assert atanh(-I) == -I*pi/4
|
| 1047 |
+
assert atanh(1) is oo
|
| 1048 |
+
assert atanh(-1) is -oo
|
| 1049 |
+
assert atanh(nan) is nan
|
| 1050 |
+
|
| 1051 |
+
# at infinites
|
| 1052 |
+
assert atanh(oo) == -I*pi/2
|
| 1053 |
+
assert atanh(-oo) == I*pi/2
|
| 1054 |
+
|
| 1055 |
+
assert atanh(I*oo) == I*pi/2
|
| 1056 |
+
assert atanh(-I*oo) == -I*pi/2
|
| 1057 |
+
|
| 1058 |
+
assert atanh(zoo) == I*AccumBounds(-pi/2, pi/2)
|
| 1059 |
+
|
| 1060 |
+
# properties
|
| 1061 |
+
assert atanh(-x) == -atanh(x)
|
| 1062 |
+
|
| 1063 |
+
# reality
|
| 1064 |
+
assert atanh(S(2)).is_real is False
|
| 1065 |
+
assert atanh(S(-1)/5).is_real is True
|
| 1066 |
+
assert atanh(symbols('y', extended_real=True)).is_real is None
|
| 1067 |
+
assert atanh(S(1)).is_real is False
|
| 1068 |
+
assert atanh(S(1)).is_extended_real is True
|
| 1069 |
+
assert atanh(S(-1)).is_real is False
|
| 1070 |
+
|
| 1071 |
+
# special values
|
| 1072 |
+
assert atanh(I/sqrt(3)) == I*pi/6
|
| 1073 |
+
assert atanh(-I/sqrt(3)) == -I*pi/6
|
| 1074 |
+
assert atanh(I*sqrt(3)) == I*pi/3
|
| 1075 |
+
assert atanh(-I*sqrt(3)) == -I*pi/3
|
| 1076 |
+
assert atanh(I*(1 + sqrt(2))) == pi*I*Rational(3, 8)
|
| 1077 |
+
assert atanh(I*(sqrt(2) - 1)) == pi*I/8
|
| 1078 |
+
assert atanh(I*(1 - sqrt(2))) == -pi*I/8
|
| 1079 |
+
assert atanh(-I*(1 + sqrt(2))) == pi*I*Rational(-3, 8)
|
| 1080 |
+
assert atanh(I*sqrt(5 + 2*sqrt(5))) == I*pi*Rational(2, 5)
|
| 1081 |
+
assert atanh(-I*sqrt(5 + 2*sqrt(5))) == I*pi*Rational(-2, 5)
|
| 1082 |
+
assert atanh(I*(2 - sqrt(3))) == pi*I/12
|
| 1083 |
+
assert atanh(I*(sqrt(3) - 2)) == -pi*I/12
|
| 1084 |
+
assert atanh(oo) == -I*pi/2
|
| 1085 |
+
|
| 1086 |
+
# Symmetry
|
| 1087 |
+
assert atanh(Rational(-1, 2)) == -atanh(S.Half)
|
| 1088 |
+
|
| 1089 |
+
# inverse composition
|
| 1090 |
+
assert unchanged(atanh, tanh(Symbol('v1')))
|
| 1091 |
+
|
| 1092 |
+
assert atanh(tanh(-5, evaluate=False)) == -5
|
| 1093 |
+
assert atanh(tanh(0, evaluate=False)) == 0
|
| 1094 |
+
assert atanh(tanh(7, evaluate=False)) == 7
|
| 1095 |
+
assert atanh(tanh(I, evaluate=False)) == I
|
| 1096 |
+
assert atanh(tanh(-I, evaluate=False)) == -I
|
| 1097 |
+
assert atanh(tanh(-11*I, evaluate=False)) == -11*I + 4*I*pi
|
| 1098 |
+
assert atanh(tanh(3 + I)) == 3 + I
|
| 1099 |
+
assert atanh(tanh(4 + 5*I)) == 4 - 2*I*pi + 5*I
|
| 1100 |
+
assert atanh(tanh(pi/2)) == pi/2
|
| 1101 |
+
assert atanh(tanh(pi)) == pi
|
| 1102 |
+
assert atanh(tanh(-3 + 7*I)) == -3 - 2*I*pi + 7*I
|
| 1103 |
+
assert atanh(tanh(9 - I*2/3)) == 9 - I*2/3
|
| 1104 |
+
assert atanh(tanh(-32 - 123*I)) == -32 - 123*I + 39*I*pi
|
| 1105 |
+
|
| 1106 |
+
|
| 1107 |
+
def test_atanh_rewrite():
|
| 1108 |
+
x = Symbol('x')
|
| 1109 |
+
assert atanh(x).rewrite(log) == (log(1 + x) - log(1 - x)) / 2
|
| 1110 |
+
assert atanh(x).rewrite(asinh) == \
|
| 1111 |
+
pi*x/(2*sqrt(-x**2)) - sqrt(-x)*sqrt(1 - x**2)*sqrt(1/(x**2 - 1))*asinh(sqrt(1/(x**2 - 1)))/sqrt(x)
|
| 1112 |
+
|
| 1113 |
+
|
| 1114 |
+
def test_atanh_leading_term():
|
| 1115 |
+
x = Symbol('x')
|
| 1116 |
+
assert atanh(x).as_leading_term(x) == x
|
| 1117 |
+
# Tests concerning branch points
|
| 1118 |
+
assert atanh(x + 1).as_leading_term(x, cdir=1) == -log(x)/2 + log(2)/2 - I*pi/2
|
| 1119 |
+
assert atanh(x + 1).as_leading_term(x, cdir=-1) == -log(x)/2 + log(2)/2 + I*pi/2
|
| 1120 |
+
assert atanh(x - 1).as_leading_term(x, cdir=1) == log(x)/2 - log(2)/2
|
| 1121 |
+
assert atanh(x - 1).as_leading_term(x, cdir=-1) == log(x)/2 - log(2)/2
|
| 1122 |
+
assert atanh(1/x).as_leading_term(x, cdir=1) == -I*pi/2
|
| 1123 |
+
assert atanh(1/x).as_leading_term(x, cdir=-1) == I*pi/2
|
| 1124 |
+
# Tests concerning points lying on branch cuts
|
| 1125 |
+
assert atanh(I*x + 2).as_leading_term(x, cdir=1) == atanh(2) + I*pi
|
| 1126 |
+
assert atanh(-I*x + 2).as_leading_term(x, cdir=1) == atanh(2)
|
| 1127 |
+
assert atanh(I*x - 2).as_leading_term(x, cdir=1) == -atanh(2)
|
| 1128 |
+
assert atanh(-I*x - 2).as_leading_term(x, cdir=1) == -I*pi - atanh(2)
|
| 1129 |
+
# Tests concerning im(ndir) == 0
|
| 1130 |
+
assert atanh(-I*x**2 + x - 2).as_leading_term(x, cdir=1) == -log(3)/2 - I*pi/2
|
| 1131 |
+
assert atanh(-I*x**2 + x - 2).as_leading_term(x, cdir=-1) == -log(3)/2 - I*pi/2
|
| 1132 |
+
|
| 1133 |
+
|
| 1134 |
+
def test_atanh_series():
|
| 1135 |
+
x = Symbol('x')
|
| 1136 |
+
assert atanh(x).series(x, 0, 10) == \
|
| 1137 |
+
x + x**3/3 + x**5/5 + x**7/7 + x**9/9 + O(x**10)
|
| 1138 |
+
|
| 1139 |
+
|
| 1140 |
+
def test_atanh_nseries():
|
| 1141 |
+
x = Symbol('x')
|
| 1142 |
+
# Tests concerning branch points
|
| 1143 |
+
assert atanh(x + 1)._eval_nseries(x, 4, None, cdir=1) == -I*pi/2 + log(2)/2 - \
|
| 1144 |
+
log(x)/2 + x/4 - x**2/16 + x**3/48 + O(x**4)
|
| 1145 |
+
assert atanh(x + 1)._eval_nseries(x, 4, None, cdir=-1) == I*pi/2 + log(2)/2 - \
|
| 1146 |
+
log(x)/2 + x/4 - x**2/16 + x**3/48 + O(x**4)
|
| 1147 |
+
assert atanh(x - 1)._eval_nseries(x, 4, None, cdir=1) == -log(2)/2 + log(x)/2 + \
|
| 1148 |
+
x/4 + x**2/16 + x**3/48 + O(x**4)
|
| 1149 |
+
assert atanh(x - 1)._eval_nseries(x, 4, None, cdir=-1) == -log(2)/2 + log(x)/2 + \
|
| 1150 |
+
x/4 + x**2/16 + x**3/48 + O(x**4)
|
| 1151 |
+
# Tests concerning points lying on branch cuts
|
| 1152 |
+
assert atanh(I*x + 2)._eval_nseries(x, 4, None, cdir=1) == I*pi + atanh(2) - \
|
| 1153 |
+
I*x/3 - 2*x**2/9 + 13*I*x**3/81 + O(x**4)
|
| 1154 |
+
assert atanh(I*x + 2)._eval_nseries(x, 4, None, cdir=-1) == atanh(2) - I*x/3 - \
|
| 1155 |
+
2*x**2/9 + 13*I*x**3/81 + O(x**4)
|
| 1156 |
+
assert atanh(I*x - 2)._eval_nseries(x, 4, None, cdir=1) == -atanh(2) - I*x/3 + \
|
| 1157 |
+
2*x**2/9 + 13*I*x**3/81 + O(x**4)
|
| 1158 |
+
assert atanh(I*x - 2)._eval_nseries(x, 4, None, cdir=-1) == -atanh(2) - I*pi - \
|
| 1159 |
+
I*x/3 + 2*x**2/9 + 13*I*x**3/81 + O(x**4)
|
| 1160 |
+
# Tests concerning im(ndir) == 0
|
| 1161 |
+
assert atanh(-I*x**2 + x - 2)._eval_nseries(x, 4, None) == -I*pi/2 - log(3)/2 - x/3 + \
|
| 1162 |
+
x**2*(-S(1)/4 + I/2) + x**2*(S(1)/36 - I/6) + x**3*(-S(1)/6 + I/2) + x**3*(S(1)/162 - I/18) + O(x**4)
|
| 1163 |
+
|
| 1164 |
+
|
| 1165 |
+
def test_atanh_fdiff():
|
| 1166 |
+
x = Symbol('x')
|
| 1167 |
+
raises(ArgumentIndexError, lambda: atanh(x).fdiff(2))
|
| 1168 |
+
|
| 1169 |
+
|
| 1170 |
+
def test_acoth():
|
| 1171 |
+
x = Symbol('x')
|
| 1172 |
+
|
| 1173 |
+
#at specific points
|
| 1174 |
+
assert acoth(0) == I*pi/2
|
| 1175 |
+
assert acoth(I) == -I*pi/4
|
| 1176 |
+
assert acoth(-I) == I*pi/4
|
| 1177 |
+
assert acoth(1) is oo
|
| 1178 |
+
assert acoth(-1) is -oo
|
| 1179 |
+
assert acoth(nan) is nan
|
| 1180 |
+
|
| 1181 |
+
# at infinites
|
| 1182 |
+
assert acoth(oo) == 0
|
| 1183 |
+
assert acoth(-oo) == 0
|
| 1184 |
+
assert acoth(I*oo) == 0
|
| 1185 |
+
assert acoth(-I*oo) == 0
|
| 1186 |
+
assert acoth(zoo) == 0
|
| 1187 |
+
|
| 1188 |
+
#properties
|
| 1189 |
+
assert acoth(-x) == -acoth(x)
|
| 1190 |
+
|
| 1191 |
+
assert acoth(I/sqrt(3)) == -I*pi/3
|
| 1192 |
+
assert acoth(-I/sqrt(3)) == I*pi/3
|
| 1193 |
+
assert acoth(I*sqrt(3)) == -I*pi/6
|
| 1194 |
+
assert acoth(-I*sqrt(3)) == I*pi/6
|
| 1195 |
+
assert acoth(I*(1 + sqrt(2))) == -pi*I/8
|
| 1196 |
+
assert acoth(-I*(sqrt(2) + 1)) == pi*I/8
|
| 1197 |
+
assert acoth(I*(1 - sqrt(2))) == pi*I*Rational(3, 8)
|
| 1198 |
+
assert acoth(I*(sqrt(2) - 1)) == pi*I*Rational(-3, 8)
|
| 1199 |
+
assert acoth(I*sqrt(5 + 2*sqrt(5))) == -I*pi/10
|
| 1200 |
+
assert acoth(-I*sqrt(5 + 2*sqrt(5))) == I*pi/10
|
| 1201 |
+
assert acoth(I*(2 + sqrt(3))) == -pi*I/12
|
| 1202 |
+
assert acoth(-I*(2 + sqrt(3))) == pi*I/12
|
| 1203 |
+
assert acoth(I*(2 - sqrt(3))) == pi*I*Rational(-5, 12)
|
| 1204 |
+
assert acoth(I*(sqrt(3) - 2)) == pi*I*Rational(5, 12)
|
| 1205 |
+
|
| 1206 |
+
# reality
|
| 1207 |
+
assert acoth(S(2)).is_real is True
|
| 1208 |
+
assert acoth(S(2)).is_finite is True
|
| 1209 |
+
assert acoth(S(2)).is_extended_real is True
|
| 1210 |
+
assert acoth(S(-2)).is_real is True
|
| 1211 |
+
assert acoth(S(1)).is_real is False
|
| 1212 |
+
assert acoth(S(1)).is_extended_real is True
|
| 1213 |
+
assert acoth(S(-1)).is_real is False
|
| 1214 |
+
assert acoth(symbols('y', real=True)).is_real is None
|
| 1215 |
+
|
| 1216 |
+
# Symmetry
|
| 1217 |
+
assert acoth(Rational(-1, 2)) == -acoth(S.Half)
|
| 1218 |
+
|
| 1219 |
+
|
| 1220 |
+
def test_acoth_rewrite():
|
| 1221 |
+
x = Symbol('x')
|
| 1222 |
+
assert acoth(x).rewrite(log) == (log(1 + 1/x) - log(1 - 1/x)) / 2
|
| 1223 |
+
assert acoth(x).rewrite(atanh) == atanh(1/x)
|
| 1224 |
+
assert acoth(x).rewrite(asinh) == \
|
| 1225 |
+
x*sqrt(x**(-2))*asinh(sqrt(1/(x**2 - 1))) + I*pi*(sqrt((x - 1)/x)*sqrt(x/(x - 1)) - sqrt(x/(x + 1))*sqrt(1 + 1/x))/2
|
| 1226 |
+
|
| 1227 |
+
|
| 1228 |
+
def test_acoth_leading_term():
|
| 1229 |
+
x = Symbol('x')
|
| 1230 |
+
# Tests concerning branch points
|
| 1231 |
+
assert acoth(x + 1).as_leading_term(x, cdir=1) == -log(x)/2 + log(2)/2
|
| 1232 |
+
assert acoth(x + 1).as_leading_term(x, cdir=-1) == -log(x)/2 + log(2)/2
|
| 1233 |
+
assert acoth(x - 1).as_leading_term(x, cdir=1) == log(x)/2 - log(2)/2 + I*pi/2
|
| 1234 |
+
assert acoth(x - 1).as_leading_term(x, cdir=-1) == log(x)/2 - log(2)/2 - I*pi/2
|
| 1235 |
+
# Tests concerning points lying on branch cuts
|
| 1236 |
+
assert acoth(x).as_leading_term(x, cdir=-1) == I*pi/2
|
| 1237 |
+
assert acoth(x).as_leading_term(x, cdir=1) == -I*pi/2
|
| 1238 |
+
assert acoth(I*x + 1/2).as_leading_term(x, cdir=1) == acoth(1/2)
|
| 1239 |
+
assert acoth(-I*x + 1/2).as_leading_term(x, cdir=1) == acoth(1/2) + I*pi
|
| 1240 |
+
assert acoth(I*x - 1/2).as_leading_term(x, cdir=1) == -I*pi - acoth(1/2)
|
| 1241 |
+
assert acoth(-I*x - 1/2).as_leading_term(x, cdir=1) == -acoth(1/2)
|
| 1242 |
+
# Tests concerning im(ndir) == 0
|
| 1243 |
+
assert acoth(-I*x**2 - x - S(1)/2).as_leading_term(x, cdir=1) == -log(3)/2 + I*pi/2
|
| 1244 |
+
assert acoth(-I*x**2 - x - S(1)/2).as_leading_term(x, cdir=-1) == -log(3)/2 + I*pi/2
|
| 1245 |
+
|
| 1246 |
+
|
| 1247 |
+
def test_acoth_series():
|
| 1248 |
+
x = Symbol('x')
|
| 1249 |
+
assert acoth(x).series(x, 0, 10) == \
|
| 1250 |
+
-I*pi/2 + x + x**3/3 + x**5/5 + x**7/7 + x**9/9 + O(x**10)
|
| 1251 |
+
|
| 1252 |
+
|
| 1253 |
+
def test_acoth_nseries():
|
| 1254 |
+
x = Symbol('x')
|
| 1255 |
+
# Tests concerning branch points
|
| 1256 |
+
assert acoth(x + 1)._eval_nseries(x, 4, None) == log(2)/2 - log(x)/2 + x/4 - \
|
| 1257 |
+
x**2/16 + x**3/48 + O(x**4)
|
| 1258 |
+
assert acoth(x - 1)._eval_nseries(x, 4, None, cdir=1) == I*pi/2 - log(2)/2 + \
|
| 1259 |
+
log(x)/2 + x/4 + x**2/16 + x**3/48 + O(x**4)
|
| 1260 |
+
assert acoth(x - 1)._eval_nseries(x, 4, None, cdir=-1) == -I*pi/2 - log(2)/2 + \
|
| 1261 |
+
log(x)/2 + x/4 + x**2/16 + x**3/48 + O(x**4)
|
| 1262 |
+
# Tests concerning points lying on branch cuts
|
| 1263 |
+
assert acoth(I*x + S(1)/2)._eval_nseries(x, 4, None, cdir=1) == acoth(S(1)/2) + \
|
| 1264 |
+
4*I*x/3 - 8*x**2/9 - 112*I*x**3/81 + O(x**4)
|
| 1265 |
+
assert acoth(I*x + S(1)/2)._eval_nseries(x, 4, None, cdir=-1) == I*pi + \
|
| 1266 |
+
acoth(S(1)/2) + 4*I*x/3 - 8*x**2/9 - 112*I*x**3/81 + O(x**4)
|
| 1267 |
+
assert acoth(I*x - S(1)/2)._eval_nseries(x, 4, None, cdir=1) == -acoth(S(1)/2) - \
|
| 1268 |
+
I*pi + 4*I*x/3 + 8*x**2/9 - 112*I*x**3/81 + O(x**4)
|
| 1269 |
+
assert acoth(I*x - S(1)/2)._eval_nseries(x, 4, None, cdir=-1) == -acoth(S(1)/2) + \
|
| 1270 |
+
4*I*x/3 + 8*x**2/9 - 112*I*x**3/81 + O(x**4)
|
| 1271 |
+
# Tests concerning im(ndir) == 0
|
| 1272 |
+
assert acoth(-I*x**2 - x - S(1)/2)._eval_nseries(x, 4, None) == I*pi/2 - log(3)/2 - \
|
| 1273 |
+
4*x/3 + x**2*(-S(8)/9 + 2*I/3) - 2*I*x**2 + x**3*(S(104)/81 - 16*I/9) - 8*x**3/3 + O(x**4)
|
| 1274 |
+
|
| 1275 |
+
|
| 1276 |
+
def test_acoth_fdiff():
|
| 1277 |
+
x = Symbol('x')
|
| 1278 |
+
raises(ArgumentIndexError, lambda: acoth(x).fdiff(2))
|
| 1279 |
+
|
| 1280 |
+
|
| 1281 |
+
def test_inverses():
|
| 1282 |
+
x = Symbol('x')
|
| 1283 |
+
assert sinh(x).inverse() == asinh
|
| 1284 |
+
raises(AttributeError, lambda: cosh(x).inverse())
|
| 1285 |
+
assert tanh(x).inverse() == atanh
|
| 1286 |
+
assert coth(x).inverse() == acoth
|
| 1287 |
+
assert asinh(x).inverse() == sinh
|
| 1288 |
+
assert acosh(x).inverse() == cosh
|
| 1289 |
+
assert atanh(x).inverse() == tanh
|
| 1290 |
+
assert acoth(x).inverse() == coth
|
| 1291 |
+
assert asech(x).inverse() == sech
|
| 1292 |
+
assert acsch(x).inverse() == csch
|
| 1293 |
+
|
| 1294 |
+
|
| 1295 |
+
def test_leading_term():
|
| 1296 |
+
x = Symbol('x')
|
| 1297 |
+
assert cosh(x).as_leading_term(x) == 1
|
| 1298 |
+
assert coth(x).as_leading_term(x) == 1/x
|
| 1299 |
+
for func in [sinh, tanh]:
|
| 1300 |
+
assert func(x).as_leading_term(x) == x
|
| 1301 |
+
for func in [sinh, cosh, tanh, coth]:
|
| 1302 |
+
for ar in (1/x, S.Half):
|
| 1303 |
+
eq = func(ar)
|
| 1304 |
+
assert eq.as_leading_term(x) == eq
|
| 1305 |
+
for func in [csch, sech]:
|
| 1306 |
+
eq = func(S.Half)
|
| 1307 |
+
assert eq.as_leading_term(x) == eq
|
| 1308 |
+
|
| 1309 |
+
|
| 1310 |
+
def test_complex():
|
| 1311 |
+
a, b = symbols('a,b', real=True)
|
| 1312 |
+
z = a + b*I
|
| 1313 |
+
for func in [sinh, cosh, tanh, coth, sech, csch]:
|
| 1314 |
+
assert func(z).conjugate() == func(a - b*I)
|
| 1315 |
+
for deep in [True, False]:
|
| 1316 |
+
assert sinh(z).expand(
|
| 1317 |
+
complex=True, deep=deep) == sinh(a)*cos(b) + I*cosh(a)*sin(b)
|
| 1318 |
+
assert cosh(z).expand(
|
| 1319 |
+
complex=True, deep=deep) == cosh(a)*cos(b) + I*sinh(a)*sin(b)
|
| 1320 |
+
assert tanh(z).expand(complex=True, deep=deep) == sinh(a)*cosh(
|
| 1321 |
+
a)/(cos(b)**2 + sinh(a)**2) + I*sin(b)*cos(b)/(cos(b)**2 + sinh(a)**2)
|
| 1322 |
+
assert coth(z).expand(complex=True, deep=deep) == sinh(a)*cosh(
|
| 1323 |
+
a)/(sin(b)**2 + sinh(a)**2) - I*sin(b)*cos(b)/(sin(b)**2 + sinh(a)**2)
|
| 1324 |
+
assert csch(z).expand(complex=True, deep=deep) == cos(b) * sinh(a) / (sin(b)**2\
|
| 1325 |
+
*cosh(a)**2 + cos(b)**2 * sinh(a)**2) - I*sin(b) * cosh(a) / (sin(b)**2\
|
| 1326 |
+
*cosh(a)**2 + cos(b)**2 * sinh(a)**2)
|
| 1327 |
+
assert sech(z).expand(complex=True, deep=deep) == cos(b) * cosh(a) / (sin(b)**2\
|
| 1328 |
+
*sinh(a)**2 + cos(b)**2 * cosh(a)**2) - I*sin(b) * sinh(a) / (sin(b)**2\
|
| 1329 |
+
*sinh(a)**2 + cos(b)**2 * cosh(a)**2)
|
| 1330 |
+
|
| 1331 |
+
|
| 1332 |
+
def test_complex_2899():
|
| 1333 |
+
a, b = symbols('a,b', real=True)
|
| 1334 |
+
for deep in [True, False]:
|
| 1335 |
+
for func in [sinh, cosh, tanh, coth]:
|
| 1336 |
+
assert func(a).expand(complex=True, deep=deep) == func(a)
|
| 1337 |
+
|
| 1338 |
+
|
| 1339 |
+
def test_simplifications():
|
| 1340 |
+
x = Symbol('x')
|
| 1341 |
+
assert sinh(asinh(x)) == x
|
| 1342 |
+
assert sinh(acosh(x)) == sqrt(x - 1) * sqrt(x + 1)
|
| 1343 |
+
assert sinh(atanh(x)) == x/sqrt(1 - x**2)
|
| 1344 |
+
assert sinh(acoth(x)) == 1/(sqrt(x - 1) * sqrt(x + 1))
|
| 1345 |
+
|
| 1346 |
+
assert cosh(asinh(x)) == sqrt(1 + x**2)
|
| 1347 |
+
assert cosh(acosh(x)) == x
|
| 1348 |
+
assert cosh(atanh(x)) == 1/sqrt(1 - x**2)
|
| 1349 |
+
assert cosh(acoth(x)) == x/(sqrt(x - 1) * sqrt(x + 1))
|
| 1350 |
+
|
| 1351 |
+
assert tanh(asinh(x)) == x/sqrt(1 + x**2)
|
| 1352 |
+
assert tanh(acosh(x)) == sqrt(x - 1) * sqrt(x + 1) / x
|
| 1353 |
+
assert tanh(atanh(x)) == x
|
| 1354 |
+
assert tanh(acoth(x)) == 1/x
|
| 1355 |
+
|
| 1356 |
+
assert coth(asinh(x)) == sqrt(1 + x**2)/x
|
| 1357 |
+
assert coth(acosh(x)) == x/(sqrt(x - 1) * sqrt(x + 1))
|
| 1358 |
+
assert coth(atanh(x)) == 1/x
|
| 1359 |
+
assert coth(acoth(x)) == x
|
| 1360 |
+
|
| 1361 |
+
assert csch(asinh(x)) == 1/x
|
| 1362 |
+
assert csch(acosh(x)) == 1/(sqrt(x - 1) * sqrt(x + 1))
|
| 1363 |
+
assert csch(atanh(x)) == sqrt(1 - x**2)/x
|
| 1364 |
+
assert csch(acoth(x)) == sqrt(x - 1) * sqrt(x + 1)
|
| 1365 |
+
|
| 1366 |
+
assert sech(asinh(x)) == 1/sqrt(1 + x**2)
|
| 1367 |
+
assert sech(acosh(x)) == 1/x
|
| 1368 |
+
assert sech(atanh(x)) == sqrt(1 - x**2)
|
| 1369 |
+
assert sech(acoth(x)) == sqrt(x - 1) * sqrt(x + 1)/x
|
| 1370 |
+
|
| 1371 |
+
|
| 1372 |
+
def test_issue_4136():
|
| 1373 |
+
assert cosh(asinh(Integer(3)/2)) == sqrt(Integer(13)/4)
|
| 1374 |
+
|
| 1375 |
+
|
| 1376 |
+
def test_sinh_rewrite():
|
| 1377 |
+
x = Symbol('x')
|
| 1378 |
+
assert sinh(x).rewrite(exp) == (exp(x) - exp(-x))/2 \
|
| 1379 |
+
== sinh(x).rewrite('tractable')
|
| 1380 |
+
assert sinh(x).rewrite(cosh) == -I*cosh(x + I*pi/2)
|
| 1381 |
+
tanh_half = tanh(S.Half*x)
|
| 1382 |
+
assert sinh(x).rewrite(tanh) == 2*tanh_half/(1 - tanh_half**2)
|
| 1383 |
+
coth_half = coth(S.Half*x)
|
| 1384 |
+
assert sinh(x).rewrite(coth) == 2*coth_half/(coth_half**2 - 1)
|
| 1385 |
+
|
| 1386 |
+
|
| 1387 |
+
def test_cosh_rewrite():
|
| 1388 |
+
x = Symbol('x')
|
| 1389 |
+
assert cosh(x).rewrite(exp) == (exp(x) + exp(-x))/2 \
|
| 1390 |
+
== cosh(x).rewrite('tractable')
|
| 1391 |
+
assert cosh(x).rewrite(sinh) == -I*sinh(x + I*pi/2, evaluate=False)
|
| 1392 |
+
tanh_half = tanh(S.Half*x)**2
|
| 1393 |
+
assert cosh(x).rewrite(tanh) == (1 + tanh_half)/(1 - tanh_half)
|
| 1394 |
+
coth_half = coth(S.Half*x)**2
|
| 1395 |
+
assert cosh(x).rewrite(coth) == (coth_half + 1)/(coth_half - 1)
|
| 1396 |
+
|
| 1397 |
+
|
| 1398 |
+
def test_tanh_rewrite():
|
| 1399 |
+
x = Symbol('x')
|
| 1400 |
+
assert tanh(x).rewrite(exp) == (exp(x) - exp(-x))/(exp(x) + exp(-x)) \
|
| 1401 |
+
== tanh(x).rewrite('tractable')
|
| 1402 |
+
assert tanh(x).rewrite(sinh) == I*sinh(x)/sinh(I*pi/2 - x, evaluate=False)
|
| 1403 |
+
assert tanh(x).rewrite(cosh) == I*cosh(I*pi/2 - x, evaluate=False)/cosh(x)
|
| 1404 |
+
assert tanh(x).rewrite(coth) == 1/coth(x)
|
| 1405 |
+
|
| 1406 |
+
|
| 1407 |
+
def test_coth_rewrite():
|
| 1408 |
+
x = Symbol('x')
|
| 1409 |
+
assert coth(x).rewrite(exp) == (exp(x) + exp(-x))/(exp(x) - exp(-x)) \
|
| 1410 |
+
== coth(x).rewrite('tractable')
|
| 1411 |
+
assert coth(x).rewrite(sinh) == -I*sinh(I*pi/2 - x, evaluate=False)/sinh(x)
|
| 1412 |
+
assert coth(x).rewrite(cosh) == -I*cosh(x)/cosh(I*pi/2 - x, evaluate=False)
|
| 1413 |
+
assert coth(x).rewrite(tanh) == 1/tanh(x)
|
| 1414 |
+
|
| 1415 |
+
|
| 1416 |
+
def test_csch_rewrite():
|
| 1417 |
+
x = Symbol('x')
|
| 1418 |
+
assert csch(x).rewrite(exp) == 1 / (exp(x)/2 - exp(-x)/2) \
|
| 1419 |
+
== csch(x).rewrite('tractable')
|
| 1420 |
+
assert csch(x).rewrite(cosh) == I/cosh(x + I*pi/2, evaluate=False)
|
| 1421 |
+
tanh_half = tanh(S.Half*x)
|
| 1422 |
+
assert csch(x).rewrite(tanh) == (1 - tanh_half**2)/(2*tanh_half)
|
| 1423 |
+
coth_half = coth(S.Half*x)
|
| 1424 |
+
assert csch(x).rewrite(coth) == (coth_half**2 - 1)/(2*coth_half)
|
| 1425 |
+
|
| 1426 |
+
|
| 1427 |
+
def test_sech_rewrite():
|
| 1428 |
+
x = Symbol('x')
|
| 1429 |
+
assert sech(x).rewrite(exp) == 1 / (exp(x)/2 + exp(-x)/2) \
|
| 1430 |
+
== sech(x).rewrite('tractable')
|
| 1431 |
+
assert sech(x).rewrite(sinh) == I/sinh(x + I*pi/2, evaluate=False)
|
| 1432 |
+
tanh_half = tanh(S.Half*x)**2
|
| 1433 |
+
assert sech(x).rewrite(tanh) == (1 - tanh_half)/(1 + tanh_half)
|
| 1434 |
+
coth_half = coth(S.Half*x)**2
|
| 1435 |
+
assert sech(x).rewrite(coth) == (coth_half - 1)/(coth_half + 1)
|
| 1436 |
+
|
| 1437 |
+
|
| 1438 |
+
def test_derivs():
|
| 1439 |
+
x = Symbol('x')
|
| 1440 |
+
assert coth(x).diff(x) == -sinh(x)**(-2)
|
| 1441 |
+
assert sinh(x).diff(x) == cosh(x)
|
| 1442 |
+
assert cosh(x).diff(x) == sinh(x)
|
| 1443 |
+
assert tanh(x).diff(x) == -tanh(x)**2 + 1
|
| 1444 |
+
assert csch(x).diff(x) == -coth(x)*csch(x)
|
| 1445 |
+
assert sech(x).diff(x) == -tanh(x)*sech(x)
|
| 1446 |
+
assert acoth(x).diff(x) == 1/(-x**2 + 1)
|
| 1447 |
+
assert asinh(x).diff(x) == 1/sqrt(x**2 + 1)
|
| 1448 |
+
assert acosh(x).diff(x) == 1/(sqrt(x - 1)*sqrt(x + 1))
|
| 1449 |
+
assert acosh(x).diff(x) == acosh(x).rewrite(log).diff(x).together()
|
| 1450 |
+
assert atanh(x).diff(x) == 1/(-x**2 + 1)
|
| 1451 |
+
assert asech(x).diff(x) == -1/(x*sqrt(1 - x**2))
|
| 1452 |
+
assert acsch(x).diff(x) == -1/(x**2*sqrt(1 + x**(-2)))
|
| 1453 |
+
|
| 1454 |
+
|
| 1455 |
+
def test_sinh_expansion():
|
| 1456 |
+
x, y = symbols('x,y')
|
| 1457 |
+
assert sinh(x+y).expand(trig=True) == sinh(x)*cosh(y) + cosh(x)*sinh(y)
|
| 1458 |
+
assert sinh(2*x).expand(trig=True) == 2*sinh(x)*cosh(x)
|
| 1459 |
+
assert sinh(3*x).expand(trig=True).expand() == \
|
| 1460 |
+
sinh(x)**3 + 3*sinh(x)*cosh(x)**2
|
| 1461 |
+
|
| 1462 |
+
|
| 1463 |
+
def test_cosh_expansion():
|
| 1464 |
+
x, y = symbols('x,y')
|
| 1465 |
+
assert cosh(x+y).expand(trig=True) == cosh(x)*cosh(y) + sinh(x)*sinh(y)
|
| 1466 |
+
assert cosh(2*x).expand(trig=True) == cosh(x)**2 + sinh(x)**2
|
| 1467 |
+
assert cosh(3*x).expand(trig=True).expand() == \
|
| 1468 |
+
3*sinh(x)**2*cosh(x) + cosh(x)**3
|
| 1469 |
+
|
| 1470 |
+
def test_cosh_positive():
|
| 1471 |
+
# See issue 11721
|
| 1472 |
+
# cosh(x) is positive for real values of x
|
| 1473 |
+
k = symbols('k', real=True)
|
| 1474 |
+
n = symbols('n', integer=True)
|
| 1475 |
+
|
| 1476 |
+
assert cosh(k, evaluate=False).is_positive is True
|
| 1477 |
+
assert cosh(k + 2*n*pi*I, evaluate=False).is_positive is True
|
| 1478 |
+
assert cosh(I*pi/4, evaluate=False).is_positive is True
|
| 1479 |
+
assert cosh(3*I*pi/4, evaluate=False).is_positive is False
|
| 1480 |
+
|
| 1481 |
+
def test_cosh_nonnegative():
|
| 1482 |
+
k = symbols('k', real=True)
|
| 1483 |
+
n = symbols('n', integer=True)
|
| 1484 |
+
|
| 1485 |
+
assert cosh(k, evaluate=False).is_nonnegative is True
|
| 1486 |
+
assert cosh(k + 2*n*pi*I, evaluate=False).is_nonnegative is True
|
| 1487 |
+
assert cosh(I*pi/4, evaluate=False).is_nonnegative is True
|
| 1488 |
+
assert cosh(3*I*pi/4, evaluate=False).is_nonnegative is False
|
| 1489 |
+
assert cosh(S.Zero, evaluate=False).is_nonnegative is True
|
| 1490 |
+
|
| 1491 |
+
def test_real_assumptions():
|
| 1492 |
+
z = Symbol('z', real=False)
|
| 1493 |
+
assert sinh(z).is_real is None
|
| 1494 |
+
assert cosh(z).is_real is None
|
| 1495 |
+
assert tanh(z).is_real is None
|
| 1496 |
+
assert sech(z).is_real is None
|
| 1497 |
+
assert csch(z).is_real is None
|
| 1498 |
+
assert coth(z).is_real is None
|
| 1499 |
+
|
| 1500 |
+
def test_sign_assumptions():
|
| 1501 |
+
p = Symbol('p', positive=True)
|
| 1502 |
+
n = Symbol('n', negative=True)
|
| 1503 |
+
assert sinh(n).is_negative is True
|
| 1504 |
+
assert sinh(p).is_positive is True
|
| 1505 |
+
assert cosh(n).is_positive is True
|
| 1506 |
+
assert cosh(p).is_positive is True
|
| 1507 |
+
assert tanh(n).is_negative is True
|
| 1508 |
+
assert tanh(p).is_positive is True
|
| 1509 |
+
assert csch(n).is_negative is True
|
| 1510 |
+
assert csch(p).is_positive is True
|
| 1511 |
+
assert sech(n).is_positive is True
|
| 1512 |
+
assert sech(p).is_positive is True
|
| 1513 |
+
assert coth(n).is_negative is True
|
| 1514 |
+
assert coth(p).is_positive is True
|
| 1515 |
+
|
| 1516 |
+
|
| 1517 |
+
def test_issue_25847():
|
| 1518 |
+
x = Symbol('x')
|
| 1519 |
+
|
| 1520 |
+
#atanh
|
| 1521 |
+
assert atanh(sin(x)/x).as_leading_term(x) == atanh(sin(x)/x)
|
| 1522 |
+
raises(PoleError, lambda: atanh(exp(1/x)).as_leading_term(x))
|
| 1523 |
+
|
| 1524 |
+
#asinh
|
| 1525 |
+
assert asinh(sin(x)/x).as_leading_term(x) == log(1 + sqrt(2))
|
| 1526 |
+
raises(PoleError, lambda: asinh(exp(1/x)).as_leading_term(x))
|
| 1527 |
+
|
| 1528 |
+
#acosh
|
| 1529 |
+
assert acosh(sin(x)/x).as_leading_term(x) == 0
|
| 1530 |
+
raises(PoleError, lambda: acosh(exp(1/x)).as_leading_term(x))
|
| 1531 |
+
|
| 1532 |
+
#acoth
|
| 1533 |
+
assert acoth(sin(x)/x).as_leading_term(x) == acoth(sin(x)/x)
|
| 1534 |
+
raises(PoleError, lambda: acoth(exp(1/x)).as_leading_term(x))
|
| 1535 |
+
|
| 1536 |
+
#asech
|
| 1537 |
+
assert asech(sinh(x)/x).as_leading_term(x) == 0
|
| 1538 |
+
raises(PoleError, lambda: asech(exp(1/x)).as_leading_term(x))
|
| 1539 |
+
|
| 1540 |
+
#acsch
|
| 1541 |
+
assert acsch(sin(x)/x).as_leading_term(x) == log(1 + sqrt(2))
|
| 1542 |
+
raises(PoleError, lambda: acsch(exp(1/x)).as_leading_term(x))
|
evalkit_tf437/lib/python3.10/site-packages/sympy/functions/elementary/tests/test_interface.py
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# This test file tests the SymPy function interface, that people use to create
|
| 2 |
+
# their own new functions. It should be as easy as possible.
|
| 3 |
+
from sympy.core.function import Function
|
| 4 |
+
from sympy.core.sympify import sympify
|
| 5 |
+
from sympy.functions.elementary.hyperbolic import tanh
|
| 6 |
+
from sympy.functions.elementary.trigonometric import (cos, sin)
|
| 7 |
+
from sympy.series.limits import limit
|
| 8 |
+
from sympy.abc import x
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def test_function_series1():
|
| 12 |
+
"""Create our new "sin" function."""
|
| 13 |
+
|
| 14 |
+
class my_function(Function):
|
| 15 |
+
|
| 16 |
+
def fdiff(self, argindex=1):
|
| 17 |
+
return cos(self.args[0])
|
| 18 |
+
|
| 19 |
+
@classmethod
|
| 20 |
+
def eval(cls, arg):
|
| 21 |
+
arg = sympify(arg)
|
| 22 |
+
if arg == 0:
|
| 23 |
+
return sympify(0)
|
| 24 |
+
|
| 25 |
+
#Test that the taylor series is correct
|
| 26 |
+
assert my_function(x).series(x, 0, 10) == sin(x).series(x, 0, 10)
|
| 27 |
+
assert limit(my_function(x)/x, x, 0) == 1
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def test_function_series2():
|
| 31 |
+
"""Create our new "cos" function."""
|
| 32 |
+
|
| 33 |
+
class my_function2(Function):
|
| 34 |
+
|
| 35 |
+
def fdiff(self, argindex=1):
|
| 36 |
+
return -sin(self.args[0])
|
| 37 |
+
|
| 38 |
+
@classmethod
|
| 39 |
+
def eval(cls, arg):
|
| 40 |
+
arg = sympify(arg)
|
| 41 |
+
if arg == 0:
|
| 42 |
+
return sympify(1)
|
| 43 |
+
|
| 44 |
+
#Test that the taylor series is correct
|
| 45 |
+
assert my_function2(x).series(x, 0, 10) == cos(x).series(x, 0, 10)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def test_function_series3():
|
| 49 |
+
"""
|
| 50 |
+
Test our easy "tanh" function.
|
| 51 |
+
|
| 52 |
+
This test tests two things:
|
| 53 |
+
* that the Function interface works as expected and it's easy to use
|
| 54 |
+
* that the general algorithm for the series expansion works even when the
|
| 55 |
+
derivative is defined recursively in terms of the original function,
|
| 56 |
+
since tanh(x).diff(x) == 1-tanh(x)**2
|
| 57 |
+
"""
|
| 58 |
+
|
| 59 |
+
class mytanh(Function):
|
| 60 |
+
|
| 61 |
+
def fdiff(self, argindex=1):
|
| 62 |
+
return 1 - mytanh(self.args[0])**2
|
| 63 |
+
|
| 64 |
+
@classmethod
|
| 65 |
+
def eval(cls, arg):
|
| 66 |
+
arg = sympify(arg)
|
| 67 |
+
if arg == 0:
|
| 68 |
+
return sympify(0)
|
| 69 |
+
|
| 70 |
+
e = tanh(x)
|
| 71 |
+
f = mytanh(x)
|
| 72 |
+
assert e.series(x, 0, 6) == f.series(x, 0, 6)
|
evalkit_tf437/lib/python3.10/site-packages/sympy/testing/__init__.py
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""This module contains code for running the tests in SymPy."""
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
from .runtests import doctest
|
| 5 |
+
from .runtests_pytest import test
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
__all__ = [
|
| 9 |
+
'test', 'doctest',
|
| 10 |
+
]
|
evalkit_tf437/lib/python3.10/site-packages/sympy/testing/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (361 Bytes). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/sympy/testing/__pycache__/matrices.cpython-310.pyc
ADDED
|
Binary file (438 Bytes). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/sympy/testing/__pycache__/pytest.cpython-310.pyc
ADDED
|
Binary file (13.6 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/sympy/testing/__pycache__/quality_unicode.cpython-310.pyc
ADDED
|
Binary file (2.25 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/sympy/testing/__pycache__/randtest.cpython-310.pyc
ADDED
|
Binary file (750 Bytes). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/sympy/testing/__pycache__/runtests.cpython-310.pyc
ADDED
|
Binary file (64.3 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/sympy/testing/__pycache__/runtests_pytest.cpython-310.pyc
ADDED
|
Binary file (16.5 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/sympy/testing/__pycache__/tmpfiles.cpython-310.pyc
ADDED
|
Binary file (1.61 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/sympy/testing/matrices.py
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
def allclose(A, B, rtol=1e-05, atol=1e-08):
|
| 2 |
+
if len(A) != len(B):
|
| 3 |
+
return False
|
| 4 |
+
|
| 5 |
+
for x, y in zip(A, B):
|
| 6 |
+
if abs(x-y) > atol + rtol * max(abs(x), abs(y)):
|
| 7 |
+
return False
|
| 8 |
+
return True
|
evalkit_tf437/lib/python3.10/site-packages/sympy/testing/pytest.py
ADDED
|
@@ -0,0 +1,401 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""py.test hacks to support XFAIL/XPASS"""
|
| 2 |
+
|
| 3 |
+
import sys
|
| 4 |
+
import re
|
| 5 |
+
import functools
|
| 6 |
+
import os
|
| 7 |
+
import contextlib
|
| 8 |
+
import warnings
|
| 9 |
+
import inspect
|
| 10 |
+
import pathlib
|
| 11 |
+
from typing import Any, Callable
|
| 12 |
+
|
| 13 |
+
from sympy.utilities.exceptions import SymPyDeprecationWarning
|
| 14 |
+
# Imported here for backwards compatibility. Note: do not import this from
|
| 15 |
+
# here in library code (importing sympy.pytest in library code will break the
|
| 16 |
+
# pytest integration).
|
| 17 |
+
from sympy.utilities.exceptions import ignore_warnings # noqa:F401
|
| 18 |
+
|
| 19 |
+
ON_CI = os.getenv('CI', None) == "true"
|
| 20 |
+
|
| 21 |
+
try:
|
| 22 |
+
import pytest
|
| 23 |
+
USE_PYTEST = getattr(sys, '_running_pytest', False)
|
| 24 |
+
except ImportError:
|
| 25 |
+
USE_PYTEST = False
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
raises: Callable[[Any, Any], Any]
|
| 29 |
+
XFAIL: Callable[[Any], Any]
|
| 30 |
+
skip: Callable[[Any], Any]
|
| 31 |
+
SKIP: Callable[[Any], Any]
|
| 32 |
+
slow: Callable[[Any], Any]
|
| 33 |
+
tooslow: Callable[[Any], Any]
|
| 34 |
+
nocache_fail: Callable[[Any], Any]
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
if USE_PYTEST:
|
| 38 |
+
raises = pytest.raises
|
| 39 |
+
skip = pytest.skip
|
| 40 |
+
XFAIL = pytest.mark.xfail
|
| 41 |
+
SKIP = pytest.mark.skip
|
| 42 |
+
slow = pytest.mark.slow
|
| 43 |
+
tooslow = pytest.mark.tooslow
|
| 44 |
+
nocache_fail = pytest.mark.nocache_fail
|
| 45 |
+
from _pytest.outcomes import Failed
|
| 46 |
+
|
| 47 |
+
else:
|
| 48 |
+
# Not using pytest so define the things that would have been imported from
|
| 49 |
+
# there.
|
| 50 |
+
|
| 51 |
+
# _pytest._code.code.ExceptionInfo
|
| 52 |
+
class ExceptionInfo:
|
| 53 |
+
def __init__(self, value):
|
| 54 |
+
self.value = value
|
| 55 |
+
|
| 56 |
+
def __repr__(self):
|
| 57 |
+
return "<ExceptionInfo {!r}>".format(self.value)
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def raises(expectedException, code=None):
|
| 61 |
+
"""
|
| 62 |
+
Tests that ``code`` raises the exception ``expectedException``.
|
| 63 |
+
|
| 64 |
+
``code`` may be a callable, such as a lambda expression or function
|
| 65 |
+
name.
|
| 66 |
+
|
| 67 |
+
If ``code`` is not given or None, ``raises`` will return a context
|
| 68 |
+
manager for use in ``with`` statements; the code to execute then
|
| 69 |
+
comes from the scope of the ``with``.
|
| 70 |
+
|
| 71 |
+
``raises()`` does nothing if the callable raises the expected exception,
|
| 72 |
+
otherwise it raises an AssertionError.
|
| 73 |
+
|
| 74 |
+
Examples
|
| 75 |
+
========
|
| 76 |
+
|
| 77 |
+
>>> from sympy.testing.pytest import raises
|
| 78 |
+
|
| 79 |
+
>>> raises(ZeroDivisionError, lambda: 1/0)
|
| 80 |
+
<ExceptionInfo ZeroDivisionError(...)>
|
| 81 |
+
>>> raises(ZeroDivisionError, lambda: 1/2)
|
| 82 |
+
Traceback (most recent call last):
|
| 83 |
+
...
|
| 84 |
+
Failed: DID NOT RAISE
|
| 85 |
+
|
| 86 |
+
>>> with raises(ZeroDivisionError):
|
| 87 |
+
... n = 1/0
|
| 88 |
+
>>> with raises(ZeroDivisionError):
|
| 89 |
+
... n = 1/2
|
| 90 |
+
Traceback (most recent call last):
|
| 91 |
+
...
|
| 92 |
+
Failed: DID NOT RAISE
|
| 93 |
+
|
| 94 |
+
Note that you cannot test multiple statements via
|
| 95 |
+
``with raises``:
|
| 96 |
+
|
| 97 |
+
>>> with raises(ZeroDivisionError):
|
| 98 |
+
... n = 1/0 # will execute and raise, aborting the ``with``
|
| 99 |
+
... n = 9999/0 # never executed
|
| 100 |
+
|
| 101 |
+
This is just what ``with`` is supposed to do: abort the
|
| 102 |
+
contained statement sequence at the first exception and let
|
| 103 |
+
the context manager deal with the exception.
|
| 104 |
+
|
| 105 |
+
To test multiple statements, you'll need a separate ``with``
|
| 106 |
+
for each:
|
| 107 |
+
|
| 108 |
+
>>> with raises(ZeroDivisionError):
|
| 109 |
+
... n = 1/0 # will execute and raise
|
| 110 |
+
>>> with raises(ZeroDivisionError):
|
| 111 |
+
... n = 9999/0 # will also execute and raise
|
| 112 |
+
|
| 113 |
+
"""
|
| 114 |
+
if code is None:
|
| 115 |
+
return RaisesContext(expectedException)
|
| 116 |
+
elif callable(code):
|
| 117 |
+
try:
|
| 118 |
+
code()
|
| 119 |
+
except expectedException as e:
|
| 120 |
+
return ExceptionInfo(e)
|
| 121 |
+
raise Failed("DID NOT RAISE")
|
| 122 |
+
elif isinstance(code, str):
|
| 123 |
+
raise TypeError(
|
| 124 |
+
'\'raises(xxx, "code")\' has been phased out; '
|
| 125 |
+
'change \'raises(xxx, "expression")\' '
|
| 126 |
+
'to \'raises(xxx, lambda: expression)\', '
|
| 127 |
+
'\'raises(xxx, "statement")\' '
|
| 128 |
+
'to \'with raises(xxx): statement\'')
|
| 129 |
+
else:
|
| 130 |
+
raise TypeError(
|
| 131 |
+
'raises() expects a callable for the 2nd argument.')
|
| 132 |
+
|
| 133 |
+
class RaisesContext:
|
| 134 |
+
def __init__(self, expectedException):
|
| 135 |
+
self.expectedException = expectedException
|
| 136 |
+
|
| 137 |
+
def __enter__(self):
|
| 138 |
+
return None
|
| 139 |
+
|
| 140 |
+
def __exit__(self, exc_type, exc_value, traceback):
|
| 141 |
+
if exc_type is None:
|
| 142 |
+
raise Failed("DID NOT RAISE")
|
| 143 |
+
return issubclass(exc_type, self.expectedException)
|
| 144 |
+
|
| 145 |
+
class XFail(Exception):
|
| 146 |
+
pass
|
| 147 |
+
|
| 148 |
+
class XPass(Exception):
|
| 149 |
+
pass
|
| 150 |
+
|
| 151 |
+
class Skipped(Exception):
|
| 152 |
+
pass
|
| 153 |
+
|
| 154 |
+
class Failed(Exception): # type: ignore
|
| 155 |
+
pass
|
| 156 |
+
|
| 157 |
+
def XFAIL(func):
|
| 158 |
+
def wrapper():
|
| 159 |
+
try:
|
| 160 |
+
func()
|
| 161 |
+
except Exception as e:
|
| 162 |
+
message = str(e)
|
| 163 |
+
if message != "Timeout":
|
| 164 |
+
raise XFail(func.__name__)
|
| 165 |
+
else:
|
| 166 |
+
raise Skipped("Timeout")
|
| 167 |
+
raise XPass(func.__name__)
|
| 168 |
+
|
| 169 |
+
wrapper = functools.update_wrapper(wrapper, func)
|
| 170 |
+
return wrapper
|
| 171 |
+
|
| 172 |
+
def skip(str):
|
| 173 |
+
raise Skipped(str)
|
| 174 |
+
|
| 175 |
+
def SKIP(reason):
|
| 176 |
+
"""Similar to ``skip()``, but this is a decorator. """
|
| 177 |
+
def wrapper(func):
|
| 178 |
+
def func_wrapper():
|
| 179 |
+
raise Skipped(reason)
|
| 180 |
+
|
| 181 |
+
func_wrapper = functools.update_wrapper(func_wrapper, func)
|
| 182 |
+
return func_wrapper
|
| 183 |
+
|
| 184 |
+
return wrapper
|
| 185 |
+
|
| 186 |
+
def slow(func):
|
| 187 |
+
func._slow = True
|
| 188 |
+
|
| 189 |
+
def func_wrapper():
|
| 190 |
+
func()
|
| 191 |
+
|
| 192 |
+
func_wrapper = functools.update_wrapper(func_wrapper, func)
|
| 193 |
+
func_wrapper.__wrapped__ = func
|
| 194 |
+
return func_wrapper
|
| 195 |
+
|
| 196 |
+
def tooslow(func):
|
| 197 |
+
func._slow = True
|
| 198 |
+
func._tooslow = True
|
| 199 |
+
|
| 200 |
+
def func_wrapper():
|
| 201 |
+
skip("Too slow")
|
| 202 |
+
|
| 203 |
+
func_wrapper = functools.update_wrapper(func_wrapper, func)
|
| 204 |
+
func_wrapper.__wrapped__ = func
|
| 205 |
+
return func_wrapper
|
| 206 |
+
|
| 207 |
+
def nocache_fail(func):
|
| 208 |
+
"Dummy decorator for marking tests that fail when cache is disabled"
|
| 209 |
+
return func
|
| 210 |
+
|
| 211 |
+
@contextlib.contextmanager
|
| 212 |
+
def warns(warningcls, *, match='', test_stacklevel=True):
|
| 213 |
+
'''
|
| 214 |
+
Like raises but tests that warnings are emitted.
|
| 215 |
+
|
| 216 |
+
>>> from sympy.testing.pytest import warns
|
| 217 |
+
>>> import warnings
|
| 218 |
+
|
| 219 |
+
>>> with warns(UserWarning):
|
| 220 |
+
... warnings.warn('deprecated', UserWarning, stacklevel=2)
|
| 221 |
+
|
| 222 |
+
>>> with warns(UserWarning):
|
| 223 |
+
... pass
|
| 224 |
+
Traceback (most recent call last):
|
| 225 |
+
...
|
| 226 |
+
Failed: DID NOT WARN. No warnings of type UserWarning\
|
| 227 |
+
was emitted. The list of emitted warnings is: [].
|
| 228 |
+
|
| 229 |
+
``test_stacklevel`` makes it check that the ``stacklevel`` parameter to
|
| 230 |
+
``warn()`` is set so that the warning shows the user line of code (the
|
| 231 |
+
code under the warns() context manager). Set this to False if this is
|
| 232 |
+
ambiguous or if the context manager does not test the direct user code
|
| 233 |
+
that emits the warning.
|
| 234 |
+
|
| 235 |
+
If the warning is a ``SymPyDeprecationWarning``, this additionally tests
|
| 236 |
+
that the ``active_deprecations_target`` is a real target in the
|
| 237 |
+
``active-deprecations.md`` file.
|
| 238 |
+
|
| 239 |
+
'''
|
| 240 |
+
# Absorbs all warnings in warnrec
|
| 241 |
+
with warnings.catch_warnings(record=True) as warnrec:
|
| 242 |
+
# Any warning other than the one we are looking for is an error
|
| 243 |
+
warnings.simplefilter("error")
|
| 244 |
+
warnings.filterwarnings("always", category=warningcls)
|
| 245 |
+
# Now run the test
|
| 246 |
+
yield warnrec
|
| 247 |
+
|
| 248 |
+
# Raise if expected warning not found
|
| 249 |
+
if not any(issubclass(w.category, warningcls) for w in warnrec):
|
| 250 |
+
msg = ('Failed: DID NOT WARN.'
|
| 251 |
+
' No warnings of type %s was emitted.'
|
| 252 |
+
' The list of emitted warnings is: %s.'
|
| 253 |
+
) % (warningcls, [w.message for w in warnrec])
|
| 254 |
+
raise Failed(msg)
|
| 255 |
+
|
| 256 |
+
# We don't include the match in the filter above because it would then
|
| 257 |
+
# fall to the error filter, so we instead manually check that it matches
|
| 258 |
+
# here
|
| 259 |
+
for w in warnrec:
|
| 260 |
+
# Should always be true due to the filters above
|
| 261 |
+
assert issubclass(w.category, warningcls)
|
| 262 |
+
if not re.compile(match, re.I).match(str(w.message)):
|
| 263 |
+
raise Failed(f"Failed: WRONG MESSAGE. A warning with of the correct category ({warningcls.__name__}) was issued, but it did not match the given match regex ({match!r})")
|
| 264 |
+
|
| 265 |
+
if test_stacklevel:
|
| 266 |
+
for f in inspect.stack():
|
| 267 |
+
thisfile = f.filename
|
| 268 |
+
file = os.path.split(thisfile)[1]
|
| 269 |
+
if file.startswith('test_'):
|
| 270 |
+
break
|
| 271 |
+
elif file == 'doctest.py':
|
| 272 |
+
# skip the stacklevel testing in the doctests of this
|
| 273 |
+
# function
|
| 274 |
+
return
|
| 275 |
+
else:
|
| 276 |
+
raise RuntimeError("Could not find the file for the given warning to test the stacklevel")
|
| 277 |
+
for w in warnrec:
|
| 278 |
+
if w.filename != thisfile:
|
| 279 |
+
msg = f'''\
|
| 280 |
+
Failed: Warning has the wrong stacklevel. The warning stacklevel needs to be
|
| 281 |
+
set so that the line of code shown in the warning message is user code that
|
| 282 |
+
calls the deprecated code (the current stacklevel is showing code from
|
| 283 |
+
{w.filename} (line {w.lineno}), expected {thisfile})'''.replace('\n', ' ')
|
| 284 |
+
raise Failed(msg)
|
| 285 |
+
|
| 286 |
+
if warningcls == SymPyDeprecationWarning:
|
| 287 |
+
this_file = pathlib.Path(__file__)
|
| 288 |
+
active_deprecations_file = (this_file.parent.parent.parent / 'doc' /
|
| 289 |
+
'src' / 'explanation' /
|
| 290 |
+
'active-deprecations.md')
|
| 291 |
+
if not active_deprecations_file.exists():
|
| 292 |
+
# We can only test that the active_deprecations_target works if we are
|
| 293 |
+
# in the git repo.
|
| 294 |
+
return
|
| 295 |
+
targets = []
|
| 296 |
+
for w in warnrec:
|
| 297 |
+
targets.append(w.message.active_deprecations_target)
|
| 298 |
+
with open(active_deprecations_file, encoding="utf-8") as f:
|
| 299 |
+
text = f.read()
|
| 300 |
+
for target in targets:
|
| 301 |
+
if f'({target})=' not in text:
|
| 302 |
+
raise Failed(f"The active deprecations target {target!r} does not appear to be a valid target in the active-deprecations.md file ({active_deprecations_file}).")
|
| 303 |
+
|
| 304 |
+
def _both_exp_pow(func):
|
| 305 |
+
"""
|
| 306 |
+
Decorator used to run the test twice: the first time `e^x` is represented
|
| 307 |
+
as ``Pow(E, x)``, the second time as ``exp(x)`` (exponential object is not
|
| 308 |
+
a power).
|
| 309 |
+
|
| 310 |
+
This is a temporary trick helping to manage the elimination of the class
|
| 311 |
+
``exp`` in favor of a replacement by ``Pow(E, ...)``.
|
| 312 |
+
"""
|
| 313 |
+
from sympy.core.parameters import _exp_is_pow
|
| 314 |
+
|
| 315 |
+
def func_wrap():
|
| 316 |
+
with _exp_is_pow(True):
|
| 317 |
+
func()
|
| 318 |
+
with _exp_is_pow(False):
|
| 319 |
+
func()
|
| 320 |
+
|
| 321 |
+
wrapper = functools.update_wrapper(func_wrap, func)
|
| 322 |
+
return wrapper
|
| 323 |
+
|
| 324 |
+
|
| 325 |
+
@contextlib.contextmanager
|
| 326 |
+
def warns_deprecated_sympy():
|
| 327 |
+
'''
|
| 328 |
+
Shorthand for ``warns(SymPyDeprecationWarning)``
|
| 329 |
+
|
| 330 |
+
This is the recommended way to test that ``SymPyDeprecationWarning`` is
|
| 331 |
+
emitted for deprecated features in SymPy. To test for other warnings use
|
| 332 |
+
``warns``. To suppress warnings without asserting that they are emitted
|
| 333 |
+
use ``ignore_warnings``.
|
| 334 |
+
|
| 335 |
+
.. note::
|
| 336 |
+
|
| 337 |
+
``warns_deprecated_sympy()`` is only intended for internal use in the
|
| 338 |
+
SymPy test suite to test that a deprecation warning triggers properly.
|
| 339 |
+
All other code in the SymPy codebase, including documentation examples,
|
| 340 |
+
should not use deprecated behavior.
|
| 341 |
+
|
| 342 |
+
If you are a user of SymPy and you want to disable
|
| 343 |
+
SymPyDeprecationWarnings, use ``warnings`` filters (see
|
| 344 |
+
:ref:`silencing-sympy-deprecation-warnings`).
|
| 345 |
+
|
| 346 |
+
>>> from sympy.testing.pytest import warns_deprecated_sympy
|
| 347 |
+
>>> from sympy.utilities.exceptions import sympy_deprecation_warning
|
| 348 |
+
>>> with warns_deprecated_sympy():
|
| 349 |
+
... sympy_deprecation_warning("Don't use",
|
| 350 |
+
... deprecated_since_version="1.0",
|
| 351 |
+
... active_deprecations_target="active-deprecations")
|
| 352 |
+
|
| 353 |
+
>>> with warns_deprecated_sympy():
|
| 354 |
+
... pass
|
| 355 |
+
Traceback (most recent call last):
|
| 356 |
+
...
|
| 357 |
+
Failed: DID NOT WARN. No warnings of type \
|
| 358 |
+
SymPyDeprecationWarning was emitted. The list of emitted warnings is: [].
|
| 359 |
+
|
| 360 |
+
.. note::
|
| 361 |
+
|
| 362 |
+
Sometimes the stacklevel test will fail because the same warning is
|
| 363 |
+
emitted multiple times. In this case, you can use
|
| 364 |
+
:func:`sympy.utilities.exceptions.ignore_warnings` in the code to
|
| 365 |
+
prevent the ``SymPyDeprecationWarning`` from being emitted again
|
| 366 |
+
recursively. In rare cases it is impossible to have a consistent
|
| 367 |
+
``stacklevel`` for deprecation warnings because different ways of
|
| 368 |
+
calling a function will produce different call stacks.. In those cases,
|
| 369 |
+
use ``warns(SymPyDeprecationWarning)`` instead.
|
| 370 |
+
|
| 371 |
+
See Also
|
| 372 |
+
========
|
| 373 |
+
sympy.utilities.exceptions.SymPyDeprecationWarning
|
| 374 |
+
sympy.utilities.exceptions.sympy_deprecation_warning
|
| 375 |
+
sympy.utilities.decorator.deprecated
|
| 376 |
+
|
| 377 |
+
'''
|
| 378 |
+
with warns(SymPyDeprecationWarning):
|
| 379 |
+
yield
|
| 380 |
+
|
| 381 |
+
|
| 382 |
+
def _running_under_pyodide():
|
| 383 |
+
"""Test if running under pyodide."""
|
| 384 |
+
try:
|
| 385 |
+
import pyodide_js # type: ignore # noqa
|
| 386 |
+
except ImportError:
|
| 387 |
+
return False
|
| 388 |
+
else:
|
| 389 |
+
return True
|
| 390 |
+
|
| 391 |
+
|
| 392 |
+
def skip_under_pyodide(message):
|
| 393 |
+
"""Decorator to skip a test if running under pyodide."""
|
| 394 |
+
def decorator(test_func):
|
| 395 |
+
@functools.wraps(test_func)
|
| 396 |
+
def test_wrapper():
|
| 397 |
+
if _running_under_pyodide():
|
| 398 |
+
skip(message)
|
| 399 |
+
return test_func()
|
| 400 |
+
return test_wrapper
|
| 401 |
+
return decorator
|
evalkit_tf437/lib/python3.10/site-packages/sympy/testing/quality_unicode.py
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import re
|
| 2 |
+
import fnmatch
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
message_unicode_B = \
|
| 6 |
+
"File contains a unicode character : %s, line %s. " \
|
| 7 |
+
"But not in the whitelist. " \
|
| 8 |
+
"Add the file to the whitelist in " + __file__
|
| 9 |
+
message_unicode_D = \
|
| 10 |
+
"File does not contain a unicode character : %s." \
|
| 11 |
+
"but is in the whitelist. " \
|
| 12 |
+
"Remove the file from the whitelist in " + __file__
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
encoding_header_re = re.compile(
|
| 16 |
+
r'^[ \t\f]*#.*?coding[:=][ \t]*([-_.a-zA-Z0-9]+)')
|
| 17 |
+
|
| 18 |
+
# Whitelist pattern for files which can have unicode.
|
| 19 |
+
unicode_whitelist = [
|
| 20 |
+
# Author names can include non-ASCII characters
|
| 21 |
+
r'*/bin/authors_update.py',
|
| 22 |
+
r'*/bin/mailmap_check.py',
|
| 23 |
+
|
| 24 |
+
# These files have functions and test functions for unicode input and
|
| 25 |
+
# output.
|
| 26 |
+
r'*/sympy/testing/tests/test_code_quality.py',
|
| 27 |
+
r'*/sympy/physics/vector/tests/test_printing.py',
|
| 28 |
+
r'*/physics/quantum/tests/test_printing.py',
|
| 29 |
+
r'*/sympy/vector/tests/test_printing.py',
|
| 30 |
+
r'*/sympy/parsing/tests/test_sympy_parser.py',
|
| 31 |
+
r'*/sympy/printing/pretty/stringpict.py',
|
| 32 |
+
r'*/sympy/printing/pretty/tests/test_pretty.py',
|
| 33 |
+
r'*/sympy/printing/tests/test_conventions.py',
|
| 34 |
+
r'*/sympy/printing/tests/test_preview.py',
|
| 35 |
+
r'*/liealgebras/type_g.py',
|
| 36 |
+
r'*/liealgebras/weyl_group.py',
|
| 37 |
+
r'*/liealgebras/tests/test_type_G.py',
|
| 38 |
+
|
| 39 |
+
# wigner.py and polarization.py have unicode doctests. These probably
|
| 40 |
+
# don't need to be there but some of the examples that are there are
|
| 41 |
+
# pretty ugly without use_unicode (matrices need to be wrapped across
|
| 42 |
+
# multiple lines etc)
|
| 43 |
+
r'*/sympy/physics/wigner.py',
|
| 44 |
+
r'*/sympy/physics/optics/polarization.py',
|
| 45 |
+
|
| 46 |
+
# joint.py uses some unicode for variable names in the docstrings
|
| 47 |
+
r'*/sympy/physics/mechanics/joint.py',
|
| 48 |
+
|
| 49 |
+
# lll method has unicode in docstring references and author name
|
| 50 |
+
r'*/sympy/polys/matrices/domainmatrix.py',
|
| 51 |
+
r'*/sympy/matrices/repmatrix.py',
|
| 52 |
+
|
| 53 |
+
# Explanation of symbols uses greek letters
|
| 54 |
+
r'*/sympy/core/symbol.py',
|
| 55 |
+
]
|
| 56 |
+
|
| 57 |
+
unicode_strict_whitelist = [
|
| 58 |
+
r'*/sympy/parsing/latex/_antlr/__init__.py',
|
| 59 |
+
# test_mathematica.py uses some unicode for testing Greek characters are working #24055
|
| 60 |
+
r'*/sympy/parsing/tests/test_mathematica.py',
|
| 61 |
+
]
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def _test_this_file_encoding(
|
| 65 |
+
fname, test_file,
|
| 66 |
+
unicode_whitelist=unicode_whitelist,
|
| 67 |
+
unicode_strict_whitelist=unicode_strict_whitelist):
|
| 68 |
+
"""Test helper function for unicode test
|
| 69 |
+
|
| 70 |
+
The test may have to operate on filewise manner, so it had moved
|
| 71 |
+
to a separate process.
|
| 72 |
+
"""
|
| 73 |
+
has_unicode = False
|
| 74 |
+
|
| 75 |
+
is_in_whitelist = False
|
| 76 |
+
is_in_strict_whitelist = False
|
| 77 |
+
for patt in unicode_whitelist:
|
| 78 |
+
if fnmatch.fnmatch(fname, patt):
|
| 79 |
+
is_in_whitelist = True
|
| 80 |
+
break
|
| 81 |
+
for patt in unicode_strict_whitelist:
|
| 82 |
+
if fnmatch.fnmatch(fname, patt):
|
| 83 |
+
is_in_strict_whitelist = True
|
| 84 |
+
is_in_whitelist = True
|
| 85 |
+
break
|
| 86 |
+
|
| 87 |
+
if is_in_whitelist:
|
| 88 |
+
for idx, line in enumerate(test_file):
|
| 89 |
+
try:
|
| 90 |
+
line.encode(encoding='ascii')
|
| 91 |
+
except (UnicodeEncodeError, UnicodeDecodeError):
|
| 92 |
+
has_unicode = True
|
| 93 |
+
|
| 94 |
+
if not has_unicode and not is_in_strict_whitelist:
|
| 95 |
+
assert False, message_unicode_D % fname
|
| 96 |
+
|
| 97 |
+
else:
|
| 98 |
+
for idx, line in enumerate(test_file):
|
| 99 |
+
try:
|
| 100 |
+
line.encode(encoding='ascii')
|
| 101 |
+
except (UnicodeEncodeError, UnicodeDecodeError):
|
| 102 |
+
assert False, message_unicode_B % (fname, idx + 1)
|
evalkit_tf437/lib/python3.10/site-packages/sympy/testing/randtest.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
.. deprecated:: 1.10
|
| 3 |
+
|
| 4 |
+
``sympy.testing.randtest`` functions have been moved to
|
| 5 |
+
:mod:`sympy.core.random`.
|
| 6 |
+
|
| 7 |
+
"""
|
| 8 |
+
from sympy.utilities.exceptions import sympy_deprecation_warning
|
| 9 |
+
|
| 10 |
+
sympy_deprecation_warning("The sympy.testing.randtest submodule is deprecated. Use sympy.core.random instead.",
|
| 11 |
+
deprecated_since_version="1.10",
|
| 12 |
+
active_deprecations_target="deprecated-sympy-testing-randtest")
|
| 13 |
+
|
| 14 |
+
from sympy.core.random import ( # noqa:F401
|
| 15 |
+
random_complex_number,
|
| 16 |
+
verify_numerically,
|
| 17 |
+
test_derivative_numerically,
|
| 18 |
+
_randrange,
|
| 19 |
+
_randint)
|
evalkit_tf437/lib/python3.10/site-packages/sympy/testing/runtests.py
ADDED
|
@@ -0,0 +1,2409 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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| 6 |
+
* it should be compatible with py.test and operate very similarly
|
| 7 |
+
(or identically)
|
| 8 |
+
* does not require any external dependencies
|
| 9 |
+
* preferably all the functionality should be in this file only
|
| 10 |
+
* no magic, just import the test file and execute the test functions, that's it
|
| 11 |
+
* portable
|
| 12 |
+
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
import os
|
| 16 |
+
import sys
|
| 17 |
+
import platform
|
| 18 |
+
import inspect
|
| 19 |
+
import traceback
|
| 20 |
+
import pdb
|
| 21 |
+
import re
|
| 22 |
+
import linecache
|
| 23 |
+
import time
|
| 24 |
+
from fnmatch import fnmatch
|
| 25 |
+
from timeit import default_timer as clock
|
| 26 |
+
import doctest as pdoctest # avoid clashing with our doctest() function
|
| 27 |
+
from doctest import DocTestFinder, DocTestRunner
|
| 28 |
+
import random
|
| 29 |
+
import subprocess
|
| 30 |
+
import shutil
|
| 31 |
+
import signal
|
| 32 |
+
import stat
|
| 33 |
+
import tempfile
|
| 34 |
+
import warnings
|
| 35 |
+
from contextlib import contextmanager
|
| 36 |
+
from inspect import unwrap
|
| 37 |
+
|
| 38 |
+
from sympy.core.cache import clear_cache
|
| 39 |
+
from sympy.external import import_module
|
| 40 |
+
from sympy.external.gmpy import GROUND_TYPES
|
| 41 |
+
|
| 42 |
+
IS_WINDOWS = (os.name == 'nt')
|
| 43 |
+
ON_CI = os.getenv('CI', None)
|
| 44 |
+
|
| 45 |
+
# empirically generated list of the proportion of time spent running
|
| 46 |
+
# an even split of tests. This should periodically be regenerated.
|
| 47 |
+
# A list of [.6, .1, .3] would mean that if the tests are evenly split
|
| 48 |
+
# into '1/3', '2/3', '3/3', the first split would take 60% of the time,
|
| 49 |
+
# the second 10% and the third 30%. These lists are normalized to sum
|
| 50 |
+
# to 1, so [60, 10, 30] has the same behavior as [6, 1, 3] or [.6, .1, .3].
|
| 51 |
+
#
|
| 52 |
+
# This list can be generated with the code:
|
| 53 |
+
# from time import time
|
| 54 |
+
# import sympy
|
| 55 |
+
# import os
|
| 56 |
+
# os.environ["CI"] = 'true' # Mock CI to get more correct densities
|
| 57 |
+
# delays, num_splits = [], 30
|
| 58 |
+
# for i in range(1, num_splits + 1):
|
| 59 |
+
# tic = time()
|
| 60 |
+
# sympy.test(split='{}/{}'.format(i, num_splits), time_balance=False) # Add slow=True for slow tests
|
| 61 |
+
# delays.append(time() - tic)
|
| 62 |
+
# tot = sum(delays)
|
| 63 |
+
# print([round(x / tot, 4) for x in delays])
|
| 64 |
+
SPLIT_DENSITY = [
|
| 65 |
+
0.0059, 0.0027, 0.0068, 0.0011, 0.0006,
|
| 66 |
+
0.0058, 0.0047, 0.0046, 0.004, 0.0257,
|
| 67 |
+
0.0017, 0.0026, 0.004, 0.0032, 0.0016,
|
| 68 |
+
0.0015, 0.0004, 0.0011, 0.0016, 0.0014,
|
| 69 |
+
0.0077, 0.0137, 0.0217, 0.0074, 0.0043,
|
| 70 |
+
0.0067, 0.0236, 0.0004, 0.1189, 0.0142,
|
| 71 |
+
0.0234, 0.0003, 0.0003, 0.0047, 0.0006,
|
| 72 |
+
0.0013, 0.0004, 0.0008, 0.0007, 0.0006,
|
| 73 |
+
0.0139, 0.0013, 0.0007, 0.0051, 0.002,
|
| 74 |
+
0.0004, 0.0005, 0.0213, 0.0048, 0.0016,
|
| 75 |
+
0.0012, 0.0014, 0.0024, 0.0015, 0.0004,
|
| 76 |
+
0.0005, 0.0007, 0.011, 0.0062, 0.0015,
|
| 77 |
+
0.0021, 0.0049, 0.0006, 0.0006, 0.0011,
|
| 78 |
+
0.0006, 0.0019, 0.003, 0.0044, 0.0054,
|
| 79 |
+
0.0057, 0.0049, 0.0016, 0.0006, 0.0009,
|
| 80 |
+
0.0006, 0.0012, 0.0006, 0.0149, 0.0532,
|
| 81 |
+
0.0076, 0.0041, 0.0024, 0.0135, 0.0081,
|
| 82 |
+
0.2209, 0.0459, 0.0438, 0.0488, 0.0137,
|
| 83 |
+
0.002, 0.0003, 0.0008, 0.0039, 0.0024,
|
| 84 |
+
0.0005, 0.0004, 0.003, 0.056, 0.0026]
|
| 85 |
+
SPLIT_DENSITY_SLOW = [0.0086, 0.0004, 0.0568, 0.0003, 0.0032, 0.0005, 0.0004, 0.0013, 0.0016, 0.0648, 0.0198, 0.1285, 0.098, 0.0005, 0.0064, 0.0003, 0.0004, 0.0026, 0.0007, 0.0051, 0.0089, 0.0024, 0.0033, 0.0057, 0.0005, 0.0003, 0.001, 0.0045, 0.0091, 0.0006, 0.0005, 0.0321, 0.0059, 0.1105, 0.216, 0.1489, 0.0004, 0.0003, 0.0006, 0.0483]
|
| 86 |
+
|
| 87 |
+
class Skipped(Exception):
|
| 88 |
+
pass
|
| 89 |
+
|
| 90 |
+
class TimeOutError(Exception):
|
| 91 |
+
pass
|
| 92 |
+
|
| 93 |
+
class DependencyError(Exception):
|
| 94 |
+
pass
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def _indent(s, indent=4):
|
| 98 |
+
"""
|
| 99 |
+
Add the given number of space characters to the beginning of
|
| 100 |
+
every non-blank line in ``s``, and return the result.
|
| 101 |
+
If the string ``s`` is Unicode, it is encoded using the stdout
|
| 102 |
+
encoding and the ``backslashreplace`` error handler.
|
| 103 |
+
"""
|
| 104 |
+
# This regexp matches the start of non-blank lines:
|
| 105 |
+
return re.sub('(?m)^(?!$)', indent*' ', s)
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
pdoctest._indent = _indent # type: ignore
|
| 109 |
+
|
| 110 |
+
# override reporter to maintain windows and python3
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def _report_failure(self, out, test, example, got):
|
| 114 |
+
"""
|
| 115 |
+
Report that the given example failed.
|
| 116 |
+
"""
|
| 117 |
+
s = self._checker.output_difference(example, got, self.optionflags)
|
| 118 |
+
s = s.encode('raw_unicode_escape').decode('utf8', 'ignore')
|
| 119 |
+
out(self._failure_header(test, example) + s)
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
if IS_WINDOWS:
|
| 123 |
+
DocTestRunner.report_failure = _report_failure # type: ignore
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def convert_to_native_paths(lst):
|
| 127 |
+
"""
|
| 128 |
+
Converts a list of '/' separated paths into a list of
|
| 129 |
+
native (os.sep separated) paths and converts to lowercase
|
| 130 |
+
if the system is case insensitive.
|
| 131 |
+
"""
|
| 132 |
+
newlst = []
|
| 133 |
+
for i, rv in enumerate(lst):
|
| 134 |
+
rv = os.path.join(*rv.split("/"))
|
| 135 |
+
# on windows the slash after the colon is dropped
|
| 136 |
+
if sys.platform == "win32":
|
| 137 |
+
pos = rv.find(':')
|
| 138 |
+
if pos != -1:
|
| 139 |
+
if rv[pos + 1] != '\\':
|
| 140 |
+
rv = rv[:pos + 1] + '\\' + rv[pos + 1:]
|
| 141 |
+
newlst.append(os.path.normcase(rv))
|
| 142 |
+
return newlst
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
def get_sympy_dir():
|
| 146 |
+
"""
|
| 147 |
+
Returns the root SymPy directory and set the global value
|
| 148 |
+
indicating whether the system is case sensitive or not.
|
| 149 |
+
"""
|
| 150 |
+
this_file = os.path.abspath(__file__)
|
| 151 |
+
sympy_dir = os.path.join(os.path.dirname(this_file), "..", "..")
|
| 152 |
+
sympy_dir = os.path.normpath(sympy_dir)
|
| 153 |
+
return os.path.normcase(sympy_dir)
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
def setup_pprint(disable_line_wrap=True):
|
| 157 |
+
from sympy.interactive.printing import init_printing
|
| 158 |
+
from sympy.printing.pretty.pretty import pprint_use_unicode
|
| 159 |
+
import sympy.interactive.printing as interactive_printing
|
| 160 |
+
from sympy.printing.pretty import stringpict
|
| 161 |
+
|
| 162 |
+
# Prevent init_printing() in doctests from affecting other doctests
|
| 163 |
+
interactive_printing.NO_GLOBAL = True
|
| 164 |
+
|
| 165 |
+
# force pprint to be in ascii mode in doctests
|
| 166 |
+
use_unicode_prev = pprint_use_unicode(False)
|
| 167 |
+
|
| 168 |
+
# disable line wrapping for pprint() outputs
|
| 169 |
+
wrap_line_prev = stringpict._GLOBAL_WRAP_LINE
|
| 170 |
+
if disable_line_wrap:
|
| 171 |
+
stringpict._GLOBAL_WRAP_LINE = False
|
| 172 |
+
|
| 173 |
+
# hook our nice, hash-stable strprinter
|
| 174 |
+
init_printing(pretty_print=False)
|
| 175 |
+
|
| 176 |
+
return use_unicode_prev, wrap_line_prev
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
@contextmanager
|
| 180 |
+
def raise_on_deprecated():
|
| 181 |
+
"""Context manager to make DeprecationWarning raise an error
|
| 182 |
+
|
| 183 |
+
This is to catch SymPyDeprecationWarning from library code while running
|
| 184 |
+
tests and doctests. It is important to use this context manager around
|
| 185 |
+
each individual test/doctest in case some tests modify the warning
|
| 186 |
+
filters.
|
| 187 |
+
"""
|
| 188 |
+
with warnings.catch_warnings():
|
| 189 |
+
warnings.filterwarnings('error', '.*', DeprecationWarning, module='sympy.*')
|
| 190 |
+
yield
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
def run_in_subprocess_with_hash_randomization(
|
| 194 |
+
function, function_args=(),
|
| 195 |
+
function_kwargs=None, command=sys.executable,
|
| 196 |
+
module='sympy.testing.runtests', force=False):
|
| 197 |
+
"""
|
| 198 |
+
Run a function in a Python subprocess with hash randomization enabled.
|
| 199 |
+
|
| 200 |
+
If hash randomization is not supported by the version of Python given, it
|
| 201 |
+
returns False. Otherwise, it returns the exit value of the command. The
|
| 202 |
+
function is passed to sys.exit(), so the return value of the function will
|
| 203 |
+
be the return value.
|
| 204 |
+
|
| 205 |
+
The environment variable PYTHONHASHSEED is used to seed Python's hash
|
| 206 |
+
randomization. If it is set, this function will return False, because
|
| 207 |
+
starting a new subprocess is unnecessary in that case. If it is not set,
|
| 208 |
+
one is set at random, and the tests are run. Note that if this
|
| 209 |
+
environment variable is set when Python starts, hash randomization is
|
| 210 |
+
automatically enabled. To force a subprocess to be created even if
|
| 211 |
+
PYTHONHASHSEED is set, pass ``force=True``. This flag will not force a
|
| 212 |
+
subprocess in Python versions that do not support hash randomization (see
|
| 213 |
+
below), because those versions of Python do not support the ``-R`` flag.
|
| 214 |
+
|
| 215 |
+
``function`` should be a string name of a function that is importable from
|
| 216 |
+
the module ``module``, like "_test". The default for ``module`` is
|
| 217 |
+
"sympy.testing.runtests". ``function_args`` and ``function_kwargs``
|
| 218 |
+
should be a repr-able tuple and dict, respectively. The default Python
|
| 219 |
+
command is sys.executable, which is the currently running Python command.
|
| 220 |
+
|
| 221 |
+
This function is necessary because the seed for hash randomization must be
|
| 222 |
+
set by the environment variable before Python starts. Hence, in order to
|
| 223 |
+
use a predetermined seed for tests, we must start Python in a separate
|
| 224 |
+
subprocess.
|
| 225 |
+
|
| 226 |
+
Hash randomization was added in the minor Python versions 2.6.8, 2.7.3,
|
| 227 |
+
3.1.5, and 3.2.3, and is enabled by default in all Python versions after
|
| 228 |
+
and including 3.3.0.
|
| 229 |
+
|
| 230 |
+
Examples
|
| 231 |
+
========
|
| 232 |
+
|
| 233 |
+
>>> from sympy.testing.runtests import (
|
| 234 |
+
... run_in_subprocess_with_hash_randomization)
|
| 235 |
+
>>> # run the core tests in verbose mode
|
| 236 |
+
>>> run_in_subprocess_with_hash_randomization("_test",
|
| 237 |
+
... function_args=("core",),
|
| 238 |
+
... function_kwargs={'verbose': True}) # doctest: +SKIP
|
| 239 |
+
# Will return 0 if sys.executable supports hash randomization and tests
|
| 240 |
+
# pass, 1 if they fail, and False if it does not support hash
|
| 241 |
+
# randomization.
|
| 242 |
+
|
| 243 |
+
"""
|
| 244 |
+
cwd = get_sympy_dir()
|
| 245 |
+
# Note, we must return False everywhere, not None, as subprocess.call will
|
| 246 |
+
# sometimes return None.
|
| 247 |
+
|
| 248 |
+
# First check if the Python version supports hash randomization
|
| 249 |
+
# If it does not have this support, it won't recognize the -R flag
|
| 250 |
+
p = subprocess.Popen([command, "-RV"], stdout=subprocess.PIPE,
|
| 251 |
+
stderr=subprocess.STDOUT, cwd=cwd)
|
| 252 |
+
p.communicate()
|
| 253 |
+
if p.returncode != 0:
|
| 254 |
+
return False
|
| 255 |
+
|
| 256 |
+
hash_seed = os.getenv("PYTHONHASHSEED")
|
| 257 |
+
if not hash_seed:
|
| 258 |
+
os.environ["PYTHONHASHSEED"] = str(random.randrange(2**32))
|
| 259 |
+
else:
|
| 260 |
+
if not force:
|
| 261 |
+
return False
|
| 262 |
+
|
| 263 |
+
function_kwargs = function_kwargs or {}
|
| 264 |
+
|
| 265 |
+
# Now run the command
|
| 266 |
+
commandstring = ("import sys; from %s import %s;sys.exit(%s(*%s, **%s))" %
|
| 267 |
+
(module, function, function, repr(function_args),
|
| 268 |
+
repr(function_kwargs)))
|
| 269 |
+
|
| 270 |
+
try:
|
| 271 |
+
p = subprocess.Popen([command, "-R", "-c", commandstring], cwd=cwd)
|
| 272 |
+
p.communicate()
|
| 273 |
+
except KeyboardInterrupt:
|
| 274 |
+
p.wait()
|
| 275 |
+
finally:
|
| 276 |
+
# Put the environment variable back, so that it reads correctly for
|
| 277 |
+
# the current Python process.
|
| 278 |
+
if hash_seed is None:
|
| 279 |
+
del os.environ["PYTHONHASHSEED"]
|
| 280 |
+
else:
|
| 281 |
+
os.environ["PYTHONHASHSEED"] = hash_seed
|
| 282 |
+
return p.returncode
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
def run_all_tests(test_args=(), test_kwargs=None,
|
| 286 |
+
doctest_args=(), doctest_kwargs=None,
|
| 287 |
+
examples_args=(), examples_kwargs=None):
|
| 288 |
+
"""
|
| 289 |
+
Run all tests.
|
| 290 |
+
|
| 291 |
+
Right now, this runs the regular tests (bin/test), the doctests
|
| 292 |
+
(bin/doctest), and the examples (examples/all.py).
|
| 293 |
+
|
| 294 |
+
This is what ``setup.py test`` uses.
|
| 295 |
+
|
| 296 |
+
You can pass arguments and keyword arguments to the test functions that
|
| 297 |
+
support them (for now, test, doctest, and the examples). See the
|
| 298 |
+
docstrings of those functions for a description of the available options.
|
| 299 |
+
|
| 300 |
+
For example, to run the solvers tests with colors turned off:
|
| 301 |
+
|
| 302 |
+
>>> from sympy.testing.runtests import run_all_tests
|
| 303 |
+
>>> run_all_tests(test_args=("solvers",),
|
| 304 |
+
... test_kwargs={"colors:False"}) # doctest: +SKIP
|
| 305 |
+
|
| 306 |
+
"""
|
| 307 |
+
tests_successful = True
|
| 308 |
+
|
| 309 |
+
test_kwargs = test_kwargs or {}
|
| 310 |
+
doctest_kwargs = doctest_kwargs or {}
|
| 311 |
+
examples_kwargs = examples_kwargs or {'quiet': True}
|
| 312 |
+
|
| 313 |
+
try:
|
| 314 |
+
# Regular tests
|
| 315 |
+
if not test(*test_args, **test_kwargs):
|
| 316 |
+
# some regular test fails, so set the tests_successful
|
| 317 |
+
# flag to false and continue running the doctests
|
| 318 |
+
tests_successful = False
|
| 319 |
+
|
| 320 |
+
# Doctests
|
| 321 |
+
print()
|
| 322 |
+
if not doctest(*doctest_args, **doctest_kwargs):
|
| 323 |
+
tests_successful = False
|
| 324 |
+
|
| 325 |
+
# Examples
|
| 326 |
+
print()
|
| 327 |
+
sys.path.append("examples") # examples/all.py
|
| 328 |
+
from all import run_examples # type: ignore
|
| 329 |
+
if not run_examples(*examples_args, **examples_kwargs):
|
| 330 |
+
tests_successful = False
|
| 331 |
+
|
| 332 |
+
if tests_successful:
|
| 333 |
+
return
|
| 334 |
+
else:
|
| 335 |
+
# Return nonzero exit code
|
| 336 |
+
sys.exit(1)
|
| 337 |
+
except KeyboardInterrupt:
|
| 338 |
+
print()
|
| 339 |
+
print("DO *NOT* COMMIT!")
|
| 340 |
+
sys.exit(1)
|
| 341 |
+
|
| 342 |
+
|
| 343 |
+
def test(*paths, subprocess=True, rerun=0, **kwargs):
|
| 344 |
+
"""
|
| 345 |
+
Run tests in the specified test_*.py files.
|
| 346 |
+
|
| 347 |
+
Tests in a particular test_*.py file are run if any of the given strings
|
| 348 |
+
in ``paths`` matches a part of the test file's path. If ``paths=[]``,
|
| 349 |
+
tests in all test_*.py files are run.
|
| 350 |
+
|
| 351 |
+
Notes:
|
| 352 |
+
|
| 353 |
+
- If sort=False, tests are run in random order (not default).
|
| 354 |
+
- Paths can be entered in native system format or in unix,
|
| 355 |
+
forward-slash format.
|
| 356 |
+
- Files that are on the blacklist can be tested by providing
|
| 357 |
+
their path; they are only excluded if no paths are given.
|
| 358 |
+
|
| 359 |
+
**Explanation of test results**
|
| 360 |
+
|
| 361 |
+
====== ===============================================================
|
| 362 |
+
Output Meaning
|
| 363 |
+
====== ===============================================================
|
| 364 |
+
. passed
|
| 365 |
+
F failed
|
| 366 |
+
X XPassed (expected to fail but passed)
|
| 367 |
+
f XFAILed (expected to fail and indeed failed)
|
| 368 |
+
s skipped
|
| 369 |
+
w slow
|
| 370 |
+
T timeout (e.g., when ``--timeout`` is used)
|
| 371 |
+
K KeyboardInterrupt (when running the slow tests with ``--slow``,
|
| 372 |
+
you can interrupt one of them without killing the test runner)
|
| 373 |
+
====== ===============================================================
|
| 374 |
+
|
| 375 |
+
|
| 376 |
+
Colors have no additional meaning and are used just to facilitate
|
| 377 |
+
interpreting the output.
|
| 378 |
+
|
| 379 |
+
Examples
|
| 380 |
+
========
|
| 381 |
+
|
| 382 |
+
>>> import sympy
|
| 383 |
+
|
| 384 |
+
Run all tests:
|
| 385 |
+
|
| 386 |
+
>>> sympy.test() # doctest: +SKIP
|
| 387 |
+
|
| 388 |
+
Run one file:
|
| 389 |
+
|
| 390 |
+
>>> sympy.test("sympy/core/tests/test_basic.py") # doctest: +SKIP
|
| 391 |
+
>>> sympy.test("_basic") # doctest: +SKIP
|
| 392 |
+
|
| 393 |
+
Run all tests in sympy/functions/ and some particular file:
|
| 394 |
+
|
| 395 |
+
>>> sympy.test("sympy/core/tests/test_basic.py",
|
| 396 |
+
... "sympy/functions") # doctest: +SKIP
|
| 397 |
+
|
| 398 |
+
Run all tests in sympy/core and sympy/utilities:
|
| 399 |
+
|
| 400 |
+
>>> sympy.test("/core", "/util") # doctest: +SKIP
|
| 401 |
+
|
| 402 |
+
Run specific test from a file:
|
| 403 |
+
|
| 404 |
+
>>> sympy.test("sympy/core/tests/test_basic.py",
|
| 405 |
+
... kw="test_equality") # doctest: +SKIP
|
| 406 |
+
|
| 407 |
+
Run specific test from any file:
|
| 408 |
+
|
| 409 |
+
>>> sympy.test(kw="subs") # doctest: +SKIP
|
| 410 |
+
|
| 411 |
+
Run the tests with verbose mode on:
|
| 412 |
+
|
| 413 |
+
>>> sympy.test(verbose=True) # doctest: +SKIP
|
| 414 |
+
|
| 415 |
+
Do not sort the test output:
|
| 416 |
+
|
| 417 |
+
>>> sympy.test(sort=False) # doctest: +SKIP
|
| 418 |
+
|
| 419 |
+
Turn on post-mortem pdb:
|
| 420 |
+
|
| 421 |
+
>>> sympy.test(pdb=True) # doctest: +SKIP
|
| 422 |
+
|
| 423 |
+
Turn off colors:
|
| 424 |
+
|
| 425 |
+
>>> sympy.test(colors=False) # doctest: +SKIP
|
| 426 |
+
|
| 427 |
+
Force colors, even when the output is not to a terminal (this is useful,
|
| 428 |
+
e.g., if you are piping to ``less -r`` and you still want colors)
|
| 429 |
+
|
| 430 |
+
>>> sympy.test(force_colors=False) # doctest: +SKIP
|
| 431 |
+
|
| 432 |
+
The traceback verboseness can be set to "short" or "no" (default is
|
| 433 |
+
"short")
|
| 434 |
+
|
| 435 |
+
>>> sympy.test(tb='no') # doctest: +SKIP
|
| 436 |
+
|
| 437 |
+
The ``split`` option can be passed to split the test run into parts. The
|
| 438 |
+
split currently only splits the test files, though this may change in the
|
| 439 |
+
future. ``split`` should be a string of the form 'a/b', which will run
|
| 440 |
+
part ``a`` of ``b``. For instance, to run the first half of the test suite:
|
| 441 |
+
|
| 442 |
+
>>> sympy.test(split='1/2') # doctest: +SKIP
|
| 443 |
+
|
| 444 |
+
The ``time_balance`` option can be passed in conjunction with ``split``.
|
| 445 |
+
If ``time_balance=True`` (the default for ``sympy.test``), SymPy will attempt
|
| 446 |
+
to split the tests such that each split takes equal time. This heuristic
|
| 447 |
+
for balancing is based on pre-recorded test data.
|
| 448 |
+
|
| 449 |
+
>>> sympy.test(split='1/2', time_balance=True) # doctest: +SKIP
|
| 450 |
+
|
| 451 |
+
You can disable running the tests in a separate subprocess using
|
| 452 |
+
``subprocess=False``. This is done to support seeding hash randomization,
|
| 453 |
+
which is enabled by default in the Python versions where it is supported.
|
| 454 |
+
If subprocess=False, hash randomization is enabled/disabled according to
|
| 455 |
+
whether it has been enabled or not in the calling Python process.
|
| 456 |
+
However, even if it is enabled, the seed cannot be printed unless it is
|
| 457 |
+
called from a new Python process.
|
| 458 |
+
|
| 459 |
+
Hash randomization was added in the minor Python versions 2.6.8, 2.7.3,
|
| 460 |
+
3.1.5, and 3.2.3, and is enabled by default in all Python versions after
|
| 461 |
+
and including 3.3.0.
|
| 462 |
+
|
| 463 |
+
If hash randomization is not supported ``subprocess=False`` is used
|
| 464 |
+
automatically.
|
| 465 |
+
|
| 466 |
+
>>> sympy.test(subprocess=False) # doctest: +SKIP
|
| 467 |
+
|
| 468 |
+
To set the hash randomization seed, set the environment variable
|
| 469 |
+
``PYTHONHASHSEED`` before running the tests. This can be done from within
|
| 470 |
+
Python using
|
| 471 |
+
|
| 472 |
+
>>> import os
|
| 473 |
+
>>> os.environ['PYTHONHASHSEED'] = '42' # doctest: +SKIP
|
| 474 |
+
|
| 475 |
+
Or from the command line using
|
| 476 |
+
|
| 477 |
+
$ PYTHONHASHSEED=42 ./bin/test
|
| 478 |
+
|
| 479 |
+
If the seed is not set, a random seed will be chosen.
|
| 480 |
+
|
| 481 |
+
Note that to reproduce the same hash values, you must use both the same seed
|
| 482 |
+
as well as the same architecture (32-bit vs. 64-bit).
|
| 483 |
+
|
| 484 |
+
"""
|
| 485 |
+
# count up from 0, do not print 0
|
| 486 |
+
print_counter = lambda i : (print("rerun %d" % (rerun-i))
|
| 487 |
+
if rerun-i else None)
|
| 488 |
+
|
| 489 |
+
if subprocess:
|
| 490 |
+
# loop backwards so last i is 0
|
| 491 |
+
for i in range(rerun, -1, -1):
|
| 492 |
+
print_counter(i)
|
| 493 |
+
ret = run_in_subprocess_with_hash_randomization("_test",
|
| 494 |
+
function_args=paths, function_kwargs=kwargs)
|
| 495 |
+
if ret is False:
|
| 496 |
+
break
|
| 497 |
+
val = not bool(ret)
|
| 498 |
+
# exit on the first failure or if done
|
| 499 |
+
if not val or i == 0:
|
| 500 |
+
return val
|
| 501 |
+
|
| 502 |
+
# rerun even if hash randomization is not supported
|
| 503 |
+
for i in range(rerun, -1, -1):
|
| 504 |
+
print_counter(i)
|
| 505 |
+
val = not bool(_test(*paths, **kwargs))
|
| 506 |
+
if not val or i == 0:
|
| 507 |
+
return val
|
| 508 |
+
|
| 509 |
+
|
| 510 |
+
def _test(*paths,
|
| 511 |
+
verbose=False, tb="short", kw=None, pdb=False, colors=True,
|
| 512 |
+
force_colors=False, sort=True, seed=None, timeout=False,
|
| 513 |
+
fail_on_timeout=False, slow=False, enhance_asserts=False, split=None,
|
| 514 |
+
time_balance=True, blacklist=(),
|
| 515 |
+
fast_threshold=None, slow_threshold=None):
|
| 516 |
+
"""
|
| 517 |
+
Internal function that actually runs the tests.
|
| 518 |
+
|
| 519 |
+
All keyword arguments from ``test()`` are passed to this function except for
|
| 520 |
+
``subprocess``.
|
| 521 |
+
|
| 522 |
+
Returns 0 if tests passed and 1 if they failed. See the docstring of
|
| 523 |
+
``test()`` for more information.
|
| 524 |
+
"""
|
| 525 |
+
kw = kw or ()
|
| 526 |
+
# ensure that kw is a tuple
|
| 527 |
+
if isinstance(kw, str):
|
| 528 |
+
kw = (kw,)
|
| 529 |
+
post_mortem = pdb
|
| 530 |
+
if seed is None:
|
| 531 |
+
seed = random.randrange(100000000)
|
| 532 |
+
if ON_CI and timeout is False:
|
| 533 |
+
timeout = 595
|
| 534 |
+
fail_on_timeout = True
|
| 535 |
+
if ON_CI:
|
| 536 |
+
blacklist = list(blacklist) + ['sympy/plotting/pygletplot/tests']
|
| 537 |
+
blacklist = convert_to_native_paths(blacklist)
|
| 538 |
+
r = PyTestReporter(verbose=verbose, tb=tb, colors=colors,
|
| 539 |
+
force_colors=force_colors, split=split)
|
| 540 |
+
# This won't strictly run the test for the corresponding file, but it is
|
| 541 |
+
# good enough for copying and pasting the failing test.
|
| 542 |
+
_paths = []
|
| 543 |
+
for path in paths:
|
| 544 |
+
if '::' in path:
|
| 545 |
+
path, _kw = path.split('::', 1)
|
| 546 |
+
kw += (_kw,)
|
| 547 |
+
_paths.append(path)
|
| 548 |
+
paths = _paths
|
| 549 |
+
|
| 550 |
+
t = SymPyTests(r, kw, post_mortem, seed,
|
| 551 |
+
fast_threshold=fast_threshold,
|
| 552 |
+
slow_threshold=slow_threshold)
|
| 553 |
+
|
| 554 |
+
test_files = t.get_test_files('sympy')
|
| 555 |
+
|
| 556 |
+
not_blacklisted = [f for f in test_files
|
| 557 |
+
if not any(b in f for b in blacklist)]
|
| 558 |
+
|
| 559 |
+
if len(paths) == 0:
|
| 560 |
+
matched = not_blacklisted
|
| 561 |
+
else:
|
| 562 |
+
paths = convert_to_native_paths(paths)
|
| 563 |
+
matched = []
|
| 564 |
+
for f in not_blacklisted:
|
| 565 |
+
basename = os.path.basename(f)
|
| 566 |
+
for p in paths:
|
| 567 |
+
if p in f or fnmatch(basename, p):
|
| 568 |
+
matched.append(f)
|
| 569 |
+
break
|
| 570 |
+
|
| 571 |
+
density = None
|
| 572 |
+
if time_balance:
|
| 573 |
+
if slow:
|
| 574 |
+
density = SPLIT_DENSITY_SLOW
|
| 575 |
+
else:
|
| 576 |
+
density = SPLIT_DENSITY
|
| 577 |
+
|
| 578 |
+
if split:
|
| 579 |
+
matched = split_list(matched, split, density=density)
|
| 580 |
+
|
| 581 |
+
t._testfiles.extend(matched)
|
| 582 |
+
|
| 583 |
+
return int(not t.test(sort=sort, timeout=timeout, slow=slow,
|
| 584 |
+
enhance_asserts=enhance_asserts, fail_on_timeout=fail_on_timeout))
|
| 585 |
+
|
| 586 |
+
|
| 587 |
+
def doctest(*paths, subprocess=True, rerun=0, **kwargs):
|
| 588 |
+
r"""
|
| 589 |
+
Runs doctests in all \*.py files in the SymPy directory which match
|
| 590 |
+
any of the given strings in ``paths`` or all tests if paths=[].
|
| 591 |
+
|
| 592 |
+
Notes:
|
| 593 |
+
|
| 594 |
+
- Paths can be entered in native system format or in unix,
|
| 595 |
+
forward-slash format.
|
| 596 |
+
- Files that are on the blacklist can be tested by providing
|
| 597 |
+
their path; they are only excluded if no paths are given.
|
| 598 |
+
|
| 599 |
+
Examples
|
| 600 |
+
========
|
| 601 |
+
|
| 602 |
+
>>> import sympy
|
| 603 |
+
|
| 604 |
+
Run all tests:
|
| 605 |
+
|
| 606 |
+
>>> sympy.doctest() # doctest: +SKIP
|
| 607 |
+
|
| 608 |
+
Run one file:
|
| 609 |
+
|
| 610 |
+
>>> sympy.doctest("sympy/core/basic.py") # doctest: +SKIP
|
| 611 |
+
>>> sympy.doctest("polynomial.rst") # doctest: +SKIP
|
| 612 |
+
|
| 613 |
+
Run all tests in sympy/functions/ and some particular file:
|
| 614 |
+
|
| 615 |
+
>>> sympy.doctest("/functions", "basic.py") # doctest: +SKIP
|
| 616 |
+
|
| 617 |
+
Run any file having polynomial in its name, doc/src/modules/polynomial.rst,
|
| 618 |
+
sympy/functions/special/polynomials.py, and sympy/polys/polynomial.py:
|
| 619 |
+
|
| 620 |
+
>>> sympy.doctest("polynomial") # doctest: +SKIP
|
| 621 |
+
|
| 622 |
+
The ``split`` option can be passed to split the test run into parts. The
|
| 623 |
+
split currently only splits the test files, though this may change in the
|
| 624 |
+
future. ``split`` should be a string of the form 'a/b', which will run
|
| 625 |
+
part ``a`` of ``b``. Note that the regular doctests and the Sphinx
|
| 626 |
+
doctests are split independently. For instance, to run the first half of
|
| 627 |
+
the test suite:
|
| 628 |
+
|
| 629 |
+
>>> sympy.doctest(split='1/2') # doctest: +SKIP
|
| 630 |
+
|
| 631 |
+
The ``subprocess`` and ``verbose`` options are the same as with the function
|
| 632 |
+
``test()`` (see the docstring of that function for more information) except
|
| 633 |
+
that ``verbose`` may also be set equal to ``2`` in order to print
|
| 634 |
+
individual doctest lines, as they are being tested.
|
| 635 |
+
"""
|
| 636 |
+
# count up from 0, do not print 0
|
| 637 |
+
print_counter = lambda i : (print("rerun %d" % (rerun-i))
|
| 638 |
+
if rerun-i else None)
|
| 639 |
+
|
| 640 |
+
if subprocess:
|
| 641 |
+
# loop backwards so last i is 0
|
| 642 |
+
for i in range(rerun, -1, -1):
|
| 643 |
+
print_counter(i)
|
| 644 |
+
ret = run_in_subprocess_with_hash_randomization("_doctest",
|
| 645 |
+
function_args=paths, function_kwargs=kwargs)
|
| 646 |
+
if ret is False:
|
| 647 |
+
break
|
| 648 |
+
val = not bool(ret)
|
| 649 |
+
# exit on the first failure or if done
|
| 650 |
+
if not val or i == 0:
|
| 651 |
+
return val
|
| 652 |
+
|
| 653 |
+
# rerun even if hash randomization is not supported
|
| 654 |
+
for i in range(rerun, -1, -1):
|
| 655 |
+
print_counter(i)
|
| 656 |
+
val = not bool(_doctest(*paths, **kwargs))
|
| 657 |
+
if not val or i == 0:
|
| 658 |
+
return val
|
| 659 |
+
|
| 660 |
+
|
| 661 |
+
def _get_doctest_blacklist():
|
| 662 |
+
'''Get the default blacklist for the doctests'''
|
| 663 |
+
blacklist = []
|
| 664 |
+
|
| 665 |
+
blacklist.extend([
|
| 666 |
+
"doc/src/modules/plotting.rst", # generates live plots
|
| 667 |
+
"doc/src/modules/physics/mechanics/autolev_parser.rst",
|
| 668 |
+
"sympy/codegen/array_utils.py", # raises deprecation warning
|
| 669 |
+
"sympy/core/compatibility.py", # backwards compatibility shim, importing it triggers a deprecation warning
|
| 670 |
+
"sympy/core/trace.py", # backwards compatibility shim, importing it triggers a deprecation warning
|
| 671 |
+
"sympy/galgebra.py", # no longer part of SymPy
|
| 672 |
+
"sympy/parsing/autolev/_antlr/autolevlexer.py", # generated code
|
| 673 |
+
"sympy/parsing/autolev/_antlr/autolevlistener.py", # generated code
|
| 674 |
+
"sympy/parsing/autolev/_antlr/autolevparser.py", # generated code
|
| 675 |
+
"sympy/parsing/latex/_antlr/latexlexer.py", # generated code
|
| 676 |
+
"sympy/parsing/latex/_antlr/latexparser.py", # generated code
|
| 677 |
+
"sympy/plotting/pygletplot/__init__.py", # crashes on some systems
|
| 678 |
+
"sympy/plotting/pygletplot/plot.py", # crashes on some systems
|
| 679 |
+
"sympy/printing/ccode.py", # backwards compatibility shim, importing it breaks the codegen doctests
|
| 680 |
+
"sympy/printing/cxxcode.py", # backwards compatibility shim, importing it breaks the codegen doctests
|
| 681 |
+
"sympy/printing/fcode.py", # backwards compatibility shim, importing it breaks the codegen doctests
|
| 682 |
+
"sympy/testing/randtest.py", # backwards compatibility shim, importing it triggers a deprecation warning
|
| 683 |
+
"sympy/this.py", # prints text
|
| 684 |
+
])
|
| 685 |
+
# autolev parser tests
|
| 686 |
+
num = 12
|
| 687 |
+
for i in range (1, num+1):
|
| 688 |
+
blacklist.append("sympy/parsing/autolev/test-examples/ruletest" + str(i) + ".py")
|
| 689 |
+
blacklist.extend(["sympy/parsing/autolev/test-examples/pydy-example-repo/mass_spring_damper.py",
|
| 690 |
+
"sympy/parsing/autolev/test-examples/pydy-example-repo/chaos_pendulum.py",
|
| 691 |
+
"sympy/parsing/autolev/test-examples/pydy-example-repo/double_pendulum.py",
|
| 692 |
+
"sympy/parsing/autolev/test-examples/pydy-example-repo/non_min_pendulum.py"])
|
| 693 |
+
|
| 694 |
+
if import_module('numpy') is None:
|
| 695 |
+
blacklist.extend([
|
| 696 |
+
"sympy/plotting/experimental_lambdify.py",
|
| 697 |
+
"sympy/plotting/plot_implicit.py",
|
| 698 |
+
"examples/advanced/autowrap_integrators.py",
|
| 699 |
+
"examples/advanced/autowrap_ufuncify.py",
|
| 700 |
+
"examples/intermediate/sample.py",
|
| 701 |
+
"examples/intermediate/mplot2d.py",
|
| 702 |
+
"examples/intermediate/mplot3d.py",
|
| 703 |
+
"doc/src/modules/numeric-computation.rst",
|
| 704 |
+
"doc/src/explanation/best-practices.md",
|
| 705 |
+
"doc/src/tutorials/physics/biomechanics/biomechanical-model-example.rst",
|
| 706 |
+
"doc/src/tutorials/physics/biomechanics/biomechanics.rst",
|
| 707 |
+
])
|
| 708 |
+
else:
|
| 709 |
+
if import_module('matplotlib') is None:
|
| 710 |
+
blacklist.extend([
|
| 711 |
+
"examples/intermediate/mplot2d.py",
|
| 712 |
+
"examples/intermediate/mplot3d.py"
|
| 713 |
+
])
|
| 714 |
+
else:
|
| 715 |
+
# Use a non-windowed backend, so that the tests work on CI
|
| 716 |
+
import matplotlib
|
| 717 |
+
matplotlib.use('Agg')
|
| 718 |
+
|
| 719 |
+
if ON_CI or import_module('pyglet') is None:
|
| 720 |
+
blacklist.extend(["sympy/plotting/pygletplot"])
|
| 721 |
+
|
| 722 |
+
if import_module('aesara') is None:
|
| 723 |
+
blacklist.extend([
|
| 724 |
+
"sympy/printing/aesaracode.py",
|
| 725 |
+
"doc/src/modules/numeric-computation.rst",
|
| 726 |
+
])
|
| 727 |
+
|
| 728 |
+
if import_module('cupy') is None:
|
| 729 |
+
blacklist.extend([
|
| 730 |
+
"doc/src/modules/numeric-computation.rst",
|
| 731 |
+
])
|
| 732 |
+
|
| 733 |
+
if import_module('jax') is None:
|
| 734 |
+
blacklist.extend([
|
| 735 |
+
"doc/src/modules/numeric-computation.rst",
|
| 736 |
+
])
|
| 737 |
+
|
| 738 |
+
if import_module('antlr4') is None:
|
| 739 |
+
blacklist.extend([
|
| 740 |
+
"sympy/parsing/autolev/__init__.py",
|
| 741 |
+
"sympy/parsing/latex/_parse_latex_antlr.py",
|
| 742 |
+
])
|
| 743 |
+
|
| 744 |
+
if import_module('lfortran') is None:
|
| 745 |
+
#throws ImportError when lfortran not installed
|
| 746 |
+
blacklist.extend([
|
| 747 |
+
"sympy/parsing/sym_expr.py",
|
| 748 |
+
])
|
| 749 |
+
|
| 750 |
+
if import_module("scipy") is None:
|
| 751 |
+
# throws ModuleNotFoundError when scipy not installed
|
| 752 |
+
blacklist.extend([
|
| 753 |
+
"doc/src/guides/solving/solve-numerically.md",
|
| 754 |
+
"doc/src/guides/solving/solve-ode.md",
|
| 755 |
+
])
|
| 756 |
+
|
| 757 |
+
if import_module("numpy") is None:
|
| 758 |
+
# throws ModuleNotFoundError when numpy not installed
|
| 759 |
+
blacklist.extend([
|
| 760 |
+
"doc/src/guides/solving/solve-ode.md",
|
| 761 |
+
"doc/src/guides/solving/solve-numerically.md",
|
| 762 |
+
])
|
| 763 |
+
|
| 764 |
+
# disabled because of doctest failures in asmeurer's bot
|
| 765 |
+
blacklist.extend([
|
| 766 |
+
"sympy/utilities/autowrap.py",
|
| 767 |
+
"examples/advanced/autowrap_integrators.py",
|
| 768 |
+
"examples/advanced/autowrap_ufuncify.py"
|
| 769 |
+
])
|
| 770 |
+
|
| 771 |
+
blacklist.extend([
|
| 772 |
+
"sympy/conftest.py", # Depends on pytest
|
| 773 |
+
])
|
| 774 |
+
|
| 775 |
+
# These are deprecated stubs to be removed:
|
| 776 |
+
blacklist.extend([
|
| 777 |
+
"sympy/utilities/tmpfiles.py",
|
| 778 |
+
"sympy/utilities/pytest.py",
|
| 779 |
+
"sympy/utilities/runtests.py",
|
| 780 |
+
"sympy/utilities/quality_unicode.py",
|
| 781 |
+
"sympy/utilities/randtest.py",
|
| 782 |
+
])
|
| 783 |
+
|
| 784 |
+
blacklist = convert_to_native_paths(blacklist)
|
| 785 |
+
return blacklist
|
| 786 |
+
|
| 787 |
+
|
| 788 |
+
def _doctest(*paths, **kwargs):
|
| 789 |
+
"""
|
| 790 |
+
Internal function that actually runs the doctests.
|
| 791 |
+
|
| 792 |
+
All keyword arguments from ``doctest()`` are passed to this function
|
| 793 |
+
except for ``subprocess``.
|
| 794 |
+
|
| 795 |
+
Returns 0 if tests passed and 1 if they failed. See the docstrings of
|
| 796 |
+
``doctest()`` and ``test()`` for more information.
|
| 797 |
+
"""
|
| 798 |
+
from sympy.printing.pretty.pretty import pprint_use_unicode
|
| 799 |
+
from sympy.printing.pretty import stringpict
|
| 800 |
+
|
| 801 |
+
normal = kwargs.get("normal", False)
|
| 802 |
+
verbose = kwargs.get("verbose", False)
|
| 803 |
+
colors = kwargs.get("colors", True)
|
| 804 |
+
force_colors = kwargs.get("force_colors", False)
|
| 805 |
+
blacklist = kwargs.get("blacklist", [])
|
| 806 |
+
split = kwargs.get('split', None)
|
| 807 |
+
|
| 808 |
+
blacklist.extend(_get_doctest_blacklist())
|
| 809 |
+
|
| 810 |
+
# Use a non-windowed backend, so that the tests work on CI
|
| 811 |
+
if import_module('matplotlib') is not None:
|
| 812 |
+
import matplotlib
|
| 813 |
+
matplotlib.use('Agg')
|
| 814 |
+
|
| 815 |
+
# Disable warnings for external modules
|
| 816 |
+
import sympy.external
|
| 817 |
+
sympy.external.importtools.WARN_OLD_VERSION = False
|
| 818 |
+
sympy.external.importtools.WARN_NOT_INSTALLED = False
|
| 819 |
+
|
| 820 |
+
# Disable showing up of plots
|
| 821 |
+
from sympy.plotting.plot import unset_show
|
| 822 |
+
unset_show()
|
| 823 |
+
|
| 824 |
+
r = PyTestReporter(verbose, split=split, colors=colors,\
|
| 825 |
+
force_colors=force_colors)
|
| 826 |
+
t = SymPyDocTests(r, normal)
|
| 827 |
+
|
| 828 |
+
test_files = t.get_test_files('sympy')
|
| 829 |
+
test_files.extend(t.get_test_files('examples', init_only=False))
|
| 830 |
+
|
| 831 |
+
not_blacklisted = [f for f in test_files
|
| 832 |
+
if not any(b in f for b in blacklist)]
|
| 833 |
+
if len(paths) == 0:
|
| 834 |
+
matched = not_blacklisted
|
| 835 |
+
else:
|
| 836 |
+
# take only what was requested...but not blacklisted items
|
| 837 |
+
# and allow for partial match anywhere or fnmatch of name
|
| 838 |
+
paths = convert_to_native_paths(paths)
|
| 839 |
+
matched = []
|
| 840 |
+
for f in not_blacklisted:
|
| 841 |
+
basename = os.path.basename(f)
|
| 842 |
+
for p in paths:
|
| 843 |
+
if p in f or fnmatch(basename, p):
|
| 844 |
+
matched.append(f)
|
| 845 |
+
break
|
| 846 |
+
|
| 847 |
+
matched.sort()
|
| 848 |
+
|
| 849 |
+
if split:
|
| 850 |
+
matched = split_list(matched, split)
|
| 851 |
+
|
| 852 |
+
t._testfiles.extend(matched)
|
| 853 |
+
|
| 854 |
+
# run the tests and record the result for this *py portion of the tests
|
| 855 |
+
if t._testfiles:
|
| 856 |
+
failed = not t.test()
|
| 857 |
+
else:
|
| 858 |
+
failed = False
|
| 859 |
+
|
| 860 |
+
# N.B.
|
| 861 |
+
# --------------------------------------------------------------------
|
| 862 |
+
# Here we test *.rst and *.md files at or below doc/src. Code from these
|
| 863 |
+
# must be self supporting in terms of imports since there is no importing
|
| 864 |
+
# of necessary modules by doctest.testfile. If you try to pass *.py files
|
| 865 |
+
# through this they might fail because they will lack the needed imports
|
| 866 |
+
# and smarter parsing that can be done with source code.
|
| 867 |
+
#
|
| 868 |
+
test_files_rst = t.get_test_files('doc/src', '*.rst', init_only=False)
|
| 869 |
+
test_files_md = t.get_test_files('doc/src', '*.md', init_only=False)
|
| 870 |
+
test_files = test_files_rst + test_files_md
|
| 871 |
+
test_files.sort()
|
| 872 |
+
|
| 873 |
+
not_blacklisted = [f for f in test_files
|
| 874 |
+
if not any(b in f for b in blacklist)]
|
| 875 |
+
|
| 876 |
+
if len(paths) == 0:
|
| 877 |
+
matched = not_blacklisted
|
| 878 |
+
else:
|
| 879 |
+
# Take only what was requested as long as it's not on the blacklist.
|
| 880 |
+
# Paths were already made native in *py tests so don't repeat here.
|
| 881 |
+
# There's no chance of having a *py file slip through since we
|
| 882 |
+
# only have *rst files in test_files.
|
| 883 |
+
matched = []
|
| 884 |
+
for f in not_blacklisted:
|
| 885 |
+
basename = os.path.basename(f)
|
| 886 |
+
for p in paths:
|
| 887 |
+
if p in f or fnmatch(basename, p):
|
| 888 |
+
matched.append(f)
|
| 889 |
+
break
|
| 890 |
+
|
| 891 |
+
if split:
|
| 892 |
+
matched = split_list(matched, split)
|
| 893 |
+
|
| 894 |
+
first_report = True
|
| 895 |
+
for rst_file in matched:
|
| 896 |
+
if not os.path.isfile(rst_file):
|
| 897 |
+
continue
|
| 898 |
+
old_displayhook = sys.displayhook
|
| 899 |
+
try:
|
| 900 |
+
use_unicode_prev, wrap_line_prev = setup_pprint()
|
| 901 |
+
out = sympytestfile(
|
| 902 |
+
rst_file, module_relative=False, encoding='utf-8',
|
| 903 |
+
optionflags=pdoctest.ELLIPSIS | pdoctest.NORMALIZE_WHITESPACE |
|
| 904 |
+
pdoctest.IGNORE_EXCEPTION_DETAIL)
|
| 905 |
+
finally:
|
| 906 |
+
# make sure we return to the original displayhook in case some
|
| 907 |
+
# doctest has changed that
|
| 908 |
+
sys.displayhook = old_displayhook
|
| 909 |
+
# The NO_GLOBAL flag overrides the no_global flag to init_printing
|
| 910 |
+
# if True
|
| 911 |
+
import sympy.interactive.printing as interactive_printing
|
| 912 |
+
interactive_printing.NO_GLOBAL = False
|
| 913 |
+
pprint_use_unicode(use_unicode_prev)
|
| 914 |
+
stringpict._GLOBAL_WRAP_LINE = wrap_line_prev
|
| 915 |
+
|
| 916 |
+
rstfailed, tested = out
|
| 917 |
+
if tested:
|
| 918 |
+
failed = rstfailed or failed
|
| 919 |
+
if first_report:
|
| 920 |
+
first_report = False
|
| 921 |
+
msg = 'rst/md doctests start'
|
| 922 |
+
if not t._testfiles:
|
| 923 |
+
r.start(msg=msg)
|
| 924 |
+
else:
|
| 925 |
+
r.write_center(msg)
|
| 926 |
+
print()
|
| 927 |
+
# use as the id, everything past the first 'sympy'
|
| 928 |
+
file_id = rst_file[rst_file.find('sympy') + len('sympy') + 1:]
|
| 929 |
+
print(file_id, end=" ")
|
| 930 |
+
# get at least the name out so it is know who is being tested
|
| 931 |
+
wid = r.terminal_width - len(file_id) - 1 # update width
|
| 932 |
+
test_file = '[%s]' % (tested)
|
| 933 |
+
report = '[%s]' % (rstfailed or 'OK')
|
| 934 |
+
print(''.join(
|
| 935 |
+
[test_file, ' '*(wid - len(test_file) - len(report)), report])
|
| 936 |
+
)
|
| 937 |
+
|
| 938 |
+
# the doctests for *py will have printed this message already if there was
|
| 939 |
+
# a failure, so now only print it if there was intervening reporting by
|
| 940 |
+
# testing the *rst as evidenced by first_report no longer being True.
|
| 941 |
+
if not first_report and failed:
|
| 942 |
+
print()
|
| 943 |
+
print("DO *NOT* COMMIT!")
|
| 944 |
+
|
| 945 |
+
return int(failed)
|
| 946 |
+
|
| 947 |
+
sp = re.compile(r'([0-9]+)/([1-9][0-9]*)')
|
| 948 |
+
|
| 949 |
+
def split_list(l, split, density=None):
|
| 950 |
+
"""
|
| 951 |
+
Splits a list into part a of b
|
| 952 |
+
|
| 953 |
+
split should be a string of the form 'a/b'. For instance, '1/3' would give
|
| 954 |
+
the split one of three.
|
| 955 |
+
|
| 956 |
+
If the length of the list is not divisible by the number of splits, the
|
| 957 |
+
last split will have more items.
|
| 958 |
+
|
| 959 |
+
`density` may be specified as a list. If specified,
|
| 960 |
+
tests will be balanced so that each split has as equal-as-possible
|
| 961 |
+
amount of mass according to `density`.
|
| 962 |
+
|
| 963 |
+
>>> from sympy.testing.runtests import split_list
|
| 964 |
+
>>> a = list(range(10))
|
| 965 |
+
>>> split_list(a, '1/3')
|
| 966 |
+
[0, 1, 2]
|
| 967 |
+
>>> split_list(a, '2/3')
|
| 968 |
+
[3, 4, 5]
|
| 969 |
+
>>> split_list(a, '3/3')
|
| 970 |
+
[6, 7, 8, 9]
|
| 971 |
+
"""
|
| 972 |
+
m = sp.match(split)
|
| 973 |
+
if not m:
|
| 974 |
+
raise ValueError("split must be a string of the form a/b where a and b are ints")
|
| 975 |
+
i, t = map(int, m.groups())
|
| 976 |
+
|
| 977 |
+
if not density:
|
| 978 |
+
return l[(i - 1)*len(l)//t : i*len(l)//t]
|
| 979 |
+
|
| 980 |
+
# normalize density
|
| 981 |
+
tot = sum(density)
|
| 982 |
+
density = [x / tot for x in density]
|
| 983 |
+
|
| 984 |
+
def density_inv(x):
|
| 985 |
+
"""Interpolate the inverse to the cumulative
|
| 986 |
+
distribution function given by density"""
|
| 987 |
+
if x <= 0:
|
| 988 |
+
return 0
|
| 989 |
+
if x >= sum(density):
|
| 990 |
+
return 1
|
| 991 |
+
|
| 992 |
+
# find the first time the cumulative sum surpasses x
|
| 993 |
+
# and linearly interpolate
|
| 994 |
+
cumm = 0
|
| 995 |
+
for i, d in enumerate(density):
|
| 996 |
+
cumm += d
|
| 997 |
+
if cumm >= x:
|
| 998 |
+
break
|
| 999 |
+
frac = (d - (cumm - x)) / d
|
| 1000 |
+
return (i + frac) / len(density)
|
| 1001 |
+
|
| 1002 |
+
lower_frac = density_inv((i - 1) / t)
|
| 1003 |
+
higher_frac = density_inv(i / t)
|
| 1004 |
+
return l[int(lower_frac*len(l)) : int(higher_frac*len(l))]
|
| 1005 |
+
|
| 1006 |
+
from collections import namedtuple
|
| 1007 |
+
SymPyTestResults = namedtuple('SymPyTestResults', 'failed attempted')
|
| 1008 |
+
|
| 1009 |
+
def sympytestfile(filename, module_relative=True, name=None, package=None,
|
| 1010 |
+
globs=None, verbose=None, report=True, optionflags=0,
|
| 1011 |
+
extraglobs=None, raise_on_error=False,
|
| 1012 |
+
parser=pdoctest.DocTestParser(), encoding=None):
|
| 1013 |
+
|
| 1014 |
+
"""
|
| 1015 |
+
Test examples in the given file. Return (#failures, #tests).
|
| 1016 |
+
|
| 1017 |
+
Optional keyword arg ``module_relative`` specifies how filenames
|
| 1018 |
+
should be interpreted:
|
| 1019 |
+
|
| 1020 |
+
- If ``module_relative`` is True (the default), then ``filename``
|
| 1021 |
+
specifies a module-relative path. By default, this path is
|
| 1022 |
+
relative to the calling module's directory; but if the
|
| 1023 |
+
``package`` argument is specified, then it is relative to that
|
| 1024 |
+
package. To ensure os-independence, ``filename`` should use
|
| 1025 |
+
"/" characters to separate path segments, and should not
|
| 1026 |
+
be an absolute path (i.e., it may not begin with "/").
|
| 1027 |
+
|
| 1028 |
+
- If ``module_relative`` is False, then ``filename`` specifies an
|
| 1029 |
+
os-specific path. The path may be absolute or relative (to
|
| 1030 |
+
the current working directory).
|
| 1031 |
+
|
| 1032 |
+
Optional keyword arg ``name`` gives the name of the test; by default
|
| 1033 |
+
use the file's basename.
|
| 1034 |
+
|
| 1035 |
+
Optional keyword argument ``package`` is a Python package or the
|
| 1036 |
+
name of a Python package whose directory should be used as the
|
| 1037 |
+
base directory for a module relative filename. If no package is
|
| 1038 |
+
specified, then the calling module's directory is used as the base
|
| 1039 |
+
directory for module relative filenames. It is an error to
|
| 1040 |
+
specify ``package`` if ``module_relative`` is False.
|
| 1041 |
+
|
| 1042 |
+
Optional keyword arg ``globs`` gives a dict to be used as the globals
|
| 1043 |
+
when executing examples; by default, use {}. A copy of this dict
|
| 1044 |
+
is actually used for each docstring, so that each docstring's
|
| 1045 |
+
examples start with a clean slate.
|
| 1046 |
+
|
| 1047 |
+
Optional keyword arg ``extraglobs`` gives a dictionary that should be
|
| 1048 |
+
merged into the globals that are used to execute examples. By
|
| 1049 |
+
default, no extra globals are used.
|
| 1050 |
+
|
| 1051 |
+
Optional keyword arg ``verbose`` prints lots of stuff if true, prints
|
| 1052 |
+
only failures if false; by default, it's true iff "-v" is in sys.argv.
|
| 1053 |
+
|
| 1054 |
+
Optional keyword arg ``report`` prints a summary at the end when true,
|
| 1055 |
+
else prints nothing at the end. In verbose mode, the summary is
|
| 1056 |
+
detailed, else very brief (in fact, empty if all tests passed).
|
| 1057 |
+
|
| 1058 |
+
Optional keyword arg ``optionflags`` or's together module constants,
|
| 1059 |
+
and defaults to 0. Possible values (see the docs for details):
|
| 1060 |
+
|
| 1061 |
+
- DONT_ACCEPT_TRUE_FOR_1
|
| 1062 |
+
- DONT_ACCEPT_BLANKLINE
|
| 1063 |
+
- NORMALIZE_WHITESPACE
|
| 1064 |
+
- ELLIPSIS
|
| 1065 |
+
- SKIP
|
| 1066 |
+
- IGNORE_EXCEPTION_DETAIL
|
| 1067 |
+
- REPORT_UDIFF
|
| 1068 |
+
- REPORT_CDIFF
|
| 1069 |
+
- REPORT_NDIFF
|
| 1070 |
+
- REPORT_ONLY_FIRST_FAILURE
|
| 1071 |
+
|
| 1072 |
+
Optional keyword arg ``raise_on_error`` raises an exception on the
|
| 1073 |
+
first unexpected exception or failure. This allows failures to be
|
| 1074 |
+
post-mortem debugged.
|
| 1075 |
+
|
| 1076 |
+
Optional keyword arg ``parser`` specifies a DocTestParser (or
|
| 1077 |
+
subclass) that should be used to extract tests from the files.
|
| 1078 |
+
|
| 1079 |
+
Optional keyword arg ``encoding`` specifies an encoding that should
|
| 1080 |
+
be used to convert the file to unicode.
|
| 1081 |
+
|
| 1082 |
+
Advanced tomfoolery: testmod runs methods of a local instance of
|
| 1083 |
+
class doctest.Tester, then merges the results into (or creates)
|
| 1084 |
+
global Tester instance doctest.master. Methods of doctest.master
|
| 1085 |
+
can be called directly too, if you want to do something unusual.
|
| 1086 |
+
Passing report=0 to testmod is especially useful then, to delay
|
| 1087 |
+
displaying a summary. Invoke doctest.master.summarize(verbose)
|
| 1088 |
+
when you're done fiddling.
|
| 1089 |
+
"""
|
| 1090 |
+
if package and not module_relative:
|
| 1091 |
+
raise ValueError("Package may only be specified for module-"
|
| 1092 |
+
"relative paths.")
|
| 1093 |
+
|
| 1094 |
+
# Relativize the path
|
| 1095 |
+
text, filename = pdoctest._load_testfile(
|
| 1096 |
+
filename, package, module_relative, encoding)
|
| 1097 |
+
|
| 1098 |
+
# If no name was given, then use the file's name.
|
| 1099 |
+
if name is None:
|
| 1100 |
+
name = os.path.basename(filename)
|
| 1101 |
+
|
| 1102 |
+
# Assemble the globals.
|
| 1103 |
+
if globs is None:
|
| 1104 |
+
globs = {}
|
| 1105 |
+
else:
|
| 1106 |
+
globs = globs.copy()
|
| 1107 |
+
if extraglobs is not None:
|
| 1108 |
+
globs.update(extraglobs)
|
| 1109 |
+
if '__name__' not in globs:
|
| 1110 |
+
globs['__name__'] = '__main__'
|
| 1111 |
+
|
| 1112 |
+
if raise_on_error:
|
| 1113 |
+
runner = pdoctest.DebugRunner(verbose=verbose, optionflags=optionflags)
|
| 1114 |
+
else:
|
| 1115 |
+
runner = SymPyDocTestRunner(verbose=verbose, optionflags=optionflags)
|
| 1116 |
+
runner._checker = SymPyOutputChecker()
|
| 1117 |
+
|
| 1118 |
+
# Read the file, convert it to a test, and run it.
|
| 1119 |
+
test = parser.get_doctest(text, globs, name, filename, 0)
|
| 1120 |
+
runner.run(test)
|
| 1121 |
+
|
| 1122 |
+
if report:
|
| 1123 |
+
runner.summarize()
|
| 1124 |
+
|
| 1125 |
+
if pdoctest.master is None:
|
| 1126 |
+
pdoctest.master = runner
|
| 1127 |
+
else:
|
| 1128 |
+
pdoctest.master.merge(runner)
|
| 1129 |
+
|
| 1130 |
+
return SymPyTestResults(runner.failures, runner.tries)
|
| 1131 |
+
|
| 1132 |
+
|
| 1133 |
+
class SymPyTests:
|
| 1134 |
+
|
| 1135 |
+
def __init__(self, reporter, kw="", post_mortem=False,
|
| 1136 |
+
seed=None, fast_threshold=None, slow_threshold=None):
|
| 1137 |
+
self._post_mortem = post_mortem
|
| 1138 |
+
self._kw = kw
|
| 1139 |
+
self._count = 0
|
| 1140 |
+
self._root_dir = get_sympy_dir()
|
| 1141 |
+
self._reporter = reporter
|
| 1142 |
+
self._reporter.root_dir(self._root_dir)
|
| 1143 |
+
self._testfiles = []
|
| 1144 |
+
self._seed = seed if seed is not None else random.random()
|
| 1145 |
+
|
| 1146 |
+
# Defaults in seconds, from human / UX design limits
|
| 1147 |
+
# http://www.nngroup.com/articles/response-times-3-important-limits/
|
| 1148 |
+
#
|
| 1149 |
+
# These defaults are *NOT* set in stone as we are measuring different
|
| 1150 |
+
# things, so others feel free to come up with a better yardstick :)
|
| 1151 |
+
if fast_threshold:
|
| 1152 |
+
self._fast_threshold = float(fast_threshold)
|
| 1153 |
+
else:
|
| 1154 |
+
self._fast_threshold = 8
|
| 1155 |
+
if slow_threshold:
|
| 1156 |
+
self._slow_threshold = float(slow_threshold)
|
| 1157 |
+
else:
|
| 1158 |
+
self._slow_threshold = 10
|
| 1159 |
+
|
| 1160 |
+
def test(self, sort=False, timeout=False, slow=False,
|
| 1161 |
+
enhance_asserts=False, fail_on_timeout=False):
|
| 1162 |
+
"""
|
| 1163 |
+
Runs the tests returning True if all tests pass, otherwise False.
|
| 1164 |
+
|
| 1165 |
+
If sort=False run tests in random order.
|
| 1166 |
+
"""
|
| 1167 |
+
if sort:
|
| 1168 |
+
self._testfiles.sort()
|
| 1169 |
+
elif slow:
|
| 1170 |
+
pass
|
| 1171 |
+
else:
|
| 1172 |
+
random.seed(self._seed)
|
| 1173 |
+
random.shuffle(self._testfiles)
|
| 1174 |
+
self._reporter.start(self._seed)
|
| 1175 |
+
for f in self._testfiles:
|
| 1176 |
+
try:
|
| 1177 |
+
self.test_file(f, sort, timeout, slow,
|
| 1178 |
+
enhance_asserts, fail_on_timeout)
|
| 1179 |
+
except KeyboardInterrupt:
|
| 1180 |
+
print(" interrupted by user")
|
| 1181 |
+
self._reporter.finish()
|
| 1182 |
+
raise
|
| 1183 |
+
return self._reporter.finish()
|
| 1184 |
+
|
| 1185 |
+
def _enhance_asserts(self, source):
|
| 1186 |
+
from ast import (NodeTransformer, Compare, Name, Store, Load, Tuple,
|
| 1187 |
+
Assign, BinOp, Str, Mod, Assert, parse, fix_missing_locations)
|
| 1188 |
+
|
| 1189 |
+
ops = {"Eq": '==', "NotEq": '!=', "Lt": '<', "LtE": '<=',
|
| 1190 |
+
"Gt": '>', "GtE": '>=', "Is": 'is', "IsNot": 'is not',
|
| 1191 |
+
"In": 'in', "NotIn": 'not in'}
|
| 1192 |
+
|
| 1193 |
+
class Transform(NodeTransformer):
|
| 1194 |
+
def visit_Assert(self, stmt):
|
| 1195 |
+
if isinstance(stmt.test, Compare):
|
| 1196 |
+
compare = stmt.test
|
| 1197 |
+
values = [compare.left] + compare.comparators
|
| 1198 |
+
names = [ "_%s" % i for i, _ in enumerate(values) ]
|
| 1199 |
+
names_store = [ Name(n, Store()) for n in names ]
|
| 1200 |
+
names_load = [ Name(n, Load()) for n in names ]
|
| 1201 |
+
target = Tuple(names_store, Store())
|
| 1202 |
+
value = Tuple(values, Load())
|
| 1203 |
+
assign = Assign([target], value)
|
| 1204 |
+
new_compare = Compare(names_load[0], compare.ops, names_load[1:])
|
| 1205 |
+
msg_format = "\n%s " + "\n%s ".join([ ops[op.__class__.__name__] for op in compare.ops ]) + "\n%s"
|
| 1206 |
+
msg = BinOp(Str(msg_format), Mod(), Tuple(names_load, Load()))
|
| 1207 |
+
test = Assert(new_compare, msg, lineno=stmt.lineno, col_offset=stmt.col_offset)
|
| 1208 |
+
return [assign, test]
|
| 1209 |
+
else:
|
| 1210 |
+
return stmt
|
| 1211 |
+
|
| 1212 |
+
tree = parse(source)
|
| 1213 |
+
new_tree = Transform().visit(tree)
|
| 1214 |
+
return fix_missing_locations(new_tree)
|
| 1215 |
+
|
| 1216 |
+
def test_file(self, filename, sort=True, timeout=False, slow=False,
|
| 1217 |
+
enhance_asserts=False, fail_on_timeout=False):
|
| 1218 |
+
reporter = self._reporter
|
| 1219 |
+
funcs = []
|
| 1220 |
+
try:
|
| 1221 |
+
gl = {'__file__': filename}
|
| 1222 |
+
try:
|
| 1223 |
+
open_file = lambda: open(filename, encoding="utf8")
|
| 1224 |
+
|
| 1225 |
+
with open_file() as f:
|
| 1226 |
+
source = f.read()
|
| 1227 |
+
if self._kw:
|
| 1228 |
+
for l in source.splitlines():
|
| 1229 |
+
if l.lstrip().startswith('def '):
|
| 1230 |
+
if any(l.lower().find(k.lower()) != -1 for k in self._kw):
|
| 1231 |
+
break
|
| 1232 |
+
else:
|
| 1233 |
+
return
|
| 1234 |
+
|
| 1235 |
+
if enhance_asserts:
|
| 1236 |
+
try:
|
| 1237 |
+
source = self._enhance_asserts(source)
|
| 1238 |
+
except ImportError:
|
| 1239 |
+
pass
|
| 1240 |
+
|
| 1241 |
+
code = compile(source, filename, "exec", flags=0, dont_inherit=True)
|
| 1242 |
+
exec(code, gl)
|
| 1243 |
+
except (SystemExit, KeyboardInterrupt):
|
| 1244 |
+
raise
|
| 1245 |
+
except ImportError:
|
| 1246 |
+
reporter.import_error(filename, sys.exc_info())
|
| 1247 |
+
return
|
| 1248 |
+
except Exception:
|
| 1249 |
+
reporter.test_exception(sys.exc_info())
|
| 1250 |
+
|
| 1251 |
+
clear_cache()
|
| 1252 |
+
self._count += 1
|
| 1253 |
+
random.seed(self._seed)
|
| 1254 |
+
disabled = gl.get("disabled", False)
|
| 1255 |
+
if not disabled:
|
| 1256 |
+
# we need to filter only those functions that begin with 'test_'
|
| 1257 |
+
# We have to be careful about decorated functions. As long as
|
| 1258 |
+
# the decorator uses functools.wraps, we can detect it.
|
| 1259 |
+
funcs = []
|
| 1260 |
+
for f in gl:
|
| 1261 |
+
if (f.startswith("test_") and (inspect.isfunction(gl[f])
|
| 1262 |
+
or inspect.ismethod(gl[f]))):
|
| 1263 |
+
func = gl[f]
|
| 1264 |
+
# Handle multiple decorators
|
| 1265 |
+
while hasattr(func, '__wrapped__'):
|
| 1266 |
+
func = func.__wrapped__
|
| 1267 |
+
|
| 1268 |
+
if inspect.getsourcefile(func) == filename:
|
| 1269 |
+
funcs.append(gl[f])
|
| 1270 |
+
if slow:
|
| 1271 |
+
funcs = [f for f in funcs if getattr(f, '_slow', False)]
|
| 1272 |
+
# Sorting of XFAILed functions isn't fixed yet :-(
|
| 1273 |
+
funcs.sort(key=lambda x: inspect.getsourcelines(x)[1])
|
| 1274 |
+
i = 0
|
| 1275 |
+
while i < len(funcs):
|
| 1276 |
+
if inspect.isgeneratorfunction(funcs[i]):
|
| 1277 |
+
# some tests can be generators, that return the actual
|
| 1278 |
+
# test functions. We unpack it below:
|
| 1279 |
+
f = funcs.pop(i)
|
| 1280 |
+
for fg in f():
|
| 1281 |
+
func = fg[0]
|
| 1282 |
+
args = fg[1:]
|
| 1283 |
+
fgw = lambda: func(*args)
|
| 1284 |
+
funcs.insert(i, fgw)
|
| 1285 |
+
i += 1
|
| 1286 |
+
else:
|
| 1287 |
+
i += 1
|
| 1288 |
+
# drop functions that are not selected with the keyword expression:
|
| 1289 |
+
funcs = [x for x in funcs if self.matches(x)]
|
| 1290 |
+
|
| 1291 |
+
if not funcs:
|
| 1292 |
+
return
|
| 1293 |
+
except Exception:
|
| 1294 |
+
reporter.entering_filename(filename, len(funcs))
|
| 1295 |
+
raise
|
| 1296 |
+
|
| 1297 |
+
reporter.entering_filename(filename, len(funcs))
|
| 1298 |
+
if not sort:
|
| 1299 |
+
random.shuffle(funcs)
|
| 1300 |
+
|
| 1301 |
+
for f in funcs:
|
| 1302 |
+
start = time.time()
|
| 1303 |
+
reporter.entering_test(f)
|
| 1304 |
+
try:
|
| 1305 |
+
if getattr(f, '_slow', False) and not slow:
|
| 1306 |
+
raise Skipped("Slow")
|
| 1307 |
+
with raise_on_deprecated():
|
| 1308 |
+
if timeout:
|
| 1309 |
+
self._timeout(f, timeout, fail_on_timeout)
|
| 1310 |
+
else:
|
| 1311 |
+
random.seed(self._seed)
|
| 1312 |
+
f()
|
| 1313 |
+
except KeyboardInterrupt:
|
| 1314 |
+
if getattr(f, '_slow', False):
|
| 1315 |
+
reporter.test_skip("KeyboardInterrupt")
|
| 1316 |
+
else:
|
| 1317 |
+
raise
|
| 1318 |
+
except Exception:
|
| 1319 |
+
if timeout:
|
| 1320 |
+
signal.alarm(0) # Disable the alarm. It could not be handled before.
|
| 1321 |
+
t, v, tr = sys.exc_info()
|
| 1322 |
+
if t is AssertionError:
|
| 1323 |
+
reporter.test_fail((t, v, tr))
|
| 1324 |
+
if self._post_mortem:
|
| 1325 |
+
pdb.post_mortem(tr)
|
| 1326 |
+
elif t.__name__ == "Skipped":
|
| 1327 |
+
reporter.test_skip(v)
|
| 1328 |
+
elif t.__name__ == "XFail":
|
| 1329 |
+
reporter.test_xfail()
|
| 1330 |
+
elif t.__name__ == "XPass":
|
| 1331 |
+
reporter.test_xpass(v)
|
| 1332 |
+
else:
|
| 1333 |
+
reporter.test_exception((t, v, tr))
|
| 1334 |
+
if self._post_mortem:
|
| 1335 |
+
pdb.post_mortem(tr)
|
| 1336 |
+
else:
|
| 1337 |
+
reporter.test_pass()
|
| 1338 |
+
taken = time.time() - start
|
| 1339 |
+
if taken > self._slow_threshold:
|
| 1340 |
+
filename = os.path.relpath(filename, reporter._root_dir)
|
| 1341 |
+
reporter.slow_test_functions.append(
|
| 1342 |
+
(filename + "::" + f.__name__, taken))
|
| 1343 |
+
if getattr(f, '_slow', False) and slow:
|
| 1344 |
+
if taken < self._fast_threshold:
|
| 1345 |
+
filename = os.path.relpath(filename, reporter._root_dir)
|
| 1346 |
+
reporter.fast_test_functions.append(
|
| 1347 |
+
(filename + "::" + f.__name__, taken))
|
| 1348 |
+
reporter.leaving_filename()
|
| 1349 |
+
|
| 1350 |
+
def _timeout(self, function, timeout, fail_on_timeout):
|
| 1351 |
+
def callback(x, y):
|
| 1352 |
+
signal.alarm(0)
|
| 1353 |
+
if fail_on_timeout:
|
| 1354 |
+
raise TimeOutError("Timed out after %d seconds" % timeout)
|
| 1355 |
+
else:
|
| 1356 |
+
raise Skipped("Timeout")
|
| 1357 |
+
signal.signal(signal.SIGALRM, callback)
|
| 1358 |
+
signal.alarm(timeout) # Set an alarm with a given timeout
|
| 1359 |
+
function()
|
| 1360 |
+
signal.alarm(0) # Disable the alarm
|
| 1361 |
+
|
| 1362 |
+
def matches(self, x):
|
| 1363 |
+
"""
|
| 1364 |
+
Does the keyword expression self._kw match "x"? Returns True/False.
|
| 1365 |
+
|
| 1366 |
+
Always returns True if self._kw is "".
|
| 1367 |
+
"""
|
| 1368 |
+
if not self._kw:
|
| 1369 |
+
return True
|
| 1370 |
+
for kw in self._kw:
|
| 1371 |
+
if x.__name__.lower().find(kw.lower()) != -1:
|
| 1372 |
+
return True
|
| 1373 |
+
return False
|
| 1374 |
+
|
| 1375 |
+
def get_test_files(self, dir, pat='test_*.py'):
|
| 1376 |
+
"""
|
| 1377 |
+
Returns the list of test_*.py (default) files at or below directory
|
| 1378 |
+
``dir`` relative to the SymPy home directory.
|
| 1379 |
+
"""
|
| 1380 |
+
dir = os.path.join(self._root_dir, convert_to_native_paths([dir])[0])
|
| 1381 |
+
|
| 1382 |
+
g = []
|
| 1383 |
+
for path, folders, files in os.walk(dir):
|
| 1384 |
+
g.extend([os.path.join(path, f) for f in files if fnmatch(f, pat)])
|
| 1385 |
+
|
| 1386 |
+
return sorted([os.path.normcase(gi) for gi in g])
|
| 1387 |
+
|
| 1388 |
+
|
| 1389 |
+
class SymPyDocTests:
|
| 1390 |
+
|
| 1391 |
+
def __init__(self, reporter, normal):
|
| 1392 |
+
self._count = 0
|
| 1393 |
+
self._root_dir = get_sympy_dir()
|
| 1394 |
+
self._reporter = reporter
|
| 1395 |
+
self._reporter.root_dir(self._root_dir)
|
| 1396 |
+
self._normal = normal
|
| 1397 |
+
|
| 1398 |
+
self._testfiles = []
|
| 1399 |
+
|
| 1400 |
+
def test(self):
|
| 1401 |
+
"""
|
| 1402 |
+
Runs the tests and returns True if all tests pass, otherwise False.
|
| 1403 |
+
"""
|
| 1404 |
+
self._reporter.start()
|
| 1405 |
+
for f in self._testfiles:
|
| 1406 |
+
try:
|
| 1407 |
+
self.test_file(f)
|
| 1408 |
+
except KeyboardInterrupt:
|
| 1409 |
+
print(" interrupted by user")
|
| 1410 |
+
self._reporter.finish()
|
| 1411 |
+
raise
|
| 1412 |
+
return self._reporter.finish()
|
| 1413 |
+
|
| 1414 |
+
def test_file(self, filename):
|
| 1415 |
+
clear_cache()
|
| 1416 |
+
|
| 1417 |
+
from io import StringIO
|
| 1418 |
+
import sympy.interactive.printing as interactive_printing
|
| 1419 |
+
from sympy.printing.pretty.pretty import pprint_use_unicode
|
| 1420 |
+
from sympy.printing.pretty import stringpict
|
| 1421 |
+
|
| 1422 |
+
rel_name = filename[len(self._root_dir) + 1:]
|
| 1423 |
+
dirname, file = os.path.split(filename)
|
| 1424 |
+
module = rel_name.replace(os.sep, '.')[:-3]
|
| 1425 |
+
|
| 1426 |
+
if rel_name.startswith("examples"):
|
| 1427 |
+
# Examples files do not have __init__.py files,
|
| 1428 |
+
# So we have to temporarily extend sys.path to import them
|
| 1429 |
+
sys.path.insert(0, dirname)
|
| 1430 |
+
module = file[:-3] # remove ".py"
|
| 1431 |
+
try:
|
| 1432 |
+
module = pdoctest._normalize_module(module)
|
| 1433 |
+
tests = SymPyDocTestFinder().find(module)
|
| 1434 |
+
except (SystemExit, KeyboardInterrupt):
|
| 1435 |
+
raise
|
| 1436 |
+
except ImportError:
|
| 1437 |
+
self._reporter.import_error(filename, sys.exc_info())
|
| 1438 |
+
return
|
| 1439 |
+
finally:
|
| 1440 |
+
if rel_name.startswith("examples"):
|
| 1441 |
+
del sys.path[0]
|
| 1442 |
+
|
| 1443 |
+
tests = [test for test in tests if len(test.examples) > 0]
|
| 1444 |
+
# By default tests are sorted by alphabetical order by function name.
|
| 1445 |
+
# We sort by line number so one can edit the file sequentially from
|
| 1446 |
+
# bottom to top. However, if there are decorated functions, their line
|
| 1447 |
+
# numbers will be too large and for now one must just search for these
|
| 1448 |
+
# by text and function name.
|
| 1449 |
+
tests.sort(key=lambda x: -x.lineno)
|
| 1450 |
+
|
| 1451 |
+
if not tests:
|
| 1452 |
+
return
|
| 1453 |
+
self._reporter.entering_filename(filename, len(tests))
|
| 1454 |
+
for test in tests:
|
| 1455 |
+
assert len(test.examples) != 0
|
| 1456 |
+
|
| 1457 |
+
if self._reporter._verbose:
|
| 1458 |
+
self._reporter.write("\n{} ".format(test.name))
|
| 1459 |
+
|
| 1460 |
+
# check if there are external dependencies which need to be met
|
| 1461 |
+
if '_doctest_depends_on' in test.globs:
|
| 1462 |
+
try:
|
| 1463 |
+
self._check_dependencies(**test.globs['_doctest_depends_on'])
|
| 1464 |
+
except DependencyError as e:
|
| 1465 |
+
self._reporter.test_skip(v=str(e))
|
| 1466 |
+
continue
|
| 1467 |
+
|
| 1468 |
+
runner = SymPyDocTestRunner(verbose=self._reporter._verbose==2,
|
| 1469 |
+
optionflags=pdoctest.ELLIPSIS |
|
| 1470 |
+
pdoctest.NORMALIZE_WHITESPACE |
|
| 1471 |
+
pdoctest.IGNORE_EXCEPTION_DETAIL)
|
| 1472 |
+
runner._checker = SymPyOutputChecker()
|
| 1473 |
+
old = sys.stdout
|
| 1474 |
+
new = old if self._reporter._verbose==2 else StringIO()
|
| 1475 |
+
sys.stdout = new
|
| 1476 |
+
# If the testing is normal, the doctests get importing magic to
|
| 1477 |
+
# provide the global namespace. If not normal (the default) then
|
| 1478 |
+
# then must run on their own; all imports must be explicit within
|
| 1479 |
+
# a function's docstring. Once imported that import will be
|
| 1480 |
+
# available to the rest of the tests in a given function's
|
| 1481 |
+
# docstring (unless clear_globs=True below).
|
| 1482 |
+
if not self._normal:
|
| 1483 |
+
test.globs = {}
|
| 1484 |
+
# if this is uncommented then all the test would get is what
|
| 1485 |
+
# comes by default with a "from sympy import *"
|
| 1486 |
+
#exec('from sympy import *') in test.globs
|
| 1487 |
+
old_displayhook = sys.displayhook
|
| 1488 |
+
use_unicode_prev, wrap_line_prev = setup_pprint()
|
| 1489 |
+
|
| 1490 |
+
try:
|
| 1491 |
+
f, t = runner.run(test,
|
| 1492 |
+
out=new.write, clear_globs=False)
|
| 1493 |
+
except KeyboardInterrupt:
|
| 1494 |
+
raise
|
| 1495 |
+
finally:
|
| 1496 |
+
sys.stdout = old
|
| 1497 |
+
if f > 0:
|
| 1498 |
+
self._reporter.doctest_fail(test.name, new.getvalue())
|
| 1499 |
+
else:
|
| 1500 |
+
self._reporter.test_pass()
|
| 1501 |
+
sys.displayhook = old_displayhook
|
| 1502 |
+
interactive_printing.NO_GLOBAL = False
|
| 1503 |
+
pprint_use_unicode(use_unicode_prev)
|
| 1504 |
+
stringpict._GLOBAL_WRAP_LINE = wrap_line_prev
|
| 1505 |
+
|
| 1506 |
+
self._reporter.leaving_filename()
|
| 1507 |
+
|
| 1508 |
+
def get_test_files(self, dir, pat='*.py', init_only=True):
|
| 1509 |
+
r"""
|
| 1510 |
+
Returns the list of \*.py files (default) from which docstrings
|
| 1511 |
+
will be tested which are at or below directory ``dir``. By default,
|
| 1512 |
+
only those that have an __init__.py in their parent directory
|
| 1513 |
+
and do not start with ``test_`` will be included.
|
| 1514 |
+
"""
|
| 1515 |
+
def importable(x):
|
| 1516 |
+
"""
|
| 1517 |
+
Checks if given pathname x is an importable module by checking for
|
| 1518 |
+
__init__.py file.
|
| 1519 |
+
|
| 1520 |
+
Returns True/False.
|
| 1521 |
+
|
| 1522 |
+
Currently we only test if the __init__.py file exists in the
|
| 1523 |
+
directory with the file "x" (in theory we should also test all the
|
| 1524 |
+
parent dirs).
|
| 1525 |
+
"""
|
| 1526 |
+
init_py = os.path.join(os.path.dirname(x), "__init__.py")
|
| 1527 |
+
return os.path.exists(init_py)
|
| 1528 |
+
|
| 1529 |
+
dir = os.path.join(self._root_dir, convert_to_native_paths([dir])[0])
|
| 1530 |
+
|
| 1531 |
+
g = []
|
| 1532 |
+
for path, folders, files in os.walk(dir):
|
| 1533 |
+
g.extend([os.path.join(path, f) for f in files
|
| 1534 |
+
if not f.startswith('test_') and fnmatch(f, pat)])
|
| 1535 |
+
if init_only:
|
| 1536 |
+
# skip files that are not importable (i.e. missing __init__.py)
|
| 1537 |
+
g = [x for x in g if importable(x)]
|
| 1538 |
+
|
| 1539 |
+
return [os.path.normcase(gi) for gi in g]
|
| 1540 |
+
|
| 1541 |
+
def _check_dependencies(self,
|
| 1542 |
+
executables=(),
|
| 1543 |
+
modules=(),
|
| 1544 |
+
disable_viewers=(),
|
| 1545 |
+
python_version=(3, 5),
|
| 1546 |
+
ground_types=None):
|
| 1547 |
+
"""
|
| 1548 |
+
Checks if the dependencies for the test are installed.
|
| 1549 |
+
|
| 1550 |
+
Raises ``DependencyError`` it at least one dependency is not installed.
|
| 1551 |
+
"""
|
| 1552 |
+
|
| 1553 |
+
for executable in executables:
|
| 1554 |
+
if not shutil.which(executable):
|
| 1555 |
+
raise DependencyError("Could not find %s" % executable)
|
| 1556 |
+
|
| 1557 |
+
for module in modules:
|
| 1558 |
+
if module == 'matplotlib':
|
| 1559 |
+
matplotlib = import_module(
|
| 1560 |
+
'matplotlib',
|
| 1561 |
+
import_kwargs={'fromlist':
|
| 1562 |
+
['pyplot', 'cm', 'collections']},
|
| 1563 |
+
min_module_version='1.0.0', catch=(RuntimeError,))
|
| 1564 |
+
if matplotlib is None:
|
| 1565 |
+
raise DependencyError("Could not import matplotlib")
|
| 1566 |
+
else:
|
| 1567 |
+
if not import_module(module):
|
| 1568 |
+
raise DependencyError("Could not import %s" % module)
|
| 1569 |
+
|
| 1570 |
+
if disable_viewers:
|
| 1571 |
+
tempdir = tempfile.mkdtemp()
|
| 1572 |
+
os.environ['PATH'] = '%s:%s' % (tempdir, os.environ['PATH'])
|
| 1573 |
+
|
| 1574 |
+
vw = ('#!/usr/bin/env python3\n'
|
| 1575 |
+
'import sys\n'
|
| 1576 |
+
'if len(sys.argv) <= 1:\n'
|
| 1577 |
+
' exit("wrong number of args")\n')
|
| 1578 |
+
|
| 1579 |
+
for viewer in disable_viewers:
|
| 1580 |
+
with open(os.path.join(tempdir, viewer), 'w') as fh:
|
| 1581 |
+
fh.write(vw)
|
| 1582 |
+
|
| 1583 |
+
# make the file executable
|
| 1584 |
+
os.chmod(os.path.join(tempdir, viewer),
|
| 1585 |
+
stat.S_IREAD | stat.S_IWRITE | stat.S_IXUSR)
|
| 1586 |
+
|
| 1587 |
+
if python_version:
|
| 1588 |
+
if sys.version_info < python_version:
|
| 1589 |
+
raise DependencyError("Requires Python >= " + '.'.join(map(str, python_version)))
|
| 1590 |
+
|
| 1591 |
+
if ground_types is not None:
|
| 1592 |
+
if GROUND_TYPES not in ground_types:
|
| 1593 |
+
raise DependencyError("Requires ground_types in " + str(ground_types))
|
| 1594 |
+
|
| 1595 |
+
if 'pyglet' in modules:
|
| 1596 |
+
# monkey-patch pyglet s.t. it does not open a window during
|
| 1597 |
+
# doctesting
|
| 1598 |
+
import pyglet
|
| 1599 |
+
class DummyWindow:
|
| 1600 |
+
def __init__(self, *args, **kwargs):
|
| 1601 |
+
self.has_exit = True
|
| 1602 |
+
self.width = 600
|
| 1603 |
+
self.height = 400
|
| 1604 |
+
|
| 1605 |
+
def set_vsync(self, x):
|
| 1606 |
+
pass
|
| 1607 |
+
|
| 1608 |
+
def switch_to(self):
|
| 1609 |
+
pass
|
| 1610 |
+
|
| 1611 |
+
def push_handlers(self, x):
|
| 1612 |
+
pass
|
| 1613 |
+
|
| 1614 |
+
def close(self):
|
| 1615 |
+
pass
|
| 1616 |
+
|
| 1617 |
+
pyglet.window.Window = DummyWindow
|
| 1618 |
+
|
| 1619 |
+
|
| 1620 |
+
class SymPyDocTestFinder(DocTestFinder):
|
| 1621 |
+
"""
|
| 1622 |
+
A class used to extract the DocTests that are relevant to a given
|
| 1623 |
+
object, from its docstring and the docstrings of its contained
|
| 1624 |
+
objects. Doctests can currently be extracted from the following
|
| 1625 |
+
object types: modules, functions, classes, methods, staticmethods,
|
| 1626 |
+
classmethods, and properties.
|
| 1627 |
+
|
| 1628 |
+
Modified from doctest's version to look harder for code that
|
| 1629 |
+
appears comes from a different module. For example, the @vectorize
|
| 1630 |
+
decorator makes it look like functions come from multidimensional.py
|
| 1631 |
+
even though their code exists elsewhere.
|
| 1632 |
+
"""
|
| 1633 |
+
|
| 1634 |
+
def _find(self, tests, obj, name, module, source_lines, globs, seen):
|
| 1635 |
+
"""
|
| 1636 |
+
Find tests for the given object and any contained objects, and
|
| 1637 |
+
add them to ``tests``.
|
| 1638 |
+
"""
|
| 1639 |
+
if self._verbose:
|
| 1640 |
+
print('Finding tests in %s' % name)
|
| 1641 |
+
|
| 1642 |
+
# If we've already processed this object, then ignore it.
|
| 1643 |
+
if id(obj) in seen:
|
| 1644 |
+
return
|
| 1645 |
+
seen[id(obj)] = 1
|
| 1646 |
+
|
| 1647 |
+
# Make sure we don't run doctests for classes outside of sympy, such
|
| 1648 |
+
# as in numpy or scipy.
|
| 1649 |
+
if inspect.isclass(obj):
|
| 1650 |
+
if obj.__module__.split('.')[0] != 'sympy':
|
| 1651 |
+
return
|
| 1652 |
+
|
| 1653 |
+
# Find a test for this object, and add it to the list of tests.
|
| 1654 |
+
test = self._get_test(obj, name, module, globs, source_lines)
|
| 1655 |
+
if test is not None:
|
| 1656 |
+
tests.append(test)
|
| 1657 |
+
|
| 1658 |
+
if not self._recurse:
|
| 1659 |
+
return
|
| 1660 |
+
|
| 1661 |
+
# Look for tests in a module's contained objects.
|
| 1662 |
+
if inspect.ismodule(obj):
|
| 1663 |
+
for rawname, val in obj.__dict__.items():
|
| 1664 |
+
# Recurse to functions & classes.
|
| 1665 |
+
if inspect.isfunction(val) or inspect.isclass(val):
|
| 1666 |
+
# Make sure we don't run doctests functions or classes
|
| 1667 |
+
# from different modules
|
| 1668 |
+
if val.__module__ != module.__name__:
|
| 1669 |
+
continue
|
| 1670 |
+
|
| 1671 |
+
assert self._from_module(module, val), \
|
| 1672 |
+
"%s is not in module %s (rawname %s)" % (val, module, rawname)
|
| 1673 |
+
|
| 1674 |
+
try:
|
| 1675 |
+
valname = '%s.%s' % (name, rawname)
|
| 1676 |
+
self._find(tests, val, valname, module,
|
| 1677 |
+
source_lines, globs, seen)
|
| 1678 |
+
except KeyboardInterrupt:
|
| 1679 |
+
raise
|
| 1680 |
+
|
| 1681 |
+
# Look for tests in a module's __test__ dictionary.
|
| 1682 |
+
for valname, val in getattr(obj, '__test__', {}).items():
|
| 1683 |
+
if not isinstance(valname, str):
|
| 1684 |
+
raise ValueError("SymPyDocTestFinder.find: __test__ keys "
|
| 1685 |
+
"must be strings: %r" %
|
| 1686 |
+
(type(valname),))
|
| 1687 |
+
if not (inspect.isfunction(val) or inspect.isclass(val) or
|
| 1688 |
+
inspect.ismethod(val) or inspect.ismodule(val) or
|
| 1689 |
+
isinstance(val, str)):
|
| 1690 |
+
raise ValueError("SymPyDocTestFinder.find: __test__ values "
|
| 1691 |
+
"must be strings, functions, methods, "
|
| 1692 |
+
"classes, or modules: %r" %
|
| 1693 |
+
(type(val),))
|
| 1694 |
+
valname = '%s.__test__.%s' % (name, valname)
|
| 1695 |
+
self._find(tests, val, valname, module, source_lines,
|
| 1696 |
+
globs, seen)
|
| 1697 |
+
|
| 1698 |
+
|
| 1699 |
+
# Look for tests in a class's contained objects.
|
| 1700 |
+
if inspect.isclass(obj):
|
| 1701 |
+
for valname, val in obj.__dict__.items():
|
| 1702 |
+
# Special handling for staticmethod/classmethod.
|
| 1703 |
+
if isinstance(val, staticmethod):
|
| 1704 |
+
val = getattr(obj, valname)
|
| 1705 |
+
if isinstance(val, classmethod):
|
| 1706 |
+
val = getattr(obj, valname).__func__
|
| 1707 |
+
|
| 1708 |
+
|
| 1709 |
+
# Recurse to methods, properties, and nested classes.
|
| 1710 |
+
if ((inspect.isfunction(unwrap(val)) or
|
| 1711 |
+
inspect.isclass(val) or
|
| 1712 |
+
isinstance(val, property)) and
|
| 1713 |
+
self._from_module(module, val)):
|
| 1714 |
+
# Make sure we don't run doctests functions or classes
|
| 1715 |
+
# from different modules
|
| 1716 |
+
if isinstance(val, property):
|
| 1717 |
+
if hasattr(val.fget, '__module__'):
|
| 1718 |
+
if val.fget.__module__ != module.__name__:
|
| 1719 |
+
continue
|
| 1720 |
+
else:
|
| 1721 |
+
if val.__module__ != module.__name__:
|
| 1722 |
+
continue
|
| 1723 |
+
|
| 1724 |
+
assert self._from_module(module, val), \
|
| 1725 |
+
"%s is not in module %s (valname %s)" % (
|
| 1726 |
+
val, module, valname)
|
| 1727 |
+
|
| 1728 |
+
valname = '%s.%s' % (name, valname)
|
| 1729 |
+
self._find(tests, val, valname, module, source_lines,
|
| 1730 |
+
globs, seen)
|
| 1731 |
+
|
| 1732 |
+
def _get_test(self, obj, name, module, globs, source_lines):
|
| 1733 |
+
"""
|
| 1734 |
+
Return a DocTest for the given object, if it defines a docstring;
|
| 1735 |
+
otherwise, return None.
|
| 1736 |
+
"""
|
| 1737 |
+
|
| 1738 |
+
lineno = None
|
| 1739 |
+
|
| 1740 |
+
# Extract the object's docstring. If it does not have one,
|
| 1741 |
+
# then return None (no test for this object).
|
| 1742 |
+
if isinstance(obj, str):
|
| 1743 |
+
# obj is a string in the case for objects in the polys package.
|
| 1744 |
+
# Note that source_lines is a binary string (compiled polys
|
| 1745 |
+
# modules), which can't be handled by _find_lineno so determine
|
| 1746 |
+
# the line number here.
|
| 1747 |
+
|
| 1748 |
+
docstring = obj
|
| 1749 |
+
|
| 1750 |
+
matches = re.findall(r"line \d+", name)
|
| 1751 |
+
assert len(matches) == 1, \
|
| 1752 |
+
"string '%s' does not contain lineno " % name
|
| 1753 |
+
|
| 1754 |
+
# NOTE: this is not the exact linenumber but its better than no
|
| 1755 |
+
# lineno ;)
|
| 1756 |
+
lineno = int(matches[0][5:])
|
| 1757 |
+
|
| 1758 |
+
else:
|
| 1759 |
+
docstring = getattr(obj, '__doc__', '')
|
| 1760 |
+
if docstring is None:
|
| 1761 |
+
docstring = ''
|
| 1762 |
+
if not isinstance(docstring, str):
|
| 1763 |
+
docstring = str(docstring)
|
| 1764 |
+
|
| 1765 |
+
# Don't bother if the docstring is empty.
|
| 1766 |
+
if self._exclude_empty and not docstring:
|
| 1767 |
+
return None
|
| 1768 |
+
|
| 1769 |
+
# check that properties have a docstring because _find_lineno
|
| 1770 |
+
# assumes it
|
| 1771 |
+
if isinstance(obj, property):
|
| 1772 |
+
if obj.fget.__doc__ is None:
|
| 1773 |
+
return None
|
| 1774 |
+
|
| 1775 |
+
# Find the docstring's location in the file.
|
| 1776 |
+
if lineno is None:
|
| 1777 |
+
obj = unwrap(obj)
|
| 1778 |
+
# handling of properties is not implemented in _find_lineno so do
|
| 1779 |
+
# it here
|
| 1780 |
+
if hasattr(obj, 'func_closure') and obj.func_closure is not None:
|
| 1781 |
+
tobj = obj.func_closure[0].cell_contents
|
| 1782 |
+
elif isinstance(obj, property):
|
| 1783 |
+
tobj = obj.fget
|
| 1784 |
+
else:
|
| 1785 |
+
tobj = obj
|
| 1786 |
+
lineno = self._find_lineno(tobj, source_lines)
|
| 1787 |
+
|
| 1788 |
+
if lineno is None:
|
| 1789 |
+
return None
|
| 1790 |
+
|
| 1791 |
+
# Return a DocTest for this object.
|
| 1792 |
+
if module is None:
|
| 1793 |
+
filename = None
|
| 1794 |
+
else:
|
| 1795 |
+
filename = getattr(module, '__file__', module.__name__)
|
| 1796 |
+
if filename[-4:] in (".pyc", ".pyo"):
|
| 1797 |
+
filename = filename[:-1]
|
| 1798 |
+
|
| 1799 |
+
globs['_doctest_depends_on'] = getattr(obj, '_doctest_depends_on', {})
|
| 1800 |
+
|
| 1801 |
+
return self._parser.get_doctest(docstring, globs, name,
|
| 1802 |
+
filename, lineno)
|
| 1803 |
+
|
| 1804 |
+
|
| 1805 |
+
class SymPyDocTestRunner(DocTestRunner):
|
| 1806 |
+
"""
|
| 1807 |
+
A class used to run DocTest test cases, and accumulate statistics.
|
| 1808 |
+
The ``run`` method is used to process a single DocTest case. It
|
| 1809 |
+
returns a tuple ``(f, t)``, where ``t`` is the number of test cases
|
| 1810 |
+
tried, and ``f`` is the number of test cases that failed.
|
| 1811 |
+
|
| 1812 |
+
Modified from the doctest version to not reset the sys.displayhook (see
|
| 1813 |
+
issue 5140).
|
| 1814 |
+
|
| 1815 |
+
See the docstring of the original DocTestRunner for more information.
|
| 1816 |
+
"""
|
| 1817 |
+
|
| 1818 |
+
def run(self, test, compileflags=None, out=None, clear_globs=True):
|
| 1819 |
+
"""
|
| 1820 |
+
Run the examples in ``test``, and display the results using the
|
| 1821 |
+
writer function ``out``.
|
| 1822 |
+
|
| 1823 |
+
The examples are run in the namespace ``test.globs``. If
|
| 1824 |
+
``clear_globs`` is true (the default), then this namespace will
|
| 1825 |
+
be cleared after the test runs, to help with garbage
|
| 1826 |
+
collection. If you would like to examine the namespace after
|
| 1827 |
+
the test completes, then use ``clear_globs=False``.
|
| 1828 |
+
|
| 1829 |
+
``compileflags`` gives the set of flags that should be used by
|
| 1830 |
+
the Python compiler when running the examples. If not
|
| 1831 |
+
specified, then it will default to the set of future-import
|
| 1832 |
+
flags that apply to ``globs``.
|
| 1833 |
+
|
| 1834 |
+
The output of each example is checked using
|
| 1835 |
+
``SymPyDocTestRunner.check_output``, and the results are
|
| 1836 |
+
formatted by the ``SymPyDocTestRunner.report_*`` methods.
|
| 1837 |
+
"""
|
| 1838 |
+
self.test = test
|
| 1839 |
+
|
| 1840 |
+
# Remove ``` from the end of example, which may appear in Markdown
|
| 1841 |
+
# files
|
| 1842 |
+
for example in test.examples:
|
| 1843 |
+
example.want = example.want.replace('```\n', '')
|
| 1844 |
+
example.exc_msg = example.exc_msg and example.exc_msg.replace('```\n', '')
|
| 1845 |
+
|
| 1846 |
+
|
| 1847 |
+
if compileflags is None:
|
| 1848 |
+
compileflags = pdoctest._extract_future_flags(test.globs)
|
| 1849 |
+
|
| 1850 |
+
save_stdout = sys.stdout
|
| 1851 |
+
if out is None:
|
| 1852 |
+
out = save_stdout.write
|
| 1853 |
+
sys.stdout = self._fakeout
|
| 1854 |
+
|
| 1855 |
+
# Patch pdb.set_trace to restore sys.stdout during interactive
|
| 1856 |
+
# debugging (so it's not still redirected to self._fakeout).
|
| 1857 |
+
# Note that the interactive output will go to *our*
|
| 1858 |
+
# save_stdout, even if that's not the real sys.stdout; this
|
| 1859 |
+
# allows us to write test cases for the set_trace behavior.
|
| 1860 |
+
save_set_trace = pdb.set_trace
|
| 1861 |
+
self.debugger = pdoctest._OutputRedirectingPdb(save_stdout)
|
| 1862 |
+
self.debugger.reset()
|
| 1863 |
+
pdb.set_trace = self.debugger.set_trace
|
| 1864 |
+
|
| 1865 |
+
# Patch linecache.getlines, so we can see the example's source
|
| 1866 |
+
# when we're inside the debugger.
|
| 1867 |
+
self.save_linecache_getlines = pdoctest.linecache.getlines
|
| 1868 |
+
linecache.getlines = self.__patched_linecache_getlines
|
| 1869 |
+
|
| 1870 |
+
# Fail for deprecation warnings
|
| 1871 |
+
with raise_on_deprecated():
|
| 1872 |
+
try:
|
| 1873 |
+
return self.__run(test, compileflags, out)
|
| 1874 |
+
finally:
|
| 1875 |
+
sys.stdout = save_stdout
|
| 1876 |
+
pdb.set_trace = save_set_trace
|
| 1877 |
+
linecache.getlines = self.save_linecache_getlines
|
| 1878 |
+
if clear_globs:
|
| 1879 |
+
test.globs.clear()
|
| 1880 |
+
|
| 1881 |
+
|
| 1882 |
+
# We have to override the name mangled methods.
|
| 1883 |
+
monkeypatched_methods = [
|
| 1884 |
+
'patched_linecache_getlines',
|
| 1885 |
+
'run',
|
| 1886 |
+
'record_outcome'
|
| 1887 |
+
]
|
| 1888 |
+
for method in monkeypatched_methods:
|
| 1889 |
+
oldname = '_DocTestRunner__' + method
|
| 1890 |
+
newname = '_SymPyDocTestRunner__' + method
|
| 1891 |
+
setattr(SymPyDocTestRunner, newname, getattr(DocTestRunner, oldname))
|
| 1892 |
+
|
| 1893 |
+
|
| 1894 |
+
class SymPyOutputChecker(pdoctest.OutputChecker):
|
| 1895 |
+
"""
|
| 1896 |
+
Compared to the OutputChecker from the stdlib our OutputChecker class
|
| 1897 |
+
supports numerical comparison of floats occurring in the output of the
|
| 1898 |
+
doctest examples
|
| 1899 |
+
"""
|
| 1900 |
+
|
| 1901 |
+
def __init__(self):
|
| 1902 |
+
# NOTE OutputChecker is an old-style class with no __init__ method,
|
| 1903 |
+
# so we can't call the base class version of __init__ here
|
| 1904 |
+
|
| 1905 |
+
got_floats = r'(\d+\.\d*|\.\d+)'
|
| 1906 |
+
|
| 1907 |
+
# floats in the 'want' string may contain ellipses
|
| 1908 |
+
want_floats = got_floats + r'(\.{3})?'
|
| 1909 |
+
|
| 1910 |
+
front_sep = r'\s|\+|\-|\*|,'
|
| 1911 |
+
back_sep = front_sep + r'|j|e'
|
| 1912 |
+
|
| 1913 |
+
fbeg = r'^%s(?=%s|$)' % (got_floats, back_sep)
|
| 1914 |
+
fmidend = r'(?<=%s)%s(?=%s|$)' % (front_sep, got_floats, back_sep)
|
| 1915 |
+
self.num_got_rgx = re.compile(r'(%s|%s)' %(fbeg, fmidend))
|
| 1916 |
+
|
| 1917 |
+
fbeg = r'^%s(?=%s|$)' % (want_floats, back_sep)
|
| 1918 |
+
fmidend = r'(?<=%s)%s(?=%s|$)' % (front_sep, want_floats, back_sep)
|
| 1919 |
+
self.num_want_rgx = re.compile(r'(%s|%s)' %(fbeg, fmidend))
|
| 1920 |
+
|
| 1921 |
+
def check_output(self, want, got, optionflags):
|
| 1922 |
+
"""
|
| 1923 |
+
Return True iff the actual output from an example (`got`)
|
| 1924 |
+
matches the expected output (`want`). These strings are
|
| 1925 |
+
always considered to match if they are identical; but
|
| 1926 |
+
depending on what option flags the test runner is using,
|
| 1927 |
+
several non-exact match types are also possible. See the
|
| 1928 |
+
documentation for `TestRunner` for more information about
|
| 1929 |
+
option flags.
|
| 1930 |
+
"""
|
| 1931 |
+
# Handle the common case first, for efficiency:
|
| 1932 |
+
# if they're string-identical, always return true.
|
| 1933 |
+
if got == want:
|
| 1934 |
+
return True
|
| 1935 |
+
|
| 1936 |
+
# TODO parse integers as well ?
|
| 1937 |
+
# Parse floats and compare them. If some of the parsed floats contain
|
| 1938 |
+
# ellipses, skip the comparison.
|
| 1939 |
+
matches = self.num_got_rgx.finditer(got)
|
| 1940 |
+
numbers_got = [match.group(1) for match in matches] # list of strs
|
| 1941 |
+
matches = self.num_want_rgx.finditer(want)
|
| 1942 |
+
numbers_want = [match.group(1) for match in matches] # list of strs
|
| 1943 |
+
if len(numbers_got) != len(numbers_want):
|
| 1944 |
+
return False
|
| 1945 |
+
|
| 1946 |
+
if len(numbers_got) > 0:
|
| 1947 |
+
nw_ = []
|
| 1948 |
+
for ng, nw in zip(numbers_got, numbers_want):
|
| 1949 |
+
if '...' in nw:
|
| 1950 |
+
nw_.append(ng)
|
| 1951 |
+
continue
|
| 1952 |
+
else:
|
| 1953 |
+
nw_.append(nw)
|
| 1954 |
+
|
| 1955 |
+
if abs(float(ng)-float(nw)) > 1e-5:
|
| 1956 |
+
return False
|
| 1957 |
+
|
| 1958 |
+
got = self.num_got_rgx.sub(r'%s', got)
|
| 1959 |
+
got = got % tuple(nw_)
|
| 1960 |
+
|
| 1961 |
+
# <BLANKLINE> can be used as a special sequence to signify a
|
| 1962 |
+
# blank line, unless the DONT_ACCEPT_BLANKLINE flag is used.
|
| 1963 |
+
if not (optionflags & pdoctest.DONT_ACCEPT_BLANKLINE):
|
| 1964 |
+
# Replace <BLANKLINE> in want with a blank line.
|
| 1965 |
+
want = re.sub(r'(?m)^%s\s*?$' % re.escape(pdoctest.BLANKLINE_MARKER),
|
| 1966 |
+
'', want)
|
| 1967 |
+
# If a line in got contains only spaces, then remove the
|
| 1968 |
+
# spaces.
|
| 1969 |
+
got = re.sub(r'(?m)^\s*?$', '', got)
|
| 1970 |
+
if got == want:
|
| 1971 |
+
return True
|
| 1972 |
+
|
| 1973 |
+
# This flag causes doctest to ignore any differences in the
|
| 1974 |
+
# contents of whitespace strings. Note that this can be used
|
| 1975 |
+
# in conjunction with the ELLIPSIS flag.
|
| 1976 |
+
if optionflags & pdoctest.NORMALIZE_WHITESPACE:
|
| 1977 |
+
got = ' '.join(got.split())
|
| 1978 |
+
want = ' '.join(want.split())
|
| 1979 |
+
if got == want:
|
| 1980 |
+
return True
|
| 1981 |
+
|
| 1982 |
+
# The ELLIPSIS flag says to let the sequence "..." in `want`
|
| 1983 |
+
# match any substring in `got`.
|
| 1984 |
+
if optionflags & pdoctest.ELLIPSIS:
|
| 1985 |
+
if pdoctest._ellipsis_match(want, got):
|
| 1986 |
+
return True
|
| 1987 |
+
|
| 1988 |
+
# We didn't find any match; return false.
|
| 1989 |
+
return False
|
| 1990 |
+
|
| 1991 |
+
|
| 1992 |
+
class Reporter:
|
| 1993 |
+
"""
|
| 1994 |
+
Parent class for all reporters.
|
| 1995 |
+
"""
|
| 1996 |
+
pass
|
| 1997 |
+
|
| 1998 |
+
|
| 1999 |
+
class PyTestReporter(Reporter):
|
| 2000 |
+
"""
|
| 2001 |
+
Py.test like reporter. Should produce output identical to py.test.
|
| 2002 |
+
"""
|
| 2003 |
+
|
| 2004 |
+
def __init__(self, verbose=False, tb="short", colors=True,
|
| 2005 |
+
force_colors=False, split=None):
|
| 2006 |
+
self._verbose = verbose
|
| 2007 |
+
self._tb_style = tb
|
| 2008 |
+
self._colors = colors
|
| 2009 |
+
self._force_colors = force_colors
|
| 2010 |
+
self._xfailed = 0
|
| 2011 |
+
self._xpassed = []
|
| 2012 |
+
self._failed = []
|
| 2013 |
+
self._failed_doctest = []
|
| 2014 |
+
self._passed = 0
|
| 2015 |
+
self._skipped = 0
|
| 2016 |
+
self._exceptions = []
|
| 2017 |
+
self._terminal_width = None
|
| 2018 |
+
self._default_width = 80
|
| 2019 |
+
self._split = split
|
| 2020 |
+
self._active_file = ''
|
| 2021 |
+
self._active_f = None
|
| 2022 |
+
|
| 2023 |
+
# TODO: Should these be protected?
|
| 2024 |
+
self.slow_test_functions = []
|
| 2025 |
+
self.fast_test_functions = []
|
| 2026 |
+
|
| 2027 |
+
# this tracks the x-position of the cursor (useful for positioning
|
| 2028 |
+
# things on the screen), without the need for any readline library:
|
| 2029 |
+
self._write_pos = 0
|
| 2030 |
+
self._line_wrap = False
|
| 2031 |
+
|
| 2032 |
+
def root_dir(self, dir):
|
| 2033 |
+
self._root_dir = dir
|
| 2034 |
+
|
| 2035 |
+
@property
|
| 2036 |
+
def terminal_width(self):
|
| 2037 |
+
if self._terminal_width is not None:
|
| 2038 |
+
return self._terminal_width
|
| 2039 |
+
|
| 2040 |
+
def findout_terminal_width():
|
| 2041 |
+
if sys.platform == "win32":
|
| 2042 |
+
# Windows support is based on:
|
| 2043 |
+
#
|
| 2044 |
+
# http://code.activestate.com/recipes/
|
| 2045 |
+
# 440694-determine-size-of-console-window-on-windows/
|
| 2046 |
+
|
| 2047 |
+
from ctypes import windll, create_string_buffer
|
| 2048 |
+
|
| 2049 |
+
h = windll.kernel32.GetStdHandle(-12)
|
| 2050 |
+
csbi = create_string_buffer(22)
|
| 2051 |
+
res = windll.kernel32.GetConsoleScreenBufferInfo(h, csbi)
|
| 2052 |
+
|
| 2053 |
+
if res:
|
| 2054 |
+
import struct
|
| 2055 |
+
(_, _, _, _, _, left, _, right, _, _, _) = \
|
| 2056 |
+
struct.unpack("hhhhHhhhhhh", csbi.raw)
|
| 2057 |
+
return right - left
|
| 2058 |
+
else:
|
| 2059 |
+
return self._default_width
|
| 2060 |
+
|
| 2061 |
+
if hasattr(sys.stdout, 'isatty') and not sys.stdout.isatty():
|
| 2062 |
+
return self._default_width # leave PIPEs alone
|
| 2063 |
+
|
| 2064 |
+
try:
|
| 2065 |
+
process = subprocess.Popen(['stty', '-a'],
|
| 2066 |
+
stdout=subprocess.PIPE,
|
| 2067 |
+
stderr=subprocess.PIPE)
|
| 2068 |
+
stdout, stderr = process.communicate()
|
| 2069 |
+
stdout = stdout.decode("utf-8")
|
| 2070 |
+
except OSError:
|
| 2071 |
+
pass
|
| 2072 |
+
else:
|
| 2073 |
+
# We support the following output formats from stty:
|
| 2074 |
+
#
|
| 2075 |
+
# 1) Linux -> columns 80
|
| 2076 |
+
# 2) OS X -> 80 columns
|
| 2077 |
+
# 3) Solaris -> columns = 80
|
| 2078 |
+
|
| 2079 |
+
re_linux = r"columns\s+(?P<columns>\d+);"
|
| 2080 |
+
re_osx = r"(?P<columns>\d+)\s*columns;"
|
| 2081 |
+
re_solaris = r"columns\s+=\s+(?P<columns>\d+);"
|
| 2082 |
+
|
| 2083 |
+
for regex in (re_linux, re_osx, re_solaris):
|
| 2084 |
+
match = re.search(regex, stdout)
|
| 2085 |
+
|
| 2086 |
+
if match is not None:
|
| 2087 |
+
columns = match.group('columns')
|
| 2088 |
+
|
| 2089 |
+
try:
|
| 2090 |
+
width = int(columns)
|
| 2091 |
+
except ValueError:
|
| 2092 |
+
pass
|
| 2093 |
+
if width != 0:
|
| 2094 |
+
return width
|
| 2095 |
+
|
| 2096 |
+
return self._default_width
|
| 2097 |
+
|
| 2098 |
+
width = findout_terminal_width()
|
| 2099 |
+
self._terminal_width = width
|
| 2100 |
+
|
| 2101 |
+
return width
|
| 2102 |
+
|
| 2103 |
+
def write(self, text, color="", align="left", width=None,
|
| 2104 |
+
force_colors=False):
|
| 2105 |
+
"""
|
| 2106 |
+
Prints a text on the screen.
|
| 2107 |
+
|
| 2108 |
+
It uses sys.stdout.write(), so no readline library is necessary.
|
| 2109 |
+
|
| 2110 |
+
Parameters
|
| 2111 |
+
==========
|
| 2112 |
+
|
| 2113 |
+
color : choose from the colors below, "" means default color
|
| 2114 |
+
align : "left"/"right", "left" is a normal print, "right" is aligned on
|
| 2115 |
+
the right-hand side of the screen, filled with spaces if
|
| 2116 |
+
necessary
|
| 2117 |
+
width : the screen width
|
| 2118 |
+
|
| 2119 |
+
"""
|
| 2120 |
+
color_templates = (
|
| 2121 |
+
("Black", "0;30"),
|
| 2122 |
+
("Red", "0;31"),
|
| 2123 |
+
("Green", "0;32"),
|
| 2124 |
+
("Brown", "0;33"),
|
| 2125 |
+
("Blue", "0;34"),
|
| 2126 |
+
("Purple", "0;35"),
|
| 2127 |
+
("Cyan", "0;36"),
|
| 2128 |
+
("LightGray", "0;37"),
|
| 2129 |
+
("DarkGray", "1;30"),
|
| 2130 |
+
("LightRed", "1;31"),
|
| 2131 |
+
("LightGreen", "1;32"),
|
| 2132 |
+
("Yellow", "1;33"),
|
| 2133 |
+
("LightBlue", "1;34"),
|
| 2134 |
+
("LightPurple", "1;35"),
|
| 2135 |
+
("LightCyan", "1;36"),
|
| 2136 |
+
("White", "1;37"),
|
| 2137 |
+
)
|
| 2138 |
+
|
| 2139 |
+
colors = {}
|
| 2140 |
+
|
| 2141 |
+
for name, value in color_templates:
|
| 2142 |
+
colors[name] = value
|
| 2143 |
+
c_normal = '\033[0m'
|
| 2144 |
+
c_color = '\033[%sm'
|
| 2145 |
+
|
| 2146 |
+
if width is None:
|
| 2147 |
+
width = self.terminal_width
|
| 2148 |
+
|
| 2149 |
+
if align == "right":
|
| 2150 |
+
if self._write_pos + len(text) > width:
|
| 2151 |
+
# we don't fit on the current line, create a new line
|
| 2152 |
+
self.write("\n")
|
| 2153 |
+
self.write(" "*(width - self._write_pos - len(text)))
|
| 2154 |
+
|
| 2155 |
+
if not self._force_colors and hasattr(sys.stdout, 'isatty') and not \
|
| 2156 |
+
sys.stdout.isatty():
|
| 2157 |
+
# the stdout is not a terminal, this for example happens if the
|
| 2158 |
+
# output is piped to less, e.g. "bin/test | less". In this case,
|
| 2159 |
+
# the terminal control sequences would be printed verbatim, so
|
| 2160 |
+
# don't use any colors.
|
| 2161 |
+
color = ""
|
| 2162 |
+
elif sys.platform == "win32":
|
| 2163 |
+
# Windows consoles don't support ANSI escape sequences
|
| 2164 |
+
color = ""
|
| 2165 |
+
elif not self._colors:
|
| 2166 |
+
color = ""
|
| 2167 |
+
|
| 2168 |
+
if self._line_wrap:
|
| 2169 |
+
if text[0] != "\n":
|
| 2170 |
+
sys.stdout.write("\n")
|
| 2171 |
+
|
| 2172 |
+
# Avoid UnicodeEncodeError when printing out test failures
|
| 2173 |
+
if IS_WINDOWS:
|
| 2174 |
+
text = text.encode('raw_unicode_escape').decode('utf8', 'ignore')
|
| 2175 |
+
elif not sys.stdout.encoding.lower().startswith('utf'):
|
| 2176 |
+
text = text.encode(sys.stdout.encoding, 'backslashreplace'
|
| 2177 |
+
).decode(sys.stdout.encoding)
|
| 2178 |
+
|
| 2179 |
+
if color == "":
|
| 2180 |
+
sys.stdout.write(text)
|
| 2181 |
+
else:
|
| 2182 |
+
sys.stdout.write("%s%s%s" %
|
| 2183 |
+
(c_color % colors[color], text, c_normal))
|
| 2184 |
+
sys.stdout.flush()
|
| 2185 |
+
l = text.rfind("\n")
|
| 2186 |
+
if l == -1:
|
| 2187 |
+
self._write_pos += len(text)
|
| 2188 |
+
else:
|
| 2189 |
+
self._write_pos = len(text) - l - 1
|
| 2190 |
+
self._line_wrap = self._write_pos >= width
|
| 2191 |
+
self._write_pos %= width
|
| 2192 |
+
|
| 2193 |
+
def write_center(self, text, delim="="):
|
| 2194 |
+
width = self.terminal_width
|
| 2195 |
+
if text != "":
|
| 2196 |
+
text = " %s " % text
|
| 2197 |
+
idx = (width - len(text)) // 2
|
| 2198 |
+
t = delim*idx + text + delim*(width - idx - len(text))
|
| 2199 |
+
self.write(t + "\n")
|
| 2200 |
+
|
| 2201 |
+
def write_exception(self, e, val, tb):
|
| 2202 |
+
# remove the first item, as that is always runtests.py
|
| 2203 |
+
tb = tb.tb_next
|
| 2204 |
+
t = traceback.format_exception(e, val, tb)
|
| 2205 |
+
self.write("".join(t))
|
| 2206 |
+
|
| 2207 |
+
def start(self, seed=None, msg="test process starts"):
|
| 2208 |
+
self.write_center(msg)
|
| 2209 |
+
executable = sys.executable
|
| 2210 |
+
v = tuple(sys.version_info)
|
| 2211 |
+
python_version = "%s.%s.%s-%s-%s" % v
|
| 2212 |
+
implementation = platform.python_implementation()
|
| 2213 |
+
if implementation == 'PyPy':
|
| 2214 |
+
implementation += " %s.%s.%s-%s-%s" % sys.pypy_version_info
|
| 2215 |
+
self.write("executable: %s (%s) [%s]\n" %
|
| 2216 |
+
(executable, python_version, implementation))
|
| 2217 |
+
from sympy.utilities.misc import ARCH
|
| 2218 |
+
self.write("architecture: %s\n" % ARCH)
|
| 2219 |
+
from sympy.core.cache import USE_CACHE
|
| 2220 |
+
self.write("cache: %s\n" % USE_CACHE)
|
| 2221 |
+
version = ''
|
| 2222 |
+
if GROUND_TYPES =='gmpy':
|
| 2223 |
+
import gmpy2 as gmpy
|
| 2224 |
+
version = gmpy.version()
|
| 2225 |
+
self.write("ground types: %s %s\n" % (GROUND_TYPES, version))
|
| 2226 |
+
numpy = import_module('numpy')
|
| 2227 |
+
self.write("numpy: %s\n" % (None if not numpy else numpy.__version__))
|
| 2228 |
+
if seed is not None:
|
| 2229 |
+
self.write("random seed: %d\n" % seed)
|
| 2230 |
+
from sympy.utilities.misc import HASH_RANDOMIZATION
|
| 2231 |
+
self.write("hash randomization: ")
|
| 2232 |
+
hash_seed = os.getenv("PYTHONHASHSEED") or '0'
|
| 2233 |
+
if HASH_RANDOMIZATION and (hash_seed == "random" or int(hash_seed)):
|
| 2234 |
+
self.write("on (PYTHONHASHSEED=%s)\n" % hash_seed)
|
| 2235 |
+
else:
|
| 2236 |
+
self.write("off\n")
|
| 2237 |
+
if self._split:
|
| 2238 |
+
self.write("split: %s\n" % self._split)
|
| 2239 |
+
self.write('\n')
|
| 2240 |
+
self._t_start = clock()
|
| 2241 |
+
|
| 2242 |
+
def finish(self):
|
| 2243 |
+
self._t_end = clock()
|
| 2244 |
+
self.write("\n")
|
| 2245 |
+
global text, linelen
|
| 2246 |
+
text = "tests finished: %d passed, " % self._passed
|
| 2247 |
+
linelen = len(text)
|
| 2248 |
+
|
| 2249 |
+
def add_text(mytext):
|
| 2250 |
+
global text, linelen
|
| 2251 |
+
"""Break new text if too long."""
|
| 2252 |
+
if linelen + len(mytext) > self.terminal_width:
|
| 2253 |
+
text += '\n'
|
| 2254 |
+
linelen = 0
|
| 2255 |
+
text += mytext
|
| 2256 |
+
linelen += len(mytext)
|
| 2257 |
+
|
| 2258 |
+
if len(self._failed) > 0:
|
| 2259 |
+
add_text("%d failed, " % len(self._failed))
|
| 2260 |
+
if len(self._failed_doctest) > 0:
|
| 2261 |
+
add_text("%d failed, " % len(self._failed_doctest))
|
| 2262 |
+
if self._skipped > 0:
|
| 2263 |
+
add_text("%d skipped, " % self._skipped)
|
| 2264 |
+
if self._xfailed > 0:
|
| 2265 |
+
add_text("%d expected to fail, " % self._xfailed)
|
| 2266 |
+
if len(self._xpassed) > 0:
|
| 2267 |
+
add_text("%d expected to fail but passed, " % len(self._xpassed))
|
| 2268 |
+
if len(self._exceptions) > 0:
|
| 2269 |
+
add_text("%d exceptions, " % len(self._exceptions))
|
| 2270 |
+
add_text("in %.2f seconds" % (self._t_end - self._t_start))
|
| 2271 |
+
|
| 2272 |
+
if self.slow_test_functions:
|
| 2273 |
+
self.write_center('slowest tests', '_')
|
| 2274 |
+
sorted_slow = sorted(self.slow_test_functions, key=lambda r: r[1])
|
| 2275 |
+
for slow_func_name, taken in sorted_slow:
|
| 2276 |
+
print('%s - Took %.3f seconds' % (slow_func_name, taken))
|
| 2277 |
+
|
| 2278 |
+
if self.fast_test_functions:
|
| 2279 |
+
self.write_center('unexpectedly fast tests', '_')
|
| 2280 |
+
sorted_fast = sorted(self.fast_test_functions,
|
| 2281 |
+
key=lambda r: r[1])
|
| 2282 |
+
for fast_func_name, taken in sorted_fast:
|
| 2283 |
+
print('%s - Took %.3f seconds' % (fast_func_name, taken))
|
| 2284 |
+
|
| 2285 |
+
if len(self._xpassed) > 0:
|
| 2286 |
+
self.write_center("xpassed tests", "_")
|
| 2287 |
+
for e in self._xpassed:
|
| 2288 |
+
self.write("%s: %s\n" % (e[0], e[1]))
|
| 2289 |
+
self.write("\n")
|
| 2290 |
+
|
| 2291 |
+
if self._tb_style != "no" and len(self._exceptions) > 0:
|
| 2292 |
+
for e in self._exceptions:
|
| 2293 |
+
filename, f, (t, val, tb) = e
|
| 2294 |
+
self.write_center("", "_")
|
| 2295 |
+
if f is None:
|
| 2296 |
+
s = "%s" % filename
|
| 2297 |
+
else:
|
| 2298 |
+
s = "%s:%s" % (filename, f.__name__)
|
| 2299 |
+
self.write_center(s, "_")
|
| 2300 |
+
self.write_exception(t, val, tb)
|
| 2301 |
+
self.write("\n")
|
| 2302 |
+
|
| 2303 |
+
if self._tb_style != "no" and len(self._failed) > 0:
|
| 2304 |
+
for e in self._failed:
|
| 2305 |
+
filename, f, (t, val, tb) = e
|
| 2306 |
+
self.write_center("", "_")
|
| 2307 |
+
self.write_center("%s::%s" % (filename, f.__name__), "_")
|
| 2308 |
+
self.write_exception(t, val, tb)
|
| 2309 |
+
self.write("\n")
|
| 2310 |
+
|
| 2311 |
+
if self._tb_style != "no" and len(self._failed_doctest) > 0:
|
| 2312 |
+
for e in self._failed_doctest:
|
| 2313 |
+
filename, msg = e
|
| 2314 |
+
self.write_center("", "_")
|
| 2315 |
+
self.write_center("%s" % filename, "_")
|
| 2316 |
+
self.write(msg)
|
| 2317 |
+
self.write("\n")
|
| 2318 |
+
|
| 2319 |
+
self.write_center(text)
|
| 2320 |
+
ok = len(self._failed) == 0 and len(self._exceptions) == 0 and \
|
| 2321 |
+
len(self._failed_doctest) == 0
|
| 2322 |
+
if not ok:
|
| 2323 |
+
self.write("DO *NOT* COMMIT!\n")
|
| 2324 |
+
return ok
|
| 2325 |
+
|
| 2326 |
+
def entering_filename(self, filename, n):
|
| 2327 |
+
rel_name = filename[len(self._root_dir) + 1:]
|
| 2328 |
+
self._active_file = rel_name
|
| 2329 |
+
self._active_file_error = False
|
| 2330 |
+
self.write(rel_name)
|
| 2331 |
+
self.write("[%d] " % n)
|
| 2332 |
+
|
| 2333 |
+
def leaving_filename(self):
|
| 2334 |
+
self.write(" ")
|
| 2335 |
+
if self._active_file_error:
|
| 2336 |
+
self.write("[FAIL]", "Red", align="right")
|
| 2337 |
+
else:
|
| 2338 |
+
self.write("[OK]", "Green", align="right")
|
| 2339 |
+
self.write("\n")
|
| 2340 |
+
if self._verbose:
|
| 2341 |
+
self.write("\n")
|
| 2342 |
+
|
| 2343 |
+
def entering_test(self, f):
|
| 2344 |
+
self._active_f = f
|
| 2345 |
+
if self._verbose:
|
| 2346 |
+
self.write("\n" + f.__name__ + " ")
|
| 2347 |
+
|
| 2348 |
+
def test_xfail(self):
|
| 2349 |
+
self._xfailed += 1
|
| 2350 |
+
self.write("f", "Green")
|
| 2351 |
+
|
| 2352 |
+
def test_xpass(self, v):
|
| 2353 |
+
message = str(v)
|
| 2354 |
+
self._xpassed.append((self._active_file, message))
|
| 2355 |
+
self.write("X", "Green")
|
| 2356 |
+
|
| 2357 |
+
def test_fail(self, exc_info):
|
| 2358 |
+
self._failed.append((self._active_file, self._active_f, exc_info))
|
| 2359 |
+
self.write("F", "Red")
|
| 2360 |
+
self._active_file_error = True
|
| 2361 |
+
|
| 2362 |
+
def doctest_fail(self, name, error_msg):
|
| 2363 |
+
# the first line contains "******", remove it:
|
| 2364 |
+
error_msg = "\n".join(error_msg.split("\n")[1:])
|
| 2365 |
+
self._failed_doctest.append((name, error_msg))
|
| 2366 |
+
self.write("F", "Red")
|
| 2367 |
+
self._active_file_error = True
|
| 2368 |
+
|
| 2369 |
+
def test_pass(self, char="."):
|
| 2370 |
+
self._passed += 1
|
| 2371 |
+
if self._verbose:
|
| 2372 |
+
self.write("ok", "Green")
|
| 2373 |
+
else:
|
| 2374 |
+
self.write(char, "Green")
|
| 2375 |
+
|
| 2376 |
+
def test_skip(self, v=None):
|
| 2377 |
+
char = "s"
|
| 2378 |
+
self._skipped += 1
|
| 2379 |
+
if v is not None:
|
| 2380 |
+
message = str(v)
|
| 2381 |
+
if message == "KeyboardInterrupt":
|
| 2382 |
+
char = "K"
|
| 2383 |
+
elif message == "Timeout":
|
| 2384 |
+
char = "T"
|
| 2385 |
+
elif message == "Slow":
|
| 2386 |
+
char = "w"
|
| 2387 |
+
if self._verbose:
|
| 2388 |
+
if v is not None:
|
| 2389 |
+
self.write(message + ' ', "Blue")
|
| 2390 |
+
else:
|
| 2391 |
+
self.write(" - ", "Blue")
|
| 2392 |
+
self.write(char, "Blue")
|
| 2393 |
+
|
| 2394 |
+
def test_exception(self, exc_info):
|
| 2395 |
+
self._exceptions.append((self._active_file, self._active_f, exc_info))
|
| 2396 |
+
if exc_info[0] is TimeOutError:
|
| 2397 |
+
self.write("T", "Red")
|
| 2398 |
+
else:
|
| 2399 |
+
self.write("E", "Red")
|
| 2400 |
+
self._active_file_error = True
|
| 2401 |
+
|
| 2402 |
+
def import_error(self, filename, exc_info):
|
| 2403 |
+
self._exceptions.append((filename, None, exc_info))
|
| 2404 |
+
rel_name = filename[len(self._root_dir) + 1:]
|
| 2405 |
+
self.write(rel_name)
|
| 2406 |
+
self.write("[?] Failed to import", "Red")
|
| 2407 |
+
self.write(" ")
|
| 2408 |
+
self.write("[FAIL]", "Red", align="right")
|
| 2409 |
+
self.write("\n")
|
evalkit_tf437/lib/python3.10/site-packages/sympy/testing/runtests_pytest.py
ADDED
|
@@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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Backwards compatible functions for running tests from SymPy using pytest.
|
| 2 |
+
|
| 3 |
+
SymPy historically had its own testing framework that aimed to:
|
| 4 |
+
- be compatible with pytest;
|
| 5 |
+
- operate similarly (or identically) to pytest;
|
| 6 |
+
- not require any external dependencies;
|
| 7 |
+
- have all the functionality in one file only;
|
| 8 |
+
- have no magic, just import the test file and execute the test functions; and
|
| 9 |
+
- be portable.
|
| 10 |
+
|
| 11 |
+
To reduce the maintence burden of developing an independent testing framework
|
| 12 |
+
and to leverage the benefits of existing Python testing infrastructure, SymPy
|
| 13 |
+
now uses pytest (and various of its plugins) to run the test suite.
|
| 14 |
+
|
| 15 |
+
To maintain backwards compatibility with the legacy testing interface of SymPy,
|
| 16 |
+
which implemented functions that allowed users to run the tests on their
|
| 17 |
+
installed version of SymPy, the functions in this module are implemented to
|
| 18 |
+
match the existing API while thinly wrapping pytest.
|
| 19 |
+
|
| 20 |
+
These two key functions are `test` and `doctest`.
|
| 21 |
+
|
| 22 |
+
"""
|
| 23 |
+
|
| 24 |
+
import functools
|
| 25 |
+
import importlib.util
|
| 26 |
+
import os
|
| 27 |
+
import pathlib
|
| 28 |
+
import re
|
| 29 |
+
from fnmatch import fnmatch
|
| 30 |
+
from typing import List, Optional, Tuple
|
| 31 |
+
|
| 32 |
+
try:
|
| 33 |
+
import pytest
|
| 34 |
+
except ImportError:
|
| 35 |
+
|
| 36 |
+
class NoPytestError(Exception):
|
| 37 |
+
"""Raise when an internal test helper function is called with pytest."""
|
| 38 |
+
|
| 39 |
+
class pytest: # type: ignore
|
| 40 |
+
"""Shadow to support pytest features when pytest can't be imported."""
|
| 41 |
+
|
| 42 |
+
@staticmethod
|
| 43 |
+
def main(*args, **kwargs):
|
| 44 |
+
msg = 'pytest must be installed to run tests via this function'
|
| 45 |
+
raise NoPytestError(msg)
|
| 46 |
+
|
| 47 |
+
from sympy.testing.runtests import test as test_sympy
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
TESTPATHS_DEFAULT = (
|
| 51 |
+
pathlib.Path('sympy'),
|
| 52 |
+
pathlib.Path('doc', 'src'),
|
| 53 |
+
)
|
| 54 |
+
BLACKLIST_DEFAULT = (
|
| 55 |
+
'sympy/integrals/rubi/rubi_tests/tests',
|
| 56 |
+
)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
class PytestPluginManager:
|
| 60 |
+
"""Module names for pytest plugins used by SymPy."""
|
| 61 |
+
PYTEST: str = 'pytest'
|
| 62 |
+
RANDOMLY: str = 'pytest_randomly'
|
| 63 |
+
SPLIT: str = 'pytest_split'
|
| 64 |
+
TIMEOUT: str = 'pytest_timeout'
|
| 65 |
+
XDIST: str = 'xdist'
|
| 66 |
+
|
| 67 |
+
@functools.cached_property
|
| 68 |
+
def has_pytest(self) -> bool:
|
| 69 |
+
return bool(importlib.util.find_spec(self.PYTEST))
|
| 70 |
+
|
| 71 |
+
@functools.cached_property
|
| 72 |
+
def has_randomly(self) -> bool:
|
| 73 |
+
return bool(importlib.util.find_spec(self.RANDOMLY))
|
| 74 |
+
|
| 75 |
+
@functools.cached_property
|
| 76 |
+
def has_split(self) -> bool:
|
| 77 |
+
return bool(importlib.util.find_spec(self.SPLIT))
|
| 78 |
+
|
| 79 |
+
@functools.cached_property
|
| 80 |
+
def has_timeout(self) -> bool:
|
| 81 |
+
return bool(importlib.util.find_spec(self.TIMEOUT))
|
| 82 |
+
|
| 83 |
+
@functools.cached_property
|
| 84 |
+
def has_xdist(self) -> bool:
|
| 85 |
+
return bool(importlib.util.find_spec(self.XDIST))
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
split_pattern = re.compile(r'([1-9][0-9]*)/([1-9][0-9]*)')
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
@functools.lru_cache
|
| 92 |
+
def sympy_dir() -> pathlib.Path:
|
| 93 |
+
"""Returns the root SymPy directory."""
|
| 94 |
+
return pathlib.Path(__file__).parents[2]
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def update_args_with_rootdir(args: List[str]) -> List[str]:
|
| 98 |
+
"""Adds `--rootdir` and path to the args `list` passed to `pytest.main`.
|
| 99 |
+
|
| 100 |
+
This is required to ensure that pytest is able to find the SymPy tests in
|
| 101 |
+
instances where it gets confused determining the root directory, e.g. when
|
| 102 |
+
running with Pyodide (e.g. `bin/test_pyodide.mjs`).
|
| 103 |
+
|
| 104 |
+
"""
|
| 105 |
+
args.extend(['--rootdir', str(sympy_dir())])
|
| 106 |
+
return args
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def update_args_with_paths(
|
| 110 |
+
paths: List[str],
|
| 111 |
+
keywords: Optional[Tuple[str]],
|
| 112 |
+
args: List[str],
|
| 113 |
+
) -> List[str]:
|
| 114 |
+
"""Appends valid paths and flags to the args `list` passed to `pytest.main`.
|
| 115 |
+
|
| 116 |
+
The are three different types of "path" that a user may pass to the `paths`
|
| 117 |
+
positional arguments, all of which need to be handled slightly differently:
|
| 118 |
+
|
| 119 |
+
1. Nothing is passed
|
| 120 |
+
The paths to the `testpaths` defined in `pytest.ini` need to be appended
|
| 121 |
+
to the arguments list.
|
| 122 |
+
2. Full, valid paths are passed
|
| 123 |
+
These paths need to be validated but can then be directly appended to
|
| 124 |
+
the arguments list.
|
| 125 |
+
3. Partial paths are passed.
|
| 126 |
+
The `testpaths` defined in `pytest.ini` need to be recursed and any
|
| 127 |
+
matches be appended to the arguments list.
|
| 128 |
+
|
| 129 |
+
"""
|
| 130 |
+
|
| 131 |
+
def find_paths_matching_partial(partial_paths):
|
| 132 |
+
partial_path_file_patterns = []
|
| 133 |
+
for partial_path in partial_paths:
|
| 134 |
+
if len(partial_path) >= 4:
|
| 135 |
+
has_test_prefix = partial_path[:4] == 'test'
|
| 136 |
+
has_py_suffix = partial_path[-3:] == '.py'
|
| 137 |
+
elif len(partial_path) >= 3:
|
| 138 |
+
has_test_prefix = False
|
| 139 |
+
has_py_suffix = partial_path[-3:] == '.py'
|
| 140 |
+
else:
|
| 141 |
+
has_test_prefix = False
|
| 142 |
+
has_py_suffix = False
|
| 143 |
+
if has_test_prefix and has_py_suffix:
|
| 144 |
+
partial_path_file_patterns.append(partial_path)
|
| 145 |
+
elif has_test_prefix:
|
| 146 |
+
partial_path_file_patterns.append(f'{partial_path}*.py')
|
| 147 |
+
elif has_py_suffix:
|
| 148 |
+
partial_path_file_patterns.append(f'test*{partial_path}')
|
| 149 |
+
else:
|
| 150 |
+
partial_path_file_patterns.append(f'test*{partial_path}*.py')
|
| 151 |
+
matches = []
|
| 152 |
+
for testpath in valid_testpaths_default:
|
| 153 |
+
for path, dirs, files in os.walk(testpath, topdown=True):
|
| 154 |
+
zipped = zip(partial_paths, partial_path_file_patterns)
|
| 155 |
+
for (partial_path, partial_path_file) in zipped:
|
| 156 |
+
if fnmatch(path, f'*{partial_path}*'):
|
| 157 |
+
matches.append(str(pathlib.Path(path)))
|
| 158 |
+
dirs[:] = []
|
| 159 |
+
else:
|
| 160 |
+
for file in files:
|
| 161 |
+
if fnmatch(file, partial_path_file):
|
| 162 |
+
matches.append(str(pathlib.Path(path, file)))
|
| 163 |
+
return matches
|
| 164 |
+
|
| 165 |
+
def is_tests_file(filepath: str) -> bool:
|
| 166 |
+
path = pathlib.Path(filepath)
|
| 167 |
+
if not path.is_file():
|
| 168 |
+
return False
|
| 169 |
+
if not path.parts[-1].startswith('test_'):
|
| 170 |
+
return False
|
| 171 |
+
if not path.suffix == '.py':
|
| 172 |
+
return False
|
| 173 |
+
return True
|
| 174 |
+
|
| 175 |
+
def find_tests_matching_keywords(keywords, filepath):
|
| 176 |
+
matches = []
|
| 177 |
+
with open(filepath, encoding='utf-8') as tests_file:
|
| 178 |
+
source = tests_file.read()
|
| 179 |
+
for line in source.splitlines():
|
| 180 |
+
if line.lstrip().startswith('def '):
|
| 181 |
+
for kw in keywords:
|
| 182 |
+
if line.lower().find(kw.lower()) != -1:
|
| 183 |
+
test_name = line.split(' ')[1].split('(')[0]
|
| 184 |
+
full_test_path = filepath + '::' + test_name
|
| 185 |
+
matches.append(full_test_path)
|
| 186 |
+
return matches
|
| 187 |
+
|
| 188 |
+
valid_testpaths_default = []
|
| 189 |
+
for testpath in TESTPATHS_DEFAULT:
|
| 190 |
+
absolute_testpath = pathlib.Path(sympy_dir(), testpath)
|
| 191 |
+
if absolute_testpath.exists():
|
| 192 |
+
valid_testpaths_default.append(str(absolute_testpath))
|
| 193 |
+
|
| 194 |
+
candidate_paths = []
|
| 195 |
+
if paths:
|
| 196 |
+
full_paths = []
|
| 197 |
+
partial_paths = []
|
| 198 |
+
for path in paths:
|
| 199 |
+
if pathlib.Path(path).exists():
|
| 200 |
+
full_paths.append(str(pathlib.Path(sympy_dir(), path)))
|
| 201 |
+
else:
|
| 202 |
+
partial_paths.append(path)
|
| 203 |
+
matched_paths = find_paths_matching_partial(partial_paths)
|
| 204 |
+
candidate_paths.extend(full_paths)
|
| 205 |
+
candidate_paths.extend(matched_paths)
|
| 206 |
+
else:
|
| 207 |
+
candidate_paths.extend(valid_testpaths_default)
|
| 208 |
+
|
| 209 |
+
if keywords is not None and keywords != ():
|
| 210 |
+
matches = []
|
| 211 |
+
for path in candidate_paths:
|
| 212 |
+
if is_tests_file(path):
|
| 213 |
+
test_matches = find_tests_matching_keywords(keywords, path)
|
| 214 |
+
matches.extend(test_matches)
|
| 215 |
+
else:
|
| 216 |
+
for root, dirnames, filenames in os.walk(path):
|
| 217 |
+
for filename in filenames:
|
| 218 |
+
absolute_filepath = str(pathlib.Path(root, filename))
|
| 219 |
+
if is_tests_file(absolute_filepath):
|
| 220 |
+
test_matches = find_tests_matching_keywords(
|
| 221 |
+
keywords,
|
| 222 |
+
absolute_filepath,
|
| 223 |
+
)
|
| 224 |
+
matches.extend(test_matches)
|
| 225 |
+
args.extend(matches)
|
| 226 |
+
else:
|
| 227 |
+
args.extend(candidate_paths)
|
| 228 |
+
|
| 229 |
+
return args
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
def make_absolute_path(partial_path: str) -> str:
|
| 233 |
+
"""Convert a partial path to an absolute path.
|
| 234 |
+
|
| 235 |
+
A path such a `sympy/core` might be needed. However, absolute paths should
|
| 236 |
+
be used in the arguments to pytest in all cases as it avoids errors that
|
| 237 |
+
arise from nonexistent paths.
|
| 238 |
+
|
| 239 |
+
This function assumes that partial_paths will be passed in such that they
|
| 240 |
+
begin with the explicit `sympy` directory, i.e. `sympy/...`.
|
| 241 |
+
|
| 242 |
+
"""
|
| 243 |
+
|
| 244 |
+
def is_valid_partial_path(partial_path: str) -> bool:
|
| 245 |
+
"""Assumption that partial paths are defined from the `sympy` root."""
|
| 246 |
+
return pathlib.Path(partial_path).parts[0] == 'sympy'
|
| 247 |
+
|
| 248 |
+
if not is_valid_partial_path(partial_path):
|
| 249 |
+
msg = (
|
| 250 |
+
f'Partial path {dir(partial_path)} is invalid, partial paths are '
|
| 251 |
+
f'expected to be defined with the `sympy` directory as the root.'
|
| 252 |
+
)
|
| 253 |
+
raise ValueError(msg)
|
| 254 |
+
|
| 255 |
+
absolute_path = str(pathlib.Path(sympy_dir(), partial_path))
|
| 256 |
+
return absolute_path
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
def test(*paths, subprocess=True, rerun=0, **kwargs):
|
| 260 |
+
"""Interface to run tests via pytest compatible with SymPy's test runner.
|
| 261 |
+
|
| 262 |
+
Explanation
|
| 263 |
+
===========
|
| 264 |
+
|
| 265 |
+
Note that a `pytest.ExitCode`, which is an `enum`, is returned. This is
|
| 266 |
+
different to the legacy SymPy test runner which would return a `bool`. If
|
| 267 |
+
all tests sucessfully pass the `pytest.ExitCode.OK` with value `0` is
|
| 268 |
+
returned, whereas the legacy SymPy test runner would return `True`. In any
|
| 269 |
+
other scenario, a non-zero `enum` value is returned, whereas the legacy
|
| 270 |
+
SymPy test runner would return `False`. Users need to, therefore, be careful
|
| 271 |
+
if treating the pytest exit codes as booleans because
|
| 272 |
+
`bool(pytest.ExitCode.OK)` evaluates to `False`, the opposite of legacy
|
| 273 |
+
behaviour.
|
| 274 |
+
|
| 275 |
+
Examples
|
| 276 |
+
========
|
| 277 |
+
|
| 278 |
+
>>> import sympy # doctest: +SKIP
|
| 279 |
+
|
| 280 |
+
Run one file:
|
| 281 |
+
|
| 282 |
+
>>> sympy.test('sympy/core/tests/test_basic.py') # doctest: +SKIP
|
| 283 |
+
>>> sympy.test('_basic') # doctest: +SKIP
|
| 284 |
+
|
| 285 |
+
Run all tests in sympy/functions/ and some particular file:
|
| 286 |
+
|
| 287 |
+
>>> sympy.test("sympy/core/tests/test_basic.py",
|
| 288 |
+
... "sympy/functions") # doctest: +SKIP
|
| 289 |
+
|
| 290 |
+
Run all tests in sympy/core and sympy/utilities:
|
| 291 |
+
|
| 292 |
+
>>> sympy.test("/core", "/util") # doctest: +SKIP
|
| 293 |
+
|
| 294 |
+
Run specific test from a file:
|
| 295 |
+
|
| 296 |
+
>>> sympy.test("sympy/core/tests/test_basic.py",
|
| 297 |
+
... kw="test_equality") # doctest: +SKIP
|
| 298 |
+
|
| 299 |
+
Run specific test from any file:
|
| 300 |
+
|
| 301 |
+
>>> sympy.test(kw="subs") # doctest: +SKIP
|
| 302 |
+
|
| 303 |
+
Run the tests using the legacy SymPy runner:
|
| 304 |
+
|
| 305 |
+
>>> sympy.test(use_sympy_runner=True) # doctest: +SKIP
|
| 306 |
+
|
| 307 |
+
Note that this option is slated for deprecation in the near future and is
|
| 308 |
+
only currently provided to ensure users have an alternative option while the
|
| 309 |
+
pytest-based runner receives real-world testing.
|
| 310 |
+
|
| 311 |
+
Parameters
|
| 312 |
+
==========
|
| 313 |
+
paths : first n positional arguments of strings
|
| 314 |
+
Paths, both partial and absolute, describing which subset(s) of the test
|
| 315 |
+
suite are to be run.
|
| 316 |
+
subprocess : bool, default is True
|
| 317 |
+
Legacy option, is currently ignored.
|
| 318 |
+
rerun : int, default is 0
|
| 319 |
+
Legacy option, is ignored.
|
| 320 |
+
use_sympy_runner : bool or None, default is None
|
| 321 |
+
Temporary option to invoke the legacy SymPy test runner instead of
|
| 322 |
+
`pytest.main`. Will be removed in the near future.
|
| 323 |
+
verbose : bool, default is False
|
| 324 |
+
Sets the verbosity of the pytest output. Using `True` will add the
|
| 325 |
+
`--verbose` option to the pytest call.
|
| 326 |
+
tb : str, 'auto', 'long', 'short', 'line', 'native', or 'no'
|
| 327 |
+
Sets the traceback print mode of pytest using the `--tb` option.
|
| 328 |
+
kw : str
|
| 329 |
+
Only run tests which match the given substring expression. An expression
|
| 330 |
+
is a Python evaluatable expression where all names are substring-matched
|
| 331 |
+
against test names and their parent classes. Example: -k 'test_method or
|
| 332 |
+
test_other' matches all test functions and classes whose name contains
|
| 333 |
+
'test_method' or 'test_other', while -k 'not test_method' matches those
|
| 334 |
+
that don't contain 'test_method' in their names. -k 'not test_method and
|
| 335 |
+
not test_other' will eliminate the matches. Additionally keywords are
|
| 336 |
+
matched to classes and functions containing extra names in their
|
| 337 |
+
'extra_keyword_matches' set, as well as functions which have names
|
| 338 |
+
assigned directly to them. The matching is case-insensitive.
|
| 339 |
+
pdb : bool, default is False
|
| 340 |
+
Start the interactive Python debugger on errors or `KeyboardInterrupt`.
|
| 341 |
+
colors : bool, default is True
|
| 342 |
+
Color terminal output.
|
| 343 |
+
force_colors : bool, default is False
|
| 344 |
+
Legacy option, is ignored.
|
| 345 |
+
sort : bool, default is True
|
| 346 |
+
Run the tests in sorted order. pytest uses a sorted test order by
|
| 347 |
+
default. Requires pytest-randomly.
|
| 348 |
+
seed : int
|
| 349 |
+
Seed to use for random number generation. Requires pytest-randomly.
|
| 350 |
+
timeout : int, default is 0
|
| 351 |
+
Timeout in seconds before dumping the stacks. 0 means no timeout.
|
| 352 |
+
Requires pytest-timeout.
|
| 353 |
+
fail_on_timeout : bool, default is False
|
| 354 |
+
Legacy option, is currently ignored.
|
| 355 |
+
slow : bool, default is False
|
| 356 |
+
Run the subset of tests marked as `slow`.
|
| 357 |
+
enhance_asserts : bool, default is False
|
| 358 |
+
Legacy option, is currently ignored.
|
| 359 |
+
split : string in form `<SPLIT>/<GROUPS>` or None, default is None
|
| 360 |
+
Used to split the tests up. As an example, if `split='2/3' is used then
|
| 361 |
+
only the middle third of tests are run. Requires pytest-split.
|
| 362 |
+
time_balance : bool, default is True
|
| 363 |
+
Legacy option, is currently ignored.
|
| 364 |
+
blacklist : iterable of test paths as strings, default is BLACKLIST_DEFAULT
|
| 365 |
+
Blacklisted test paths are ignored using the `--ignore` option. Paths
|
| 366 |
+
may be partial or absolute. If partial then they are matched against
|
| 367 |
+
all paths in the pytest tests path.
|
| 368 |
+
parallel : bool, default is False
|
| 369 |
+
Parallelize the test running using pytest-xdist. If `True` then pytest
|
| 370 |
+
will automatically detect the number of CPU cores available and use them
|
| 371 |
+
all. Requires pytest-xdist.
|
| 372 |
+
store_durations : bool, False
|
| 373 |
+
Store test durations into the file `.test_durations`. The is used by
|
| 374 |
+
`pytest-split` to help determine more even splits when more than one
|
| 375 |
+
test group is being used. Requires pytest-split.
|
| 376 |
+
|
| 377 |
+
"""
|
| 378 |
+
# NOTE: to be removed alongside SymPy test runner
|
| 379 |
+
if kwargs.get('use_sympy_runner', False):
|
| 380 |
+
kwargs.pop('parallel', False)
|
| 381 |
+
kwargs.pop('store_durations', False)
|
| 382 |
+
kwargs.pop('use_sympy_runner', True)
|
| 383 |
+
if kwargs.get('slow') is None:
|
| 384 |
+
kwargs['slow'] = False
|
| 385 |
+
return test_sympy(*paths, subprocess=True, rerun=0, **kwargs)
|
| 386 |
+
|
| 387 |
+
pytest_plugin_manager = PytestPluginManager()
|
| 388 |
+
if not pytest_plugin_manager.has_pytest:
|
| 389 |
+
pytest.main()
|
| 390 |
+
|
| 391 |
+
args = []
|
| 392 |
+
args = update_args_with_rootdir(args)
|
| 393 |
+
|
| 394 |
+
if kwargs.get('verbose', False):
|
| 395 |
+
args.append('--verbose')
|
| 396 |
+
|
| 397 |
+
if tb := kwargs.get('tb'):
|
| 398 |
+
args.extend(['--tb', tb])
|
| 399 |
+
|
| 400 |
+
if kwargs.get('pdb'):
|
| 401 |
+
args.append('--pdb')
|
| 402 |
+
|
| 403 |
+
if not kwargs.get('colors', True):
|
| 404 |
+
args.extend(['--color', 'no'])
|
| 405 |
+
|
| 406 |
+
if seed := kwargs.get('seed'):
|
| 407 |
+
if not pytest_plugin_manager.has_randomly:
|
| 408 |
+
msg = '`pytest-randomly` plugin required to control random seed.'
|
| 409 |
+
raise ModuleNotFoundError(msg)
|
| 410 |
+
args.extend(['--randomly-seed', str(seed)])
|
| 411 |
+
|
| 412 |
+
if kwargs.get('sort', True) and pytest_plugin_manager.has_randomly:
|
| 413 |
+
args.append('--randomly-dont-reorganize')
|
| 414 |
+
elif not kwargs.get('sort', True) and not pytest_plugin_manager.has_randomly:
|
| 415 |
+
msg = '`pytest-randomly` plugin required to randomize test order.'
|
| 416 |
+
raise ModuleNotFoundError(msg)
|
| 417 |
+
|
| 418 |
+
if timeout := kwargs.get('timeout', None):
|
| 419 |
+
if not pytest_plugin_manager.has_timeout:
|
| 420 |
+
msg = '`pytest-timeout` plugin required to apply timeout to tests.'
|
| 421 |
+
raise ModuleNotFoundError(msg)
|
| 422 |
+
args.extend(['--timeout', str(int(timeout))])
|
| 423 |
+
|
| 424 |
+
# Skip slow tests by default and always skip tooslow tests
|
| 425 |
+
if kwargs.get('slow', False):
|
| 426 |
+
args.extend(['-m', 'slow and not tooslow'])
|
| 427 |
+
else:
|
| 428 |
+
args.extend(['-m', 'not slow and not tooslow'])
|
| 429 |
+
|
| 430 |
+
if (split := kwargs.get('split')) is not None:
|
| 431 |
+
if not pytest_plugin_manager.has_split:
|
| 432 |
+
msg = '`pytest-split` plugin required to run tests as groups.'
|
| 433 |
+
raise ModuleNotFoundError(msg)
|
| 434 |
+
match = split_pattern.match(split)
|
| 435 |
+
if not match:
|
| 436 |
+
msg = ('split must be a string of the form a/b where a and b are '
|
| 437 |
+
'positive nonzero ints')
|
| 438 |
+
raise ValueError(msg)
|
| 439 |
+
group, splits = map(str, match.groups())
|
| 440 |
+
args.extend(['--group', group, '--splits', splits])
|
| 441 |
+
if group > splits:
|
| 442 |
+
msg = (f'cannot have a group number {group} with only {splits} '
|
| 443 |
+
'splits')
|
| 444 |
+
raise ValueError(msg)
|
| 445 |
+
|
| 446 |
+
if blacklist := kwargs.get('blacklist', BLACKLIST_DEFAULT):
|
| 447 |
+
for path in blacklist:
|
| 448 |
+
args.extend(['--ignore', make_absolute_path(path)])
|
| 449 |
+
|
| 450 |
+
if kwargs.get('parallel', False):
|
| 451 |
+
if not pytest_plugin_manager.has_xdist:
|
| 452 |
+
msg = '`pytest-xdist` plugin required to run tests in parallel.'
|
| 453 |
+
raise ModuleNotFoundError(msg)
|
| 454 |
+
args.extend(['-n', 'auto'])
|
| 455 |
+
|
| 456 |
+
if kwargs.get('store_durations', False):
|
| 457 |
+
if not pytest_plugin_manager.has_split:
|
| 458 |
+
msg = '`pytest-split` plugin required to store test durations.'
|
| 459 |
+
raise ModuleNotFoundError(msg)
|
| 460 |
+
args.append('--store-durations')
|
| 461 |
+
|
| 462 |
+
if (keywords := kwargs.get('kw')) is not None:
|
| 463 |
+
keywords = tuple(str(kw) for kw in keywords)
|
| 464 |
+
else:
|
| 465 |
+
keywords = ()
|
| 466 |
+
|
| 467 |
+
args = update_args_with_paths(paths, keywords, args)
|
| 468 |
+
exit_code = pytest.main(args)
|
| 469 |
+
return exit_code
|
| 470 |
+
|
| 471 |
+
|
| 472 |
+
def doctest():
|
| 473 |
+
"""Interface to run doctests via pytest compatible with SymPy's test runner.
|
| 474 |
+
"""
|
| 475 |
+
raise NotImplementedError
|
evalkit_tf437/lib/python3.10/site-packages/sympy/testing/tests/__init__.py
ADDED
|
File without changes
|
evalkit_tf437/lib/python3.10/site-packages/sympy/testing/tests/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (178 Bytes). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/sympy/testing/tests/__pycache__/diagnose_imports.cpython-310.pyc
ADDED
|
Binary file (6.52 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/sympy/testing/tests/__pycache__/test_code_quality.cpython-310.pyc
ADDED
|
Binary file (16.2 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/sympy/testing/tests/__pycache__/test_deprecated.cpython-310.pyc
ADDED
|
Binary file (466 Bytes). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/sympy/testing/tests/__pycache__/test_module_imports.cpython-310.pyc
ADDED
|
Binary file (1.61 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/sympy/testing/tests/__pycache__/test_pytest.cpython-310.pyc
ADDED
|
Binary file (7.85 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/sympy/testing/tests/__pycache__/test_runtests_pytest.cpython-310.pyc
ADDED
|
Binary file (5.77 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/sympy/testing/tests/diagnose_imports.py
ADDED
|
@@ -0,0 +1,218 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
|
| 3 |
+
"""
|
| 4 |
+
Import diagnostics. Run bin/diagnose_imports.py --help for details.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
if __name__ == "__main__":
|
| 10 |
+
|
| 11 |
+
import sys
|
| 12 |
+
import inspect
|
| 13 |
+
import builtins
|
| 14 |
+
|
| 15 |
+
import optparse
|
| 16 |
+
|
| 17 |
+
from os.path import abspath, dirname, join, normpath
|
| 18 |
+
this_file = abspath(__file__)
|
| 19 |
+
sympy_dir = join(dirname(this_file), '..', '..', '..')
|
| 20 |
+
sympy_dir = normpath(sympy_dir)
|
| 21 |
+
sys.path.insert(0, sympy_dir)
|
| 22 |
+
|
| 23 |
+
option_parser = optparse.OptionParser(
|
| 24 |
+
usage=
|
| 25 |
+
"Usage: %prog option [options]\n"
|
| 26 |
+
"\n"
|
| 27 |
+
"Import analysis for imports between SymPy modules.")
|
| 28 |
+
option_group = optparse.OptionGroup(
|
| 29 |
+
option_parser,
|
| 30 |
+
'Analysis options',
|
| 31 |
+
'Options that define what to do. Exactly one of these must be given.')
|
| 32 |
+
option_group.add_option(
|
| 33 |
+
'--problems',
|
| 34 |
+
help=
|
| 35 |
+
'Print all import problems, that is: '
|
| 36 |
+
'If an import pulls in a package instead of a module '
|
| 37 |
+
'(e.g. sympy.core instead of sympy.core.add); ' # see ##PACKAGE##
|
| 38 |
+
'if it imports a symbol that is already present; ' # see ##DUPLICATE##
|
| 39 |
+
'if it imports a symbol '
|
| 40 |
+
'from somewhere other than the defining module.', # see ##ORIGIN##
|
| 41 |
+
action='count')
|
| 42 |
+
option_group.add_option(
|
| 43 |
+
'--origins',
|
| 44 |
+
help=
|
| 45 |
+
'For each imported symbol in each module, '
|
| 46 |
+
'print the module that defined it. '
|
| 47 |
+
'(This is useful for import refactoring.)',
|
| 48 |
+
action='count')
|
| 49 |
+
option_parser.add_option_group(option_group)
|
| 50 |
+
option_group = optparse.OptionGroup(
|
| 51 |
+
option_parser,
|
| 52 |
+
'Sort options',
|
| 53 |
+
'These options define the sort order for output lines. '
|
| 54 |
+
'At most one of these options is allowed. '
|
| 55 |
+
'Unsorted output will reflect the order in which imports happened.')
|
| 56 |
+
option_group.add_option(
|
| 57 |
+
'--by-importer',
|
| 58 |
+
help='Sort output lines by name of importing module.',
|
| 59 |
+
action='count')
|
| 60 |
+
option_group.add_option(
|
| 61 |
+
'--by-origin',
|
| 62 |
+
help='Sort output lines by name of imported module.',
|
| 63 |
+
action='count')
|
| 64 |
+
option_parser.add_option_group(option_group)
|
| 65 |
+
(options, args) = option_parser.parse_args()
|
| 66 |
+
if args:
|
| 67 |
+
option_parser.error(
|
| 68 |
+
'Unexpected arguments %s (try %s --help)' % (args, sys.argv[0]))
|
| 69 |
+
if options.problems > 1:
|
| 70 |
+
option_parser.error('--problems must not be given more than once.')
|
| 71 |
+
if options.origins > 1:
|
| 72 |
+
option_parser.error('--origins must not be given more than once.')
|
| 73 |
+
if options.by_importer > 1:
|
| 74 |
+
option_parser.error('--by-importer must not be given more than once.')
|
| 75 |
+
if options.by_origin > 1:
|
| 76 |
+
option_parser.error('--by-origin must not be given more than once.')
|
| 77 |
+
options.problems = options.problems == 1
|
| 78 |
+
options.origins = options.origins == 1
|
| 79 |
+
options.by_importer = options.by_importer == 1
|
| 80 |
+
options.by_origin = options.by_origin == 1
|
| 81 |
+
if not options.problems and not options.origins:
|
| 82 |
+
option_parser.error(
|
| 83 |
+
'At least one of --problems and --origins is required')
|
| 84 |
+
if options.problems and options.origins:
|
| 85 |
+
option_parser.error(
|
| 86 |
+
'At most one of --problems and --origins is allowed')
|
| 87 |
+
if options.by_importer and options.by_origin:
|
| 88 |
+
option_parser.error(
|
| 89 |
+
'At most one of --by-importer and --by-origin is allowed')
|
| 90 |
+
options.by_process = not options.by_importer and not options.by_origin
|
| 91 |
+
|
| 92 |
+
builtin_import = builtins.__import__
|
| 93 |
+
|
| 94 |
+
class Definition:
|
| 95 |
+
"""Information about a symbol's definition."""
|
| 96 |
+
def __init__(self, name, value, definer):
|
| 97 |
+
self.name = name
|
| 98 |
+
self.value = value
|
| 99 |
+
self.definer = definer
|
| 100 |
+
def __hash__(self):
|
| 101 |
+
return hash(self.name)
|
| 102 |
+
def __eq__(self, other):
|
| 103 |
+
return self.name == other.name and self.value == other.value
|
| 104 |
+
def __ne__(self, other):
|
| 105 |
+
return not (self == other)
|
| 106 |
+
def __repr__(self):
|
| 107 |
+
return 'Definition(%s, ..., %s)' % (
|
| 108 |
+
repr(self.name), repr(self.definer))
|
| 109 |
+
|
| 110 |
+
# Maps each function/variable to name of module to define it
|
| 111 |
+
symbol_definers: dict[Definition, str] = {}
|
| 112 |
+
|
| 113 |
+
def in_module(a, b):
|
| 114 |
+
"""Is a the same module as or a submodule of b?"""
|
| 115 |
+
return a == b or a != None and b != None and a.startswith(b + '.')
|
| 116 |
+
|
| 117 |
+
def relevant(module):
|
| 118 |
+
"""Is module relevant for import checking?
|
| 119 |
+
|
| 120 |
+
Only imports between relevant modules will be checked."""
|
| 121 |
+
return in_module(module, 'sympy')
|
| 122 |
+
|
| 123 |
+
sorted_messages = []
|
| 124 |
+
|
| 125 |
+
def msg(msg, *args):
|
| 126 |
+
global options, sorted_messages
|
| 127 |
+
if options.by_process:
|
| 128 |
+
print(msg % args)
|
| 129 |
+
else:
|
| 130 |
+
sorted_messages.append(msg % args)
|
| 131 |
+
|
| 132 |
+
def tracking_import(module, globals=globals(), locals=[], fromlist=None, level=-1):
|
| 133 |
+
"""__import__ wrapper - does not change imports at all, but tracks them.
|
| 134 |
+
|
| 135 |
+
Default order is implemented by doing output directly.
|
| 136 |
+
All other orders are implemented by collecting output information into
|
| 137 |
+
a sorted list that will be emitted after all imports are processed.
|
| 138 |
+
|
| 139 |
+
Indirect imports can only occur after the requested symbol has been
|
| 140 |
+
imported directly (because the indirect import would not have a module
|
| 141 |
+
to pick the symbol up from).
|
| 142 |
+
So this code detects indirect imports by checking whether the symbol in
|
| 143 |
+
question was already imported.
|
| 144 |
+
|
| 145 |
+
Keeps the semantics of __import__ unchanged."""
|
| 146 |
+
global options, symbol_definers
|
| 147 |
+
caller_frame = inspect.getframeinfo(sys._getframe(1))
|
| 148 |
+
importer_filename = caller_frame.filename
|
| 149 |
+
importer_module = globals['__name__']
|
| 150 |
+
if importer_filename == caller_frame.filename:
|
| 151 |
+
importer_reference = '%s line %s' % (
|
| 152 |
+
importer_filename, str(caller_frame.lineno))
|
| 153 |
+
else:
|
| 154 |
+
importer_reference = importer_filename
|
| 155 |
+
result = builtin_import(module, globals, locals, fromlist, level)
|
| 156 |
+
importee_module = result.__name__
|
| 157 |
+
# We're only interested if importer and importee are in SymPy
|
| 158 |
+
if relevant(importer_module) and relevant(importee_module):
|
| 159 |
+
for symbol in result.__dict__.iterkeys():
|
| 160 |
+
definition = Definition(
|
| 161 |
+
symbol, result.__dict__[symbol], importer_module)
|
| 162 |
+
if definition not in symbol_definers:
|
| 163 |
+
symbol_definers[definition] = importee_module
|
| 164 |
+
if hasattr(result, '__path__'):
|
| 165 |
+
##PACKAGE##
|
| 166 |
+
# The existence of __path__ is documented in the tutorial on modules.
|
| 167 |
+
# Python 3.3 documents this in http://docs.python.org/3.3/reference/import.html
|
| 168 |
+
if options.by_origin:
|
| 169 |
+
msg('Error: %s (a package) is imported by %s',
|
| 170 |
+
module, importer_reference)
|
| 171 |
+
else:
|
| 172 |
+
msg('Error: %s contains package import %s',
|
| 173 |
+
importer_reference, module)
|
| 174 |
+
if fromlist != None:
|
| 175 |
+
symbol_list = fromlist
|
| 176 |
+
if '*' in symbol_list:
|
| 177 |
+
if (importer_filename.endswith(("__init__.py", "__init__.pyc", "__init__.pyo"))):
|
| 178 |
+
# We do not check starred imports inside __init__
|
| 179 |
+
# That's the normal "please copy over its imports to my namespace"
|
| 180 |
+
symbol_list = []
|
| 181 |
+
else:
|
| 182 |
+
symbol_list = result.__dict__.iterkeys()
|
| 183 |
+
for symbol in symbol_list:
|
| 184 |
+
if symbol not in result.__dict__:
|
| 185 |
+
if options.by_origin:
|
| 186 |
+
msg('Error: %s.%s is not defined (yet), but %s tries to import it',
|
| 187 |
+
importee_module, symbol, importer_reference)
|
| 188 |
+
else:
|
| 189 |
+
msg('Error: %s tries to import %s.%s, which did not define it (yet)',
|
| 190 |
+
importer_reference, importee_module, symbol)
|
| 191 |
+
else:
|
| 192 |
+
definition = Definition(
|
| 193 |
+
symbol, result.__dict__[symbol], importer_module)
|
| 194 |
+
symbol_definer = symbol_definers[definition]
|
| 195 |
+
if symbol_definer == importee_module:
|
| 196 |
+
##DUPLICATE##
|
| 197 |
+
if options.by_origin:
|
| 198 |
+
msg('Error: %s.%s is imported again into %s',
|
| 199 |
+
importee_module, symbol, importer_reference)
|
| 200 |
+
else:
|
| 201 |
+
msg('Error: %s imports %s.%s again',
|
| 202 |
+
importer_reference, importee_module, symbol)
|
| 203 |
+
else:
|
| 204 |
+
##ORIGIN##
|
| 205 |
+
if options.by_origin:
|
| 206 |
+
msg('Error: %s.%s is imported by %s, which should import %s.%s instead',
|
| 207 |
+
importee_module, symbol, importer_reference, symbol_definer, symbol)
|
| 208 |
+
else:
|
| 209 |
+
msg('Error: %s imports %s.%s but should import %s.%s instead',
|
| 210 |
+
importer_reference, importee_module, symbol, symbol_definer, symbol)
|
| 211 |
+
return result
|
| 212 |
+
|
| 213 |
+
builtins.__import__ = tracking_import
|
| 214 |
+
__import__('sympy')
|
| 215 |
+
|
| 216 |
+
sorted_messages.sort()
|
| 217 |
+
for message in sorted_messages:
|
| 218 |
+
print(message)
|
evalkit_tf437/lib/python3.10/site-packages/sympy/testing/tests/test_code_quality.py
ADDED
|
@@ -0,0 +1,510 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
from os import walk, sep, pardir
|
| 3 |
+
from os.path import split, join, abspath, exists, isfile
|
| 4 |
+
from glob import glob
|
| 5 |
+
import re
|
| 6 |
+
import random
|
| 7 |
+
import ast
|
| 8 |
+
|
| 9 |
+
from sympy.testing.pytest import raises
|
| 10 |
+
from sympy.testing.quality_unicode import _test_this_file_encoding
|
| 11 |
+
|
| 12 |
+
# System path separator (usually slash or backslash) to be
|
| 13 |
+
# used with excluded files, e.g.
|
| 14 |
+
# exclude = set([
|
| 15 |
+
# "%(sep)smpmath%(sep)s" % sepd,
|
| 16 |
+
# ])
|
| 17 |
+
sepd = {"sep": sep}
|
| 18 |
+
|
| 19 |
+
# path and sympy_path
|
| 20 |
+
SYMPY_PATH = abspath(join(split(__file__)[0], pardir, pardir)) # go to sympy/
|
| 21 |
+
assert exists(SYMPY_PATH)
|
| 22 |
+
|
| 23 |
+
TOP_PATH = abspath(join(SYMPY_PATH, pardir))
|
| 24 |
+
BIN_PATH = join(TOP_PATH, "bin")
|
| 25 |
+
EXAMPLES_PATH = join(TOP_PATH, "examples")
|
| 26 |
+
|
| 27 |
+
# Error messages
|
| 28 |
+
message_space = "File contains trailing whitespace: %s, line %s."
|
| 29 |
+
message_implicit = "File contains an implicit import: %s, line %s."
|
| 30 |
+
message_tabs = "File contains tabs instead of spaces: %s, line %s."
|
| 31 |
+
message_carriage = "File contains carriage returns at end of line: %s, line %s"
|
| 32 |
+
message_str_raise = "File contains string exception: %s, line %s"
|
| 33 |
+
message_gen_raise = "File contains generic exception: %s, line %s"
|
| 34 |
+
message_old_raise = "File contains old-style raise statement: %s, line %s, \"%s\""
|
| 35 |
+
message_eof = "File does not end with a newline: %s, line %s"
|
| 36 |
+
message_multi_eof = "File ends with more than 1 newline: %s, line %s"
|
| 37 |
+
message_test_suite_def = "Function should start with 'test_' or '_': %s, line %s"
|
| 38 |
+
message_duplicate_test = "This is a duplicate test function: %s, line %s"
|
| 39 |
+
message_self_assignments = "File contains assignments to self/cls: %s, line %s."
|
| 40 |
+
message_func_is = "File contains '.func is': %s, line %s."
|
| 41 |
+
message_bare_expr = "File contains bare expression: %s, line %s."
|
| 42 |
+
|
| 43 |
+
implicit_test_re = re.compile(r'^\s*(>>> )?(\.\.\. )?from .* import .*\*')
|
| 44 |
+
str_raise_re = re.compile(
|
| 45 |
+
r'^\s*(>>> )?(\.\.\. )?raise(\s+(\'|\")|\s*(\(\s*)+(\'|\"))')
|
| 46 |
+
gen_raise_re = re.compile(
|
| 47 |
+
r'^\s*(>>> )?(\.\.\. )?raise(\s+Exception|\s*(\(\s*)+Exception)')
|
| 48 |
+
old_raise_re = re.compile(r'^\s*(>>> )?(\.\.\. )?raise((\s*\(\s*)|\s+)\w+\s*,')
|
| 49 |
+
test_suite_def_re = re.compile(r'^def\s+(?!(_|test))[^(]*\(\s*\)\s*:$')
|
| 50 |
+
test_ok_def_re = re.compile(r'^def\s+test_.*:$')
|
| 51 |
+
test_file_re = re.compile(r'.*[/\\]test_.*\.py$')
|
| 52 |
+
func_is_re = re.compile(r'\.\s*func\s+is')
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def tab_in_leading(s):
|
| 56 |
+
"""Returns True if there are tabs in the leading whitespace of a line,
|
| 57 |
+
including the whitespace of docstring code samples."""
|
| 58 |
+
n = len(s) - len(s.lstrip())
|
| 59 |
+
if not s[n:n + 3] in ['...', '>>>']:
|
| 60 |
+
check = s[:n]
|
| 61 |
+
else:
|
| 62 |
+
smore = s[n + 3:]
|
| 63 |
+
check = s[:n] + smore[:len(smore) - len(smore.lstrip())]
|
| 64 |
+
return not (check.expandtabs() == check)
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def find_self_assignments(s):
|
| 68 |
+
"""Returns a list of "bad" assignments: if there are instances
|
| 69 |
+
of assigning to the first argument of the class method (except
|
| 70 |
+
for staticmethod's).
|
| 71 |
+
"""
|
| 72 |
+
t = [n for n in ast.parse(s).body if isinstance(n, ast.ClassDef)]
|
| 73 |
+
|
| 74 |
+
bad = []
|
| 75 |
+
for c in t:
|
| 76 |
+
for n in c.body:
|
| 77 |
+
if not isinstance(n, ast.FunctionDef):
|
| 78 |
+
continue
|
| 79 |
+
if any(d.id == 'staticmethod'
|
| 80 |
+
for d in n.decorator_list if isinstance(d, ast.Name)):
|
| 81 |
+
continue
|
| 82 |
+
if n.name == '__new__':
|
| 83 |
+
continue
|
| 84 |
+
if not n.args.args:
|
| 85 |
+
continue
|
| 86 |
+
first_arg = n.args.args[0].arg
|
| 87 |
+
|
| 88 |
+
for m in ast.walk(n):
|
| 89 |
+
if isinstance(m, ast.Assign):
|
| 90 |
+
for a in m.targets:
|
| 91 |
+
if isinstance(a, ast.Name) and a.id == first_arg:
|
| 92 |
+
bad.append(m)
|
| 93 |
+
elif (isinstance(a, ast.Tuple) and
|
| 94 |
+
any(q.id == first_arg for q in a.elts
|
| 95 |
+
if isinstance(q, ast.Name))):
|
| 96 |
+
bad.append(m)
|
| 97 |
+
|
| 98 |
+
return bad
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def check_directory_tree(base_path, file_check, exclusions=set(), pattern="*.py"):
|
| 102 |
+
"""
|
| 103 |
+
Checks all files in the directory tree (with base_path as starting point)
|
| 104 |
+
with the file_check function provided, skipping files that contain
|
| 105 |
+
any of the strings in the set provided by exclusions.
|
| 106 |
+
"""
|
| 107 |
+
if not base_path:
|
| 108 |
+
return
|
| 109 |
+
for root, dirs, files in walk(base_path):
|
| 110 |
+
check_files(glob(join(root, pattern)), file_check, exclusions)
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def check_files(files, file_check, exclusions=set(), pattern=None):
|
| 114 |
+
"""
|
| 115 |
+
Checks all files with the file_check function provided, skipping files
|
| 116 |
+
that contain any of the strings in the set provided by exclusions.
|
| 117 |
+
"""
|
| 118 |
+
if not files:
|
| 119 |
+
return
|
| 120 |
+
for fname in files:
|
| 121 |
+
if not exists(fname) or not isfile(fname):
|
| 122 |
+
continue
|
| 123 |
+
if any(ex in fname for ex in exclusions):
|
| 124 |
+
continue
|
| 125 |
+
if pattern is None or re.match(pattern, fname):
|
| 126 |
+
file_check(fname)
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
class _Visit(ast.NodeVisitor):
|
| 130 |
+
"""return the line number corresponding to the
|
| 131 |
+
line on which a bare expression appears if it is a binary op
|
| 132 |
+
or a comparison that is not in a with block.
|
| 133 |
+
|
| 134 |
+
EXAMPLES
|
| 135 |
+
========
|
| 136 |
+
|
| 137 |
+
>>> import ast
|
| 138 |
+
>>> class _Visit(ast.NodeVisitor):
|
| 139 |
+
... def visit_Expr(self, node):
|
| 140 |
+
... if isinstance(node.value, (ast.BinOp, ast.Compare)):
|
| 141 |
+
... print(node.lineno)
|
| 142 |
+
... def visit_With(self, node):
|
| 143 |
+
... pass # no checking there
|
| 144 |
+
...
|
| 145 |
+
>>> code='''x = 1 # line 1
|
| 146 |
+
... for i in range(3):
|
| 147 |
+
... x == 2 # <-- 3
|
| 148 |
+
... if x == 2:
|
| 149 |
+
... x == 3 # <-- 5
|
| 150 |
+
... x + 1 # <-- 6
|
| 151 |
+
... x = 1
|
| 152 |
+
... if x == 1:
|
| 153 |
+
... print(1)
|
| 154 |
+
... while x != 1:
|
| 155 |
+
... x == 1 # <-- 11
|
| 156 |
+
... with raises(TypeError):
|
| 157 |
+
... c == 1
|
| 158 |
+
... raise TypeError
|
| 159 |
+
... assert x == 1
|
| 160 |
+
... '''
|
| 161 |
+
>>> _Visit().visit(ast.parse(code))
|
| 162 |
+
3
|
| 163 |
+
5
|
| 164 |
+
6
|
| 165 |
+
11
|
| 166 |
+
"""
|
| 167 |
+
def visit_Expr(self, node):
|
| 168 |
+
if isinstance(node.value, (ast.BinOp, ast.Compare)):
|
| 169 |
+
assert None, message_bare_expr % ('', node.lineno)
|
| 170 |
+
def visit_With(self, node):
|
| 171 |
+
pass
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
BareExpr = _Visit()
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def line_with_bare_expr(code):
|
| 178 |
+
"""return None or else 0-based line number of code on which
|
| 179 |
+
a bare expression appeared.
|
| 180 |
+
"""
|
| 181 |
+
tree = ast.parse(code)
|
| 182 |
+
try:
|
| 183 |
+
BareExpr.visit(tree)
|
| 184 |
+
except AssertionError as msg:
|
| 185 |
+
assert msg.args
|
| 186 |
+
msg = msg.args[0]
|
| 187 |
+
assert msg.startswith(message_bare_expr.split(':', 1)[0])
|
| 188 |
+
return int(msg.rsplit(' ', 1)[1].rstrip('.')) # the line number
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
def test_files():
|
| 192 |
+
"""
|
| 193 |
+
This test tests all files in SymPy and checks that:
|
| 194 |
+
o no lines contains a trailing whitespace
|
| 195 |
+
o no lines end with \r\n
|
| 196 |
+
o no line uses tabs instead of spaces
|
| 197 |
+
o that the file ends with a single newline
|
| 198 |
+
o there are no general or string exceptions
|
| 199 |
+
o there are no old style raise statements
|
| 200 |
+
o name of arg-less test suite functions start with _ or test_
|
| 201 |
+
o no duplicate function names that start with test_
|
| 202 |
+
o no assignments to self variable in class methods
|
| 203 |
+
o no lines contain ".func is" except in the test suite
|
| 204 |
+
o there is no do-nothing expression like `a == b` or `x + 1`
|
| 205 |
+
"""
|
| 206 |
+
|
| 207 |
+
def test(fname):
|
| 208 |
+
with open(fname, encoding="utf8") as test_file:
|
| 209 |
+
test_this_file(fname, test_file)
|
| 210 |
+
with open(fname, encoding='utf8') as test_file:
|
| 211 |
+
_test_this_file_encoding(fname, test_file)
|
| 212 |
+
|
| 213 |
+
def test_this_file(fname, test_file):
|
| 214 |
+
idx = None
|
| 215 |
+
code = test_file.read()
|
| 216 |
+
test_file.seek(0) # restore reader to head
|
| 217 |
+
py = fname if sep not in fname else fname.rsplit(sep, 1)[-1]
|
| 218 |
+
if py.startswith('test_'):
|
| 219 |
+
idx = line_with_bare_expr(code)
|
| 220 |
+
if idx is not None:
|
| 221 |
+
assert False, message_bare_expr % (fname, idx + 1)
|
| 222 |
+
|
| 223 |
+
line = None # to flag the case where there were no lines in file
|
| 224 |
+
tests = 0
|
| 225 |
+
test_set = set()
|
| 226 |
+
for idx, line in enumerate(test_file):
|
| 227 |
+
if test_file_re.match(fname):
|
| 228 |
+
if test_suite_def_re.match(line):
|
| 229 |
+
assert False, message_test_suite_def % (fname, idx + 1)
|
| 230 |
+
if test_ok_def_re.match(line):
|
| 231 |
+
tests += 1
|
| 232 |
+
test_set.add(line[3:].split('(')[0].strip())
|
| 233 |
+
if len(test_set) != tests:
|
| 234 |
+
assert False, message_duplicate_test % (fname, idx + 1)
|
| 235 |
+
if line.endswith((" \n", "\t\n")):
|
| 236 |
+
assert False, message_space % (fname, idx + 1)
|
| 237 |
+
if line.endswith("\r\n"):
|
| 238 |
+
assert False, message_carriage % (fname, idx + 1)
|
| 239 |
+
if tab_in_leading(line):
|
| 240 |
+
assert False, message_tabs % (fname, idx + 1)
|
| 241 |
+
if str_raise_re.search(line):
|
| 242 |
+
assert False, message_str_raise % (fname, idx + 1)
|
| 243 |
+
if gen_raise_re.search(line):
|
| 244 |
+
assert False, message_gen_raise % (fname, idx + 1)
|
| 245 |
+
if (implicit_test_re.search(line) and
|
| 246 |
+
not list(filter(lambda ex: ex in fname, import_exclude))):
|
| 247 |
+
assert False, message_implicit % (fname, idx + 1)
|
| 248 |
+
if func_is_re.search(line) and not test_file_re.search(fname):
|
| 249 |
+
assert False, message_func_is % (fname, idx + 1)
|
| 250 |
+
|
| 251 |
+
result = old_raise_re.search(line)
|
| 252 |
+
|
| 253 |
+
if result is not None:
|
| 254 |
+
assert False, message_old_raise % (
|
| 255 |
+
fname, idx + 1, result.group(2))
|
| 256 |
+
|
| 257 |
+
if line is not None:
|
| 258 |
+
if line == '\n' and idx > 0:
|
| 259 |
+
assert False, message_multi_eof % (fname, idx + 1)
|
| 260 |
+
elif not line.endswith('\n'):
|
| 261 |
+
# eof newline check
|
| 262 |
+
assert False, message_eof % (fname, idx + 1)
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
# Files to test at top level
|
| 266 |
+
top_level_files = [join(TOP_PATH, file) for file in [
|
| 267 |
+
"isympy.py",
|
| 268 |
+
"build.py",
|
| 269 |
+
"setup.py",
|
| 270 |
+
]]
|
| 271 |
+
# Files to exclude from all tests
|
| 272 |
+
exclude = {
|
| 273 |
+
"%(sep)ssympy%(sep)sparsing%(sep)sautolev%(sep)s_antlr%(sep)sautolevparser.py" % sepd,
|
| 274 |
+
"%(sep)ssympy%(sep)sparsing%(sep)sautolev%(sep)s_antlr%(sep)sautolevlexer.py" % sepd,
|
| 275 |
+
"%(sep)ssympy%(sep)sparsing%(sep)sautolev%(sep)s_antlr%(sep)sautolevlistener.py" % sepd,
|
| 276 |
+
"%(sep)ssympy%(sep)sparsing%(sep)slatex%(sep)s_antlr%(sep)slatexparser.py" % sepd,
|
| 277 |
+
"%(sep)ssympy%(sep)sparsing%(sep)slatex%(sep)s_antlr%(sep)slatexlexer.py" % sepd,
|
| 278 |
+
}
|
| 279 |
+
# Files to exclude from the implicit import test
|
| 280 |
+
import_exclude = {
|
| 281 |
+
# glob imports are allowed in top-level __init__.py:
|
| 282 |
+
"%(sep)ssympy%(sep)s__init__.py" % sepd,
|
| 283 |
+
# these __init__.py should be fixed:
|
| 284 |
+
# XXX: not really, they use useful import pattern (DRY)
|
| 285 |
+
"%(sep)svector%(sep)s__init__.py" % sepd,
|
| 286 |
+
"%(sep)smechanics%(sep)s__init__.py" % sepd,
|
| 287 |
+
"%(sep)squantum%(sep)s__init__.py" % sepd,
|
| 288 |
+
"%(sep)spolys%(sep)s__init__.py" % sepd,
|
| 289 |
+
"%(sep)spolys%(sep)sdomains%(sep)s__init__.py" % sepd,
|
| 290 |
+
# interactive SymPy executes ``from sympy import *``:
|
| 291 |
+
"%(sep)sinteractive%(sep)ssession.py" % sepd,
|
| 292 |
+
# isympy.py executes ``from sympy import *``:
|
| 293 |
+
"%(sep)sisympy.py" % sepd,
|
| 294 |
+
# these two are import timing tests:
|
| 295 |
+
"%(sep)sbin%(sep)ssympy_time.py" % sepd,
|
| 296 |
+
"%(sep)sbin%(sep)ssympy_time_cache.py" % sepd,
|
| 297 |
+
# Taken from Python stdlib:
|
| 298 |
+
"%(sep)sparsing%(sep)ssympy_tokenize.py" % sepd,
|
| 299 |
+
# this one should be fixed:
|
| 300 |
+
"%(sep)splotting%(sep)spygletplot%(sep)s" % sepd,
|
| 301 |
+
# False positive in the docstring
|
| 302 |
+
"%(sep)sbin%(sep)stest_external_imports.py" % sepd,
|
| 303 |
+
"%(sep)sbin%(sep)stest_submodule_imports.py" % sepd,
|
| 304 |
+
# These are deprecated stubs that can be removed at some point:
|
| 305 |
+
"%(sep)sutilities%(sep)sruntests.py" % sepd,
|
| 306 |
+
"%(sep)sutilities%(sep)spytest.py" % sepd,
|
| 307 |
+
"%(sep)sutilities%(sep)srandtest.py" % sepd,
|
| 308 |
+
"%(sep)sutilities%(sep)stmpfiles.py" % sepd,
|
| 309 |
+
"%(sep)sutilities%(sep)squality_unicode.py" % sepd,
|
| 310 |
+
}
|
| 311 |
+
check_files(top_level_files, test)
|
| 312 |
+
check_directory_tree(BIN_PATH, test, {"~", ".pyc", ".sh", ".mjs"}, "*")
|
| 313 |
+
check_directory_tree(SYMPY_PATH, test, exclude)
|
| 314 |
+
check_directory_tree(EXAMPLES_PATH, test, exclude)
|
| 315 |
+
|
| 316 |
+
|
| 317 |
+
def _with_space(c):
|
| 318 |
+
# return c with a random amount of leading space
|
| 319 |
+
return random.randint(0, 10)*' ' + c
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
def test_raise_statement_regular_expression():
|
| 323 |
+
candidates_ok = [
|
| 324 |
+
"some text # raise Exception, 'text'",
|
| 325 |
+
"raise ValueError('text') # raise Exception, 'text'",
|
| 326 |
+
"raise ValueError('text')",
|
| 327 |
+
"raise ValueError",
|
| 328 |
+
"raise ValueError('text')",
|
| 329 |
+
"raise ValueError('text') #,",
|
| 330 |
+
# Talking about an exception in a docstring
|
| 331 |
+
''''"""This function will raise ValueError, except when it doesn't"""''',
|
| 332 |
+
"raise (ValueError('text')",
|
| 333 |
+
]
|
| 334 |
+
str_candidates_fail = [
|
| 335 |
+
"raise 'exception'",
|
| 336 |
+
"raise 'Exception'",
|
| 337 |
+
'raise "exception"',
|
| 338 |
+
'raise "Exception"',
|
| 339 |
+
"raise 'ValueError'",
|
| 340 |
+
]
|
| 341 |
+
gen_candidates_fail = [
|
| 342 |
+
"raise Exception('text') # raise Exception, 'text'",
|
| 343 |
+
"raise Exception('text')",
|
| 344 |
+
"raise Exception",
|
| 345 |
+
"raise Exception('text')",
|
| 346 |
+
"raise Exception('text') #,",
|
| 347 |
+
"raise Exception, 'text'",
|
| 348 |
+
"raise Exception, 'text' # raise Exception('text')",
|
| 349 |
+
"raise Exception, 'text' # raise Exception, 'text'",
|
| 350 |
+
">>> raise Exception, 'text'",
|
| 351 |
+
">>> raise Exception, 'text' # raise Exception('text')",
|
| 352 |
+
">>> raise Exception, 'text' # raise Exception, 'text'",
|
| 353 |
+
]
|
| 354 |
+
old_candidates_fail = [
|
| 355 |
+
"raise Exception, 'text'",
|
| 356 |
+
"raise Exception, 'text' # raise Exception('text')",
|
| 357 |
+
"raise Exception, 'text' # raise Exception, 'text'",
|
| 358 |
+
">>> raise Exception, 'text'",
|
| 359 |
+
">>> raise Exception, 'text' # raise Exception('text')",
|
| 360 |
+
">>> raise Exception, 'text' # raise Exception, 'text'",
|
| 361 |
+
"raise ValueError, 'text'",
|
| 362 |
+
"raise ValueError, 'text' # raise Exception('text')",
|
| 363 |
+
"raise ValueError, 'text' # raise Exception, 'text'",
|
| 364 |
+
">>> raise ValueError, 'text'",
|
| 365 |
+
">>> raise ValueError, 'text' # raise Exception('text')",
|
| 366 |
+
">>> raise ValueError, 'text' # raise Exception, 'text'",
|
| 367 |
+
"raise(ValueError,",
|
| 368 |
+
"raise (ValueError,",
|
| 369 |
+
"raise( ValueError,",
|
| 370 |
+
"raise ( ValueError,",
|
| 371 |
+
"raise(ValueError ,",
|
| 372 |
+
"raise (ValueError ,",
|
| 373 |
+
"raise( ValueError ,",
|
| 374 |
+
"raise ( ValueError ,",
|
| 375 |
+
]
|
| 376 |
+
|
| 377 |
+
for c in candidates_ok:
|
| 378 |
+
assert str_raise_re.search(_with_space(c)) is None, c
|
| 379 |
+
assert gen_raise_re.search(_with_space(c)) is None, c
|
| 380 |
+
assert old_raise_re.search(_with_space(c)) is None, c
|
| 381 |
+
for c in str_candidates_fail:
|
| 382 |
+
assert str_raise_re.search(_with_space(c)) is not None, c
|
| 383 |
+
for c in gen_candidates_fail:
|
| 384 |
+
assert gen_raise_re.search(_with_space(c)) is not None, c
|
| 385 |
+
for c in old_candidates_fail:
|
| 386 |
+
assert old_raise_re.search(_with_space(c)) is not None, c
|
| 387 |
+
|
| 388 |
+
|
| 389 |
+
def test_implicit_imports_regular_expression():
|
| 390 |
+
candidates_ok = [
|
| 391 |
+
"from sympy import something",
|
| 392 |
+
">>> from sympy import something",
|
| 393 |
+
"from sympy.somewhere import something",
|
| 394 |
+
">>> from sympy.somewhere import something",
|
| 395 |
+
"import sympy",
|
| 396 |
+
">>> import sympy",
|
| 397 |
+
"import sympy.something.something",
|
| 398 |
+
"... import sympy",
|
| 399 |
+
"... import sympy.something.something",
|
| 400 |
+
"... from sympy import something",
|
| 401 |
+
"... from sympy.somewhere import something",
|
| 402 |
+
">> from sympy import *", # To allow 'fake' docstrings
|
| 403 |
+
"# from sympy import *",
|
| 404 |
+
"some text # from sympy import *",
|
| 405 |
+
]
|
| 406 |
+
candidates_fail = [
|
| 407 |
+
"from sympy import *",
|
| 408 |
+
">>> from sympy import *",
|
| 409 |
+
"from sympy.somewhere import *",
|
| 410 |
+
">>> from sympy.somewhere import *",
|
| 411 |
+
"... from sympy import *",
|
| 412 |
+
"... from sympy.somewhere import *",
|
| 413 |
+
]
|
| 414 |
+
for c in candidates_ok:
|
| 415 |
+
assert implicit_test_re.search(_with_space(c)) is None, c
|
| 416 |
+
for c in candidates_fail:
|
| 417 |
+
assert implicit_test_re.search(_with_space(c)) is not None, c
|
| 418 |
+
|
| 419 |
+
|
| 420 |
+
def test_test_suite_defs():
|
| 421 |
+
candidates_ok = [
|
| 422 |
+
" def foo():\n",
|
| 423 |
+
"def foo(arg):\n",
|
| 424 |
+
"def _foo():\n",
|
| 425 |
+
"def test_foo():\n",
|
| 426 |
+
]
|
| 427 |
+
candidates_fail = [
|
| 428 |
+
"def foo():\n",
|
| 429 |
+
"def foo() :\n",
|
| 430 |
+
"def foo( ):\n",
|
| 431 |
+
"def foo():\n",
|
| 432 |
+
]
|
| 433 |
+
for c in candidates_ok:
|
| 434 |
+
assert test_suite_def_re.search(c) is None, c
|
| 435 |
+
for c in candidates_fail:
|
| 436 |
+
assert test_suite_def_re.search(c) is not None, c
|
| 437 |
+
|
| 438 |
+
|
| 439 |
+
def test_test_duplicate_defs():
|
| 440 |
+
candidates_ok = [
|
| 441 |
+
"def foo():\ndef foo():\n",
|
| 442 |
+
"def test():\ndef test_():\n",
|
| 443 |
+
"def test_():\ndef test__():\n",
|
| 444 |
+
]
|
| 445 |
+
candidates_fail = [
|
| 446 |
+
"def test_():\ndef test_ ():\n",
|
| 447 |
+
"def test_1():\ndef test_1():\n",
|
| 448 |
+
]
|
| 449 |
+
ok = (None, 'check')
|
| 450 |
+
def check(file):
|
| 451 |
+
tests = 0
|
| 452 |
+
test_set = set()
|
| 453 |
+
for idx, line in enumerate(file.splitlines()):
|
| 454 |
+
if test_ok_def_re.match(line):
|
| 455 |
+
tests += 1
|
| 456 |
+
test_set.add(line[3:].split('(')[0].strip())
|
| 457 |
+
if len(test_set) != tests:
|
| 458 |
+
return False, message_duplicate_test % ('check', idx + 1)
|
| 459 |
+
return None, 'check'
|
| 460 |
+
for c in candidates_ok:
|
| 461 |
+
assert check(c) == ok
|
| 462 |
+
for c in candidates_fail:
|
| 463 |
+
assert check(c) != ok
|
| 464 |
+
|
| 465 |
+
|
| 466 |
+
def test_find_self_assignments():
|
| 467 |
+
candidates_ok = [
|
| 468 |
+
"class A(object):\n def foo(self, arg): arg = self\n",
|
| 469 |
+
"class A(object):\n def foo(self, arg): self.prop = arg\n",
|
| 470 |
+
"class A(object):\n def foo(self, arg): obj, obj2 = arg, self\n",
|
| 471 |
+
"class A(object):\n @classmethod\n def bar(cls, arg): arg = cls\n",
|
| 472 |
+
"class A(object):\n def foo(var, arg): arg = var\n",
|
| 473 |
+
]
|
| 474 |
+
candidates_fail = [
|
| 475 |
+
"class A(object):\n def foo(self, arg): self = arg\n",
|
| 476 |
+
"class A(object):\n def foo(self, arg): obj, self = arg, arg\n",
|
| 477 |
+
"class A(object):\n def foo(self, arg):\n if arg: self = arg",
|
| 478 |
+
"class A(object):\n @classmethod\n def foo(cls, arg): cls = arg\n",
|
| 479 |
+
"class A(object):\n def foo(var, arg): var = arg\n",
|
| 480 |
+
]
|
| 481 |
+
|
| 482 |
+
for c in candidates_ok:
|
| 483 |
+
assert find_self_assignments(c) == []
|
| 484 |
+
for c in candidates_fail:
|
| 485 |
+
assert find_self_assignments(c) != []
|
| 486 |
+
|
| 487 |
+
|
| 488 |
+
def test_test_unicode_encoding():
|
| 489 |
+
unicode_whitelist = ['foo']
|
| 490 |
+
unicode_strict_whitelist = ['bar']
|
| 491 |
+
|
| 492 |
+
fname = 'abc'
|
| 493 |
+
test_file = ['α']
|
| 494 |
+
raises(AssertionError, lambda: _test_this_file_encoding(
|
| 495 |
+
fname, test_file, unicode_whitelist, unicode_strict_whitelist))
|
| 496 |
+
|
| 497 |
+
fname = 'abc'
|
| 498 |
+
test_file = ['abc']
|
| 499 |
+
_test_this_file_encoding(
|
| 500 |
+
fname, test_file, unicode_whitelist, unicode_strict_whitelist)
|
| 501 |
+
|
| 502 |
+
fname = 'foo'
|
| 503 |
+
test_file = ['abc']
|
| 504 |
+
raises(AssertionError, lambda: _test_this_file_encoding(
|
| 505 |
+
fname, test_file, unicode_whitelist, unicode_strict_whitelist))
|
| 506 |
+
|
| 507 |
+
fname = 'bar'
|
| 508 |
+
test_file = ['abc']
|
| 509 |
+
_test_this_file_encoding(
|
| 510 |
+
fname, test_file, unicode_whitelist, unicode_strict_whitelist)
|
evalkit_tf437/lib/python3.10/site-packages/sympy/testing/tests/test_deprecated.py
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.testing.pytest import warns_deprecated_sympy
|
| 2 |
+
|
| 3 |
+
def test_deprecated_testing_randtest():
|
| 4 |
+
with warns_deprecated_sympy():
|
| 5 |
+
import sympy.testing.randtest # noqa:F401
|
evalkit_tf437/lib/python3.10/site-packages/sympy/testing/tests/test_module_imports.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Checks that SymPy does not contain indirect imports.
|
| 3 |
+
|
| 4 |
+
An indirect import is importing a symbol from a module that itself imported the
|
| 5 |
+
symbol from elsewhere. Such a constellation makes it harder to diagnose
|
| 6 |
+
inter-module dependencies and import order problems, and is therefore strongly
|
| 7 |
+
discouraged.
|
| 8 |
+
|
| 9 |
+
(Indirect imports from end-user code is fine and in fact a best practice.)
|
| 10 |
+
|
| 11 |
+
Implementation note: Forcing Python into actually unloading already-imported
|
| 12 |
+
submodules is a tricky and partly undocumented process. To avoid these issues,
|
| 13 |
+
the actual diagnostic code is in bin/diagnose_imports, which is run as a
|
| 14 |
+
separate, pristine Python process.
|
| 15 |
+
"""
|
| 16 |
+
|
| 17 |
+
import subprocess
|
| 18 |
+
import sys
|
| 19 |
+
from os.path import abspath, dirname, join, normpath
|
| 20 |
+
import inspect
|
| 21 |
+
|
| 22 |
+
from sympy.testing.pytest import XFAIL
|
| 23 |
+
|
| 24 |
+
@XFAIL
|
| 25 |
+
def test_module_imports_are_direct():
|
| 26 |
+
my_filename = abspath(inspect.getfile(inspect.currentframe()))
|
| 27 |
+
my_dirname = dirname(my_filename)
|
| 28 |
+
diagnose_imports_filename = join(my_dirname, 'diagnose_imports.py')
|
| 29 |
+
diagnose_imports_filename = normpath(diagnose_imports_filename)
|
| 30 |
+
|
| 31 |
+
process = subprocess.Popen(
|
| 32 |
+
[
|
| 33 |
+
sys.executable,
|
| 34 |
+
normpath(diagnose_imports_filename),
|
| 35 |
+
'--problems',
|
| 36 |
+
'--by-importer'
|
| 37 |
+
],
|
| 38 |
+
stdout=subprocess.PIPE,
|
| 39 |
+
stderr=subprocess.STDOUT,
|
| 40 |
+
bufsize=-1)
|
| 41 |
+
output, _ = process.communicate()
|
| 42 |
+
assert output == '', "There are import problems:\n" + output.decode()
|
evalkit_tf437/lib/python3.10/site-packages/sympy/testing/tests/test_pytest.py
ADDED
|
@@ -0,0 +1,211 @@
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import warnings
|
| 2 |
+
|
| 3 |
+
from sympy.testing.pytest import (raises, warns, ignore_warnings,
|
| 4 |
+
warns_deprecated_sympy, Failed)
|
| 5 |
+
from sympy.utilities.exceptions import sympy_deprecation_warning
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
# Test callables
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def test_expected_exception_is_silent_callable():
|
| 13 |
+
def f():
|
| 14 |
+
raise ValueError()
|
| 15 |
+
raises(ValueError, f)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
# Under pytest raises will raise Failed rather than AssertionError
|
| 19 |
+
def test_lack_of_exception_triggers_AssertionError_callable():
|
| 20 |
+
try:
|
| 21 |
+
raises(Exception, lambda: 1 + 1)
|
| 22 |
+
assert False
|
| 23 |
+
except Failed as e:
|
| 24 |
+
assert "DID NOT RAISE" in str(e)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def test_unexpected_exception_is_passed_through_callable():
|
| 28 |
+
def f():
|
| 29 |
+
raise ValueError("some error message")
|
| 30 |
+
try:
|
| 31 |
+
raises(TypeError, f)
|
| 32 |
+
assert False
|
| 33 |
+
except ValueError as e:
|
| 34 |
+
assert str(e) == "some error message"
|
| 35 |
+
|
| 36 |
+
# Test with statement
|
| 37 |
+
|
| 38 |
+
def test_expected_exception_is_silent_with():
|
| 39 |
+
with raises(ValueError):
|
| 40 |
+
raise ValueError()
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def test_lack_of_exception_triggers_AssertionError_with():
|
| 44 |
+
try:
|
| 45 |
+
with raises(Exception):
|
| 46 |
+
1 + 1
|
| 47 |
+
assert False
|
| 48 |
+
except Failed as e:
|
| 49 |
+
assert "DID NOT RAISE" in str(e)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def test_unexpected_exception_is_passed_through_with():
|
| 53 |
+
try:
|
| 54 |
+
with raises(TypeError):
|
| 55 |
+
raise ValueError("some error message")
|
| 56 |
+
assert False
|
| 57 |
+
except ValueError as e:
|
| 58 |
+
assert str(e) == "some error message"
|
| 59 |
+
|
| 60 |
+
# Now we can use raises() instead of try/catch
|
| 61 |
+
# to test that a specific exception class is raised
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def test_second_argument_should_be_callable_or_string():
|
| 65 |
+
raises(TypeError, lambda: raises("irrelevant", 42))
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def test_warns_catches_warning():
|
| 69 |
+
with warnings.catch_warnings(record=True) as w:
|
| 70 |
+
with warns(UserWarning):
|
| 71 |
+
warnings.warn('this is the warning message')
|
| 72 |
+
assert len(w) == 0
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def test_warns_raises_without_warning():
|
| 76 |
+
with raises(Failed):
|
| 77 |
+
with warns(UserWarning):
|
| 78 |
+
pass
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def test_warns_hides_other_warnings():
|
| 82 |
+
with raises(RuntimeWarning):
|
| 83 |
+
with warns(UserWarning):
|
| 84 |
+
warnings.warn('this is the warning message', UserWarning)
|
| 85 |
+
warnings.warn('this is the other message', RuntimeWarning)
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def test_warns_continues_after_warning():
|
| 89 |
+
with warnings.catch_warnings(record=True) as w:
|
| 90 |
+
finished = False
|
| 91 |
+
with warns(UserWarning):
|
| 92 |
+
warnings.warn('this is the warning message')
|
| 93 |
+
finished = True
|
| 94 |
+
assert finished
|
| 95 |
+
assert len(w) == 0
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def test_warns_many_warnings():
|
| 99 |
+
with warns(UserWarning):
|
| 100 |
+
warnings.warn('this is the warning message', UserWarning)
|
| 101 |
+
warnings.warn('this is the other warning message', UserWarning)
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def test_warns_match_matching():
|
| 105 |
+
with warnings.catch_warnings(record=True) as w:
|
| 106 |
+
with warns(UserWarning, match='this is the warning message'):
|
| 107 |
+
warnings.warn('this is the warning message', UserWarning)
|
| 108 |
+
assert len(w) == 0
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def test_warns_match_non_matching():
|
| 112 |
+
with warnings.catch_warnings(record=True) as w:
|
| 113 |
+
with raises(Failed):
|
| 114 |
+
with warns(UserWarning, match='this is the warning message'):
|
| 115 |
+
warnings.warn('this is not the expected warning message', UserWarning)
|
| 116 |
+
assert len(w) == 0
|
| 117 |
+
|
| 118 |
+
def _warn_sympy_deprecation(stacklevel=3):
|
| 119 |
+
sympy_deprecation_warning(
|
| 120 |
+
"feature",
|
| 121 |
+
active_deprecations_target="active-deprecations",
|
| 122 |
+
deprecated_since_version="0.0.0",
|
| 123 |
+
stacklevel=stacklevel,
|
| 124 |
+
)
|
| 125 |
+
|
| 126 |
+
def test_warns_deprecated_sympy_catches_warning():
|
| 127 |
+
with warnings.catch_warnings(record=True) as w:
|
| 128 |
+
with warns_deprecated_sympy():
|
| 129 |
+
_warn_sympy_deprecation()
|
| 130 |
+
assert len(w) == 0
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def test_warns_deprecated_sympy_raises_without_warning():
|
| 134 |
+
with raises(Failed):
|
| 135 |
+
with warns_deprecated_sympy():
|
| 136 |
+
pass
|
| 137 |
+
|
| 138 |
+
def test_warns_deprecated_sympy_wrong_stacklevel():
|
| 139 |
+
with raises(Failed):
|
| 140 |
+
with warns_deprecated_sympy():
|
| 141 |
+
_warn_sympy_deprecation(stacklevel=1)
|
| 142 |
+
|
| 143 |
+
def test_warns_deprecated_sympy_doesnt_hide_other_warnings():
|
| 144 |
+
# Unlike pytest's deprecated_call, we should not hide other warnings.
|
| 145 |
+
with raises(RuntimeWarning):
|
| 146 |
+
with warns_deprecated_sympy():
|
| 147 |
+
_warn_sympy_deprecation()
|
| 148 |
+
warnings.warn('this is the other message', RuntimeWarning)
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def test_warns_deprecated_sympy_continues_after_warning():
|
| 152 |
+
with warnings.catch_warnings(record=True) as w:
|
| 153 |
+
finished = False
|
| 154 |
+
with warns_deprecated_sympy():
|
| 155 |
+
_warn_sympy_deprecation()
|
| 156 |
+
finished = True
|
| 157 |
+
assert finished
|
| 158 |
+
assert len(w) == 0
|
| 159 |
+
|
| 160 |
+
def test_ignore_ignores_warning():
|
| 161 |
+
with warnings.catch_warnings(record=True) as w:
|
| 162 |
+
with ignore_warnings(UserWarning):
|
| 163 |
+
warnings.warn('this is the warning message')
|
| 164 |
+
assert len(w) == 0
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
def test_ignore_does_not_raise_without_warning():
|
| 168 |
+
with warnings.catch_warnings(record=True) as w:
|
| 169 |
+
with ignore_warnings(UserWarning):
|
| 170 |
+
pass
|
| 171 |
+
assert len(w) == 0
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
def test_ignore_allows_other_warnings():
|
| 175 |
+
with warnings.catch_warnings(record=True) as w:
|
| 176 |
+
# This is needed when pytest is run as -Werror
|
| 177 |
+
# the setting is reverted at the end of the catch_Warnings block.
|
| 178 |
+
warnings.simplefilter("always")
|
| 179 |
+
with ignore_warnings(UserWarning):
|
| 180 |
+
warnings.warn('this is the warning message', UserWarning)
|
| 181 |
+
warnings.warn('this is the other message', RuntimeWarning)
|
| 182 |
+
assert len(w) == 1
|
| 183 |
+
assert isinstance(w[0].message, RuntimeWarning)
|
| 184 |
+
assert str(w[0].message) == 'this is the other message'
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
def test_ignore_continues_after_warning():
|
| 188 |
+
with warnings.catch_warnings(record=True) as w:
|
| 189 |
+
finished = False
|
| 190 |
+
with ignore_warnings(UserWarning):
|
| 191 |
+
warnings.warn('this is the warning message')
|
| 192 |
+
finished = True
|
| 193 |
+
assert finished
|
| 194 |
+
assert len(w) == 0
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
def test_ignore_many_warnings():
|
| 198 |
+
with warnings.catch_warnings(record=True) as w:
|
| 199 |
+
# This is needed when pytest is run as -Werror
|
| 200 |
+
# the setting is reverted at the end of the catch_Warnings block.
|
| 201 |
+
warnings.simplefilter("always")
|
| 202 |
+
with ignore_warnings(UserWarning):
|
| 203 |
+
warnings.warn('this is the warning message', UserWarning)
|
| 204 |
+
warnings.warn('this is the other message', RuntimeWarning)
|
| 205 |
+
warnings.warn('this is the warning message', UserWarning)
|
| 206 |
+
warnings.warn('this is the other message', RuntimeWarning)
|
| 207 |
+
warnings.warn('this is the other message', RuntimeWarning)
|
| 208 |
+
assert len(w) == 3
|
| 209 |
+
for wi in w:
|
| 210 |
+
assert isinstance(wi.message, RuntimeWarning)
|
| 211 |
+
assert str(wi.message) == 'this is the other message'
|
evalkit_tf437/lib/python3.10/site-packages/sympy/testing/tests/test_runtests_pytest.py
ADDED
|
@@ -0,0 +1,178 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pathlib
|
| 2 |
+
from typing import List
|
| 3 |
+
|
| 4 |
+
import pytest
|
| 5 |
+
|
| 6 |
+
from sympy.testing.runtests_pytest import (
|
| 7 |
+
make_absolute_path,
|
| 8 |
+
sympy_dir,
|
| 9 |
+
update_args_with_paths,
|
| 10 |
+
update_args_with_rootdir,
|
| 11 |
+
)
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def test_update_args_with_rootdir():
|
| 15 |
+
"""`--rootdir` and directory three above this added as arguments."""
|
| 16 |
+
args = update_args_with_rootdir([])
|
| 17 |
+
assert args == ['--rootdir', str(pathlib.Path(__file__).parents[3])]
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class TestMakeAbsolutePath:
|
| 21 |
+
|
| 22 |
+
@staticmethod
|
| 23 |
+
@pytest.mark.parametrize(
|
| 24 |
+
'partial_path', ['sympy', 'sympy/core', 'sympy/nonexistant_directory'],
|
| 25 |
+
)
|
| 26 |
+
def test_valid_partial_path(partial_path: str):
|
| 27 |
+
"""Paths that start with `sympy` are valid."""
|
| 28 |
+
_ = make_absolute_path(partial_path)
|
| 29 |
+
|
| 30 |
+
@staticmethod
|
| 31 |
+
@pytest.mark.parametrize(
|
| 32 |
+
'partial_path', ['not_sympy', 'also/not/sympy'],
|
| 33 |
+
)
|
| 34 |
+
def test_invalid_partial_path_raises_value_error(partial_path: str):
|
| 35 |
+
"""A `ValueError` is raises on paths that don't start with `sympy`."""
|
| 36 |
+
with pytest.raises(ValueError):
|
| 37 |
+
_ = make_absolute_path(partial_path)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
class TestUpdateArgsWithPaths:
|
| 41 |
+
|
| 42 |
+
@staticmethod
|
| 43 |
+
def test_no_paths():
|
| 44 |
+
"""If no paths are passed, only `sympy` and `doc/src` are appended.
|
| 45 |
+
|
| 46 |
+
`sympy` and `doc/src` are the `testpaths` stated in `pytest.ini`. They
|
| 47 |
+
need to be manually added as if any path-related arguments are passed
|
| 48 |
+
to `pytest.main` then the settings in `pytest.ini` may be ignored.
|
| 49 |
+
|
| 50 |
+
"""
|
| 51 |
+
paths = []
|
| 52 |
+
args = update_args_with_paths(paths=paths, keywords=None, args=[])
|
| 53 |
+
expected = [
|
| 54 |
+
str(pathlib.Path(sympy_dir(), 'sympy')),
|
| 55 |
+
str(pathlib.Path(sympy_dir(), 'doc/src')),
|
| 56 |
+
]
|
| 57 |
+
assert args == expected
|
| 58 |
+
|
| 59 |
+
@staticmethod
|
| 60 |
+
@pytest.mark.parametrize(
|
| 61 |
+
'path',
|
| 62 |
+
['sympy/core/tests/test_basic.py', '_basic']
|
| 63 |
+
)
|
| 64 |
+
def test_one_file(path: str):
|
| 65 |
+
"""Single files/paths, full or partial, are matched correctly."""
|
| 66 |
+
args = update_args_with_paths(paths=[path], keywords=None, args=[])
|
| 67 |
+
expected = [
|
| 68 |
+
str(pathlib.Path(sympy_dir(), 'sympy/core/tests/test_basic.py')),
|
| 69 |
+
]
|
| 70 |
+
assert args == expected
|
| 71 |
+
|
| 72 |
+
@staticmethod
|
| 73 |
+
def test_partial_path_from_root():
|
| 74 |
+
"""Partial paths from the root directly are matched correctly."""
|
| 75 |
+
args = update_args_with_paths(paths=['sympy/functions'], keywords=None, args=[])
|
| 76 |
+
expected = [str(pathlib.Path(sympy_dir(), 'sympy/functions'))]
|
| 77 |
+
assert args == expected
|
| 78 |
+
|
| 79 |
+
@staticmethod
|
| 80 |
+
def test_multiple_paths_from_root():
|
| 81 |
+
"""Multiple paths, partial or full, are matched correctly."""
|
| 82 |
+
paths = ['sympy/core/tests/test_basic.py', 'sympy/functions']
|
| 83 |
+
args = update_args_with_paths(paths=paths, keywords=None, args=[])
|
| 84 |
+
expected = [
|
| 85 |
+
str(pathlib.Path(sympy_dir(), 'sympy/core/tests/test_basic.py')),
|
| 86 |
+
str(pathlib.Path(sympy_dir(), 'sympy/functions')),
|
| 87 |
+
]
|
| 88 |
+
assert args == expected
|
| 89 |
+
|
| 90 |
+
@staticmethod
|
| 91 |
+
@pytest.mark.parametrize(
|
| 92 |
+
'paths, expected_paths',
|
| 93 |
+
[
|
| 94 |
+
(
|
| 95 |
+
['/core', '/util'],
|
| 96 |
+
[
|
| 97 |
+
'doc/src/modules/utilities',
|
| 98 |
+
'doc/src/reference/public/utilities',
|
| 99 |
+
'sympy/core',
|
| 100 |
+
'sympy/logic/utilities',
|
| 101 |
+
'sympy/utilities',
|
| 102 |
+
]
|
| 103 |
+
),
|
| 104 |
+
]
|
| 105 |
+
)
|
| 106 |
+
def test_multiple_paths_from_non_root(paths: List[str], expected_paths: List[str]):
|
| 107 |
+
"""Multiple partial paths are matched correctly."""
|
| 108 |
+
args = update_args_with_paths(paths=paths, keywords=None, args=[])
|
| 109 |
+
assert len(args) == len(expected_paths)
|
| 110 |
+
for arg, expected in zip(sorted(args), expected_paths):
|
| 111 |
+
assert expected in arg
|
| 112 |
+
|
| 113 |
+
@staticmethod
|
| 114 |
+
@pytest.mark.parametrize(
|
| 115 |
+
'paths',
|
| 116 |
+
[
|
| 117 |
+
|
| 118 |
+
[],
|
| 119 |
+
['sympy/physics'],
|
| 120 |
+
['sympy/physics/mechanics'],
|
| 121 |
+
['sympy/physics/mechanics/tests'],
|
| 122 |
+
['sympy/physics/mechanics/tests/test_kane3.py'],
|
| 123 |
+
]
|
| 124 |
+
)
|
| 125 |
+
def test_string_as_keyword(paths: List[str]):
|
| 126 |
+
"""String keywords are matched correctly."""
|
| 127 |
+
keywords = ('bicycle', )
|
| 128 |
+
args = update_args_with_paths(paths=paths, keywords=keywords, args=[])
|
| 129 |
+
expected_args = ['sympy/physics/mechanics/tests/test_kane3.py::test_bicycle']
|
| 130 |
+
assert len(args) == len(expected_args)
|
| 131 |
+
for arg, expected in zip(sorted(args), expected_args):
|
| 132 |
+
assert expected in arg
|
| 133 |
+
|
| 134 |
+
@staticmethod
|
| 135 |
+
@pytest.mark.parametrize(
|
| 136 |
+
'paths',
|
| 137 |
+
[
|
| 138 |
+
|
| 139 |
+
[],
|
| 140 |
+
['sympy/core'],
|
| 141 |
+
['sympy/core/tests'],
|
| 142 |
+
['sympy/core/tests/test_sympify.py'],
|
| 143 |
+
]
|
| 144 |
+
)
|
| 145 |
+
def test_integer_as_keyword(paths: List[str]):
|
| 146 |
+
"""Integer keywords are matched correctly."""
|
| 147 |
+
keywords = ('3538', )
|
| 148 |
+
args = update_args_with_paths(paths=paths, keywords=keywords, args=[])
|
| 149 |
+
expected_args = ['sympy/core/tests/test_sympify.py::test_issue_3538']
|
| 150 |
+
assert len(args) == len(expected_args)
|
| 151 |
+
for arg, expected in zip(sorted(args), expected_args):
|
| 152 |
+
assert expected in arg
|
| 153 |
+
|
| 154 |
+
@staticmethod
|
| 155 |
+
def test_multiple_keywords():
|
| 156 |
+
"""Multiple keywords are matched correctly."""
|
| 157 |
+
keywords = ('bicycle', '3538')
|
| 158 |
+
args = update_args_with_paths(paths=[], keywords=keywords, args=[])
|
| 159 |
+
expected_args = [
|
| 160 |
+
'sympy/core/tests/test_sympify.py::test_issue_3538',
|
| 161 |
+
'sympy/physics/mechanics/tests/test_kane3.py::test_bicycle',
|
| 162 |
+
]
|
| 163 |
+
assert len(args) == len(expected_args)
|
| 164 |
+
for arg, expected in zip(sorted(args), expected_args):
|
| 165 |
+
assert expected in arg
|
| 166 |
+
|
| 167 |
+
@staticmethod
|
| 168 |
+
def test_keyword_match_in_multiple_files():
|
| 169 |
+
"""Keywords are matched across multiple files."""
|
| 170 |
+
keywords = ('1130', )
|
| 171 |
+
args = update_args_with_paths(paths=[], keywords=keywords, args=[])
|
| 172 |
+
expected_args = [
|
| 173 |
+
'sympy/integrals/tests/test_heurisch.py::test_heurisch_symbolic_coeffs_1130',
|
| 174 |
+
'sympy/utilities/tests/test_lambdify.py::test_python_div_zero_issue_11306',
|
| 175 |
+
]
|
| 176 |
+
assert len(args) == len(expected_args)
|
| 177 |
+
for arg, expected in zip(sorted(args), expected_args):
|
| 178 |
+
assert expected in arg
|