applied-ai-018 commited on
Commit
d6e9cbc
·
verified ·
1 Parent(s): 0c03f3b

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. llmeval-env/lib/python3.10/site-packages/sympy/functions/__init__.py +111 -0
  2. llmeval-env/lib/python3.10/site-packages/sympy/functions/elementary/__init__.py +1 -0
  3. llmeval-env/lib/python3.10/site-packages/sympy/functions/elementary/__pycache__/__init__.cpython-310.pyc +0 -0
  4. llmeval-env/lib/python3.10/site-packages/sympy/functions/elementary/__pycache__/_trigonometric_special.cpython-310.pyc +0 -0
  5. llmeval-env/lib/python3.10/site-packages/sympy/functions/elementary/__pycache__/hyperbolic.cpython-310.pyc +0 -0
  6. llmeval-env/lib/python3.10/site-packages/sympy/functions/elementary/__pycache__/miscellaneous.cpython-310.pyc +0 -0
  7. llmeval-env/lib/python3.10/site-packages/sympy/functions/elementary/__pycache__/piecewise.cpython-310.pyc +0 -0
  8. llmeval-env/lib/python3.10/site-packages/sympy/functions/elementary/__pycache__/trigonometric.cpython-310.pyc +0 -0
  9. llmeval-env/lib/python3.10/site-packages/sympy/functions/elementary/_trigonometric_special.py +260 -0
  10. llmeval-env/lib/python3.10/site-packages/sympy/functions/elementary/complexes.py +1465 -0
  11. llmeval-env/lib/python3.10/site-packages/sympy/functions/elementary/exponential.py +1291 -0
  12. llmeval-env/lib/python3.10/site-packages/sympy/functions/elementary/hyperbolic.py +2203 -0
  13. llmeval-env/lib/python3.10/site-packages/sympy/functions/elementary/integers.py +625 -0
  14. llmeval-env/lib/python3.10/site-packages/sympy/functions/elementary/miscellaneous.py +915 -0
  15. llmeval-env/lib/python3.10/site-packages/sympy/functions/elementary/piecewise.py +1506 -0
  16. llmeval-env/lib/python3.10/site-packages/sympy/functions/elementary/trigonometric.py +0 -0
  17. llmeval-env/lib/python3.10/site-packages/sympy/multipledispatch/__init__.py +11 -0
  18. llmeval-env/lib/python3.10/site-packages/sympy/multipledispatch/__pycache__/__init__.cpython-310.pyc +0 -0
  19. llmeval-env/lib/python3.10/site-packages/sympy/multipledispatch/__pycache__/conflict.cpython-310.pyc +0 -0
  20. llmeval-env/lib/python3.10/site-packages/sympy/multipledispatch/__pycache__/core.cpython-310.pyc +0 -0
  21. llmeval-env/lib/python3.10/site-packages/sympy/multipledispatch/__pycache__/dispatcher.cpython-310.pyc +0 -0
  22. llmeval-env/lib/python3.10/site-packages/sympy/multipledispatch/__pycache__/utils.cpython-310.pyc +0 -0
  23. llmeval-env/lib/python3.10/site-packages/sympy/multipledispatch/conflict.py +68 -0
  24. llmeval-env/lib/python3.10/site-packages/sympy/multipledispatch/core.py +83 -0
  25. llmeval-env/lib/python3.10/site-packages/sympy/multipledispatch/dispatcher.py +413 -0
  26. llmeval-env/lib/python3.10/site-packages/sympy/multipledispatch/tests/__init__.py +0 -0
  27. llmeval-env/lib/python3.10/site-packages/sympy/multipledispatch/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  28. llmeval-env/lib/python3.10/site-packages/sympy/multipledispatch/tests/__pycache__/test_conflict.cpython-310.pyc +0 -0
  29. llmeval-env/lib/python3.10/site-packages/sympy/multipledispatch/tests/__pycache__/test_core.cpython-310.pyc +0 -0
  30. llmeval-env/lib/python3.10/site-packages/sympy/multipledispatch/tests/__pycache__/test_dispatcher.cpython-310.pyc +0 -0
  31. llmeval-env/lib/python3.10/site-packages/sympy/multipledispatch/tests/test_conflict.py +62 -0
  32. llmeval-env/lib/python3.10/site-packages/sympy/multipledispatch/tests/test_core.py +213 -0
  33. llmeval-env/lib/python3.10/site-packages/sympy/multipledispatch/tests/test_dispatcher.py +284 -0
  34. llmeval-env/lib/python3.10/site-packages/sympy/multipledispatch/utils.py +105 -0
  35. llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/__pycache__/anticommutator.cpython-310.pyc +0 -0
  36. llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/__pycache__/boson.cpython-310.pyc +0 -0
  37. llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/__pycache__/cartesian.cpython-310.pyc +0 -0
  38. llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/__pycache__/cg.cpython-310.pyc +0 -0
  39. llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/__pycache__/commutator.cpython-310.pyc +0 -0
  40. llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/__pycache__/constants.cpython-310.pyc +0 -0
  41. llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/__pycache__/dagger.cpython-310.pyc +0 -0
  42. llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/__pycache__/density.cpython-310.pyc +0 -0
  43. llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/__pycache__/gate.cpython-310.pyc +0 -0
  44. llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/__pycache__/grover.cpython-310.pyc +0 -0
  45. llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/__pycache__/hilbert.cpython-310.pyc +0 -0
  46. llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/__pycache__/identitysearch.cpython-310.pyc +0 -0
  47. llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/__pycache__/innerproduct.cpython-310.pyc +0 -0
  48. llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/__pycache__/matrixcache.cpython-310.pyc +0 -0
  49. llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/__pycache__/matrixutils.cpython-310.pyc +0 -0
  50. llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/__pycache__/operator.cpython-310.pyc +0 -0
llmeval-env/lib/python3.10/site-packages/sympy/functions/__init__.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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, motzkin)
12
+ from sympy.functions.elementary.miscellaneous import (sqrt, root, Min, Max,
13
+ Id, real_root, cbrt, Rem)
14
+ from sympy.functions.elementary.complexes import (re, im, sign, Abs,
15
+ conjugate, arg, polar_lift, periodic_argument, unbranched_argument,
16
+ principal_branch, transpose, adjoint, polarify, unpolarify)
17
+ from sympy.functions.elementary.trigonometric import (sin, cos, tan,
18
+ sec, csc, cot, sinc, asin, acos, atan, asec, acsc, acot, atan2)
19
+ from sympy.functions.elementary.exponential import (exp_polar, exp, log,
20
+ LambertW)
21
+ from sympy.functions.elementary.hyperbolic import (sinh, cosh, tanh, coth,
22
+ sech, csch, asinh, acosh, atanh, acoth, asech, acsch)
23
+ from sympy.functions.elementary.integers import floor, ceiling, frac
24
+ from sympy.functions.elementary.piecewise import (Piecewise, piecewise_fold,
25
+ piecewise_exclusive)
26
+ from sympy.functions.special.error_functions import (erf, erfc, erfi, erf2,
27
+ erfinv, erfcinv, erf2inv, Ei, expint, E1, li, Li, Si, Ci, Shi, Chi,
28
+ fresnels, fresnelc)
29
+ from sympy.functions.special.gamma_functions import (gamma, lowergamma,
30
+ uppergamma, polygamma, loggamma, digamma, trigamma, multigamma)
31
+ from sympy.functions.special.zeta_functions import (dirichlet_eta, zeta,
32
+ lerchphi, polylog, stieltjes, riemann_xi)
33
+ from sympy.functions.special.tensor_functions import (Eijk, LeviCivita,
34
+ KroneckerDelta)
35
+ from sympy.functions.special.singularity_functions import SingularityFunction
36
+ from sympy.functions.special.delta_functions import DiracDelta, Heaviside
37
+ from sympy.functions.special.bsplines import bspline_basis, bspline_basis_set, interpolating_spline
38
+ from sympy.functions.special.bessel import (besselj, bessely, besseli, besselk,
39
+ hankel1, hankel2, jn, yn, jn_zeros, hn1, hn2, airyai, airybi, airyaiprime, airybiprime, marcumq)
40
+ from sympy.functions.special.hyper import hyper, meijerg, appellf1
41
+ from sympy.functions.special.polynomials import (legendre, assoc_legendre,
42
+ hermite, hermite_prob, chebyshevt, chebyshevu, chebyshevu_root,
43
+ chebyshevt_root, laguerre, assoc_laguerre, gegenbauer, jacobi, jacobi_normalized)
44
+ from sympy.functions.special.spherical_harmonics import Ynm, Ynm_c, Znm
45
+ from sympy.functions.special.elliptic_integrals import (elliptic_k,
46
+ elliptic_f, elliptic_e, elliptic_pi)
47
+ from sympy.functions.special.beta_functions import beta, betainc, betainc_regularized
48
+ from sympy.functions.special.mathieu_functions import (mathieus, mathieuc,
49
+ mathieusprime, mathieucprime)
50
+ ln = log
51
+
52
+ __all__ = [
53
+ 'factorial', 'factorial2', 'rf', 'ff', 'binomial', 'RisingFactorial',
54
+ 'FallingFactorial', 'subfactorial',
55
+
56
+ 'carmichael', 'fibonacci', 'lucas', 'motzkin', 'tribonacci', 'harmonic',
57
+ 'bernoulli', 'bell', 'euler', 'catalan', 'genocchi', 'andre', 'partition',
58
+
59
+ 'sqrt', 'root', 'Min', 'Max', 'Id', 'real_root', 'cbrt', 'Rem',
60
+
61
+ 're', 'im', 'sign', 'Abs', 'conjugate', 'arg', 'polar_lift',
62
+ 'periodic_argument', 'unbranched_argument', 'principal_branch',
63
+ 'transpose', 'adjoint', 'polarify', 'unpolarify',
64
+
65
+ 'sin', 'cos', 'tan', 'sec', 'csc', 'cot', 'sinc', 'asin', 'acos', 'atan',
66
+ 'asec', 'acsc', 'acot', 'atan2',
67
+
68
+ 'exp_polar', 'exp', 'ln', 'log', 'LambertW',
69
+
70
+ 'sinh', 'cosh', 'tanh', 'coth', 'sech', 'csch', 'asinh', 'acosh', 'atanh',
71
+ 'acoth', 'asech', 'acsch',
72
+
73
+ 'floor', 'ceiling', 'frac',
74
+
75
+ 'Piecewise', 'piecewise_fold', 'piecewise_exclusive',
76
+
77
+ 'erf', 'erfc', 'erfi', 'erf2', 'erfinv', 'erfcinv', 'erf2inv', 'Ei',
78
+ 'expint', 'E1', 'li', 'Li', 'Si', 'Ci', 'Shi', 'Chi', 'fresnels',
79
+ 'fresnelc',
80
+
81
+ 'gamma', 'lowergamma', 'uppergamma', 'polygamma', 'loggamma', 'digamma',
82
+ 'trigamma', 'multigamma',
83
+
84
+ 'dirichlet_eta', 'zeta', 'lerchphi', 'polylog', 'stieltjes', 'riemann_xi',
85
+
86
+ 'Eijk', 'LeviCivita', 'KroneckerDelta',
87
+
88
+ 'SingularityFunction',
89
+
90
+ 'DiracDelta', 'Heaviside',
91
+
92
+ 'bspline_basis', 'bspline_basis_set', 'interpolating_spline',
93
+
94
+ 'besselj', 'bessely', 'besseli', 'besselk', 'hankel1', 'hankel2', 'jn',
95
+ 'yn', 'jn_zeros', 'hn1', 'hn2', 'airyai', 'airybi', 'airyaiprime',
96
+ 'airybiprime', 'marcumq',
97
+
98
+ 'hyper', 'meijerg', 'appellf1',
99
+
100
+ 'legendre', 'assoc_legendre', 'hermite', 'hermite_prob', 'chebyshevt',
101
+ 'chebyshevu', 'chebyshevu_root', 'chebyshevt_root', 'laguerre',
102
+ 'assoc_laguerre', 'gegenbauer', 'jacobi', 'jacobi_normalized',
103
+
104
+ 'Ynm', 'Ynm_c', 'Znm',
105
+
106
+ 'elliptic_k', 'elliptic_f', 'elliptic_e', 'elliptic_pi',
107
+
108
+ 'beta', 'betainc', 'betainc_regularized',
109
+
110
+ 'mathieus', 'mathieuc', 'mathieusprime', 'mathieucprime',
111
+ ]
llmeval-env/lib/python3.10/site-packages/sympy/functions/elementary/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # Stub __init__.py for sympy.functions.elementary
llmeval-env/lib/python3.10/site-packages/sympy/functions/elementary/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (199 Bytes). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/functions/elementary/__pycache__/_trigonometric_special.cpython-310.pyc ADDED
Binary file (8.56 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/functions/elementary/__pycache__/hyperbolic.cpython-310.pyc ADDED
Binary file (55.8 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/functions/elementary/__pycache__/miscellaneous.cpython-310.pyc ADDED
Binary file (30.8 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/functions/elementary/__pycache__/piecewise.cpython-310.pyc ADDED
Binary file (44.7 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/functions/elementary/__pycache__/trigonometric.cpython-310.pyc ADDED
Binary file (91.6 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/functions/elementary/_trigonometric_special.py ADDED
@@ -0,0 +1,260 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ r"""A module for special angle forumlas for trigonometric functions
2
+
3
+ TODO
4
+ ====
5
+
6
+ This module should be developed in the future to contain direct squrae 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.numbers import igcdex, Integer
41
+ from sympy.functions.elementary.miscellaneous import sqrt
42
+ from sympy.core.cache import cacheit
43
+
44
+
45
+ def migcdex(*x: int) -> tuple[tuple[int, ...], int]:
46
+ r"""Compute extended gcd for multiple integers.
47
+
48
+ Explanation
49
+ ===========
50
+
51
+ Given the integers $x_1, \cdots, x_n$ and
52
+ an extended gcd for multiple arguments are defined as a solution
53
+ $(y_1, \cdots, y_n), g$ for the diophantine equation
54
+ $x_1 y_1 + \cdots + x_n y_n = g$ such that
55
+ $g = \gcd(x_1, \cdots, x_n)$.
56
+
57
+ Examples
58
+ ========
59
+
60
+ >>> from sympy.functions.elementary._trigonometric_special import migcdex
61
+ >>> migcdex()
62
+ ((), 0)
63
+ >>> migcdex(4)
64
+ ((1,), 4)
65
+ >>> migcdex(4, 6)
66
+ ((-1, 1), 2)
67
+ >>> migcdex(6, 10, 15)
68
+ ((1, 1, -1), 1)
69
+ """
70
+ if not x:
71
+ return (), 0
72
+
73
+ if len(x) == 1:
74
+ return (1,), x[0]
75
+
76
+ if len(x) == 2:
77
+ u, v, h = igcdex(x[0], x[1])
78
+ return (u, v), h
79
+
80
+ y, g = migcdex(*x[1:])
81
+ u, v, h = igcdex(x[0], g)
82
+ return (u, *(v * i for i in y)), h
83
+
84
+
85
+ def ipartfrac(*denoms: int) -> tuple[int, ...]:
86
+ r"""Compute the the partial fraction decomposition.
87
+
88
+ Explanation
89
+ ===========
90
+
91
+ Given a rational number $\frac{1}{q_1 \cdots q_n}$ where all
92
+ $q_1, \cdots, q_n$ are pairwise coprime,
93
+
94
+ A partial fraction decomposition is defined as
95
+
96
+ .. math::
97
+ \frac{1}{q_1 \cdots q_n} = \frac{p_1}{q_1} + \cdots + \frac{p_n}{q_n}
98
+
99
+ And it can be derived from solving the following diophantine equation for
100
+ the $p_1, \cdots, p_n$
101
+
102
+ .. math::
103
+ 1 = p_1 \prod_{i \ne 1}q_i + \cdots + p_n \prod_{i \ne n}q_i
104
+
105
+ Where $q_1, \cdots, q_n$ being pairwise coprime implies
106
+ $\gcd(\prod_{i \ne 1}q_i, \cdots, \prod_{i \ne n}q_i) = 1$,
107
+ which guarantees the existance of the solution.
108
+
109
+ It is sufficient to compute partial fraction decomposition only
110
+ for numerator $1$ because partial fraction decomposition for any
111
+ $\frac{n}{q_1 \cdots q_n}$ can be easily computed by multiplying
112
+ the result by $n$ afterwards.
113
+
114
+ Parameters
115
+ ==========
116
+
117
+ denoms : int
118
+ The pairwise coprime integer denominators $q_i$ which defines the
119
+ rational number $\frac{1}{q_1 \cdots q_n}$
120
+
121
+ Returns
122
+ =======
123
+
124
+ tuple[int, ...]
125
+ The list of numerators which semantically corresponds to $p_i$ of the
126
+ partial fraction decomposition
127
+ $\frac{1}{q_1 \cdots q_n} = \frac{p_1}{q_1} + \cdots + \frac{p_n}{q_n}$
128
+
129
+ Examples
130
+ ========
131
+
132
+ >>> from sympy import Rational, Mul
133
+ >>> from sympy.functions.elementary._trigonometric_special import ipartfrac
134
+
135
+ >>> denoms = 2, 3, 5
136
+ >>> numers = ipartfrac(2, 3, 5)
137
+ >>> numers
138
+ (1, 7, -14)
139
+
140
+ >>> Rational(1, Mul(*denoms))
141
+ 1/30
142
+ >>> out = 0
143
+ >>> for n, d in zip(numers, denoms):
144
+ ... out += Rational(n, d)
145
+ >>> out
146
+ 1/30
147
+ """
148
+ if not denoms:
149
+ return ()
150
+
151
+ def mul(x: int, y: int) -> int:
152
+ return x * y
153
+
154
+ denom = reduce(mul, denoms)
155
+ a = [denom // x for x in denoms]
156
+ h, _ = migcdex(*a)
157
+ return h
158
+
159
+
160
+ def fermat_coords(n: int) -> list[int] | None:
161
+ """If n can be factored in terms of Fermat primes with
162
+ multiplicity of each being 1, return those primes, else
163
+ None
164
+ """
165
+ primes = []
166
+ for p in [3, 5, 17, 257, 65537]:
167
+ quotient, remainder = divmod(n, p)
168
+ if remainder == 0:
169
+ n = quotient
170
+ primes.append(p)
171
+ if n == 1:
172
+ return primes
173
+ return None
174
+
175
+
176
+ @cacheit
177
+ def cos_3() -> Expr:
178
+ r"""Computes $\cos \frac{\pi}{3}$ in square roots"""
179
+ return S.Half
180
+
181
+
182
+ @cacheit
183
+ def cos_5() -> Expr:
184
+ r"""Computes $\cos \frac{\pi}{5}$ in square roots"""
185
+ return (sqrt(5) + 1) / 4
186
+
187
+
188
+ @cacheit
189
+ def cos_17() -> Expr:
190
+ r"""Computes $\cos \frac{\pi}{17}$ in square roots"""
191
+ return sqrt(
192
+ (15 + sqrt(17)) / 32 + sqrt(2) * (sqrt(17 - sqrt(17)) +
193
+ sqrt(sqrt(2) * (-8 * sqrt(17 + sqrt(17)) - (1 - sqrt(17))
194
+ * sqrt(17 - sqrt(17))) + 6 * sqrt(17) + 34)) / 32)
195
+
196
+
197
+ @cacheit
198
+ def cos_257() -> Expr:
199
+ r"""Computes $\cos \frac{\pi}{257}$ in square roots
200
+
201
+ References
202
+ ==========
203
+
204
+ .. [*] https://math.stackexchange.com/questions/516142/how-does-cos2-pi-257-look-like-in-real-radicals
205
+ .. [*] https://r-knott.surrey.ac.uk/Fibonacci/simpleTrig.html
206
+ """
207
+ def f1(a: Expr, b: Expr) -> tuple[Expr, Expr]:
208
+ return (a + sqrt(a**2 + b)) / 2, (a - sqrt(a**2 + b)) / 2
209
+
210
+ def f2(a: Expr, b: Expr) -> Expr:
211
+ return (a - sqrt(a**2 + b))/2
212
+
213
+ t1, t2 = f1(S.NegativeOne, Integer(256))
214
+ z1, z3 = f1(t1, Integer(64))
215
+ z2, z4 = f1(t2, Integer(64))
216
+ y1, y5 = f1(z1, 4*(5 + t1 + 2*z1))
217
+ y6, y2 = f1(z2, 4*(5 + t2 + 2*z2))
218
+ y3, y7 = f1(z3, 4*(5 + t1 + 2*z3))
219
+ y8, y4 = f1(z4, 4*(5 + t2 + 2*z4))
220
+ x1, x9 = f1(y1, -4*(t1 + y1 + y3 + 2*y6))
221
+ x2, x10 = f1(y2, -4*(t2 + y2 + y4 + 2*y7))
222
+ x3, x11 = f1(y3, -4*(t1 + y3 + y5 + 2*y8))
223
+ x4, x12 = f1(y4, -4*(t2 + y4 + y6 + 2*y1))
224
+ x5, x13 = f1(y5, -4*(t1 + y5 + y7 + 2*y2))
225
+ x6, x14 = f1(y6, -4*(t2 + y6 + y8 + 2*y3))
226
+ x15, x7 = f1(y7, -4*(t1 + y7 + y1 + 2*y4))
227
+ x8, x16 = f1(y8, -4*(t2 + y8 + y2 + 2*y5))
228
+ v1 = f2(x1, -4*(x1 + x2 + x3 + x6))
229
+ v2 = f2(x2, -4*(x2 + x3 + x4 + x7))
230
+ v3 = f2(x8, -4*(x8 + x9 + x10 + x13))
231
+ v4 = f2(x9, -4*(x9 + x10 + x11 + x14))
232
+ v5 = f2(x10, -4*(x10 + x11 + x12 + x15))
233
+ v6 = f2(x16, -4*(x16 + x1 + x2 + x5))
234
+ u1 = -f2(-v1, -4*(v2 + v3))
235
+ u2 = -f2(-v4, -4*(v5 + v6))
236
+ w1 = -2*f2(-u1, -4*u2)
237
+ return sqrt(sqrt(2)*sqrt(w1 + 4)/8 + S.Half)
238
+
239
+
240
+ def cos_table() -> dict[int, Callable[[], Expr]]:
241
+ r"""Lazily evaluated table for $\cos \frac{\pi}{n}$ in square roots for
242
+ $n \in \{3, 5, 17, 257, 65537\}$.
243
+
244
+ Notes
245
+ =====
246
+
247
+ 65537 is the only other known Fermat prime and it is nearly impossible to
248
+ build in the current SymPy due to performance issues.
249
+
250
+ References
251
+ ==========
252
+
253
+ https://r-knott.surrey.ac.uk/Fibonacci/simpleTrig.html
254
+ """
255
+ return {
256
+ 3: cos_3,
257
+ 5: cos_5,
258
+ 17: cos_17,
259
+ 257: cos_257
260
+ }
llmeval-env/lib/python3.10/site-packages/sympy/functions/elementary/complexes.py ADDED
@@ -0,0 +1,1465 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Tuple as tTuple
2
+
3
+ from sympy.core import S, Add, Mul, sympify, Symbol, Dummy, Basic
4
+ from sympy.core.expr import Expr
5
+ from sympy.core.exprtools 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_polar
762
+ if isinstance(arg, exp_polar):
763
+ return periodic_argument(arg, oo)
764
+ if not arg.is_Atom:
765
+ c, arg_ = factor_terms(arg).as_coeff_Mul()
766
+ if arg_.is_Mul:
767
+ arg_ = Mul(*[a if (sign(a) not in (-1, 1)) else
768
+ sign(a) for a in arg_.args])
769
+ arg_ = sign(c)*arg_
770
+ else:
771
+ arg_ = arg
772
+ if any(i.is_extended_positive is None for i in arg_.atoms(AppliedUndef)):
773
+ return
774
+ from sympy.functions.elementary.trigonometric import atan2
775
+ x, y = arg_.as_real_imag()
776
+ rv = atan2(y, x)
777
+ if rv.is_number:
778
+ return rv
779
+ if arg_ != arg:
780
+ return cls(arg_, evaluate=False)
781
+
782
+ def _eval_derivative(self, t):
783
+ x, y = self.args[0].as_real_imag()
784
+ return (x * Derivative(y, t, evaluate=True) - y *
785
+ Derivative(x, t, evaluate=True)) / (x**2 + y**2)
786
+
787
+ def _eval_rewrite_as_atan2(self, arg, **kwargs):
788
+ from sympy.functions.elementary.trigonometric import atan2
789
+ x, y = self.args[0].as_real_imag()
790
+ return atan2(y, x)
791
+
792
+
793
+ class conjugate(Function):
794
+ """
795
+ Returns the *complex conjugate* [1]_ of an argument.
796
+ In mathematics, the complex conjugate of a complex number
797
+ is given by changing the sign of the imaginary part.
798
+
799
+ Thus, the conjugate of the complex number
800
+ :math:`a + ib` (where $a$ and $b$ are real numbers) is :math:`a - ib`
801
+
802
+ Examples
803
+ ========
804
+
805
+ >>> from sympy import conjugate, I
806
+ >>> conjugate(2)
807
+ 2
808
+ >>> conjugate(I)
809
+ -I
810
+ >>> conjugate(3 + 2*I)
811
+ 3 - 2*I
812
+ >>> conjugate(5 - I)
813
+ 5 + I
814
+
815
+ Parameters
816
+ ==========
817
+
818
+ arg : Expr
819
+ Real or complex expression.
820
+
821
+ Returns
822
+ =======
823
+
824
+ arg : Expr
825
+ Complex conjugate of arg as real, imaginary or mixed expression.
826
+
827
+ See Also
828
+ ========
829
+
830
+ sign, Abs
831
+
832
+ References
833
+ ==========
834
+
835
+ .. [1] https://en.wikipedia.org/wiki/Complex_conjugation
836
+ """
837
+ _singularities = True # non-holomorphic
838
+
839
+ @classmethod
840
+ def eval(cls, arg):
841
+ obj = arg._eval_conjugate()
842
+ if obj is not None:
843
+ return obj
844
+
845
+ def inverse(self):
846
+ return conjugate
847
+
848
+ def _eval_Abs(self):
849
+ return Abs(self.args[0], evaluate=True)
850
+
851
+ def _eval_adjoint(self):
852
+ return transpose(self.args[0])
853
+
854
+ def _eval_conjugate(self):
855
+ return self.args[0]
856
+
857
+ def _eval_derivative(self, x):
858
+ if x.is_real:
859
+ return conjugate(Derivative(self.args[0], x, evaluate=True))
860
+ elif x.is_imaginary:
861
+ return -conjugate(Derivative(self.args[0], x, evaluate=True))
862
+
863
+ def _eval_transpose(self):
864
+ return adjoint(self.args[0])
865
+
866
+ def _eval_is_algebraic(self):
867
+ return self.args[0].is_algebraic
868
+
869
+
870
+ class transpose(Function):
871
+ """
872
+ Linear map transposition.
873
+
874
+ Examples
875
+ ========
876
+
877
+ >>> from sympy import transpose, Matrix, MatrixSymbol
878
+ >>> A = MatrixSymbol('A', 25, 9)
879
+ >>> transpose(A)
880
+ A.T
881
+ >>> B = MatrixSymbol('B', 9, 22)
882
+ >>> transpose(B)
883
+ B.T
884
+ >>> transpose(A*B)
885
+ B.T*A.T
886
+ >>> M = Matrix([[4, 5], [2, 1], [90, 12]])
887
+ >>> M
888
+ Matrix([
889
+ [ 4, 5],
890
+ [ 2, 1],
891
+ [90, 12]])
892
+ >>> transpose(M)
893
+ Matrix([
894
+ [4, 2, 90],
895
+ [5, 1, 12]])
896
+
897
+ Parameters
898
+ ==========
899
+
900
+ arg : Matrix
901
+ Matrix or matrix expression to take the transpose of.
902
+
903
+ Returns
904
+ =======
905
+
906
+ value : Matrix
907
+ Transpose of arg.
908
+
909
+ """
910
+
911
+ @classmethod
912
+ def eval(cls, arg):
913
+ obj = arg._eval_transpose()
914
+ if obj is not None:
915
+ return obj
916
+
917
+ def _eval_adjoint(self):
918
+ return conjugate(self.args[0])
919
+
920
+ def _eval_conjugate(self):
921
+ return adjoint(self.args[0])
922
+
923
+ def _eval_transpose(self):
924
+ return self.args[0]
925
+
926
+
927
+ class adjoint(Function):
928
+ """
929
+ Conjugate transpose or Hermite conjugation.
930
+
931
+ Examples
932
+ ========
933
+
934
+ >>> from sympy import adjoint, MatrixSymbol
935
+ >>> A = MatrixSymbol('A', 10, 5)
936
+ >>> adjoint(A)
937
+ Adjoint(A)
938
+
939
+ Parameters
940
+ ==========
941
+
942
+ arg : Matrix
943
+ Matrix or matrix expression to take the adjoint of.
944
+
945
+ Returns
946
+ =======
947
+
948
+ value : Matrix
949
+ Represents the conjugate transpose or Hermite
950
+ conjugation of arg.
951
+
952
+ """
953
+
954
+ @classmethod
955
+ def eval(cls, arg):
956
+ obj = arg._eval_adjoint()
957
+ if obj is not None:
958
+ return obj
959
+ obj = arg._eval_transpose()
960
+ if obj is not None:
961
+ return conjugate(obj)
962
+
963
+ def _eval_adjoint(self):
964
+ return self.args[0]
965
+
966
+ def _eval_conjugate(self):
967
+ return transpose(self.args[0])
968
+
969
+ def _eval_transpose(self):
970
+ return conjugate(self.args[0])
971
+
972
+ def _latex(self, printer, exp=None, *args):
973
+ arg = printer._print(self.args[0])
974
+ tex = r'%s^{\dagger}' % arg
975
+ if exp:
976
+ tex = r'\left(%s\right)^{%s}' % (tex, exp)
977
+ return tex
978
+
979
+ def _pretty(self, printer, *args):
980
+ from sympy.printing.pretty.stringpict import prettyForm
981
+ pform = printer._print(self.args[0], *args)
982
+ if printer._use_unicode:
983
+ pform = pform**prettyForm('\N{DAGGER}')
984
+ else:
985
+ pform = pform**prettyForm('+')
986
+ return pform
987
+
988
+ ###############################################################################
989
+ ############### HANDLING OF POLAR NUMBERS #####################################
990
+ ###############################################################################
991
+
992
+
993
+ class polar_lift(Function):
994
+ """
995
+ Lift argument to the Riemann surface of the logarithm, using the
996
+ standard branch.
997
+
998
+ Examples
999
+ ========
1000
+
1001
+ >>> from sympy import Symbol, polar_lift, I
1002
+ >>> p = Symbol('p', polar=True)
1003
+ >>> x = Symbol('x')
1004
+ >>> polar_lift(4)
1005
+ 4*exp_polar(0)
1006
+ >>> polar_lift(-4)
1007
+ 4*exp_polar(I*pi)
1008
+ >>> polar_lift(-I)
1009
+ exp_polar(-I*pi/2)
1010
+ >>> polar_lift(I + 2)
1011
+ polar_lift(2 + I)
1012
+
1013
+ >>> polar_lift(4*x)
1014
+ 4*polar_lift(x)
1015
+ >>> polar_lift(4*p)
1016
+ 4*p
1017
+
1018
+ Parameters
1019
+ ==========
1020
+
1021
+ arg : Expr
1022
+ Real or complex expression.
1023
+
1024
+ See Also
1025
+ ========
1026
+
1027
+ sympy.functions.elementary.exponential.exp_polar
1028
+ periodic_argument
1029
+ """
1030
+
1031
+ is_polar = True
1032
+ is_comparable = False # Cannot be evalf'd.
1033
+
1034
+ @classmethod
1035
+ def eval(cls, arg):
1036
+ from sympy.functions.elementary.complexes import arg as argument
1037
+ if arg.is_number:
1038
+ ar = argument(arg)
1039
+ # In general we want to affirm that something is known,
1040
+ # e.g. `not ar.has(argument) and not ar.has(atan)`
1041
+ # but for now we will just be more restrictive and
1042
+ # see that it has evaluated to one of the known values.
1043
+ if ar in (0, pi/2, -pi/2, pi):
1044
+ from sympy.functions.elementary.exponential import exp_polar
1045
+ return exp_polar(I*ar)*abs(arg)
1046
+
1047
+ if arg.is_Mul:
1048
+ args = arg.args
1049
+ else:
1050
+ args = [arg]
1051
+ included = []
1052
+ excluded = []
1053
+ positive = []
1054
+ for arg in args:
1055
+ if arg.is_polar:
1056
+ included += [arg]
1057
+ elif arg.is_positive:
1058
+ positive += [arg]
1059
+ else:
1060
+ excluded += [arg]
1061
+ if len(excluded) < len(args):
1062
+ if excluded:
1063
+ return Mul(*(included + positive))*polar_lift(Mul(*excluded))
1064
+ elif included:
1065
+ return Mul(*(included + positive))
1066
+ else:
1067
+ from sympy.functions.elementary.exponential import exp_polar
1068
+ return Mul(*positive)*exp_polar(0)
1069
+
1070
+ def _eval_evalf(self, prec):
1071
+ """ Careful! any evalf of polar numbers is flaky """
1072
+ return self.args[0]._eval_evalf(prec)
1073
+
1074
+ def _eval_Abs(self):
1075
+ return Abs(self.args[0], evaluate=True)
1076
+
1077
+
1078
+ class periodic_argument(Function):
1079
+ r"""
1080
+ Represent the argument on a quotient of the Riemann surface of the
1081
+ logarithm. That is, given a period $P$, always return a value in
1082
+ $(-P/2, P/2]$, by using $\exp(PI) = 1$.
1083
+
1084
+ Examples
1085
+ ========
1086
+
1087
+ >>> from sympy import exp_polar, periodic_argument
1088
+ >>> from sympy import I, pi
1089
+ >>> periodic_argument(exp_polar(10*I*pi), 2*pi)
1090
+ 0
1091
+ >>> periodic_argument(exp_polar(5*I*pi), 4*pi)
1092
+ pi
1093
+ >>> from sympy import exp_polar, periodic_argument
1094
+ >>> from sympy import I, pi
1095
+ >>> periodic_argument(exp_polar(5*I*pi), 2*pi)
1096
+ pi
1097
+ >>> periodic_argument(exp_polar(5*I*pi), 3*pi)
1098
+ -pi
1099
+ >>> periodic_argument(exp_polar(5*I*pi), pi)
1100
+ 0
1101
+
1102
+ Parameters
1103
+ ==========
1104
+
1105
+ ar : Expr
1106
+ A polar number.
1107
+
1108
+ period : Expr
1109
+ The period $P$.
1110
+
1111
+ See Also
1112
+ ========
1113
+
1114
+ sympy.functions.elementary.exponential.exp_polar
1115
+ polar_lift : Lift argument to the Riemann surface of the logarithm
1116
+ principal_branch
1117
+ """
1118
+
1119
+ @classmethod
1120
+ def _getunbranched(cls, ar):
1121
+ from sympy.functions.elementary.exponential import exp_polar, log
1122
+ if ar.is_Mul:
1123
+ args = ar.args
1124
+ else:
1125
+ args = [ar]
1126
+ unbranched = 0
1127
+ for a in args:
1128
+ if not a.is_polar:
1129
+ unbranched += arg(a)
1130
+ elif isinstance(a, exp_polar):
1131
+ unbranched += a.exp.as_real_imag()[1]
1132
+ elif a.is_Pow:
1133
+ re, im = a.exp.as_real_imag()
1134
+ unbranched += re*unbranched_argument(
1135
+ a.base) + im*log(abs(a.base))
1136
+ elif isinstance(a, polar_lift):
1137
+ unbranched += arg(a.args[0])
1138
+ else:
1139
+ return None
1140
+ return unbranched
1141
+
1142
+ @classmethod
1143
+ def eval(cls, ar, period):
1144
+ # Our strategy is to evaluate the argument on the Riemann surface of the
1145
+ # logarithm, and then reduce.
1146
+ # NOTE evidently this means it is a rather bad idea to use this with
1147
+ # period != 2*pi and non-polar numbers.
1148
+ if not period.is_extended_positive:
1149
+ return None
1150
+ if period == oo and isinstance(ar, principal_branch):
1151
+ return periodic_argument(*ar.args)
1152
+ if isinstance(ar, polar_lift) and period >= 2*pi:
1153
+ return periodic_argument(ar.args[0], period)
1154
+ if ar.is_Mul:
1155
+ newargs = [x for x in ar.args if not x.is_positive]
1156
+ if len(newargs) != len(ar.args):
1157
+ return periodic_argument(Mul(*newargs), period)
1158
+ unbranched = cls._getunbranched(ar)
1159
+ if unbranched is None:
1160
+ return None
1161
+ from sympy.functions.elementary.trigonometric import atan, atan2
1162
+ if unbranched.has(periodic_argument, atan2, atan):
1163
+ return None
1164
+ if period == oo:
1165
+ return unbranched
1166
+ if period != oo:
1167
+ from sympy.functions.elementary.integers import ceiling
1168
+ n = ceiling(unbranched/period - S.Half)*period
1169
+ if not n.has(ceiling):
1170
+ return unbranched - n
1171
+
1172
+ def _eval_evalf(self, prec):
1173
+ z, period = self.args
1174
+ if period == oo:
1175
+ unbranched = periodic_argument._getunbranched(z)
1176
+ if unbranched is None:
1177
+ return self
1178
+ return unbranched._eval_evalf(prec)
1179
+ ub = periodic_argument(z, oo)._eval_evalf(prec)
1180
+ from sympy.functions.elementary.integers import ceiling
1181
+ return (ub - ceiling(ub/period - S.Half)*period)._eval_evalf(prec)
1182
+
1183
+
1184
+ def unbranched_argument(arg):
1185
+ '''
1186
+ Returns periodic argument of arg with period as infinity.
1187
+
1188
+ Examples
1189
+ ========
1190
+
1191
+ >>> from sympy import exp_polar, unbranched_argument
1192
+ >>> from sympy import I, pi
1193
+ >>> unbranched_argument(exp_polar(15*I*pi))
1194
+ 15*pi
1195
+ >>> unbranched_argument(exp_polar(7*I*pi))
1196
+ 7*pi
1197
+
1198
+ See also
1199
+ ========
1200
+
1201
+ periodic_argument
1202
+ '''
1203
+ return periodic_argument(arg, oo)
1204
+
1205
+
1206
+ class principal_branch(Function):
1207
+ """
1208
+ Represent a polar number reduced to its principal branch on a quotient
1209
+ of the Riemann surface of the logarithm.
1210
+
1211
+ Explanation
1212
+ ===========
1213
+
1214
+ This is a function of two arguments. The first argument is a polar
1215
+ number `z`, and the second one a positive real number or infinity, `p`.
1216
+ The result is ``z mod exp_polar(I*p)``.
1217
+
1218
+ Examples
1219
+ ========
1220
+
1221
+ >>> from sympy import exp_polar, principal_branch, oo, I, pi
1222
+ >>> from sympy.abc import z
1223
+ >>> principal_branch(z, oo)
1224
+ z
1225
+ >>> principal_branch(exp_polar(2*pi*I)*3, 2*pi)
1226
+ 3*exp_polar(0)
1227
+ >>> principal_branch(exp_polar(2*pi*I)*3*z, 2*pi)
1228
+ 3*principal_branch(z, 2*pi)
1229
+
1230
+ Parameters
1231
+ ==========
1232
+
1233
+ x : Expr
1234
+ A polar number.
1235
+
1236
+ period : Expr
1237
+ Positive real number or infinity.
1238
+
1239
+ See Also
1240
+ ========
1241
+
1242
+ sympy.functions.elementary.exponential.exp_polar
1243
+ polar_lift : Lift argument to the Riemann surface of the logarithm
1244
+ periodic_argument
1245
+ """
1246
+
1247
+ is_polar = True
1248
+ is_comparable = False # cannot always be evalf'd
1249
+
1250
+ @classmethod
1251
+ def eval(self, x, period):
1252
+ from sympy.functions.elementary.exponential import exp_polar
1253
+ if isinstance(x, polar_lift):
1254
+ return principal_branch(x.args[0], period)
1255
+ if period == oo:
1256
+ return x
1257
+ ub = periodic_argument(x, oo)
1258
+ barg = periodic_argument(x, period)
1259
+ if ub != barg and not ub.has(periodic_argument) \
1260
+ and not barg.has(periodic_argument):
1261
+ pl = polar_lift(x)
1262
+
1263
+ def mr(expr):
1264
+ if not isinstance(expr, Symbol):
1265
+ return polar_lift(expr)
1266
+ return expr
1267
+ pl = pl.replace(polar_lift, mr)
1268
+ # Recompute unbranched argument
1269
+ ub = periodic_argument(pl, oo)
1270
+ if not pl.has(polar_lift):
1271
+ if ub != barg:
1272
+ res = exp_polar(I*(barg - ub))*pl
1273
+ else:
1274
+ res = pl
1275
+ if not res.is_polar and not res.has(exp_polar):
1276
+ res *= exp_polar(0)
1277
+ return res
1278
+
1279
+ if not x.free_symbols:
1280
+ c, m = x, ()
1281
+ else:
1282
+ c, m = x.as_coeff_mul(*x.free_symbols)
1283
+ others = []
1284
+ for y in m:
1285
+ if y.is_positive:
1286
+ c *= y
1287
+ else:
1288
+ others += [y]
1289
+ m = tuple(others)
1290
+ arg = periodic_argument(c, period)
1291
+ if arg.has(periodic_argument):
1292
+ return None
1293
+ if arg.is_number and (unbranched_argument(c) != arg or
1294
+ (arg == 0 and m != () and c != 1)):
1295
+ if arg == 0:
1296
+ return abs(c)*principal_branch(Mul(*m), period)
1297
+ return principal_branch(exp_polar(I*arg)*Mul(*m), period)*abs(c)
1298
+ if arg.is_number and ((abs(arg) < period/2) == True or arg == period/2) \
1299
+ and m == ():
1300
+ return exp_polar(arg*I)*abs(c)
1301
+
1302
+ def _eval_evalf(self, prec):
1303
+ z, period = self.args
1304
+ p = periodic_argument(z, period)._eval_evalf(prec)
1305
+ if abs(p) > pi or p == -pi:
1306
+ return self # Cannot evalf for this argument.
1307
+ from sympy.functions.elementary.exponential import exp
1308
+ return (abs(z)*exp(I*p))._eval_evalf(prec)
1309
+
1310
+
1311
+ def _polarify(eq, lift, pause=False):
1312
+ from sympy.integrals.integrals import Integral
1313
+ if eq.is_polar:
1314
+ return eq
1315
+ if eq.is_number and not pause:
1316
+ return polar_lift(eq)
1317
+ if isinstance(eq, Symbol) and not pause and lift:
1318
+ return polar_lift(eq)
1319
+ elif eq.is_Atom:
1320
+ return eq
1321
+ elif eq.is_Add:
1322
+ r = eq.func(*[_polarify(arg, lift, pause=True) for arg in eq.args])
1323
+ if lift:
1324
+ return polar_lift(r)
1325
+ return r
1326
+ elif eq.is_Pow and eq.base == S.Exp1:
1327
+ return eq.func(S.Exp1, _polarify(eq.exp, lift, pause=False))
1328
+ elif eq.is_Function:
1329
+ return eq.func(*[_polarify(arg, lift, pause=False) for arg in eq.args])
1330
+ elif isinstance(eq, Integral):
1331
+ # Don't lift the integration variable
1332
+ func = _polarify(eq.function, lift, pause=pause)
1333
+ limits = []
1334
+ for limit in eq.args[1:]:
1335
+ var = _polarify(limit[0], lift=False, pause=pause)
1336
+ rest = _polarify(limit[1:], lift=lift, pause=pause)
1337
+ limits.append((var,) + rest)
1338
+ return Integral(*((func,) + tuple(limits)))
1339
+ else:
1340
+ return eq.func(*[_polarify(arg, lift, pause=pause)
1341
+ if isinstance(arg, Expr) else arg for arg in eq.args])
1342
+
1343
+
1344
+ def polarify(eq, subs=True, lift=False):
1345
+ """
1346
+ Turn all numbers in eq into their polar equivalents (under the standard
1347
+ choice of argument).
1348
+
1349
+ Note that no attempt is made to guess a formal convention of adding
1350
+ polar numbers, expressions like $1 + x$ will generally not be altered.
1351
+
1352
+ Note also that this function does not promote ``exp(x)`` to ``exp_polar(x)``.
1353
+
1354
+ If ``subs`` is ``True``, all symbols which are not already polar will be
1355
+ substituted for polar dummies; in this case the function behaves much
1356
+ like :func:`~.posify`.
1357
+
1358
+ If ``lift`` is ``True``, both addition statements and non-polar symbols are
1359
+ changed to their ``polar_lift()``ed versions.
1360
+ Note that ``lift=True`` implies ``subs=False``.
1361
+
1362
+ Examples
1363
+ ========
1364
+
1365
+ >>> from sympy import polarify, sin, I
1366
+ >>> from sympy.abc import x, y
1367
+ >>> expr = (-x)**y
1368
+ >>> expr.expand()
1369
+ (-x)**y
1370
+ >>> polarify(expr)
1371
+ ((_x*exp_polar(I*pi))**_y, {_x: x, _y: y})
1372
+ >>> polarify(expr)[0].expand()
1373
+ _x**_y*exp_polar(_y*I*pi)
1374
+ >>> polarify(x, lift=True)
1375
+ polar_lift(x)
1376
+ >>> polarify(x*(1+y), lift=True)
1377
+ polar_lift(x)*polar_lift(y + 1)
1378
+
1379
+ Adds are treated carefully:
1380
+
1381
+ >>> polarify(1 + sin((1 + I)*x))
1382
+ (sin(_x*polar_lift(1 + I)) + 1, {_x: x})
1383
+ """
1384
+ if lift:
1385
+ subs = False
1386
+ eq = _polarify(sympify(eq), lift)
1387
+ if not subs:
1388
+ return eq
1389
+ reps = {s: Dummy(s.name, polar=True) for s in eq.free_symbols}
1390
+ eq = eq.subs(reps)
1391
+ return eq, {r: s for s, r in reps.items()}
1392
+
1393
+
1394
+ def _unpolarify(eq, exponents_only, pause=False):
1395
+ if not isinstance(eq, Basic) or eq.is_Atom:
1396
+ return eq
1397
+
1398
+ if not pause:
1399
+ from sympy.functions.elementary.exponential import exp, exp_polar
1400
+ if isinstance(eq, exp_polar):
1401
+ return exp(_unpolarify(eq.exp, exponents_only))
1402
+ if isinstance(eq, principal_branch) and eq.args[1] == 2*pi:
1403
+ return _unpolarify(eq.args[0], exponents_only)
1404
+ if (
1405
+ eq.is_Add or eq.is_Mul or eq.is_Boolean or
1406
+ eq.is_Relational and (
1407
+ eq.rel_op in ('==', '!=') and 0 in eq.args or
1408
+ eq.rel_op not in ('==', '!='))
1409
+ ):
1410
+ return eq.func(*[_unpolarify(x, exponents_only) for x in eq.args])
1411
+ if isinstance(eq, polar_lift):
1412
+ return _unpolarify(eq.args[0], exponents_only)
1413
+
1414
+ if eq.is_Pow:
1415
+ expo = _unpolarify(eq.exp, exponents_only)
1416
+ base = _unpolarify(eq.base, exponents_only,
1417
+ not (expo.is_integer and not pause))
1418
+ return base**expo
1419
+
1420
+ if eq.is_Function and getattr(eq.func, 'unbranched', False):
1421
+ return eq.func(*[_unpolarify(x, exponents_only, exponents_only)
1422
+ for x in eq.args])
1423
+
1424
+ return eq.func(*[_unpolarify(x, exponents_only, True) for x in eq.args])
1425
+
1426
+
1427
+ def unpolarify(eq, subs=None, exponents_only=False):
1428
+ """
1429
+ If `p` denotes the projection from the Riemann surface of the logarithm to
1430
+ the complex line, return a simplified version `eq'` of `eq` such that
1431
+ `p(eq') = p(eq)`.
1432
+ Also apply the substitution subs in the end. (This is a convenience, since
1433
+ ``unpolarify``, in a certain sense, undoes :func:`polarify`.)
1434
+
1435
+ Examples
1436
+ ========
1437
+
1438
+ >>> from sympy import unpolarify, polar_lift, sin, I
1439
+ >>> unpolarify(polar_lift(I + 2))
1440
+ 2 + I
1441
+ >>> unpolarify(sin(polar_lift(I + 7)))
1442
+ sin(7 + I)
1443
+ """
1444
+ if isinstance(eq, bool):
1445
+ return eq
1446
+
1447
+ eq = sympify(eq)
1448
+ if subs is not None:
1449
+ return unpolarify(eq.subs(subs))
1450
+ changed = True
1451
+ pause = False
1452
+ if exponents_only:
1453
+ pause = True
1454
+ while changed:
1455
+ changed = False
1456
+ res = _unpolarify(eq, exponents_only, pause)
1457
+ if res != eq:
1458
+ changed = True
1459
+ eq = res
1460
+ if isinstance(res, bool):
1461
+ return res
1462
+ # Finally, replacing Exp(0) by 1 is always correct.
1463
+ # So is polar_lift(0) -> 0.
1464
+ from sympy.functions.elementary.exponential import exp_polar
1465
+ return res.subs({exp_polar(0): 1, polar_lift(0): 0})
llmeval-env/lib/python3.10/site-packages/sympy/functions/elementary/exponential.py ADDED
@@ -0,0 +1,1291 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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, ImaginaryUnit
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
+ exp = self.exp
67
+ neg_exp = exp.is_negative
68
+ if not neg_exp and not (-exp).is_negative:
69
+ neg_exp = exp.could_extract_minus_sign()
70
+ if neg_exp:
71
+ return S.One, self.func(-exp)
72
+ return self, S.One
73
+
74
+ @property
75
+ def exp(self):
76
+ """
77
+ Returns the exponent of the function.
78
+ """
79
+ return self.args[0]
80
+
81
+ def as_base_exp(self):
82
+ """
83
+ Returns the 2-tuple (base, exponent).
84
+ """
85
+ return self.func(1), Mul(*self.args)
86
+
87
+ def _eval_adjoint(self):
88
+ return self.func(self.exp.adjoint())
89
+
90
+ def _eval_conjugate(self):
91
+ return self.func(self.exp.conjugate())
92
+
93
+ def _eval_transpose(self):
94
+ return self.func(self.exp.transpose())
95
+
96
+ def _eval_is_finite(self):
97
+ arg = self.exp
98
+ if arg.is_infinite:
99
+ if arg.is_extended_negative:
100
+ return True
101
+ if arg.is_extended_positive:
102
+ return False
103
+ if arg.is_finite:
104
+ return True
105
+
106
+ def _eval_is_rational(self):
107
+ s = self.func(*self.args)
108
+ if s.func == self.func:
109
+ z = s.exp.is_zero
110
+ if z:
111
+ return True
112
+ elif s.exp.is_rational and fuzzy_not(z):
113
+ return False
114
+ else:
115
+ return s.is_rational
116
+
117
+ def _eval_is_zero(self):
118
+ return self.exp is S.NegativeInfinity
119
+
120
+ def _eval_power(self, other):
121
+ """exp(arg)**e -> exp(arg*e) if assumptions allow it.
122
+ """
123
+ b, e = self.as_base_exp()
124
+ return Pow._eval_power(Pow(b, e, evaluate=False), other)
125
+
126
+ def _eval_expand_power_exp(self, **hints):
127
+ from sympy.concrete.products import Product
128
+ from sympy.concrete.summations import Sum
129
+ arg = self.args[0]
130
+ if arg.is_Add and arg.is_commutative:
131
+ return Mul.fromiter(self.func(x) for x in arg.args)
132
+ elif isinstance(arg, Sum) and arg.is_commutative:
133
+ return Product(self.func(arg.function), *arg.limits)
134
+ return self.func(arg)
135
+
136
+
137
+ class exp_polar(ExpBase):
138
+ r"""
139
+ Represent a *polar number* (see g-function Sphinx documentation).
140
+
141
+ Explanation
142
+ ===========
143
+
144
+ ``exp_polar`` represents the function
145
+ `Exp: \mathbb{C} \rightarrow \mathcal{S}`, sending the complex number
146
+ `z = a + bi` to the polar number `r = exp(a), \theta = b`. It is one of
147
+ the main functions to construct polar numbers.
148
+
149
+ Examples
150
+ ========
151
+
152
+ >>> from sympy import exp_polar, pi, I, exp
153
+
154
+ The main difference is that polar numbers do not "wrap around" at `2 \pi`:
155
+
156
+ >>> exp(2*pi*I)
157
+ 1
158
+ >>> exp_polar(2*pi*I)
159
+ exp_polar(2*I*pi)
160
+
161
+ apart from that they behave mostly like classical complex numbers:
162
+
163
+ >>> exp_polar(2)*exp_polar(3)
164
+ exp_polar(5)
165
+
166
+ See Also
167
+ ========
168
+
169
+ sympy.simplify.powsimp.powsimp
170
+ polar_lift
171
+ periodic_argument
172
+ principal_branch
173
+ """
174
+
175
+ is_polar = True
176
+ is_comparable = False # cannot be evalf'd
177
+
178
+ def _eval_Abs(self): # Abs is never a polar number
179
+ return exp(re(self.args[0]))
180
+
181
+ def _eval_evalf(self, prec):
182
+ """ Careful! any evalf of polar numbers is flaky """
183
+ i = im(self.args[0])
184
+ try:
185
+ bad = (i <= -pi or i > pi)
186
+ except TypeError:
187
+ bad = True
188
+ if bad:
189
+ return self # cannot evalf for this argument
190
+ res = exp(self.args[0])._eval_evalf(prec)
191
+ if i > 0 and im(res) < 0:
192
+ # i ~ pi, but exp(I*i) evaluated to argument slightly bigger than pi
193
+ return re(res)
194
+ return res
195
+
196
+ def _eval_power(self, other):
197
+ return self.func(self.args[0]*other)
198
+
199
+ def _eval_is_extended_real(self):
200
+ if self.args[0].is_extended_real:
201
+ return True
202
+
203
+ def as_base_exp(self):
204
+ # XXX exp_polar(0) is special!
205
+ if self.args[0] == 0:
206
+ return self, S.One
207
+ return ExpBase.as_base_exp(self)
208
+
209
+
210
+ class ExpMeta(FunctionClass):
211
+ def __instancecheck__(cls, instance):
212
+ if exp in instance.__class__.__mro__:
213
+ return True
214
+ return isinstance(instance, Pow) and instance.base is S.Exp1
215
+
216
+
217
+ class exp(ExpBase, metaclass=ExpMeta):
218
+ """
219
+ The exponential function, :math:`e^x`.
220
+
221
+ Examples
222
+ ========
223
+
224
+ >>> from sympy import exp, I, pi
225
+ >>> from sympy.abc import x
226
+ >>> exp(x)
227
+ exp(x)
228
+ >>> exp(x).diff(x)
229
+ exp(x)
230
+ >>> exp(I*pi)
231
+ -1
232
+
233
+ Parameters
234
+ ==========
235
+
236
+ arg : Expr
237
+
238
+ See Also
239
+ ========
240
+
241
+ log
242
+ """
243
+
244
+ def fdiff(self, argindex=1):
245
+ """
246
+ Returns the first derivative of this function.
247
+ """
248
+ if argindex == 1:
249
+ return self
250
+ else:
251
+ raise ArgumentIndexError(self, argindex)
252
+
253
+ def _eval_refine(self, assumptions):
254
+ from sympy.assumptions import ask, Q
255
+ arg = self.args[0]
256
+ if arg.is_Mul:
257
+ Ioo = I*S.Infinity
258
+ if arg in [Ioo, -Ioo]:
259
+ return S.NaN
260
+
261
+ coeff = arg.as_coefficient(pi*I)
262
+ if coeff:
263
+ if ask(Q.integer(2*coeff)):
264
+ if ask(Q.even(coeff)):
265
+ return S.One
266
+ elif ask(Q.odd(coeff)):
267
+ return S.NegativeOne
268
+ elif ask(Q.even(coeff + S.Half)):
269
+ return -I
270
+ elif ask(Q.odd(coeff + S.Half)):
271
+ return I
272
+
273
+ @classmethod
274
+ def eval(cls, arg):
275
+ from sympy.calculus import AccumBounds
276
+ from sympy.matrices.matrices import MatrixBase
277
+ from sympy.sets.setexpr import SetExpr
278
+ from sympy.simplify.simplify import logcombine
279
+ if isinstance(arg, MatrixBase):
280
+ return arg.exp()
281
+ elif global_parameters.exp_is_pow:
282
+ return Pow(S.Exp1, arg)
283
+ elif arg.is_Number:
284
+ if arg is S.NaN:
285
+ return S.NaN
286
+ elif arg.is_zero:
287
+ return S.One
288
+ elif arg is S.One:
289
+ return S.Exp1
290
+ elif arg is S.Infinity:
291
+ return S.Infinity
292
+ elif arg is S.NegativeInfinity:
293
+ return S.Zero
294
+ elif arg is S.ComplexInfinity:
295
+ return S.NaN
296
+ elif isinstance(arg, log):
297
+ return arg.args[0]
298
+ elif isinstance(arg, AccumBounds):
299
+ return AccumBounds(exp(arg.min), exp(arg.max))
300
+ elif isinstance(arg, SetExpr):
301
+ return arg._eval_func(cls)
302
+ elif arg.is_Mul:
303
+ coeff = arg.as_coefficient(pi*I)
304
+ if coeff:
305
+ if (2*coeff).is_integer:
306
+ if coeff.is_even:
307
+ return S.One
308
+ elif coeff.is_odd:
309
+ return S.NegativeOne
310
+ elif (coeff + S.Half).is_even:
311
+ return -I
312
+ elif (coeff + S.Half).is_odd:
313
+ return I
314
+ elif coeff.is_Rational:
315
+ ncoeff = coeff % 2 # restrict to [0, 2pi)
316
+ if ncoeff > 1: # restrict to (-pi, pi]
317
+ ncoeff -= 2
318
+ if ncoeff != coeff:
319
+ return cls(ncoeff*pi*I)
320
+
321
+ # Warning: code in risch.py will be very sensitive to changes
322
+ # in this (see DifferentialExtension).
323
+
324
+ # look for a single log factor
325
+
326
+ coeff, terms = arg.as_coeff_Mul()
327
+
328
+ # but it can't be multiplied by oo
329
+ if coeff in [S.NegativeInfinity, S.Infinity]:
330
+ if terms.is_number:
331
+ if coeff is S.NegativeInfinity:
332
+ terms = -terms
333
+ if re(terms).is_zero and terms is not S.Zero:
334
+ return S.NaN
335
+ if re(terms).is_positive and im(terms) is not S.Zero:
336
+ return S.ComplexInfinity
337
+ if re(terms).is_negative:
338
+ return S.Zero
339
+ return None
340
+
341
+ coeffs, log_term = [coeff], None
342
+ for term in Mul.make_args(terms):
343
+ term_ = logcombine(term)
344
+ if isinstance(term_, log):
345
+ if log_term is None:
346
+ log_term = term_.args[0]
347
+ else:
348
+ return None
349
+ elif term.is_comparable:
350
+ coeffs.append(term)
351
+ else:
352
+ return None
353
+
354
+ return log_term**Mul(*coeffs) if log_term else None
355
+
356
+ elif arg.is_Add:
357
+ out = []
358
+ add = []
359
+ argchanged = False
360
+ for a in arg.args:
361
+ if a is S.One:
362
+ add.append(a)
363
+ continue
364
+ newa = cls(a)
365
+ if isinstance(newa, cls):
366
+ if newa.args[0] != a:
367
+ add.append(newa.args[0])
368
+ argchanged = True
369
+ else:
370
+ add.append(a)
371
+ else:
372
+ out.append(newa)
373
+ if out or argchanged:
374
+ return Mul(*out)*cls(Add(*add), evaluate=False)
375
+
376
+ if arg.is_zero:
377
+ return S.One
378
+
379
+ @property
380
+ def base(self):
381
+ """
382
+ Returns the base of the exponential function.
383
+ """
384
+ return S.Exp1
385
+
386
+ @staticmethod
387
+ @cacheit
388
+ def taylor_term(n, x, *previous_terms):
389
+ """
390
+ Calculates the next term in the Taylor series expansion.
391
+ """
392
+ if n < 0:
393
+ return S.Zero
394
+ if n == 0:
395
+ return S.One
396
+ x = sympify(x)
397
+ if previous_terms:
398
+ p = previous_terms[-1]
399
+ if p is not None:
400
+ return p * x / n
401
+ return x**n/factorial(n)
402
+
403
+ def as_real_imag(self, deep=True, **hints):
404
+ """
405
+ Returns this function as a 2-tuple representing a complex number.
406
+
407
+ Examples
408
+ ========
409
+
410
+ >>> from sympy import exp, I
411
+ >>> from sympy.abc import x
412
+ >>> exp(x).as_real_imag()
413
+ (exp(re(x))*cos(im(x)), exp(re(x))*sin(im(x)))
414
+ >>> exp(1).as_real_imag()
415
+ (E, 0)
416
+ >>> exp(I).as_real_imag()
417
+ (cos(1), sin(1))
418
+ >>> exp(1+I).as_real_imag()
419
+ (E*cos(1), E*sin(1))
420
+
421
+ See Also
422
+ ========
423
+
424
+ sympy.functions.elementary.complexes.re
425
+ sympy.functions.elementary.complexes.im
426
+ """
427
+ from sympy.functions.elementary.trigonometric import cos, sin
428
+ re, im = self.args[0].as_real_imag()
429
+ if deep:
430
+ re = re.expand(deep, **hints)
431
+ im = im.expand(deep, **hints)
432
+ cos, sin = cos(im), sin(im)
433
+ return (exp(re)*cos, exp(re)*sin)
434
+
435
+ def _eval_subs(self, old, new):
436
+ # keep processing of power-like args centralized in Pow
437
+ if old.is_Pow: # handle (exp(3*log(x))).subs(x**2, z) -> z**(3/2)
438
+ old = exp(old.exp*log(old.base))
439
+ elif old is S.Exp1 and new.is_Function:
440
+ old = exp
441
+ if isinstance(old, exp) or old is S.Exp1:
442
+ f = lambda a: Pow(*a.as_base_exp(), evaluate=False) if (
443
+ a.is_Pow or isinstance(a, exp)) else a
444
+ return Pow._eval_subs(f(self), f(old), new)
445
+
446
+ if old is exp and not new.is_Function:
447
+ return new**self.exp._subs(old, new)
448
+ return Function._eval_subs(self, old, new)
449
+
450
+ def _eval_is_extended_real(self):
451
+ if self.args[0].is_extended_real:
452
+ return True
453
+ elif self.args[0].is_imaginary:
454
+ arg2 = -S(2) * I * self.args[0] / pi
455
+ return arg2.is_even
456
+
457
+ def _eval_is_complex(self):
458
+ def complex_extended_negative(arg):
459
+ yield arg.is_complex
460
+ yield arg.is_extended_negative
461
+ return fuzzy_or(complex_extended_negative(self.args[0]))
462
+
463
+ def _eval_is_algebraic(self):
464
+ if (self.exp / pi / I).is_rational:
465
+ return True
466
+ if fuzzy_not(self.exp.is_zero):
467
+ if self.exp.is_algebraic:
468
+ return False
469
+ elif (self.exp / pi).is_rational:
470
+ return False
471
+
472
+ def _eval_is_extended_positive(self):
473
+ if self.exp.is_extended_real:
474
+ return self.args[0] is not S.NegativeInfinity
475
+ elif self.exp.is_imaginary:
476
+ arg2 = -I * self.args[0] / pi
477
+ return arg2.is_even
478
+
479
+ def _eval_nseries(self, x, n, logx, cdir=0):
480
+ # NOTE Please see the comment at the beginning of this file, labelled
481
+ # IMPORTANT.
482
+ from sympy.functions.elementary.complexes import sign
483
+ from sympy.functions.elementary.integers import ceiling
484
+ from sympy.series.limits import limit
485
+ from sympy.series.order import Order
486
+ from sympy.simplify.powsimp import powsimp
487
+ arg = self.exp
488
+ arg_series = arg._eval_nseries(x, n=n, logx=logx)
489
+ if arg_series.is_Order:
490
+ return 1 + arg_series
491
+ arg0 = limit(arg_series.removeO(), x, 0)
492
+ if arg0 is S.NegativeInfinity:
493
+ return Order(x**n, x)
494
+ if arg0 is S.Infinity:
495
+ return self
496
+ # checking for indecisiveness/ sign terms in arg0
497
+ if any(isinstance(arg, (sign, ImaginaryUnit)) for arg in arg0.args):
498
+ return self
499
+ t = Dummy("t")
500
+ nterms = n
501
+ try:
502
+ cf = Order(arg.as_leading_term(x, logx=logx), x).getn()
503
+ except (NotImplementedError, PoleError):
504
+ cf = 0
505
+ if cf and cf > 0:
506
+ nterms = ceiling(n/cf)
507
+ exp_series = exp(t)._taylor(t, nterms)
508
+ r = exp(arg0)*exp_series.subs(t, arg_series - arg0)
509
+ rep = {logx: log(x)} if logx is not None else {}
510
+ if r.subs(rep) == self:
511
+ return r
512
+ if cf and cf > 1:
513
+ r += Order((arg_series - arg0)**n, x)/x**((cf-1)*n)
514
+ else:
515
+ r += Order((arg_series - arg0)**n, x)
516
+ r = r.expand()
517
+ r = powsimp(r, deep=True, combine='exp')
518
+ # powsimp may introduce unexpanded (-1)**Rational; see PR #17201
519
+ simplerat = lambda x: x.is_Rational and x.q in [3, 4, 6]
520
+ w = Wild('w', properties=[simplerat])
521
+ r = r.replace(S.NegativeOne**w, expand_complex(S.NegativeOne**w))
522
+ return r
523
+
524
+ def _taylor(self, x, n):
525
+ l = []
526
+ g = None
527
+ for i in range(n):
528
+ g = self.taylor_term(i, self.args[0], g)
529
+ g = g.nseries(x, n=n)
530
+ l.append(g.removeO())
531
+ return Add(*l)
532
+
533
+ def _eval_as_leading_term(self, x, logx=None, cdir=0):
534
+ from sympy.calculus.util import AccumBounds
535
+ arg = self.args[0].cancel().as_leading_term(x, logx=logx)
536
+ arg0 = arg.subs(x, 0)
537
+ if arg is S.NaN:
538
+ return S.NaN
539
+ if isinstance(arg0, AccumBounds):
540
+ # This check addresses a corner case involving AccumBounds.
541
+ # if isinstance(arg, AccumBounds) is True, then arg0 can either be 0,
542
+ # AccumBounds(-oo, 0) or AccumBounds(-oo, oo).
543
+ # Check out function: test_issue_18473() in test_exponential.py and
544
+ # test_limits.py for more information.
545
+ if re(cdir) < S.Zero:
546
+ return exp(-arg0)
547
+ return exp(arg0)
548
+ if arg0 is S.NaN:
549
+ arg0 = arg.limit(x, 0)
550
+ if arg0.is_infinite is False:
551
+ return exp(arg0)
552
+ raise PoleError("Cannot expand %s around 0" % (self))
553
+
554
+ def _eval_rewrite_as_sin(self, arg, **kwargs):
555
+ from sympy.functions.elementary.trigonometric import sin
556
+ return sin(I*arg + pi/2) - I*sin(I*arg)
557
+
558
+ def _eval_rewrite_as_cos(self, arg, **kwargs):
559
+ from sympy.functions.elementary.trigonometric import cos
560
+ return cos(I*arg) + I*cos(I*arg + pi/2)
561
+
562
+ def _eval_rewrite_as_tanh(self, arg, **kwargs):
563
+ from sympy.functions.elementary.hyperbolic import tanh
564
+ return (1 + tanh(arg/2))/(1 - tanh(arg/2))
565
+
566
+ def _eval_rewrite_as_sqrt(self, arg, **kwargs):
567
+ from sympy.functions.elementary.trigonometric import sin, cos
568
+ if arg.is_Mul:
569
+ coeff = arg.coeff(pi*I)
570
+ if coeff and coeff.is_number:
571
+ cosine, sine = cos(pi*coeff), sin(pi*coeff)
572
+ if not isinstance(cosine, cos) and not isinstance (sine, sin):
573
+ return cosine + I*sine
574
+
575
+ def _eval_rewrite_as_Pow(self, arg, **kwargs):
576
+ if arg.is_Mul:
577
+ logs = [a for a in arg.args if isinstance(a, log) and len(a.args) == 1]
578
+ if logs:
579
+ return Pow(logs[0].args[0], arg.coeff(logs[0]))
580
+
581
+
582
+ def match_real_imag(expr):
583
+ r"""
584
+ Try to match expr with $a + Ib$ for real $a$ and $b$.
585
+
586
+ ``match_real_imag`` returns a tuple containing the real and imaginary
587
+ parts of expr or ``(None, None)`` if direct matching is not possible. Contrary
588
+ to :func:`~.re()`, :func:`~.im()``, and ``as_real_imag()``, this helper will not force things
589
+ by returning expressions themselves containing ``re()`` or ``im()`` and it
590
+ does not expand its argument either.
591
+
592
+ """
593
+ r_, i_ = expr.as_independent(I, as_Add=True)
594
+ if i_ == 0 and r_.is_real:
595
+ return (r_, i_)
596
+ i_ = i_.as_coefficient(I)
597
+ if i_ and i_.is_real and r_.is_real:
598
+ return (r_, i_)
599
+ else:
600
+ return (None, None) # simpler to check for than None
601
+
602
+
603
+ class log(Function):
604
+ r"""
605
+ The natural logarithm function `\ln(x)` or `\log(x)`.
606
+
607
+ Explanation
608
+ ===========
609
+
610
+ Logarithms are taken with the natural base, `e`. To get
611
+ a logarithm of a different base ``b``, use ``log(x, b)``,
612
+ which is essentially short-hand for ``log(x)/log(b)``.
613
+
614
+ ``log`` represents the principal branch of the natural
615
+ logarithm. As such it has a branch cut along the negative
616
+ real axis and returns values having a complex argument in
617
+ `(-\pi, \pi]`.
618
+
619
+ Examples
620
+ ========
621
+
622
+ >>> from sympy import log, sqrt, S, I
623
+ >>> log(8, 2)
624
+ 3
625
+ >>> log(S(8)/3, 2)
626
+ -log(3)/log(2) + 3
627
+ >>> log(-1 + I*sqrt(3))
628
+ log(2) + 2*I*pi/3
629
+
630
+ See Also
631
+ ========
632
+
633
+ exp
634
+
635
+ """
636
+
637
+ args: tTuple[Expr]
638
+
639
+ _singularities = (S.Zero, S.ComplexInfinity)
640
+
641
+ def fdiff(self, argindex=1):
642
+ """
643
+ Returns the first derivative of the function.
644
+ """
645
+ if argindex == 1:
646
+ return 1/self.args[0]
647
+ else:
648
+ raise ArgumentIndexError(self, argindex)
649
+
650
+ def inverse(self, argindex=1):
651
+ r"""
652
+ Returns `e^x`, the inverse function of `\log(x)`.
653
+ """
654
+ return exp
655
+
656
+ @classmethod
657
+ def eval(cls, arg, base=None):
658
+ from sympy.calculus import AccumBounds
659
+ from sympy.sets.setexpr import SetExpr
660
+
661
+ arg = sympify(arg)
662
+
663
+ if base is not None:
664
+ base = sympify(base)
665
+ if base == 1:
666
+ if arg == 1:
667
+ return S.NaN
668
+ else:
669
+ return S.ComplexInfinity
670
+ try:
671
+ # handle extraction of powers of the base now
672
+ # or else expand_log in Mul would have to handle this
673
+ n = multiplicity(base, arg)
674
+ if n:
675
+ return n + log(arg / base**n) / log(base)
676
+ else:
677
+ return log(arg)/log(base)
678
+ except ValueError:
679
+ pass
680
+ if base is not S.Exp1:
681
+ return cls(arg)/cls(base)
682
+ else:
683
+ return cls(arg)
684
+
685
+ if arg.is_Number:
686
+ if arg.is_zero:
687
+ return S.ComplexInfinity
688
+ elif arg is S.One:
689
+ return S.Zero
690
+ elif arg is S.Infinity:
691
+ return S.Infinity
692
+ elif arg is S.NegativeInfinity:
693
+ return S.Infinity
694
+ elif arg is S.NaN:
695
+ return S.NaN
696
+ elif arg.is_Rational and arg.p == 1:
697
+ return -cls(arg.q)
698
+
699
+ if arg.is_Pow and arg.base is S.Exp1 and arg.exp.is_extended_real:
700
+ return arg.exp
701
+ if isinstance(arg, exp) and arg.exp.is_extended_real:
702
+ return arg.exp
703
+ elif isinstance(arg, exp) and arg.exp.is_number:
704
+ r_, i_ = match_real_imag(arg.exp)
705
+ if i_ and i_.is_comparable:
706
+ i_ %= 2*pi
707
+ if i_ > pi:
708
+ i_ -= 2*pi
709
+ return r_ + expand_mul(i_ * I, deep=False)
710
+ elif isinstance(arg, exp_polar):
711
+ return unpolarify(arg.exp)
712
+ elif isinstance(arg, AccumBounds):
713
+ if arg.min.is_positive:
714
+ return AccumBounds(log(arg.min), log(arg.max))
715
+ elif arg.min.is_zero:
716
+ return AccumBounds(S.NegativeInfinity, log(arg.max))
717
+ else:
718
+ return S.NaN
719
+ elif isinstance(arg, SetExpr):
720
+ return arg._eval_func(cls)
721
+
722
+ if arg.is_number:
723
+ if arg.is_negative:
724
+ return pi * I + cls(-arg)
725
+ elif arg is S.ComplexInfinity:
726
+ return S.ComplexInfinity
727
+ elif arg is S.Exp1:
728
+ return S.One
729
+
730
+ if arg.is_zero:
731
+ return S.ComplexInfinity
732
+
733
+ # don't autoexpand Pow or Mul (see the issue 3351):
734
+ if not arg.is_Add:
735
+ coeff = arg.as_coefficient(I)
736
+
737
+ if coeff is not None:
738
+ if coeff is S.Infinity:
739
+ return S.Infinity
740
+ elif coeff is S.NegativeInfinity:
741
+ return S.Infinity
742
+ elif coeff.is_Rational:
743
+ if coeff.is_nonnegative:
744
+ return pi * I * S.Half + cls(coeff)
745
+ else:
746
+ return -pi * I * S.Half + cls(-coeff)
747
+
748
+ if arg.is_number and arg.is_algebraic:
749
+ # Match arg = coeff*(r_ + i_*I) with coeff>0, r_ and i_ real.
750
+ coeff, arg_ = arg.as_independent(I, as_Add=False)
751
+ if coeff.is_negative:
752
+ coeff *= -1
753
+ arg_ *= -1
754
+ arg_ = expand_mul(arg_, deep=False)
755
+ r_, i_ = arg_.as_independent(I, as_Add=True)
756
+ i_ = i_.as_coefficient(I)
757
+ if coeff.is_real and i_ and i_.is_real and r_.is_real:
758
+ if r_.is_zero:
759
+ if i_.is_positive:
760
+ return pi * I * S.Half + cls(coeff * i_)
761
+ elif i_.is_negative:
762
+ return -pi * I * S.Half + cls(coeff * -i_)
763
+ else:
764
+ from sympy.simplify import ratsimp
765
+ # Check for arguments involving rational multiples of pi
766
+ t = (i_/r_).cancel()
767
+ t1 = (-t).cancel()
768
+ atan_table = _log_atan_table()
769
+ if t in atan_table:
770
+ modulus = ratsimp(coeff * Abs(arg_))
771
+ if r_.is_positive:
772
+ return cls(modulus) + I * atan_table[t]
773
+ else:
774
+ return cls(modulus) + I * (atan_table[t] - pi)
775
+ elif t1 in atan_table:
776
+ modulus = ratsimp(coeff * Abs(arg_))
777
+ if r_.is_positive:
778
+ return cls(modulus) + I * (-atan_table[t1])
779
+ else:
780
+ return cls(modulus) + I * (pi - atan_table[t1])
781
+
782
+ def as_base_exp(self):
783
+ """
784
+ Returns this function in the form (base, exponent).
785
+ """
786
+ return self, S.One
787
+
788
+ @staticmethod
789
+ @cacheit
790
+ def taylor_term(n, x, *previous_terms): # of log(1+x)
791
+ r"""
792
+ Returns the next term in the Taylor series expansion of `\log(1+x)`.
793
+ """
794
+ from sympy.simplify.powsimp import powsimp
795
+ if n < 0:
796
+ return S.Zero
797
+ x = sympify(x)
798
+ if n == 0:
799
+ return x
800
+ if previous_terms:
801
+ p = previous_terms[-1]
802
+ if p is not None:
803
+ return powsimp((-n) * p * x / (n + 1), deep=True, combine='exp')
804
+ return (1 - 2*(n % 2)) * x**(n + 1)/(n + 1)
805
+
806
+ def _eval_expand_log(self, deep=True, **hints):
807
+ from sympy.concrete import Sum, Product
808
+ force = hints.get('force', False)
809
+ factor = hints.get('factor', False)
810
+ if (len(self.args) == 2):
811
+ return expand_log(self.func(*self.args), deep=deep, force=force)
812
+ arg = self.args[0]
813
+ if arg.is_Integer:
814
+ # remove perfect powers
815
+ p = perfect_power(arg)
816
+ logarg = None
817
+ coeff = 1
818
+ if p is not False:
819
+ arg, coeff = p
820
+ logarg = self.func(arg)
821
+ # expand as product of its prime factors if factor=True
822
+ if factor:
823
+ p = factorint(arg)
824
+ if arg not in p.keys():
825
+ logarg = sum(n*log(val) for val, n in p.items())
826
+ if logarg is not None:
827
+ return coeff*logarg
828
+ elif arg.is_Rational:
829
+ return log(arg.p) - log(arg.q)
830
+ elif arg.is_Mul:
831
+ expr = []
832
+ nonpos = []
833
+ for x in arg.args:
834
+ if force or x.is_positive or x.is_polar:
835
+ a = self.func(x)
836
+ if isinstance(a, log):
837
+ expr.append(self.func(x)._eval_expand_log(**hints))
838
+ else:
839
+ expr.append(a)
840
+ elif x.is_negative:
841
+ a = self.func(-x)
842
+ expr.append(a)
843
+ nonpos.append(S.NegativeOne)
844
+ else:
845
+ nonpos.append(x)
846
+ return Add(*expr) + log(Mul(*nonpos))
847
+ elif arg.is_Pow or isinstance(arg, exp):
848
+ if force or (arg.exp.is_extended_real and (arg.base.is_positive or ((arg.exp+1)
849
+ .is_positive and (arg.exp-1).is_nonpositive))) or arg.base.is_polar:
850
+ b = arg.base
851
+ e = arg.exp
852
+ a = self.func(b)
853
+ if isinstance(a, log):
854
+ return unpolarify(e) * a._eval_expand_log(**hints)
855
+ else:
856
+ return unpolarify(e) * a
857
+ elif isinstance(arg, Product):
858
+ if force or arg.function.is_positive:
859
+ return Sum(log(arg.function), *arg.limits)
860
+
861
+ return self.func(arg)
862
+
863
+ def _eval_simplify(self, **kwargs):
864
+ from sympy.simplify.simplify import expand_log, simplify, inversecombine
865
+ if len(self.args) == 2: # it's unevaluated
866
+ return simplify(self.func(*self.args), **kwargs)
867
+
868
+ expr = self.func(simplify(self.args[0], **kwargs))
869
+ if kwargs['inverse']:
870
+ expr = inversecombine(expr)
871
+ expr = expand_log(expr, deep=True)
872
+ return min([expr, self], key=kwargs['measure'])
873
+
874
+ def as_real_imag(self, deep=True, **hints):
875
+ """
876
+ Returns this function as a complex coordinate.
877
+
878
+ Examples
879
+ ========
880
+
881
+ >>> from sympy import I, log
882
+ >>> from sympy.abc import x
883
+ >>> log(x).as_real_imag()
884
+ (log(Abs(x)), arg(x))
885
+ >>> log(I).as_real_imag()
886
+ (0, pi/2)
887
+ >>> log(1 + I).as_real_imag()
888
+ (log(sqrt(2)), pi/4)
889
+ >>> log(I*x).as_real_imag()
890
+ (log(Abs(x)), arg(I*x))
891
+
892
+ """
893
+ sarg = self.args[0]
894
+ if deep:
895
+ sarg = self.args[0].expand(deep, **hints)
896
+ sarg_abs = Abs(sarg)
897
+ if sarg_abs == sarg:
898
+ return self, S.Zero
899
+ sarg_arg = arg(sarg)
900
+ if hints.get('log', False): # Expand the log
901
+ hints['complex'] = False
902
+ return (log(sarg_abs).expand(deep, **hints), sarg_arg)
903
+ else:
904
+ return log(sarg_abs), sarg_arg
905
+
906
+ def _eval_is_rational(self):
907
+ s = self.func(*self.args)
908
+ if s.func == self.func:
909
+ if (self.args[0] - 1).is_zero:
910
+ return True
911
+ if s.args[0].is_rational and fuzzy_not((self.args[0] - 1).is_zero):
912
+ return False
913
+ else:
914
+ return s.is_rational
915
+
916
+ def _eval_is_algebraic(self):
917
+ s = self.func(*self.args)
918
+ if s.func == self.func:
919
+ if (self.args[0] - 1).is_zero:
920
+ return True
921
+ elif fuzzy_not((self.args[0] - 1).is_zero):
922
+ if self.args[0].is_algebraic:
923
+ return False
924
+ else:
925
+ return s.is_algebraic
926
+
927
+ def _eval_is_extended_real(self):
928
+ return self.args[0].is_extended_positive
929
+
930
+ def _eval_is_complex(self):
931
+ z = self.args[0]
932
+ return fuzzy_and([z.is_complex, fuzzy_not(z.is_zero)])
933
+
934
+ def _eval_is_finite(self):
935
+ arg = self.args[0]
936
+ if arg.is_zero:
937
+ return False
938
+ return arg.is_finite
939
+
940
+ def _eval_is_extended_positive(self):
941
+ return (self.args[0] - 1).is_extended_positive
942
+
943
+ def _eval_is_zero(self):
944
+ return (self.args[0] - 1).is_zero
945
+
946
+ def _eval_is_extended_nonnegative(self):
947
+ return (self.args[0] - 1).is_extended_nonnegative
948
+
949
+ def _eval_nseries(self, x, n, logx, cdir=0):
950
+ # NOTE Please see the comment at the beginning of this file, labelled
951
+ # IMPORTANT.
952
+ from sympy.series.order import Order
953
+ from sympy.simplify.simplify import logcombine
954
+ from sympy.core.symbol import Dummy
955
+
956
+ if self.args[0] == x:
957
+ return log(x) if logx is None else logx
958
+ arg = self.args[0]
959
+ t = Dummy('t', positive=True)
960
+ if cdir == 0:
961
+ cdir = 1
962
+ z = arg.subs(x, cdir*t)
963
+
964
+ k, l = Wild("k"), Wild("l")
965
+ r = z.match(k*t**l)
966
+ if r is not None:
967
+ k, l = r[k], r[l]
968
+ if l != 0 and not l.has(t) and not k.has(t):
969
+ r = l*log(x) if logx is None else l*logx
970
+ r += log(k) - l*log(cdir) # XXX true regardless of assumptions?
971
+ return r
972
+
973
+ def coeff_exp(term, x):
974
+ coeff, exp = S.One, S.Zero
975
+ for factor in Mul.make_args(term):
976
+ if factor.has(x):
977
+ base, exp = factor.as_base_exp()
978
+ if base != x:
979
+ try:
980
+ return term.leadterm(x)
981
+ except ValueError:
982
+ return term, S.Zero
983
+ else:
984
+ coeff *= factor
985
+ return coeff, exp
986
+
987
+ # TODO new and probably slow
988
+ try:
989
+ a, b = z.leadterm(t, logx=logx, cdir=1)
990
+ except (ValueError, NotImplementedError, PoleError):
991
+ s = z._eval_nseries(t, n=n, logx=logx, cdir=1)
992
+ while s.is_Order:
993
+ n += 1
994
+ s = z._eval_nseries(t, n=n, logx=logx, cdir=1)
995
+ try:
996
+ a, b = s.removeO().leadterm(t, cdir=1)
997
+ except ValueError:
998
+ a, b = s.removeO().as_leading_term(t, cdir=1), S.Zero
999
+
1000
+ p = (z/(a*t**b) - 1)._eval_nseries(t, n=n, logx=logx, cdir=1)
1001
+ if p.has(exp):
1002
+ p = logcombine(p)
1003
+ if isinstance(p, Order):
1004
+ n = p.getn()
1005
+ _, d = coeff_exp(p, t)
1006
+ logx = log(x) if logx is None else logx
1007
+
1008
+ if not d.is_positive:
1009
+ res = log(a) - b*log(cdir) + b*logx
1010
+ _res = res
1011
+ logflags = {"deep": True, "log": True, "mul": False, "power_exp": False,
1012
+ "power_base": False, "multinomial": False, "basic": False, "force": True,
1013
+ "factor": False}
1014
+ expr = self.expand(**logflags)
1015
+ if (not a.could_extract_minus_sign() and
1016
+ logx.could_extract_minus_sign()):
1017
+ _res = _res.subs(-logx, -log(x)).expand(**logflags)
1018
+ else:
1019
+ _res = _res.subs(logx, log(x)).expand(**logflags)
1020
+ if _res == expr:
1021
+ return res
1022
+ return res + Order(x**n, x)
1023
+
1024
+ def mul(d1, d2):
1025
+ res = {}
1026
+ for e1, e2 in product(d1, d2):
1027
+ ex = e1 + e2
1028
+ if ex < n:
1029
+ res[ex] = res.get(ex, S.Zero) + d1[e1]*d2[e2]
1030
+ return res
1031
+
1032
+ pterms = {}
1033
+
1034
+ for term in Add.make_args(p.removeO()):
1035
+ co1, e1 = coeff_exp(term, t)
1036
+ pterms[e1] = pterms.get(e1, S.Zero) + co1
1037
+
1038
+ k = S.One
1039
+ terms = {}
1040
+ pk = pterms
1041
+
1042
+ while k*d < n:
1043
+ coeff = -S.NegativeOne**k/k
1044
+ for ex in pk:
1045
+ _ = terms.get(ex, S.Zero) + coeff*pk[ex]
1046
+ terms[ex] = _.nsimplify()
1047
+ pk = mul(pk, pterms)
1048
+ k += S.One
1049
+
1050
+ res = log(a) - b*log(cdir) + b*logx
1051
+ for ex in terms:
1052
+ res += terms[ex]*t**(ex)
1053
+
1054
+ if a.is_negative and im(z) != 0:
1055
+ from sympy.functions.special.delta_functions import Heaviside
1056
+ for i, term in enumerate(z.lseries(t)):
1057
+ if not term.is_real or i == 5:
1058
+ break
1059
+ if i < 5:
1060
+ coeff, _ = term.as_coeff_exponent(t)
1061
+ res += -2*I*pi*Heaviside(-im(coeff), 0)
1062
+
1063
+ res = res.subs(t, x/cdir)
1064
+ return res + Order(x**n, x)
1065
+
1066
+ def _eval_as_leading_term(self, x, logx=None, cdir=0):
1067
+ # NOTE
1068
+ # Refer https://github.com/sympy/sympy/pull/23592 for more information
1069
+ # on each of the following steps involved in this method.
1070
+ arg0 = self.args[0].together()
1071
+
1072
+ # STEP 1
1073
+ t = Dummy('t', positive=True)
1074
+ if cdir == 0:
1075
+ cdir = 1
1076
+ z = arg0.subs(x, cdir*t)
1077
+
1078
+ # STEP 2
1079
+ try:
1080
+ c, e = z.leadterm(t, logx=logx, cdir=1)
1081
+ except ValueError:
1082
+ arg = arg0.as_leading_term(x, logx=logx, cdir=cdir)
1083
+ return log(arg)
1084
+ if c.has(t):
1085
+ c = c.subs(t, x/cdir)
1086
+ if e != 0:
1087
+ raise PoleError("Cannot expand %s around 0" % (self))
1088
+ return log(c)
1089
+
1090
+ # STEP 3
1091
+ if c == S.One and e == S.Zero:
1092
+ return (arg0 - S.One).as_leading_term(x, logx=logx)
1093
+
1094
+ # STEP 4
1095
+ res = log(c) - e*log(cdir)
1096
+ logx = log(x) if logx is None else logx
1097
+ res += e*logx
1098
+
1099
+ # STEP 5
1100
+ if c.is_negative and im(z) != 0:
1101
+ from sympy.functions.special.delta_functions import Heaviside
1102
+ for i, term in enumerate(z.lseries(t)):
1103
+ if not term.is_real or i == 5:
1104
+ break
1105
+ if i < 5:
1106
+ coeff, _ = term.as_coeff_exponent(t)
1107
+ res += -2*I*pi*Heaviside(-im(coeff), 0)
1108
+ return res
1109
+
1110
+
1111
+ class LambertW(Function):
1112
+ r"""
1113
+ The Lambert W function $W(z)$ is defined as the inverse
1114
+ function of $w \exp(w)$ [1]_.
1115
+
1116
+ Explanation
1117
+ ===========
1118
+
1119
+ In other words, the value of $W(z)$ is such that $z = W(z) \exp(W(z))$
1120
+ for any complex number $z$. The Lambert W function is a multivalued
1121
+ function with infinitely many branches $W_k(z)$, indexed by
1122
+ $k \in \mathbb{Z}$. Each branch gives a different solution $w$
1123
+ of the equation $z = w \exp(w)$.
1124
+
1125
+ The Lambert W function has two partially real branches: the
1126
+ principal branch ($k = 0$) is real for real $z > -1/e$, and the
1127
+ $k = -1$ branch is real for $-1/e < z < 0$. All branches except
1128
+ $k = 0$ have a logarithmic singularity at $z = 0$.
1129
+
1130
+ Examples
1131
+ ========
1132
+
1133
+ >>> from sympy import LambertW
1134
+ >>> LambertW(1.2)
1135
+ 0.635564016364870
1136
+ >>> LambertW(1.2, -1).n()
1137
+ -1.34747534407696 - 4.41624341514535*I
1138
+ >>> LambertW(-1).is_real
1139
+ False
1140
+
1141
+ References
1142
+ ==========
1143
+
1144
+ .. [1] https://en.wikipedia.org/wiki/Lambert_W_function
1145
+ """
1146
+ _singularities = (-Pow(S.Exp1, -1, evaluate=False), S.ComplexInfinity)
1147
+
1148
+ @classmethod
1149
+ def eval(cls, x, k=None):
1150
+ if k == S.Zero:
1151
+ return cls(x)
1152
+ elif k is None:
1153
+ k = S.Zero
1154
+
1155
+ if k.is_zero:
1156
+ if x.is_zero:
1157
+ return S.Zero
1158
+ if x is S.Exp1:
1159
+ return S.One
1160
+ if x == -1/S.Exp1:
1161
+ return S.NegativeOne
1162
+ if x == -log(2)/2:
1163
+ return -log(2)
1164
+ if x == 2*log(2):
1165
+ return log(2)
1166
+ if x == -pi/2:
1167
+ return I*pi/2
1168
+ if x == exp(1 + S.Exp1):
1169
+ return S.Exp1
1170
+ if x is S.Infinity:
1171
+ return S.Infinity
1172
+ if x.is_zero:
1173
+ return S.Zero
1174
+
1175
+ if fuzzy_not(k.is_zero):
1176
+ if x.is_zero:
1177
+ return S.NegativeInfinity
1178
+ if k is S.NegativeOne:
1179
+ if x == -pi/2:
1180
+ return -I*pi/2
1181
+ elif x == -1/S.Exp1:
1182
+ return S.NegativeOne
1183
+ elif x == -2*exp(-2):
1184
+ return -Integer(2)
1185
+
1186
+ def fdiff(self, argindex=1):
1187
+ """
1188
+ Return the first derivative of this function.
1189
+ """
1190
+ x = self.args[0]
1191
+
1192
+ if len(self.args) == 1:
1193
+ if argindex == 1:
1194
+ return LambertW(x)/(x*(1 + LambertW(x)))
1195
+ else:
1196
+ k = self.args[1]
1197
+ if argindex == 1:
1198
+ return LambertW(x, k)/(x*(1 + LambertW(x, k)))
1199
+
1200
+ raise ArgumentIndexError(self, argindex)
1201
+
1202
+ def _eval_is_extended_real(self):
1203
+ x = self.args[0]
1204
+ if len(self.args) == 1:
1205
+ k = S.Zero
1206
+ else:
1207
+ k = self.args[1]
1208
+ if k.is_zero:
1209
+ if (x + 1/S.Exp1).is_positive:
1210
+ return True
1211
+ elif (x + 1/S.Exp1).is_nonpositive:
1212
+ return False
1213
+ elif (k + 1).is_zero:
1214
+ if x.is_negative and (x + 1/S.Exp1).is_positive:
1215
+ return True
1216
+ elif x.is_nonpositive or (x + 1/S.Exp1).is_nonnegative:
1217
+ return False
1218
+ elif fuzzy_not(k.is_zero) and fuzzy_not((k + 1).is_zero):
1219
+ if x.is_extended_real:
1220
+ return False
1221
+
1222
+ def _eval_is_finite(self):
1223
+ return self.args[0].is_finite
1224
+
1225
+ def _eval_is_algebraic(self):
1226
+ s = self.func(*self.args)
1227
+ if s.func == self.func:
1228
+ if fuzzy_not(self.args[0].is_zero) and self.args[0].is_algebraic:
1229
+ return False
1230
+ else:
1231
+ return s.is_algebraic
1232
+
1233
+ def _eval_as_leading_term(self, x, logx=None, cdir=0):
1234
+ if len(self.args) == 1:
1235
+ arg = self.args[0]
1236
+ arg0 = arg.subs(x, 0).cancel()
1237
+ if not arg0.is_zero:
1238
+ return self.func(arg0)
1239
+ return arg.as_leading_term(x)
1240
+
1241
+ def _eval_nseries(self, x, n, logx, cdir=0):
1242
+ if len(self.args) == 1:
1243
+ from sympy.functions.elementary.integers import ceiling
1244
+ from sympy.series.order import Order
1245
+ arg = self.args[0].nseries(x, n=n, logx=logx)
1246
+ lt = arg.as_leading_term(x, logx=logx)
1247
+ lte = 1
1248
+ if lt.is_Pow:
1249
+ lte = lt.exp
1250
+ if ceiling(n/lte) >= 1:
1251
+ s = Add(*[(-S.One)**(k - 1)*Integer(k)**(k - 2)/
1252
+ factorial(k - 1)*arg**k for k in range(1, ceiling(n/lte))])
1253
+ s = expand_multinomial(s)
1254
+ else:
1255
+ s = S.Zero
1256
+
1257
+ return s + Order(x**n, x)
1258
+ return super()._eval_nseries(x, n, logx)
1259
+
1260
+ def _eval_is_zero(self):
1261
+ x = self.args[0]
1262
+ if len(self.args) == 1:
1263
+ return x.is_zero
1264
+ else:
1265
+ return fuzzy_and([x.is_zero, self.args[1].is_zero])
1266
+
1267
+
1268
+ @cacheit
1269
+ def _log_atan_table():
1270
+ return {
1271
+ # first quadrant only
1272
+ sqrt(3): pi / 3,
1273
+ 1: pi / 4,
1274
+ sqrt(5 - 2 * sqrt(5)): pi / 5,
1275
+ sqrt(2) * sqrt(5 - sqrt(5)) / (1 + sqrt(5)): pi / 5,
1276
+ sqrt(5 + 2 * sqrt(5)): pi * Rational(2, 5),
1277
+ sqrt(2) * sqrt(sqrt(5) + 5) / (-1 + sqrt(5)): pi * Rational(2, 5),
1278
+ sqrt(3) / 3: pi / 6,
1279
+ sqrt(2) - 1: pi / 8,
1280
+ sqrt(2 - sqrt(2)) / sqrt(sqrt(2) + 2): pi / 8,
1281
+ sqrt(2) + 1: pi * Rational(3, 8),
1282
+ sqrt(sqrt(2) + 2) / sqrt(2 - sqrt(2)): pi * Rational(3, 8),
1283
+ sqrt(1 - 2 * sqrt(5) / 5): pi / 10,
1284
+ (-sqrt(2) + sqrt(10)) / (2 * sqrt(sqrt(5) + 5)): pi / 10,
1285
+ sqrt(1 + 2 * sqrt(5) / 5): pi * Rational(3, 10),
1286
+ (sqrt(2) + sqrt(10)) / (2 * sqrt(5 - sqrt(5))): pi * Rational(3, 10),
1287
+ 2 - sqrt(3): pi / 12,
1288
+ (-1 + sqrt(3)) / (1 + sqrt(3)): pi / 12,
1289
+ 2 + sqrt(3): pi * Rational(5, 12),
1290
+ (1 + sqrt(3)) / (-1 + sqrt(3)): pi * Rational(5, 12)
1291
+ }
llmeval-env/lib/python3.10/site-packages/sympy/functions/elementary/hyperbolic.py ADDED
@@ -0,0 +1,2203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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, 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)
499
+
500
+ def _eval_rewrite_as_sec(self, arg, **kwargs):
501
+ return 1 / sec(I * arg)
502
+
503
+ def _eval_rewrite_as_sinh(self, arg, **kwargs):
504
+ return -I*sinh(arg + pi*I/2)
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)
757
+
758
+ def _eval_rewrite_as_cot(self, arg, **kwargs):
759
+ return -I / cot(I * arg)
760
+
761
+ def _eval_rewrite_as_sinh(self, arg, **kwargs):
762
+ return I*sinh(arg)/sinh(pi*I/2 - arg)
763
+
764
+ def _eval_rewrite_as_cosh(self, arg, **kwargs):
765
+ return I*cosh(pi*I/2 - arg)/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)/sinh(arg)
952
+
953
+ def _eval_rewrite_as_cosh(self, arg, **kwargs):
954
+ return -I*cosh(arg)/cosh(pi*I/2 - arg)
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)
1122
+
1123
+ def _eval_rewrite_as_csc(self, arg, **kwargs):
1124
+ return I * csc(I * arg)
1125
+
1126
+ def _eval_rewrite_as_cosh(self, arg, **kwargs):
1127
+ return I / cosh(arg + I * pi / 2)
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)
1181
+
1182
+ def _eval_rewrite_as_sec(self, arg, **kwargs):
1183
+ return sec(I * arg)
1184
+
1185
+ def _eval_rewrite_as_sinh(self, arg, **kwargs):
1186
+ return I / sinh(arg + I * pi /2)
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
+ # Handling branch points
1302
+ if x0 in (-I, I, S.ComplexInfinity):
1303
+ return self.rewrite(log)._eval_as_leading_term(x, logx=logx, cdir=cdir)
1304
+ # Handling points lying on branch cuts (-I*oo, -I) U (I, I*oo)
1305
+ if (1 + x0**2).is_negative:
1306
+ ndir = arg.dir(x, cdir if cdir else 1)
1307
+ if re(ndir).is_positive:
1308
+ if im(x0).is_negative:
1309
+ return -self.func(x0) - I*pi
1310
+ elif re(ndir).is_negative:
1311
+ if im(x0).is_positive:
1312
+ return -self.func(x0) + I*pi
1313
+ else:
1314
+ return self.rewrite(log)._eval_as_leading_term(x, logx=logx, cdir=cdir)
1315
+ return self.func(x0)
1316
+
1317
+ def _eval_nseries(self, x, n, logx, cdir=0): # asinh
1318
+ arg = self.args[0]
1319
+ arg0 = arg.subs(x, 0)
1320
+
1321
+ # Handling branch points
1322
+ if arg0 in (I, -I):
1323
+ return self.rewrite(log)._eval_nseries(x, n, logx=logx, cdir=cdir)
1324
+
1325
+ res = Function._eval_nseries(self, x, n=n, logx=logx)
1326
+ if arg0 is S.ComplexInfinity:
1327
+ return res
1328
+
1329
+ # Handling points lying on branch cuts (-I*oo, -I) U (I, I*oo)
1330
+ if (1 + arg0**2).is_negative:
1331
+ ndir = arg.dir(x, cdir if cdir else 1)
1332
+ if re(ndir).is_positive:
1333
+ if im(arg0).is_negative:
1334
+ return -res - I*pi
1335
+ elif re(ndir).is_negative:
1336
+ if im(arg0).is_positive:
1337
+ return -res + I*pi
1338
+ else:
1339
+ return self.rewrite(log)._eval_nseries(x, n, logx=logx, cdir=cdir)
1340
+ return res
1341
+
1342
+ def _eval_rewrite_as_log(self, x, **kwargs):
1343
+ return log(x + sqrt(x**2 + 1))
1344
+
1345
+ _eval_rewrite_as_tractable = _eval_rewrite_as_log
1346
+
1347
+ def _eval_rewrite_as_atanh(self, x, **kwargs):
1348
+ return atanh(x/sqrt(1 + x**2))
1349
+
1350
+ def _eval_rewrite_as_acosh(self, x, **kwargs):
1351
+ ix = I*x
1352
+ return I*(sqrt(1 - ix)/sqrt(ix - 1) * acosh(ix) - pi/2)
1353
+
1354
+ def _eval_rewrite_as_asin(self, x, **kwargs):
1355
+ return -I * asin(I * x)
1356
+
1357
+ def _eval_rewrite_as_acos(self, x, **kwargs):
1358
+ return I * acos(I * x) - I*pi/2
1359
+
1360
+ def inverse(self, argindex=1):
1361
+ """
1362
+ Returns the inverse of this function.
1363
+ """
1364
+ return sinh
1365
+
1366
+ def _eval_is_zero(self):
1367
+ return self.args[0].is_zero
1368
+
1369
+
1370
+ class acosh(InverseHyperbolicFunction):
1371
+ """
1372
+ ``acosh(x)`` is the inverse hyperbolic cosine of ``x``.
1373
+
1374
+ The inverse hyperbolic cosine function.
1375
+
1376
+ Examples
1377
+ ========
1378
+
1379
+ >>> from sympy import acosh
1380
+ >>> from sympy.abc import x
1381
+ >>> acosh(x).diff(x)
1382
+ 1/(sqrt(x - 1)*sqrt(x + 1))
1383
+ >>> acosh(1)
1384
+ 0
1385
+
1386
+ See Also
1387
+ ========
1388
+
1389
+ asinh, atanh, cosh
1390
+ """
1391
+
1392
+ def fdiff(self, argindex=1):
1393
+ if argindex == 1:
1394
+ arg = self.args[0]
1395
+ return 1/(sqrt(arg - 1)*sqrt(arg + 1))
1396
+ else:
1397
+ raise ArgumentIndexError(self, argindex)
1398
+
1399
+ @classmethod
1400
+ def eval(cls, arg):
1401
+ if arg.is_Number:
1402
+ if arg is S.NaN:
1403
+ return S.NaN
1404
+ elif arg is S.Infinity:
1405
+ return S.Infinity
1406
+ elif arg is S.NegativeInfinity:
1407
+ return S.Infinity
1408
+ elif arg.is_zero:
1409
+ return pi*I / 2
1410
+ elif arg is S.One:
1411
+ return S.Zero
1412
+ elif arg is S.NegativeOne:
1413
+ return pi*I
1414
+
1415
+ if arg.is_number:
1416
+ cst_table = _acosh_table()
1417
+
1418
+ if arg in cst_table:
1419
+ if arg.is_extended_real:
1420
+ return cst_table[arg]*I
1421
+ return cst_table[arg]
1422
+
1423
+ if arg is S.ComplexInfinity:
1424
+ return S.ComplexInfinity
1425
+ if arg == I*S.Infinity:
1426
+ return S.Infinity + I*pi/2
1427
+ if arg == -I*S.Infinity:
1428
+ return S.Infinity - I*pi/2
1429
+
1430
+ if arg.is_zero:
1431
+ return pi*I*S.Half
1432
+
1433
+ if isinstance(arg, cosh) and arg.args[0].is_number:
1434
+ z = arg.args[0]
1435
+ if z.is_real:
1436
+ return Abs(z)
1437
+ r, i = match_real_imag(z)
1438
+ if r is not None and i is not None:
1439
+ f = floor(i/pi)
1440
+ m = z - I*pi*f
1441
+ even = f.is_even
1442
+ if even is True:
1443
+ if r.is_nonnegative:
1444
+ return m
1445
+ elif r.is_negative:
1446
+ return -m
1447
+ elif even is False:
1448
+ m -= I*pi
1449
+ if r.is_nonpositive:
1450
+ return -m
1451
+ elif r.is_positive:
1452
+ return m
1453
+
1454
+ @staticmethod
1455
+ @cacheit
1456
+ def taylor_term(n, x, *previous_terms):
1457
+ if n == 0:
1458
+ return I*pi/2
1459
+ elif n < 0 or n % 2 == 0:
1460
+ return S.Zero
1461
+ else:
1462
+ x = sympify(x)
1463
+ if len(previous_terms) >= 2 and n > 2:
1464
+ p = previous_terms[-2]
1465
+ return p * (n - 2)**2/(n*(n - 1)) * x**2
1466
+ else:
1467
+ k = (n - 1) // 2
1468
+ R = RisingFactorial(S.Half, k)
1469
+ F = factorial(k)
1470
+ return -R / F * I * x**n / n
1471
+
1472
+ def _eval_as_leading_term(self, x, logx=None, cdir=0): # acosh
1473
+ arg = self.args[0]
1474
+ x0 = arg.subs(x, 0).cancel()
1475
+ # Handling branch points
1476
+ if x0 in (-S.One, S.Zero, S.One, S.ComplexInfinity):
1477
+ return self.rewrite(log)._eval_as_leading_term(x, logx=logx, cdir=cdir)
1478
+ # Handling points lying on branch cuts (-oo, 1)
1479
+ if (x0 - 1).is_negative:
1480
+ ndir = arg.dir(x, cdir if cdir else 1)
1481
+ if im(ndir).is_negative:
1482
+ if (x0 + 1).is_negative:
1483
+ return self.func(x0) - 2*I*pi
1484
+ return -self.func(x0)
1485
+ elif not im(ndir).is_positive:
1486
+ return self.rewrite(log)._eval_as_leading_term(x, logx=logx, cdir=cdir)
1487
+ return self.func(x0)
1488
+
1489
+ def _eval_nseries(self, x, n, logx, cdir=0): # acosh
1490
+ arg = self.args[0]
1491
+ arg0 = arg.subs(x, 0)
1492
+
1493
+ # Handling branch points
1494
+ if arg0 in (S.One, S.NegativeOne):
1495
+ return self.rewrite(log)._eval_nseries(x, n, logx=logx, cdir=cdir)
1496
+
1497
+ res = Function._eval_nseries(self, x, n=n, logx=logx)
1498
+ if arg0 is S.ComplexInfinity:
1499
+ return res
1500
+
1501
+ # Handling points lying on branch cuts (-oo, 1)
1502
+ if (arg0 - 1).is_negative:
1503
+ ndir = arg.dir(x, cdir if cdir else 1)
1504
+ if im(ndir).is_negative:
1505
+ if (arg0 + 1).is_negative:
1506
+ return res - 2*I*pi
1507
+ return -res
1508
+ elif not im(ndir).is_positive:
1509
+ return self.rewrite(log)._eval_nseries(x, n, logx=logx, cdir=cdir)
1510
+ return res
1511
+
1512
+ def _eval_rewrite_as_log(self, x, **kwargs):
1513
+ return log(x + sqrt(x + 1) * sqrt(x - 1))
1514
+
1515
+ _eval_rewrite_as_tractable = _eval_rewrite_as_log
1516
+
1517
+ def _eval_rewrite_as_acos(self, x, **kwargs):
1518
+ return sqrt(x - 1)/sqrt(1 - x) * acos(x)
1519
+
1520
+ def _eval_rewrite_as_asin(self, x, **kwargs):
1521
+ return sqrt(x - 1)/sqrt(1 - x) * (pi/2 - asin(x))
1522
+
1523
+ def _eval_rewrite_as_asinh(self, x, **kwargs):
1524
+ return sqrt(x - 1)/sqrt(1 - x) * (pi/2 + I*asinh(I*x))
1525
+
1526
+ def _eval_rewrite_as_atanh(self, x, **kwargs):
1527
+ sxm1 = sqrt(x - 1)
1528
+ s1mx = sqrt(1 - x)
1529
+ sx2m1 = sqrt(x**2 - 1)
1530
+ return (pi/2*sxm1/s1mx*(1 - x * sqrt(1/x**2)) +
1531
+ sxm1*sqrt(x + 1)/sx2m1 * atanh(sx2m1/x))
1532
+
1533
+ def inverse(self, argindex=1):
1534
+ """
1535
+ Returns the inverse of this function.
1536
+ """
1537
+ return cosh
1538
+
1539
+ def _eval_is_zero(self):
1540
+ if (self.args[0] - 1).is_zero:
1541
+ return True
1542
+
1543
+
1544
+ class atanh(InverseHyperbolicFunction):
1545
+ """
1546
+ ``atanh(x)`` is the inverse hyperbolic tangent of ``x``.
1547
+
1548
+ The inverse hyperbolic tangent function.
1549
+
1550
+ Examples
1551
+ ========
1552
+
1553
+ >>> from sympy import atanh
1554
+ >>> from sympy.abc import x
1555
+ >>> atanh(x).diff(x)
1556
+ 1/(1 - x**2)
1557
+
1558
+ See Also
1559
+ ========
1560
+
1561
+ asinh, acosh, tanh
1562
+ """
1563
+
1564
+ def fdiff(self, argindex=1):
1565
+ if argindex == 1:
1566
+ return 1/(1 - self.args[0]**2)
1567
+ else:
1568
+ raise ArgumentIndexError(self, argindex)
1569
+
1570
+ @classmethod
1571
+ def eval(cls, arg):
1572
+ if arg.is_Number:
1573
+ if arg is S.NaN:
1574
+ return S.NaN
1575
+ elif arg.is_zero:
1576
+ return S.Zero
1577
+ elif arg is S.One:
1578
+ return S.Infinity
1579
+ elif arg is S.NegativeOne:
1580
+ return S.NegativeInfinity
1581
+ elif arg is S.Infinity:
1582
+ return -I * atan(arg)
1583
+ elif arg is S.NegativeInfinity:
1584
+ return I * atan(-arg)
1585
+ elif arg.is_negative:
1586
+ return -cls(-arg)
1587
+ else:
1588
+ if arg is S.ComplexInfinity:
1589
+ from sympy.calculus.accumulationbounds import AccumBounds
1590
+ return I*AccumBounds(-pi/2, pi/2)
1591
+
1592
+ i_coeff = _imaginary_unit_as_coefficient(arg)
1593
+
1594
+ if i_coeff is not None:
1595
+ return I * atan(i_coeff)
1596
+ else:
1597
+ if arg.could_extract_minus_sign():
1598
+ return -cls(-arg)
1599
+
1600
+ if arg.is_zero:
1601
+ return S.Zero
1602
+
1603
+ if isinstance(arg, tanh) and arg.args[0].is_number:
1604
+ z = arg.args[0]
1605
+ if z.is_real:
1606
+ return z
1607
+ r, i = match_real_imag(z)
1608
+ if r is not None and i is not None:
1609
+ f = floor(2*i/pi)
1610
+ even = f.is_even
1611
+ m = z - I*f*pi/2
1612
+ if even is True:
1613
+ return m
1614
+ elif even is False:
1615
+ return m - I*pi/2
1616
+
1617
+ @staticmethod
1618
+ @cacheit
1619
+ def taylor_term(n, x, *previous_terms):
1620
+ if n < 0 or n % 2 == 0:
1621
+ return S.Zero
1622
+ else:
1623
+ x = sympify(x)
1624
+ return x**n / n
1625
+
1626
+ def _eval_as_leading_term(self, x, logx=None, cdir=0): # atanh
1627
+ arg = self.args[0]
1628
+ x0 = arg.subs(x, 0).cancel()
1629
+ if x0.is_zero:
1630
+ return arg.as_leading_term(x)
1631
+ # Handling branch points
1632
+ if x0 in (-S.One, S.One, S.ComplexInfinity):
1633
+ return self.rewrite(log)._eval_as_leading_term(x, logx=logx, cdir=cdir)
1634
+ # Handling points lying on branch cuts (-oo, -1] U [1, oo)
1635
+ if (1 - x0**2).is_negative:
1636
+ ndir = arg.dir(x, cdir if cdir else 1)
1637
+ if im(ndir).is_negative:
1638
+ if x0.is_negative:
1639
+ return self.func(x0) - I*pi
1640
+ elif im(ndir).is_positive:
1641
+ if x0.is_positive:
1642
+ return self.func(x0) + I*pi
1643
+ else:
1644
+ return self.rewrite(log)._eval_as_leading_term(x, logx=logx, cdir=cdir)
1645
+ return self.func(x0)
1646
+
1647
+ def _eval_nseries(self, x, n, logx, cdir=0): # atanh
1648
+ arg = self.args[0]
1649
+ arg0 = arg.subs(x, 0)
1650
+
1651
+ # Handling branch points
1652
+ if arg0 in (S.One, S.NegativeOne):
1653
+ return self.rewrite(log)._eval_nseries(x, n, logx=logx, cdir=cdir)
1654
+
1655
+ res = Function._eval_nseries(self, x, n=n, logx=logx)
1656
+ if arg0 is S.ComplexInfinity:
1657
+ return res
1658
+
1659
+ # Handling points lying on branch cuts (-oo, -1] U [1, oo)
1660
+ if (1 - arg0**2).is_negative:
1661
+ ndir = arg.dir(x, cdir if cdir else 1)
1662
+ if im(ndir).is_negative:
1663
+ if arg0.is_negative:
1664
+ return res - I*pi
1665
+ elif im(ndir).is_positive:
1666
+ if arg0.is_positive:
1667
+ return res + I*pi
1668
+ else:
1669
+ return self.rewrite(log)._eval_nseries(x, n, logx=logx, cdir=cdir)
1670
+ return res
1671
+
1672
+ def _eval_rewrite_as_log(self, x, **kwargs):
1673
+ return (log(1 + x) - log(1 - x)) / 2
1674
+
1675
+ _eval_rewrite_as_tractable = _eval_rewrite_as_log
1676
+
1677
+ def _eval_rewrite_as_asinh(self, x, **kwargs):
1678
+ f = sqrt(1/(x**2 - 1))
1679
+ return (pi*x/(2*sqrt(-x**2)) -
1680
+ sqrt(-x)*sqrt(1 - x**2)/sqrt(x)*f*asinh(f))
1681
+
1682
+ def _eval_is_zero(self):
1683
+ if self.args[0].is_zero:
1684
+ return True
1685
+
1686
+ def _eval_is_imaginary(self):
1687
+ return self.args[0].is_imaginary
1688
+
1689
+ def inverse(self, argindex=1):
1690
+ """
1691
+ Returns the inverse of this function.
1692
+ """
1693
+ return tanh
1694
+
1695
+
1696
+ class acoth(InverseHyperbolicFunction):
1697
+ """
1698
+ ``acoth(x)`` is the inverse hyperbolic cotangent of ``x``.
1699
+
1700
+ The inverse hyperbolic cotangent function.
1701
+
1702
+ Examples
1703
+ ========
1704
+
1705
+ >>> from sympy import acoth
1706
+ >>> from sympy.abc import x
1707
+ >>> acoth(x).diff(x)
1708
+ 1/(1 - x**2)
1709
+
1710
+ See Also
1711
+ ========
1712
+
1713
+ asinh, acosh, coth
1714
+ """
1715
+
1716
+ def fdiff(self, argindex=1):
1717
+ if argindex == 1:
1718
+ return 1/(1 - self.args[0]**2)
1719
+ else:
1720
+ raise ArgumentIndexError(self, argindex)
1721
+
1722
+ @classmethod
1723
+ def eval(cls, arg):
1724
+ if arg.is_Number:
1725
+ if arg is S.NaN:
1726
+ return S.NaN
1727
+ elif arg is S.Infinity:
1728
+ return S.Zero
1729
+ elif arg is S.NegativeInfinity:
1730
+ return S.Zero
1731
+ elif arg.is_zero:
1732
+ return pi*I / 2
1733
+ elif arg is S.One:
1734
+ return S.Infinity
1735
+ elif arg is S.NegativeOne:
1736
+ return S.NegativeInfinity
1737
+ elif arg.is_negative:
1738
+ return -cls(-arg)
1739
+ else:
1740
+ if arg is S.ComplexInfinity:
1741
+ return S.Zero
1742
+
1743
+ i_coeff = _imaginary_unit_as_coefficient(arg)
1744
+
1745
+ if i_coeff is not None:
1746
+ return -I * acot(i_coeff)
1747
+ else:
1748
+ if arg.could_extract_minus_sign():
1749
+ return -cls(-arg)
1750
+
1751
+ if arg.is_zero:
1752
+ return pi*I*S.Half
1753
+
1754
+ @staticmethod
1755
+ @cacheit
1756
+ def taylor_term(n, x, *previous_terms):
1757
+ if n == 0:
1758
+ return -I*pi/2
1759
+ elif n < 0 or n % 2 == 0:
1760
+ return S.Zero
1761
+ else:
1762
+ x = sympify(x)
1763
+ return x**n / n
1764
+
1765
+ def _eval_as_leading_term(self, x, logx=None, cdir=0): # acoth
1766
+ arg = self.args[0]
1767
+ x0 = arg.subs(x, 0).cancel()
1768
+ if x0 is S.ComplexInfinity:
1769
+ return (1/arg).as_leading_term(x)
1770
+ # Handling branch points
1771
+ if x0 in (-S.One, S.One, S.Zero):
1772
+ return self.rewrite(log)._eval_as_leading_term(x, logx=logx, cdir=cdir)
1773
+ # Handling points lying on branch cuts [-1, 1]
1774
+ if x0.is_real and (1 - x0**2).is_positive:
1775
+ ndir = arg.dir(x, cdir if cdir else 1)
1776
+ if im(ndir).is_negative:
1777
+ if x0.is_positive:
1778
+ return self.func(x0) + I*pi
1779
+ elif im(ndir).is_positive:
1780
+ if x0.is_negative:
1781
+ return self.func(x0) - I*pi
1782
+ else:
1783
+ return self.rewrite(log)._eval_as_leading_term(x, logx=logx, cdir=cdir)
1784
+ return self.func(x0)
1785
+
1786
+ def _eval_nseries(self, x, n, logx, cdir=0): # acoth
1787
+ arg = self.args[0]
1788
+ arg0 = arg.subs(x, 0)
1789
+
1790
+ # Handling branch points
1791
+ if arg0 in (S.One, S.NegativeOne):
1792
+ return self.rewrite(log)._eval_nseries(x, n, logx=logx, cdir=cdir)
1793
+
1794
+ res = Function._eval_nseries(self, x, n=n, logx=logx)
1795
+ if arg0 is S.ComplexInfinity:
1796
+ return res
1797
+
1798
+ # Handling points lying on branch cuts [-1, 1]
1799
+ if arg0.is_real and (1 - arg0**2).is_positive:
1800
+ ndir = arg.dir(x, cdir if cdir else 1)
1801
+ if im(ndir).is_negative:
1802
+ if arg0.is_positive:
1803
+ return res + I*pi
1804
+ elif im(ndir).is_positive:
1805
+ if arg0.is_negative:
1806
+ return res - I*pi
1807
+ else:
1808
+ return self.rewrite(log)._eval_nseries(x, n, logx=logx, cdir=cdir)
1809
+ return res
1810
+
1811
+ def _eval_rewrite_as_log(self, x, **kwargs):
1812
+ return (log(1 + 1/x) - log(1 - 1/x)) / 2
1813
+
1814
+ _eval_rewrite_as_tractable = _eval_rewrite_as_log
1815
+
1816
+ def _eval_rewrite_as_atanh(self, x, **kwargs):
1817
+ return atanh(1/x)
1818
+
1819
+ def _eval_rewrite_as_asinh(self, x, **kwargs):
1820
+ return (pi*I/2*(sqrt((x - 1)/x)*sqrt(x/(x - 1)) - sqrt(1 + 1/x)*sqrt(x/(x + 1))) +
1821
+ x*sqrt(1/x**2)*asinh(sqrt(1/(x**2 - 1))))
1822
+
1823
+ def inverse(self, argindex=1):
1824
+ """
1825
+ Returns the inverse of this function.
1826
+ """
1827
+ return coth
1828
+
1829
+
1830
+ class asech(InverseHyperbolicFunction):
1831
+ """
1832
+ ``asech(x)`` is the inverse hyperbolic secant of ``x``.
1833
+
1834
+ The inverse hyperbolic secant function.
1835
+
1836
+ Examples
1837
+ ========
1838
+
1839
+ >>> from sympy import asech, sqrt, S
1840
+ >>> from sympy.abc import x
1841
+ >>> asech(x).diff(x)
1842
+ -1/(x*sqrt(1 - x**2))
1843
+ >>> asech(1).diff(x)
1844
+ 0
1845
+ >>> asech(1)
1846
+ 0
1847
+ >>> asech(S(2))
1848
+ I*pi/3
1849
+ >>> asech(-sqrt(2))
1850
+ 3*I*pi/4
1851
+ >>> asech((sqrt(6) - sqrt(2)))
1852
+ I*pi/12
1853
+
1854
+ See Also
1855
+ ========
1856
+
1857
+ asinh, atanh, cosh, acoth
1858
+
1859
+ References
1860
+ ==========
1861
+
1862
+ .. [1] https://en.wikipedia.org/wiki/Hyperbolic_function
1863
+ .. [2] https://dlmf.nist.gov/4.37
1864
+ .. [3] https://functions.wolfram.com/ElementaryFunctions/ArcSech/
1865
+
1866
+ """
1867
+
1868
+ def fdiff(self, argindex=1):
1869
+ if argindex == 1:
1870
+ z = self.args[0]
1871
+ return -1/(z*sqrt(1 - z**2))
1872
+ else:
1873
+ raise ArgumentIndexError(self, argindex)
1874
+
1875
+ @classmethod
1876
+ def eval(cls, arg):
1877
+ if arg.is_Number:
1878
+ if arg is S.NaN:
1879
+ return S.NaN
1880
+ elif arg is S.Infinity:
1881
+ return pi*I / 2
1882
+ elif arg is S.NegativeInfinity:
1883
+ return pi*I / 2
1884
+ elif arg.is_zero:
1885
+ return S.Infinity
1886
+ elif arg is S.One:
1887
+ return S.Zero
1888
+ elif arg is S.NegativeOne:
1889
+ return pi*I
1890
+
1891
+ if arg.is_number:
1892
+ cst_table = _asech_table()
1893
+
1894
+ if arg in cst_table:
1895
+ if arg.is_extended_real:
1896
+ return cst_table[arg]*I
1897
+ return cst_table[arg]
1898
+
1899
+ if arg is S.ComplexInfinity:
1900
+ from sympy.calculus.accumulationbounds import AccumBounds
1901
+ return I*AccumBounds(-pi/2, pi/2)
1902
+
1903
+ if arg.is_zero:
1904
+ return S.Infinity
1905
+
1906
+ @staticmethod
1907
+ @cacheit
1908
+ def taylor_term(n, x, *previous_terms):
1909
+ if n == 0:
1910
+ return log(2 / x)
1911
+ elif n < 0 or n % 2 == 1:
1912
+ return S.Zero
1913
+ else:
1914
+ x = sympify(x)
1915
+ if len(previous_terms) > 2 and n > 2:
1916
+ p = previous_terms[-2]
1917
+ return p * ((n - 1)*(n-2)) * x**2/(4 * (n//2)**2)
1918
+ else:
1919
+ k = n // 2
1920
+ R = RisingFactorial(S.Half, k) * n
1921
+ F = factorial(k) * n // 2 * n // 2
1922
+ return -1 * R / F * x**n / 4
1923
+
1924
+ def _eval_as_leading_term(self, x, logx=None, cdir=0): # asech
1925
+ arg = self.args[0]
1926
+ x0 = arg.subs(x, 0).cancel()
1927
+ # Handling branch points
1928
+ if x0 in (-S.One, S.Zero, S.One, S.ComplexInfinity):
1929
+ return self.rewrite(log)._eval_as_leading_term(x, logx=logx, cdir=cdir)
1930
+ # Handling points lying on branch cuts (-oo, 0] U (1, oo)
1931
+ if x0.is_negative or (1 - x0).is_negative:
1932
+ ndir = arg.dir(x, cdir if cdir else 1)
1933
+ if im(ndir).is_positive:
1934
+ if x0.is_positive or (x0 + 1).is_negative:
1935
+ return -self.func(x0)
1936
+ return self.func(x0) - 2*I*pi
1937
+ elif not im(ndir).is_negative:
1938
+ return self.rewrite(log)._eval_as_leading_term(x, logx=logx, cdir=cdir)
1939
+ return self.func(x0)
1940
+
1941
+ def _eval_nseries(self, x, n, logx, cdir=0): # asech
1942
+ from sympy.series.order import O
1943
+ arg = self.args[0]
1944
+ arg0 = arg.subs(x, 0)
1945
+
1946
+ # Handling branch points
1947
+ if arg0 is S.One:
1948
+ t = Dummy('t', positive=True)
1949
+ ser = asech(S.One - t**2).rewrite(log).nseries(t, 0, 2*n)
1950
+ arg1 = S.One - self.args[0]
1951
+ f = arg1.as_leading_term(x)
1952
+ g = (arg1 - f)/ f
1953
+ if not g.is_meromorphic(x, 0): # cannot be expanded
1954
+ return O(1) if n == 0 else O(sqrt(x))
1955
+ res1 = sqrt(S.One + g)._eval_nseries(x, n=n, logx=logx)
1956
+ res = (res1.removeO()*sqrt(f)).expand()
1957
+ return ser.removeO().subs(t, res).expand().powsimp() + O(x**n, x)
1958
+
1959
+ if arg0 is S.NegativeOne:
1960
+ t = Dummy('t', positive=True)
1961
+ ser = asech(S.NegativeOne + t**2).rewrite(log).nseries(t, 0, 2*n)
1962
+ arg1 = S.One + self.args[0]
1963
+ f = arg1.as_leading_term(x)
1964
+ g = (arg1 - f)/ f
1965
+ if not g.is_meromorphic(x, 0): # cannot be expanded
1966
+ return O(1) if n == 0 else I*pi + O(sqrt(x))
1967
+ res1 = sqrt(S.One + g)._eval_nseries(x, n=n, logx=logx)
1968
+ res = (res1.removeO()*sqrt(f)).expand()
1969
+ return ser.removeO().subs(t, res).expand().powsimp() + O(x**n, x)
1970
+
1971
+ res = Function._eval_nseries(self, x, n=n, logx=logx)
1972
+ if arg0 is S.ComplexInfinity:
1973
+ return res
1974
+
1975
+ # Handling points lying on branch cuts (-oo, 0] U (1, oo)
1976
+ if arg0.is_negative or (1 - arg0).is_negative:
1977
+ ndir = arg.dir(x, cdir if cdir else 1)
1978
+ if im(ndir).is_positive:
1979
+ if arg0.is_positive or (arg0 + 1).is_negative:
1980
+ return -res
1981
+ return res - 2*I*pi
1982
+ elif not im(ndir).is_negative:
1983
+ return self.rewrite(log)._eval_nseries(x, n, logx=logx, cdir=cdir)
1984
+ return res
1985
+
1986
+ def inverse(self, argindex=1):
1987
+ """
1988
+ Returns the inverse of this function.
1989
+ """
1990
+ return sech
1991
+
1992
+ def _eval_rewrite_as_log(self, arg, **kwargs):
1993
+ return log(1/arg + sqrt(1/arg - 1) * sqrt(1/arg + 1))
1994
+
1995
+ _eval_rewrite_as_tractable = _eval_rewrite_as_log
1996
+
1997
+ def _eval_rewrite_as_acosh(self, arg, **kwargs):
1998
+ return acosh(1/arg)
1999
+
2000
+ def _eval_rewrite_as_asinh(self, arg, **kwargs):
2001
+ return sqrt(1/arg - 1)/sqrt(1 - 1/arg)*(I*asinh(I/arg)
2002
+ + pi*S.Half)
2003
+
2004
+ def _eval_rewrite_as_atanh(self, x, **kwargs):
2005
+ return (I*pi*(1 - sqrt(x)*sqrt(1/x) - I/2*sqrt(-x)/sqrt(x) - I/2*sqrt(x**2)/sqrt(-x**2))
2006
+ + sqrt(1/(x + 1))*sqrt(x + 1)*atanh(sqrt(1 - x**2)))
2007
+
2008
+ def _eval_rewrite_as_acsch(self, x, **kwargs):
2009
+ return sqrt(1/x - 1)/sqrt(1 - 1/x)*(pi/2 - I*acsch(I*x))
2010
+
2011
+
2012
+ class acsch(InverseHyperbolicFunction):
2013
+ """
2014
+ ``acsch(x)`` is the inverse hyperbolic cosecant of ``x``.
2015
+
2016
+ The inverse hyperbolic cosecant function.
2017
+
2018
+ Examples
2019
+ ========
2020
+
2021
+ >>> from sympy import acsch, sqrt, I
2022
+ >>> from sympy.abc import x
2023
+ >>> acsch(x).diff(x)
2024
+ -1/(x**2*sqrt(1 + x**(-2)))
2025
+ >>> acsch(1).diff(x)
2026
+ 0
2027
+ >>> acsch(1)
2028
+ log(1 + sqrt(2))
2029
+ >>> acsch(I)
2030
+ -I*pi/2
2031
+ >>> acsch(-2*I)
2032
+ I*pi/6
2033
+ >>> acsch(I*(sqrt(6) - sqrt(2)))
2034
+ -5*I*pi/12
2035
+
2036
+ See Also
2037
+ ========
2038
+
2039
+ asinh
2040
+
2041
+ References
2042
+ ==========
2043
+
2044
+ .. [1] https://en.wikipedia.org/wiki/Hyperbolic_function
2045
+ .. [2] https://dlmf.nist.gov/4.37
2046
+ .. [3] https://functions.wolfram.com/ElementaryFunctions/ArcCsch/
2047
+
2048
+ """
2049
+
2050
+ def fdiff(self, argindex=1):
2051
+ if argindex == 1:
2052
+ z = self.args[0]
2053
+ return -1/(z**2*sqrt(1 + 1/z**2))
2054
+ else:
2055
+ raise ArgumentIndexError(self, argindex)
2056
+
2057
+ @classmethod
2058
+ def eval(cls, arg):
2059
+ if arg.is_Number:
2060
+ if arg is S.NaN:
2061
+ return S.NaN
2062
+ elif arg is S.Infinity:
2063
+ return S.Zero
2064
+ elif arg is S.NegativeInfinity:
2065
+ return S.Zero
2066
+ elif arg.is_zero:
2067
+ return S.ComplexInfinity
2068
+ elif arg is S.One:
2069
+ return log(1 + sqrt(2))
2070
+ elif arg is S.NegativeOne:
2071
+ return - log(1 + sqrt(2))
2072
+
2073
+ if arg.is_number:
2074
+ cst_table = _acsch_table()
2075
+
2076
+ if arg in cst_table:
2077
+ return cst_table[arg]*I
2078
+
2079
+ if arg is S.ComplexInfinity:
2080
+ return S.Zero
2081
+
2082
+ if arg.is_infinite:
2083
+ return S.Zero
2084
+
2085
+ if arg.is_zero:
2086
+ return S.ComplexInfinity
2087
+
2088
+ if arg.could_extract_minus_sign():
2089
+ return -cls(-arg)
2090
+
2091
+ @staticmethod
2092
+ @cacheit
2093
+ def taylor_term(n, x, *previous_terms):
2094
+ if n == 0:
2095
+ return log(2 / x)
2096
+ elif n < 0 or n % 2 == 1:
2097
+ return S.Zero
2098
+ else:
2099
+ x = sympify(x)
2100
+ if len(previous_terms) > 2 and n > 2:
2101
+ p = previous_terms[-2]
2102
+ return -p * ((n - 1)*(n-2)) * x**2/(4 * (n//2)**2)
2103
+ else:
2104
+ k = n // 2
2105
+ R = RisingFactorial(S.Half, k) * n
2106
+ F = factorial(k) * n // 2 * n // 2
2107
+ return S.NegativeOne**(k +1) * R / F * x**n / 4
2108
+
2109
+ def _eval_as_leading_term(self, x, logx=None, cdir=0): # acsch
2110
+ arg = self.args[0]
2111
+ x0 = arg.subs(x, 0).cancel()
2112
+ # Handling branch points
2113
+ if x0 in (-I, I, S.Zero):
2114
+ return self.rewrite(log)._eval_as_leading_term(x, logx=logx, cdir=cdir)
2115
+ if x0 is S.ComplexInfinity:
2116
+ return (1/arg).as_leading_term(x)
2117
+ # Handling points lying on branch cuts (-I, I)
2118
+ if x0.is_imaginary and (1 + x0**2).is_positive:
2119
+ ndir = arg.dir(x, cdir if cdir else 1)
2120
+ if re(ndir).is_positive:
2121
+ if im(x0).is_positive:
2122
+ return -self.func(x0) - I*pi
2123
+ elif re(ndir).is_negative:
2124
+ if im(x0).is_negative:
2125
+ return -self.func(x0) + I*pi
2126
+ else:
2127
+ return self.rewrite(log)._eval_as_leading_term(x, logx=logx, cdir=cdir)
2128
+ return self.func(x0)
2129
+
2130
+ def _eval_nseries(self, x, n, logx, cdir=0): # acsch
2131
+ from sympy.series.order import O
2132
+ arg = self.args[0]
2133
+ arg0 = arg.subs(x, 0)
2134
+
2135
+ # Handling branch points
2136
+ if arg0 is I:
2137
+ t = Dummy('t', positive=True)
2138
+ ser = acsch(I + t**2).rewrite(log).nseries(t, 0, 2*n)
2139
+ arg1 = -I + self.args[0]
2140
+ f = arg1.as_leading_term(x)
2141
+ g = (arg1 - f)/ f
2142
+ if not g.is_meromorphic(x, 0): # cannot be expanded
2143
+ return O(1) if n == 0 else -I*pi/2 + O(sqrt(x))
2144
+ res1 = sqrt(S.One + g)._eval_nseries(x, n=n, logx=logx)
2145
+ res = (res1.removeO()*sqrt(f)).expand()
2146
+ res = ser.removeO().subs(t, res).expand().powsimp() + O(x**n, x)
2147
+ return res
2148
+
2149
+ if arg0 == S.NegativeOne*I:
2150
+ t = Dummy('t', positive=True)
2151
+ ser = acsch(-I + t**2).rewrite(log).nseries(t, 0, 2*n)
2152
+ arg1 = I + self.args[0]
2153
+ f = arg1.as_leading_term(x)
2154
+ g = (arg1 - f)/ f
2155
+ if not g.is_meromorphic(x, 0): # cannot be expanded
2156
+ return O(1) if n == 0 else I*pi/2 + O(sqrt(x))
2157
+ res1 = sqrt(S.One + g)._eval_nseries(x, n=n, logx=logx)
2158
+ res = (res1.removeO()*sqrt(f)).expand()
2159
+ return ser.removeO().subs(t, res).expand().powsimp() + O(x**n, x)
2160
+
2161
+ res = Function._eval_nseries(self, x, n=n, logx=logx)
2162
+ if arg0 is S.ComplexInfinity:
2163
+ return res
2164
+
2165
+ # Handling points lying on branch cuts (-I, I)
2166
+ if arg0.is_imaginary and (1 + arg0**2).is_positive:
2167
+ ndir = self.args[0].dir(x, cdir if cdir else 1)
2168
+ if re(ndir).is_positive:
2169
+ if im(arg0).is_positive:
2170
+ return -res - I*pi
2171
+ elif re(ndir).is_negative:
2172
+ if im(arg0).is_negative:
2173
+ return -res + I*pi
2174
+ else:
2175
+ return self.rewrite(log)._eval_nseries(x, n, logx=logx, cdir=cdir)
2176
+ return res
2177
+
2178
+ def inverse(self, argindex=1):
2179
+ """
2180
+ Returns the inverse of this function.
2181
+ """
2182
+ return csch
2183
+
2184
+ def _eval_rewrite_as_log(self, arg, **kwargs):
2185
+ return log(1/arg + sqrt(1/arg**2 + 1))
2186
+
2187
+ _eval_rewrite_as_tractable = _eval_rewrite_as_log
2188
+
2189
+ def _eval_rewrite_as_asinh(self, arg, **kwargs):
2190
+ return asinh(1/arg)
2191
+
2192
+ def _eval_rewrite_as_acosh(self, arg, **kwargs):
2193
+ return I*(sqrt(1 - I/arg)/sqrt(I/arg - 1)*
2194
+ acosh(I/arg) - pi*S.Half)
2195
+
2196
+ def _eval_rewrite_as_atanh(self, arg, **kwargs):
2197
+ arg2 = arg**2
2198
+ arg2p1 = arg2 + 1
2199
+ return sqrt(-arg2)/arg*(pi*S.Half -
2200
+ sqrt(-arg2p1**2)/arg2p1*atanh(sqrt(arg2p1)))
2201
+
2202
+ def _eval_is_zero(self):
2203
+ return self.args[0].is_infinite
llmeval-env/lib/python3.10/site-packages/sympy/functions/elementary/integers.py ADDED
@@ -0,0 +1,625 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
11
+ from sympy.core.relational import Gt, Lt, Ge, Le, Relational, is_eq
12
+ from sympy.core.symbol import Symbol
13
+ from sympy.core.sympify import _sympify
14
+ from sympy.functions.elementary.complexes import im, re
15
+ from sympy.multipledispatch import dispatch
16
+
17
+ ###############################################################################
18
+ ######################### FLOOR and CEILING FUNCTIONS #########################
19
+ ###############################################################################
20
+
21
+
22
+ class RoundFunction(Function):
23
+ """Abstract base class for rounding functions."""
24
+
25
+ args: tTuple[Expr]
26
+
27
+ @classmethod
28
+ def eval(cls, arg):
29
+ v = cls._eval_number(arg)
30
+ if v is not None:
31
+ return v
32
+
33
+ if arg.is_integer or arg.is_finite is False:
34
+ return arg
35
+ if arg.is_imaginary or (S.ImaginaryUnit*arg).is_real:
36
+ i = im(arg)
37
+ if not i.has(S.ImaginaryUnit):
38
+ return cls(i)*S.ImaginaryUnit
39
+ return cls(arg, evaluate=False)
40
+
41
+ # Integral, numerical, symbolic part
42
+ ipart = npart = spart = S.Zero
43
+
44
+ # Extract integral (or complex integral) terms
45
+ terms = Add.make_args(arg)
46
+
47
+ for t in terms:
48
+ if t.is_integer or (t.is_imaginary and im(t).is_integer):
49
+ ipart += t
50
+ elif t.has(Symbol):
51
+ spart += t
52
+ else:
53
+ npart += t
54
+
55
+ if not (npart or spart):
56
+ return ipart
57
+
58
+ # Evaluate npart numerically if independent of spart
59
+ if npart and (
60
+ not spart or
61
+ npart.is_real and (spart.is_imaginary or (S.ImaginaryUnit*spart).is_real) or
62
+ npart.is_imaginary and spart.is_real):
63
+ try:
64
+ r, i = get_integer_part(
65
+ npart, cls._dir, {}, return_ints=True)
66
+ ipart += Integer(r) + Integer(i)*S.ImaginaryUnit
67
+ npart = S.Zero
68
+ except (PrecisionExhausted, NotImplementedError):
69
+ pass
70
+
71
+ spart += npart
72
+ if not spart:
73
+ return ipart
74
+ elif spart.is_imaginary or (S.ImaginaryUnit*spart).is_real:
75
+ return ipart + cls(im(spart), evaluate=False)*S.ImaginaryUnit
76
+ elif isinstance(spart, (floor, ceiling)):
77
+ return ipart + spart
78
+ else:
79
+ return ipart + cls(spart, evaluate=False)
80
+
81
+ @classmethod
82
+ def _eval_number(cls, arg):
83
+ raise NotImplementedError()
84
+
85
+ def _eval_is_finite(self):
86
+ return self.args[0].is_finite
87
+
88
+ def _eval_is_real(self):
89
+ return self.args[0].is_real
90
+
91
+ def _eval_is_integer(self):
92
+ return self.args[0].is_real
93
+
94
+
95
+ class floor(RoundFunction):
96
+ """
97
+ Floor is a univariate function which returns the largest integer
98
+ value not greater than its argument. This implementation
99
+ generalizes floor to complex numbers by taking the floor of the
100
+ real and imaginary parts separately.
101
+
102
+ Examples
103
+ ========
104
+
105
+ >>> from sympy import floor, E, I, S, Float, Rational
106
+ >>> floor(17)
107
+ 17
108
+ >>> floor(Rational(23, 10))
109
+ 2
110
+ >>> floor(2*E)
111
+ 5
112
+ >>> floor(-Float(0.567))
113
+ -1
114
+ >>> floor(-I/2)
115
+ -I
116
+ >>> floor(S(5)/2 + 5*I/2)
117
+ 2 + 2*I
118
+
119
+ See Also
120
+ ========
121
+
122
+ sympy.functions.elementary.integers.ceiling
123
+
124
+ References
125
+ ==========
126
+
127
+ .. [1] "Concrete mathematics" by Graham, pp. 87
128
+ .. [2] https://mathworld.wolfram.com/FloorFunction.html
129
+
130
+ """
131
+ _dir = -1
132
+
133
+ @classmethod
134
+ def _eval_number(cls, arg):
135
+ if arg.is_Number:
136
+ return arg.floor()
137
+ elif any(isinstance(i, j)
138
+ for i in (arg, -arg) for j in (floor, ceiling)):
139
+ return arg
140
+ if arg.is_NumberSymbol:
141
+ return arg.approximation_interval(Integer)[0]
142
+
143
+ def _eval_as_leading_term(self, x, logx=None, cdir=0):
144
+ from sympy.calculus.accumulationbounds import AccumBounds
145
+ arg = self.args[0]
146
+ arg0 = arg.subs(x, 0)
147
+ r = self.subs(x, 0)
148
+ if arg0 is S.NaN or isinstance(arg0, AccumBounds):
149
+ arg0 = arg.limit(x, 0, dir='-' if re(cdir).is_negative else '+')
150
+ r = floor(arg0)
151
+ if arg0.is_finite:
152
+ if arg0 == r:
153
+ ndir = arg.dir(x, cdir=cdir)
154
+ return r - 1 if ndir.is_negative else r
155
+ else:
156
+ return r
157
+ return arg.as_leading_term(x, logx=logx, cdir=cdir)
158
+
159
+ def _eval_nseries(self, x, n, logx, cdir=0):
160
+ arg = self.args[0]
161
+ arg0 = arg.subs(x, 0)
162
+ r = self.subs(x, 0)
163
+ if arg0 is S.NaN:
164
+ arg0 = arg.limit(x, 0, dir='-' if re(cdir).is_negative else '+')
165
+ r = floor(arg0)
166
+ if arg0.is_infinite:
167
+ from sympy.calculus.accumulationbounds import AccumBounds
168
+ from sympy.series.order import Order
169
+ s = arg._eval_nseries(x, n, logx, cdir)
170
+ o = Order(1, (x, 0)) if n <= 0 else AccumBounds(-1, 0)
171
+ return s + o
172
+ if arg0 == r:
173
+ ndir = arg.dir(x, cdir=cdir if cdir != 0 else 1)
174
+ return r - 1 if ndir.is_negative else r
175
+ else:
176
+ return r
177
+
178
+ def _eval_is_negative(self):
179
+ return self.args[0].is_negative
180
+
181
+ def _eval_is_nonnegative(self):
182
+ return self.args[0].is_nonnegative
183
+
184
+ def _eval_rewrite_as_ceiling(self, arg, **kwargs):
185
+ return -ceiling(-arg)
186
+
187
+ def _eval_rewrite_as_frac(self, arg, **kwargs):
188
+ return arg - frac(arg)
189
+
190
+ def __le__(self, other):
191
+ other = S(other)
192
+ if self.args[0].is_real:
193
+ if other.is_integer:
194
+ return self.args[0] < other + 1
195
+ if other.is_number and other.is_real:
196
+ return self.args[0] < ceiling(other)
197
+ if self.args[0] == other and other.is_real:
198
+ return S.true
199
+ if other is S.Infinity and self.is_finite:
200
+ return S.true
201
+
202
+ return Le(self, other, evaluate=False)
203
+
204
+ def __ge__(self, other):
205
+ other = S(other)
206
+ if self.args[0].is_real:
207
+ if other.is_integer:
208
+ return self.args[0] >= other
209
+ if other.is_number and other.is_real:
210
+ return self.args[0] >= ceiling(other)
211
+ if self.args[0] == other and other.is_real:
212
+ return S.false
213
+ if other is S.NegativeInfinity and self.is_finite:
214
+ return S.true
215
+
216
+ return Ge(self, other, evaluate=False)
217
+
218
+ def __gt__(self, other):
219
+ other = S(other)
220
+ if self.args[0].is_real:
221
+ if other.is_integer:
222
+ return self.args[0] >= other + 1
223
+ if other.is_number and other.is_real:
224
+ return self.args[0] >= ceiling(other)
225
+ if self.args[0] == other and other.is_real:
226
+ return S.false
227
+ if other is S.NegativeInfinity and self.is_finite:
228
+ return S.true
229
+
230
+ return Gt(self, other, evaluate=False)
231
+
232
+ def __lt__(self, other):
233
+ other = S(other)
234
+ if self.args[0].is_real:
235
+ if other.is_integer:
236
+ return self.args[0] < other
237
+ if other.is_number and other.is_real:
238
+ return self.args[0] < ceiling(other)
239
+ if self.args[0] == other and other.is_real:
240
+ return S.false
241
+ if other is S.Infinity and self.is_finite:
242
+ return S.true
243
+
244
+ return Lt(self, other, evaluate=False)
245
+
246
+
247
+ @dispatch(floor, Expr)
248
+ def _eval_is_eq(lhs, rhs): # noqa:F811
249
+ return is_eq(lhs.rewrite(ceiling), rhs) or \
250
+ is_eq(lhs.rewrite(frac),rhs)
251
+
252
+
253
+ class ceiling(RoundFunction):
254
+ """
255
+ Ceiling is a univariate function which returns the smallest integer
256
+ value not less than its argument. This implementation
257
+ generalizes ceiling to complex numbers by taking the ceiling of the
258
+ real and imaginary parts separately.
259
+
260
+ Examples
261
+ ========
262
+
263
+ >>> from sympy import ceiling, E, I, S, Float, Rational
264
+ >>> ceiling(17)
265
+ 17
266
+ >>> ceiling(Rational(23, 10))
267
+ 3
268
+ >>> ceiling(2*E)
269
+ 6
270
+ >>> ceiling(-Float(0.567))
271
+ 0
272
+ >>> ceiling(I/2)
273
+ I
274
+ >>> ceiling(S(5)/2 + 5*I/2)
275
+ 3 + 3*I
276
+
277
+ See Also
278
+ ========
279
+
280
+ sympy.functions.elementary.integers.floor
281
+
282
+ References
283
+ ==========
284
+
285
+ .. [1] "Concrete mathematics" by Graham, pp. 87
286
+ .. [2] https://mathworld.wolfram.com/CeilingFunction.html
287
+
288
+ """
289
+ _dir = 1
290
+
291
+ @classmethod
292
+ def _eval_number(cls, arg):
293
+ if arg.is_Number:
294
+ return arg.ceiling()
295
+ elif any(isinstance(i, j)
296
+ for i in (arg, -arg) for j in (floor, ceiling)):
297
+ return arg
298
+ if arg.is_NumberSymbol:
299
+ return arg.approximation_interval(Integer)[1]
300
+
301
+ def _eval_as_leading_term(self, x, logx=None, cdir=0):
302
+ from sympy.calculus.accumulationbounds import AccumBounds
303
+ arg = self.args[0]
304
+ arg0 = arg.subs(x, 0)
305
+ r = self.subs(x, 0)
306
+ if arg0 is S.NaN or isinstance(arg0, AccumBounds):
307
+ arg0 = arg.limit(x, 0, dir='-' if re(cdir).is_negative else '+')
308
+ r = ceiling(arg0)
309
+ if arg0.is_finite:
310
+ if arg0 == r:
311
+ ndir = arg.dir(x, cdir=cdir)
312
+ return r if ndir.is_negative else r + 1
313
+ else:
314
+ return r
315
+ return arg.as_leading_term(x, logx=logx, cdir=cdir)
316
+
317
+ def _eval_nseries(self, x, n, logx, cdir=0):
318
+ arg = self.args[0]
319
+ arg0 = arg.subs(x, 0)
320
+ r = self.subs(x, 0)
321
+ if arg0 is S.NaN:
322
+ arg0 = arg.limit(x, 0, dir='-' if re(cdir).is_negative else '+')
323
+ r = ceiling(arg0)
324
+ if arg0.is_infinite:
325
+ from sympy.calculus.accumulationbounds import AccumBounds
326
+ from sympy.series.order import Order
327
+ s = arg._eval_nseries(x, n, logx, cdir)
328
+ o = Order(1, (x, 0)) if n <= 0 else AccumBounds(0, 1)
329
+ return s + o
330
+ if arg0 == r:
331
+ ndir = arg.dir(x, cdir=cdir if cdir != 0 else 1)
332
+ return r if ndir.is_negative else r + 1
333
+ else:
334
+ return r
335
+
336
+ def _eval_rewrite_as_floor(self, arg, **kwargs):
337
+ return -floor(-arg)
338
+
339
+ def _eval_rewrite_as_frac(self, arg, **kwargs):
340
+ return arg + frac(-arg)
341
+
342
+ def _eval_is_positive(self):
343
+ return self.args[0].is_positive
344
+
345
+ def _eval_is_nonpositive(self):
346
+ return self.args[0].is_nonpositive
347
+
348
+ def __lt__(self, other):
349
+ other = S(other)
350
+ if self.args[0].is_real:
351
+ if other.is_integer:
352
+ return self.args[0] <= other - 1
353
+ if other.is_number and other.is_real:
354
+ return self.args[0] <= floor(other)
355
+ if self.args[0] == other and other.is_real:
356
+ return S.false
357
+ if other is S.Infinity and self.is_finite:
358
+ return S.true
359
+
360
+ return Lt(self, other, evaluate=False)
361
+
362
+ def __gt__(self, other):
363
+ other = S(other)
364
+ if self.args[0].is_real:
365
+ if other.is_integer:
366
+ return self.args[0] > other
367
+ if other.is_number and other.is_real:
368
+ return self.args[0] > floor(other)
369
+ if self.args[0] == other and other.is_real:
370
+ return S.false
371
+ if other is S.NegativeInfinity and self.is_finite:
372
+ return S.true
373
+
374
+ return Gt(self, other, evaluate=False)
375
+
376
+ def __ge__(self, other):
377
+ other = S(other)
378
+ if self.args[0].is_real:
379
+ if other.is_integer:
380
+ return self.args[0] > other - 1
381
+ if other.is_number and other.is_real:
382
+ return self.args[0] > floor(other)
383
+ if self.args[0] == other and other.is_real:
384
+ return S.true
385
+ if other is S.NegativeInfinity and self.is_finite:
386
+ return S.true
387
+
388
+ return Ge(self, other, evaluate=False)
389
+
390
+ def __le__(self, other):
391
+ other = S(other)
392
+ if self.args[0].is_real:
393
+ if other.is_integer:
394
+ return self.args[0] <= other
395
+ if other.is_number and other.is_real:
396
+ return self.args[0] <= floor(other)
397
+ if self.args[0] == other and other.is_real:
398
+ return S.false
399
+ if other is S.Infinity and self.is_finite:
400
+ return S.true
401
+
402
+ return Le(self, other, evaluate=False)
403
+
404
+
405
+ @dispatch(ceiling, Basic) # type:ignore
406
+ def _eval_is_eq(lhs, rhs): # noqa:F811
407
+ return is_eq(lhs.rewrite(floor), rhs) or is_eq(lhs.rewrite(frac),rhs)
408
+
409
+
410
+ class frac(Function):
411
+ r"""Represents the fractional part of x
412
+
413
+ For real numbers it is defined [1]_ as
414
+
415
+ .. math::
416
+ x - \left\lfloor{x}\right\rfloor
417
+
418
+ Examples
419
+ ========
420
+
421
+ >>> from sympy import Symbol, frac, Rational, floor, I
422
+ >>> frac(Rational(4, 3))
423
+ 1/3
424
+ >>> frac(-Rational(4, 3))
425
+ 2/3
426
+
427
+ returns zero for integer arguments
428
+
429
+ >>> n = Symbol('n', integer=True)
430
+ >>> frac(n)
431
+ 0
432
+
433
+ rewrite as floor
434
+
435
+ >>> x = Symbol('x')
436
+ >>> frac(x).rewrite(floor)
437
+ x - floor(x)
438
+
439
+ for complex arguments
440
+
441
+ >>> r = Symbol('r', real=True)
442
+ >>> t = Symbol('t', real=True)
443
+ >>> frac(t + I*r)
444
+ I*frac(r) + frac(t)
445
+
446
+ See Also
447
+ ========
448
+
449
+ sympy.functions.elementary.integers.floor
450
+ sympy.functions.elementary.integers.ceiling
451
+
452
+ References
453
+ ===========
454
+
455
+ .. [1] https://en.wikipedia.org/wiki/Fractional_part
456
+ .. [2] https://mathworld.wolfram.com/FractionalPart.html
457
+
458
+ """
459
+ @classmethod
460
+ def eval(cls, arg):
461
+ from sympy.calculus.accumulationbounds import AccumBounds
462
+
463
+ def _eval(arg):
464
+ if arg in (S.Infinity, S.NegativeInfinity):
465
+ return AccumBounds(0, 1)
466
+ if arg.is_integer:
467
+ return S.Zero
468
+ if arg.is_number:
469
+ if arg is S.NaN:
470
+ return S.NaN
471
+ elif arg is S.ComplexInfinity:
472
+ return S.NaN
473
+ else:
474
+ return arg - floor(arg)
475
+ return cls(arg, evaluate=False)
476
+
477
+ terms = Add.make_args(arg)
478
+ real, imag = S.Zero, S.Zero
479
+ for t in terms:
480
+ # Two checks are needed for complex arguments
481
+ # see issue-7649 for details
482
+ if t.is_imaginary or (S.ImaginaryUnit*t).is_real:
483
+ i = im(t)
484
+ if not i.has(S.ImaginaryUnit):
485
+ imag += i
486
+ else:
487
+ real += t
488
+ else:
489
+ real += t
490
+
491
+ real = _eval(real)
492
+ imag = _eval(imag)
493
+ return real + S.ImaginaryUnit*imag
494
+
495
+ def _eval_rewrite_as_floor(self, arg, **kwargs):
496
+ return arg - floor(arg)
497
+
498
+ def _eval_rewrite_as_ceiling(self, arg, **kwargs):
499
+ return arg + ceiling(-arg)
500
+
501
+ def _eval_is_finite(self):
502
+ return True
503
+
504
+ def _eval_is_real(self):
505
+ return self.args[0].is_extended_real
506
+
507
+ def _eval_is_imaginary(self):
508
+ return self.args[0].is_imaginary
509
+
510
+ def _eval_is_integer(self):
511
+ return self.args[0].is_integer
512
+
513
+ def _eval_is_zero(self):
514
+ return fuzzy_or([self.args[0].is_zero, self.args[0].is_integer])
515
+
516
+ def _eval_is_negative(self):
517
+ return False
518
+
519
+ def __ge__(self, other):
520
+ if self.is_extended_real:
521
+ other = _sympify(other)
522
+ # Check if other <= 0
523
+ if other.is_extended_nonpositive:
524
+ return S.true
525
+ # Check if other >= 1
526
+ res = self._value_one_or_more(other)
527
+ if res is not None:
528
+ return not(res)
529
+ return Ge(self, other, evaluate=False)
530
+
531
+ def __gt__(self, other):
532
+ if self.is_extended_real:
533
+ other = _sympify(other)
534
+ # Check if other < 0
535
+ res = self._value_one_or_more(other)
536
+ if res is not None:
537
+ return not(res)
538
+ # Check if other >= 1
539
+ if other.is_extended_negative:
540
+ return S.true
541
+ return Gt(self, other, evaluate=False)
542
+
543
+ def __le__(self, other):
544
+ if self.is_extended_real:
545
+ other = _sympify(other)
546
+ # Check if other < 0
547
+ if other.is_extended_negative:
548
+ return S.false
549
+ # Check if other >= 1
550
+ res = self._value_one_or_more(other)
551
+ if res is not None:
552
+ return res
553
+ return Le(self, other, evaluate=False)
554
+
555
+ def __lt__(self, other):
556
+ if self.is_extended_real:
557
+ other = _sympify(other)
558
+ # Check if other <= 0
559
+ if other.is_extended_nonpositive:
560
+ return S.false
561
+ # Check if other >= 1
562
+ res = self._value_one_or_more(other)
563
+ if res is not None:
564
+ return res
565
+ return Lt(self, other, evaluate=False)
566
+
567
+ def _value_one_or_more(self, other):
568
+ if other.is_extended_real:
569
+ if other.is_number:
570
+ res = other >= 1
571
+ if res and not isinstance(res, Relational):
572
+ return S.true
573
+ if other.is_integer and other.is_positive:
574
+ return S.true
575
+
576
+ def _eval_as_leading_term(self, x, logx=None, cdir=0):
577
+ from sympy.calculus.accumulationbounds import AccumBounds
578
+ arg = self.args[0]
579
+ arg0 = arg.subs(x, 0)
580
+ r = self.subs(x, 0)
581
+
582
+ if arg0.is_finite:
583
+ if r.is_zero:
584
+ ndir = arg.dir(x, cdir=cdir)
585
+ if ndir.is_negative:
586
+ return S.One
587
+ return (arg - arg0).as_leading_term(x, logx=logx, cdir=cdir)
588
+ else:
589
+ return r
590
+ elif arg0 in (S.ComplexInfinity, S.Infinity, S.NegativeInfinity):
591
+ return AccumBounds(0, 1)
592
+ return arg.as_leading_term(x, logx=logx, cdir=cdir)
593
+
594
+ def _eval_nseries(self, x, n, logx, cdir=0):
595
+ from sympy.series.order import Order
596
+ arg = self.args[0]
597
+ arg0 = arg.subs(x, 0)
598
+ r = self.subs(x, 0)
599
+
600
+ if arg0.is_infinite:
601
+ from sympy.calculus.accumulationbounds import AccumBounds
602
+ o = Order(1, (x, 0)) if n <= 0 else AccumBounds(0, 1) + Order(x**n, (x, 0))
603
+ return o
604
+ else:
605
+ res = (arg - arg0)._eval_nseries(x, n, logx=logx, cdir=cdir)
606
+ if r.is_zero:
607
+ ndir = arg.dir(x, cdir=cdir)
608
+ res += S.One if ndir.is_negative else S.Zero
609
+ else:
610
+ res += r
611
+ return res
612
+
613
+
614
+ @dispatch(frac, Basic) # type:ignore
615
+ def _eval_is_eq(lhs, rhs): # noqa:F811
616
+ if (lhs.rewrite(floor) == rhs) or \
617
+ (lhs.rewrite(ceiling) == rhs):
618
+ return True
619
+ # Check if other < 0
620
+ if rhs.is_extended_negative:
621
+ return False
622
+ # Check if other >= 1
623
+ res = lhs._value_one_or_more(rhs)
624
+ if res is not None:
625
+ return False
llmeval-env/lib/python3.10/site-packages/sympy/functions/elementary/miscellaneous.py ADDED
@@ -0,0 +1,915 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.power.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.power.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/q)*q
llmeval-env/lib/python3.10/site-packages/sympy/functions/elementary/piecewise.py ADDED
@@ -0,0 +1,1506 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core import S, Function, diff, Tuple, Dummy, Mul
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):
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
+ if incl_a and incl_b:
1176
+ if a.is_infinite and b.is_infinite:
1177
+ c = S.true
1178
+ elif b.is_infinite:
1179
+ c = (x >= a)
1180
+ elif a in covered or a.is_infinite:
1181
+ c = (x <= b)
1182
+ else:
1183
+ c = And(a <= x, x <= b)
1184
+ elif incl_a:
1185
+ if a in covered or a.is_infinite:
1186
+ c = (x < b)
1187
+ else:
1188
+ c = And(a <= x, x < b)
1189
+ elif incl_b:
1190
+ if b.is_infinite:
1191
+ c = (x > a)
1192
+ else:
1193
+ c = (x <= b)
1194
+ else:
1195
+ if a in covered:
1196
+ c = (x < b)
1197
+ else:
1198
+ c = And(a < x, x < b)
1199
+ covered |= iv
1200
+ if a is S.NegativeInfinity and incl_a:
1201
+ covered |= {S.NegativeInfinity}
1202
+ if b is S.Infinity and incl_b:
1203
+ covered |= {S.Infinity}
1204
+ args.append((e, c))
1205
+ if not S.Reals.is_subset(covered):
1206
+ args.append((Undefined, True))
1207
+ if args is None:
1208
+ args = list(expr.args)
1209
+ for i in range(len(args)):
1210
+ e, c = args[i]
1211
+ if isinstance(c, Basic):
1212
+ c = simplify(c, **kwargs)
1213
+ args[i] = (e, c)
1214
+
1215
+ # simplify expressions
1216
+ doit = kwargs.pop('doit', None)
1217
+ for i in range(len(args)):
1218
+ e, c = args[i]
1219
+ if isinstance(e, Basic):
1220
+ # Skip doit to avoid growth at every call for some integrals
1221
+ # and sums, see sympy/sympy#17165
1222
+ newe = simplify(e, doit=False, **kwargs)
1223
+ if newe != e:
1224
+ e = newe
1225
+ args[i] = (e, c)
1226
+
1227
+ # restore kwargs flag
1228
+ if doit is not None:
1229
+ kwargs['doit'] = doit
1230
+
1231
+ return Piecewise(*args)
1232
+
1233
+
1234
+ def _piecewise_collapse_arguments(_args):
1235
+ newargs = [] # the unevaluated conditions
1236
+ current_cond = set() # the conditions up to a given e, c pair
1237
+ for expr, cond in _args:
1238
+ cond = cond.replace(
1239
+ lambda _: _.is_Relational, _canonical_coeff)
1240
+ # Check here if expr is a Piecewise and collapse if one of
1241
+ # the conds in expr matches cond. This allows the collapsing
1242
+ # of Piecewise((Piecewise((x,x<0)),x<0)) to Piecewise((x,x<0)).
1243
+ # This is important when using piecewise_fold to simplify
1244
+ # multiple Piecewise instances having the same conds.
1245
+ # Eventually, this code should be able to collapse Piecewise's
1246
+ # having different intervals, but this will probably require
1247
+ # using the new assumptions.
1248
+ if isinstance(expr, Piecewise):
1249
+ unmatching = []
1250
+ for i, (e, c) in enumerate(expr.args):
1251
+ if c in current_cond:
1252
+ # this would already have triggered
1253
+ continue
1254
+ if c == cond:
1255
+ if c != True:
1256
+ # nothing past this condition will ever
1257
+ # trigger and only those args before this
1258
+ # that didn't match a previous condition
1259
+ # could possibly trigger
1260
+ if unmatching:
1261
+ expr = Piecewise(*(
1262
+ unmatching + [(e, c)]))
1263
+ else:
1264
+ expr = e
1265
+ break
1266
+ else:
1267
+ unmatching.append((e, c))
1268
+
1269
+ # check for condition repeats
1270
+ got = False
1271
+ # -- if an And contains a condition that was
1272
+ # already encountered, then the And will be
1273
+ # False: if the previous condition was False
1274
+ # then the And will be False and if the previous
1275
+ # condition is True then then we wouldn't get to
1276
+ # this point. In either case, we can skip this condition.
1277
+ for i in ([cond] +
1278
+ (list(cond.args) if isinstance(cond, And) else
1279
+ [])):
1280
+ if i in current_cond:
1281
+ got = True
1282
+ break
1283
+ if got:
1284
+ continue
1285
+
1286
+ # -- if not(c) is already in current_cond then c is
1287
+ # a redundant condition in an And. This does not
1288
+ # apply to Or, however: (e1, c), (e2, Or(~c, d))
1289
+ # is not (e1, c), (e2, d) because if c and d are
1290
+ # both False this would give no results when the
1291
+ # true answer should be (e2, True)
1292
+ if isinstance(cond, And):
1293
+ nonredundant = []
1294
+ for c in cond.args:
1295
+ if isinstance(c, Relational):
1296
+ if c.negated.canonical in current_cond:
1297
+ continue
1298
+ # if a strict inequality appears after
1299
+ # a non-strict one, then the condition is
1300
+ # redundant
1301
+ if isinstance(c, (Lt, Gt)) and (
1302
+ c.weak in current_cond):
1303
+ cond = False
1304
+ break
1305
+ nonredundant.append(c)
1306
+ else:
1307
+ cond = cond.func(*nonredundant)
1308
+ elif isinstance(cond, Relational):
1309
+ if cond.negated.canonical in current_cond:
1310
+ cond = S.true
1311
+
1312
+ current_cond.add(cond)
1313
+
1314
+ # collect successive e,c pairs when exprs or cond match
1315
+ if newargs:
1316
+ if newargs[-1].expr == expr:
1317
+ orcond = Or(cond, newargs[-1].cond)
1318
+ if isinstance(orcond, (And, Or)):
1319
+ orcond = distribute_and_over_or(orcond)
1320
+ newargs[-1] = ExprCondPair(expr, orcond)
1321
+ continue
1322
+ elif newargs[-1].cond == cond:
1323
+ continue
1324
+ newargs.append(ExprCondPair(expr, cond))
1325
+ return newargs
1326
+
1327
+
1328
+ _blessed = lambda e: getattr(e.lhs, '_diff_wrt', False) and (
1329
+ getattr(e.rhs, '_diff_wrt', None) or
1330
+ isinstance(e.rhs, (Rational, NumberSymbol)))
1331
+
1332
+
1333
+ def piecewise_simplify(expr, **kwargs):
1334
+ expr = piecewise_simplify_arguments(expr, **kwargs)
1335
+ if not isinstance(expr, Piecewise):
1336
+ return expr
1337
+ args = list(expr.args)
1338
+
1339
+ args = _piecewise_simplify_eq_and(args)
1340
+ args = _piecewise_simplify_equal_to_next_segment(args)
1341
+ return Piecewise(*args)
1342
+
1343
+
1344
+ def _piecewise_simplify_equal_to_next_segment(args):
1345
+ """
1346
+ See if expressions valid for an Equal expression happens to evaluate
1347
+ to the same function as in the next piecewise segment, see:
1348
+ https://github.com/sympy/sympy/issues/8458
1349
+ """
1350
+ prevexpr = None
1351
+ for i, (expr, cond) in reversed(list(enumerate(args))):
1352
+ if prevexpr is not None:
1353
+ if isinstance(cond, And):
1354
+ eqs, other = sift(cond.args,
1355
+ lambda i: isinstance(i, Eq), binary=True)
1356
+ elif isinstance(cond, Eq):
1357
+ eqs, other = [cond], []
1358
+ else:
1359
+ eqs = other = []
1360
+ _prevexpr = prevexpr
1361
+ _expr = expr
1362
+ if eqs and not other:
1363
+ eqs = list(ordered(eqs))
1364
+ for e in eqs:
1365
+ # allow 2 args to collapse into 1 for any e
1366
+ # otherwise limit simplification to only simple-arg
1367
+ # Eq instances
1368
+ if len(args) == 2 or _blessed(e):
1369
+ _prevexpr = _prevexpr.subs(*e.args)
1370
+ _expr = _expr.subs(*e.args)
1371
+ # Did it evaluate to the same?
1372
+ if _prevexpr == _expr:
1373
+ # Set the expression for the Not equal section to the same
1374
+ # as the next. These will be merged when creating the new
1375
+ # Piecewise
1376
+ args[i] = args[i].func(args[i + 1][0], cond)
1377
+ else:
1378
+ # Update the expression that we compare against
1379
+ prevexpr = expr
1380
+ else:
1381
+ prevexpr = expr
1382
+ return args
1383
+
1384
+
1385
+ def _piecewise_simplify_eq_and(args):
1386
+ """
1387
+ Try to simplify conditions and the expression for
1388
+ equalities that are part of the condition, e.g.
1389
+ Piecewise((n, And(Eq(n,0), Eq(n + m, 0))), (1, True))
1390
+ -> Piecewise((0, And(Eq(n, 0), Eq(m, 0))), (1, True))
1391
+ """
1392
+ for i, (expr, cond) in enumerate(args):
1393
+ if isinstance(cond, And):
1394
+ eqs, other = sift(cond.args,
1395
+ lambda i: isinstance(i, Eq), binary=True)
1396
+ elif isinstance(cond, Eq):
1397
+ eqs, other = [cond], []
1398
+ else:
1399
+ eqs = other = []
1400
+ if eqs:
1401
+ eqs = list(ordered(eqs))
1402
+ for j, e in enumerate(eqs):
1403
+ # these blessed lhs objects behave like Symbols
1404
+ # and the rhs are simple replacements for the "symbols"
1405
+ if _blessed(e):
1406
+ expr = expr.subs(*e.args)
1407
+ eqs[j + 1:] = [ei.subs(*e.args) for ei in eqs[j + 1:]]
1408
+ other = [ei.subs(*e.args) for ei in other]
1409
+ cond = And(*(eqs + other))
1410
+ args[i] = args[i].func(expr, cond)
1411
+ return args
1412
+
1413
+
1414
+ def piecewise_exclusive(expr, *, skip_nan=False, deep=True):
1415
+ """
1416
+ Rewrite :class:`Piecewise` with mutually exclusive conditions.
1417
+
1418
+ Explanation
1419
+ ===========
1420
+
1421
+ SymPy represents the conditions of a :class:`Piecewise` in an
1422
+ "if-elif"-fashion, allowing more than one condition to be simultaneously
1423
+ True. The interpretation is that the first condition that is True is the
1424
+ case that holds. While this is a useful representation computationally it
1425
+ is not how a piecewise formula is typically shown in a mathematical text.
1426
+ The :func:`piecewise_exclusive` function can be used to rewrite any
1427
+ :class:`Piecewise` with more typical mutually exclusive conditions.
1428
+
1429
+ Note that further manipulation of the resulting :class:`Piecewise`, e.g.
1430
+ simplifying it, will most likely make it non-exclusive. Hence, this is
1431
+ primarily a function to be used in conjunction with printing the Piecewise
1432
+ or if one would like to reorder the expression-condition pairs.
1433
+
1434
+ If it is not possible to determine that all possibilities are covered by
1435
+ the different cases of the :class:`Piecewise` then a final
1436
+ :class:`~sympy.core.numbers.NaN` case will be included explicitly. This
1437
+ can be prevented by passing ``skip_nan=True``.
1438
+
1439
+ Examples
1440
+ ========
1441
+
1442
+ >>> from sympy import piecewise_exclusive, Symbol, Piecewise, S
1443
+ >>> x = Symbol('x', real=True)
1444
+ >>> p = Piecewise((0, x < 0), (S.Half, x <= 0), (1, True))
1445
+ >>> piecewise_exclusive(p)
1446
+ Piecewise((0, x < 0), (1/2, Eq(x, 0)), (1, x > 0))
1447
+ >>> piecewise_exclusive(Piecewise((2, x > 1)))
1448
+ Piecewise((2, x > 1), (nan, x <= 1))
1449
+ >>> piecewise_exclusive(Piecewise((2, x > 1)), skip_nan=True)
1450
+ Piecewise((2, x > 1))
1451
+
1452
+ Parameters
1453
+ ==========
1454
+
1455
+ expr: a SymPy expression.
1456
+ Any :class:`Piecewise` in the expression will be rewritten.
1457
+ skip_nan: ``bool`` (default ``False``)
1458
+ If ``skip_nan`` is set to ``True`` then a final
1459
+ :class:`~sympy.core.numbers.NaN` case will not be included.
1460
+ deep: ``bool`` (default ``True``)
1461
+ If ``deep`` is ``True`` then :func:`piecewise_exclusive` will rewrite
1462
+ any :class:`Piecewise` subexpressions in ``expr`` rather than just
1463
+ rewriting ``expr`` itself.
1464
+
1465
+ Returns
1466
+ =======
1467
+
1468
+ An expression equivalent to ``expr`` but where all :class:`Piecewise` have
1469
+ been rewritten with mutually exclusive conditions.
1470
+
1471
+ See Also
1472
+ ========
1473
+
1474
+ Piecewise
1475
+ piecewise_fold
1476
+ """
1477
+
1478
+ def make_exclusive(*pwargs):
1479
+
1480
+ cumcond = false
1481
+ newargs = []
1482
+
1483
+ # Handle the first n-1 cases
1484
+ for expr_i, cond_i in pwargs[:-1]:
1485
+ cancond = And(cond_i, Not(cumcond)).simplify()
1486
+ cumcond = Or(cond_i, cumcond).simplify()
1487
+ newargs.append((expr_i, cancond))
1488
+
1489
+ # For the nth case defer simplification of cumcond
1490
+ expr_n, cond_n = pwargs[-1]
1491
+ cancond_n = And(cond_n, Not(cumcond)).simplify()
1492
+ newargs.append((expr_n, cancond_n))
1493
+
1494
+ if not skip_nan:
1495
+ cumcond = Or(cond_n, cumcond).simplify()
1496
+ if cumcond is not true:
1497
+ newargs.append((Undefined, Not(cumcond).simplify()))
1498
+
1499
+ return Piecewise(*newargs, evaluate=False)
1500
+
1501
+ if deep:
1502
+ return expr.replace(Piecewise, make_exclusive)
1503
+ elif isinstance(expr, Piecewise):
1504
+ return make_exclusive(*expr.args)
1505
+ else:
1506
+ return expr
llmeval-env/lib/python3.10/site-packages/sympy/functions/elementary/trigonometric.py ADDED
The diff for this file is too large to render. See raw diff
 
llmeval-env/lib/python3.10/site-packages/sympy/multipledispatch/__init__.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .core import dispatch
2
+ from .dispatcher import (Dispatcher, halt_ordering, restart_ordering,
3
+ MDNotImplementedError)
4
+
5
+ __version__ = '0.4.9'
6
+
7
+ __all__ = [
8
+ 'dispatch',
9
+
10
+ 'Dispatcher', 'halt_ordering', 'restart_ordering', 'MDNotImplementedError',
11
+ ]
llmeval-env/lib/python3.10/site-packages/sympy/multipledispatch/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (432 Bytes). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/multipledispatch/__pycache__/conflict.cpython-310.pyc ADDED
Binary file (3.8 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/multipledispatch/__pycache__/core.cpython-310.pyc ADDED
Binary file (2.39 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/multipledispatch/__pycache__/dispatcher.cpython-310.pyc ADDED
Binary file (13.9 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/multipledispatch/__pycache__/utils.cpython-310.pyc ADDED
Binary file (3.62 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/multipledispatch/conflict.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .utils import _toposort, groupby
2
+
3
+ class AmbiguityWarning(Warning):
4
+ pass
5
+
6
+
7
+ def supercedes(a, b):
8
+ """ A is consistent and strictly more specific than B """
9
+ return len(a) == len(b) and all(map(issubclass, a, b))
10
+
11
+
12
+ def consistent(a, b):
13
+ """ It is possible for an argument list to satisfy both A and B """
14
+ return (len(a) == len(b) and
15
+ all(issubclass(aa, bb) or issubclass(bb, aa)
16
+ for aa, bb in zip(a, b)))
17
+
18
+
19
+ def ambiguous(a, b):
20
+ """ A is consistent with B but neither is strictly more specific """
21
+ return consistent(a, b) and not (supercedes(a, b) or supercedes(b, a))
22
+
23
+
24
+ def ambiguities(signatures):
25
+ """ All signature pairs such that A is ambiguous with B """
26
+ signatures = list(map(tuple, signatures))
27
+ return {(a, b) for a in signatures for b in signatures
28
+ if hash(a) < hash(b)
29
+ and ambiguous(a, b)
30
+ and not any(supercedes(c, a) and supercedes(c, b)
31
+ for c in signatures)}
32
+
33
+
34
+ def super_signature(signatures):
35
+ """ A signature that would break ambiguities """
36
+ n = len(signatures[0])
37
+ assert all(len(s) == n for s in signatures)
38
+
39
+ return [max([type.mro(sig[i]) for sig in signatures], key=len)[0]
40
+ for i in range(n)]
41
+
42
+
43
+ def edge(a, b, tie_breaker=hash):
44
+ """ A should be checked before B
45
+
46
+ Tie broken by tie_breaker, defaults to ``hash``
47
+ """
48
+ if supercedes(a, b):
49
+ if supercedes(b, a):
50
+ return tie_breaker(a) > tie_breaker(b)
51
+ else:
52
+ return True
53
+ return False
54
+
55
+
56
+ def ordering(signatures):
57
+ """ A sane ordering of signatures to check, first to last
58
+
59
+ Topoological sort of edges as given by ``edge`` and ``supercedes``
60
+ """
61
+ signatures = list(map(tuple, signatures))
62
+ edges = [(a, b) for a in signatures for b in signatures if edge(a, b)]
63
+ edges = groupby(lambda x: x[0], edges)
64
+ for s in signatures:
65
+ if s not in edges:
66
+ edges[s] = []
67
+ edges = {k: [b for a, b in v] for k, v in edges.items()}
68
+ return _toposort(edges)
llmeval-env/lib/python3.10/site-packages/sympy/multipledispatch/core.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ from typing import Any
3
+
4
+ import inspect
5
+
6
+ from .dispatcher import Dispatcher, MethodDispatcher, ambiguity_warn
7
+
8
+ # XXX: This parameter to dispatch isn't documented and isn't used anywhere in
9
+ # sympy. Maybe it should just be removed.
10
+ global_namespace: dict[str, Any] = {}
11
+
12
+
13
+ def dispatch(*types, namespace=global_namespace, on_ambiguity=ambiguity_warn):
14
+ """ Dispatch function on the types of the inputs
15
+
16
+ Supports dispatch on all non-keyword arguments.
17
+
18
+ Collects implementations based on the function name. Ignores namespaces.
19
+
20
+ If ambiguous type signatures occur a warning is raised when the function is
21
+ defined suggesting the additional method to break the ambiguity.
22
+
23
+ Examples
24
+ --------
25
+
26
+ >>> from sympy.multipledispatch import dispatch
27
+ >>> @dispatch(int)
28
+ ... def f(x):
29
+ ... return x + 1
30
+
31
+ >>> @dispatch(float)
32
+ ... def f(x): # noqa: F811
33
+ ... return x - 1
34
+
35
+ >>> f(3)
36
+ 4
37
+ >>> f(3.0)
38
+ 2.0
39
+
40
+ Specify an isolated namespace with the namespace keyword argument
41
+
42
+ >>> my_namespace = dict()
43
+ >>> @dispatch(int, namespace=my_namespace)
44
+ ... def foo(x):
45
+ ... return x + 1
46
+
47
+ Dispatch on instance methods within classes
48
+
49
+ >>> class MyClass(object):
50
+ ... @dispatch(list)
51
+ ... def __init__(self, data):
52
+ ... self.data = data
53
+ ... @dispatch(int)
54
+ ... def __init__(self, datum): # noqa: F811
55
+ ... self.data = [datum]
56
+ """
57
+ types = tuple(types)
58
+
59
+ def _(func):
60
+ name = func.__name__
61
+
62
+ if ismethod(func):
63
+ dispatcher = inspect.currentframe().f_back.f_locals.get(
64
+ name,
65
+ MethodDispatcher(name))
66
+ else:
67
+ if name not in namespace:
68
+ namespace[name] = Dispatcher(name)
69
+ dispatcher = namespace[name]
70
+
71
+ dispatcher.add(types, func, on_ambiguity=on_ambiguity)
72
+ return dispatcher
73
+ return _
74
+
75
+
76
+ def ismethod(func):
77
+ """ Is func a method?
78
+
79
+ Note that this has to work as the method is defined but before the class is
80
+ defined. At this stage methods look like functions.
81
+ """
82
+ signature = inspect.signature(func)
83
+ return signature.parameters.get('self', None) is not None
llmeval-env/lib/python3.10/site-packages/sympy/multipledispatch/dispatcher.py ADDED
@@ -0,0 +1,413 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from warnings import warn
4
+ import inspect
5
+ from .conflict import ordering, ambiguities, super_signature, AmbiguityWarning
6
+ from .utils import expand_tuples
7
+ import itertools as itl
8
+
9
+
10
+ class MDNotImplementedError(NotImplementedError):
11
+ """ A NotImplementedError for multiple dispatch """
12
+
13
+
14
+ ### Functions for on_ambiguity
15
+
16
+ def ambiguity_warn(dispatcher, ambiguities):
17
+ """ Raise warning when ambiguity is detected
18
+
19
+ Parameters
20
+ ----------
21
+ dispatcher : Dispatcher
22
+ The dispatcher on which the ambiguity was detected
23
+ ambiguities : set
24
+ Set of type signature pairs that are ambiguous within this dispatcher
25
+
26
+ See Also:
27
+ Dispatcher.add
28
+ warning_text
29
+ """
30
+ warn(warning_text(dispatcher.name, ambiguities), AmbiguityWarning)
31
+
32
+
33
+ class RaiseNotImplementedError:
34
+ """Raise ``NotImplementedError`` when called."""
35
+
36
+ def __init__(self, dispatcher):
37
+ self.dispatcher = dispatcher
38
+
39
+ def __call__(self, *args, **kwargs):
40
+ types = tuple(type(a) for a in args)
41
+ raise NotImplementedError(
42
+ "Ambiguous signature for %s: <%s>" % (
43
+ self.dispatcher.name, str_signature(types)
44
+ ))
45
+
46
+ def ambiguity_register_error_ignore_dup(dispatcher, ambiguities):
47
+ """
48
+ If super signature for ambiguous types is duplicate types, ignore it.
49
+ Else, register instance of ``RaiseNotImplementedError`` for ambiguous types.
50
+
51
+ Parameters
52
+ ----------
53
+ dispatcher : Dispatcher
54
+ The dispatcher on which the ambiguity was detected
55
+ ambiguities : set
56
+ Set of type signature pairs that are ambiguous within this dispatcher
57
+
58
+ See Also:
59
+ Dispatcher.add
60
+ ambiguity_warn
61
+ """
62
+ for amb in ambiguities:
63
+ signature = tuple(super_signature(amb))
64
+ if len(set(signature)) == 1:
65
+ continue
66
+ dispatcher.add(
67
+ signature, RaiseNotImplementedError(dispatcher),
68
+ on_ambiguity=ambiguity_register_error_ignore_dup
69
+ )
70
+
71
+ ###
72
+
73
+
74
+ _unresolved_dispatchers: set[Dispatcher] = set()
75
+ _resolve = [True]
76
+
77
+
78
+ def halt_ordering():
79
+ _resolve[0] = False
80
+
81
+
82
+ def restart_ordering(on_ambiguity=ambiguity_warn):
83
+ _resolve[0] = True
84
+ while _unresolved_dispatchers:
85
+ dispatcher = _unresolved_dispatchers.pop()
86
+ dispatcher.reorder(on_ambiguity=on_ambiguity)
87
+
88
+
89
+ class Dispatcher:
90
+ """ Dispatch methods based on type signature
91
+
92
+ Use ``dispatch`` to add implementations
93
+
94
+ Examples
95
+ --------
96
+
97
+ >>> from sympy.multipledispatch import dispatch
98
+ >>> @dispatch(int)
99
+ ... def f(x):
100
+ ... return x + 1
101
+
102
+ >>> @dispatch(float)
103
+ ... def f(x): # noqa: F811
104
+ ... return x - 1
105
+
106
+ >>> f(3)
107
+ 4
108
+ >>> f(3.0)
109
+ 2.0
110
+ """
111
+ __slots__ = '__name__', 'name', 'funcs', 'ordering', '_cache', 'doc'
112
+
113
+ def __init__(self, name, doc=None):
114
+ self.name = self.__name__ = name
115
+ self.funcs = {}
116
+ self._cache = {}
117
+ self.ordering = []
118
+ self.doc = doc
119
+
120
+ def register(self, *types, **kwargs):
121
+ """ Register dispatcher with new implementation
122
+
123
+ >>> from sympy.multipledispatch.dispatcher import Dispatcher
124
+ >>> f = Dispatcher('f')
125
+ >>> @f.register(int)
126
+ ... def inc(x):
127
+ ... return x + 1
128
+
129
+ >>> @f.register(float)
130
+ ... def dec(x):
131
+ ... return x - 1
132
+
133
+ >>> @f.register(list)
134
+ ... @f.register(tuple)
135
+ ... def reverse(x):
136
+ ... return x[::-1]
137
+
138
+ >>> f(1)
139
+ 2
140
+
141
+ >>> f(1.0)
142
+ 0.0
143
+
144
+ >>> f([1, 2, 3])
145
+ [3, 2, 1]
146
+ """
147
+ def _(func):
148
+ self.add(types, func, **kwargs)
149
+ return func
150
+ return _
151
+
152
+ @classmethod
153
+ def get_func_params(cls, func):
154
+ if hasattr(inspect, "signature"):
155
+ sig = inspect.signature(func)
156
+ return sig.parameters.values()
157
+
158
+ @classmethod
159
+ def get_func_annotations(cls, func):
160
+ """ Get annotations of function positional parameters
161
+ """
162
+ params = cls.get_func_params(func)
163
+ if params:
164
+ Parameter = inspect.Parameter
165
+
166
+ params = (param for param in params
167
+ if param.kind in
168
+ (Parameter.POSITIONAL_ONLY,
169
+ Parameter.POSITIONAL_OR_KEYWORD))
170
+
171
+ annotations = tuple(
172
+ param.annotation
173
+ for param in params)
174
+
175
+ if not any(ann is Parameter.empty for ann in annotations):
176
+ return annotations
177
+
178
+ def add(self, signature, func, on_ambiguity=ambiguity_warn):
179
+ """ Add new types/method pair to dispatcher
180
+
181
+ >>> from sympy.multipledispatch import Dispatcher
182
+ >>> D = Dispatcher('add')
183
+ >>> D.add((int, int), lambda x, y: x + y)
184
+ >>> D.add((float, float), lambda x, y: x + y)
185
+
186
+ >>> D(1, 2)
187
+ 3
188
+ >>> D(1, 2.0)
189
+ Traceback (most recent call last):
190
+ ...
191
+ NotImplementedError: Could not find signature for add: <int, float>
192
+
193
+ When ``add`` detects a warning it calls the ``on_ambiguity`` callback
194
+ with a dispatcher/itself, and a set of ambiguous type signature pairs
195
+ as inputs. See ``ambiguity_warn`` for an example.
196
+ """
197
+ # Handle annotations
198
+ if not signature:
199
+ annotations = self.get_func_annotations(func)
200
+ if annotations:
201
+ signature = annotations
202
+
203
+ # Handle union types
204
+ if any(isinstance(typ, tuple) for typ in signature):
205
+ for typs in expand_tuples(signature):
206
+ self.add(typs, func, on_ambiguity)
207
+ return
208
+
209
+ for typ in signature:
210
+ if not isinstance(typ, type):
211
+ str_sig = ', '.join(c.__name__ if isinstance(c, type)
212
+ else str(c) for c in signature)
213
+ raise TypeError("Tried to dispatch on non-type: %s\n"
214
+ "In signature: <%s>\n"
215
+ "In function: %s" %
216
+ (typ, str_sig, self.name))
217
+
218
+ self.funcs[signature] = func
219
+ self.reorder(on_ambiguity=on_ambiguity)
220
+ self._cache.clear()
221
+
222
+ def reorder(self, on_ambiguity=ambiguity_warn):
223
+ if _resolve[0]:
224
+ self.ordering = ordering(self.funcs)
225
+ amb = ambiguities(self.funcs)
226
+ if amb:
227
+ on_ambiguity(self, amb)
228
+ else:
229
+ _unresolved_dispatchers.add(self)
230
+
231
+ def __call__(self, *args, **kwargs):
232
+ types = tuple([type(arg) for arg in args])
233
+ try:
234
+ func = self._cache[types]
235
+ except KeyError:
236
+ func = self.dispatch(*types)
237
+ if not func:
238
+ raise NotImplementedError(
239
+ 'Could not find signature for %s: <%s>' %
240
+ (self.name, str_signature(types)))
241
+ self._cache[types] = func
242
+ try:
243
+ return func(*args, **kwargs)
244
+
245
+ except MDNotImplementedError:
246
+ funcs = self.dispatch_iter(*types)
247
+ next(funcs) # burn first
248
+ for func in funcs:
249
+ try:
250
+ return func(*args, **kwargs)
251
+ except MDNotImplementedError:
252
+ pass
253
+ raise NotImplementedError("Matching functions for "
254
+ "%s: <%s> found, but none completed successfully"
255
+ % (self.name, str_signature(types)))
256
+
257
+ def __str__(self):
258
+ return "<dispatched %s>" % self.name
259
+ __repr__ = __str__
260
+
261
+ def dispatch(self, *types):
262
+ """ Deterimine appropriate implementation for this type signature
263
+
264
+ This method is internal. Users should call this object as a function.
265
+ Implementation resolution occurs within the ``__call__`` method.
266
+
267
+ >>> from sympy.multipledispatch import dispatch
268
+ >>> @dispatch(int)
269
+ ... def inc(x):
270
+ ... return x + 1
271
+
272
+ >>> implementation = inc.dispatch(int)
273
+ >>> implementation(3)
274
+ 4
275
+
276
+ >>> print(inc.dispatch(float))
277
+ None
278
+
279
+ See Also:
280
+ ``sympy.multipledispatch.conflict`` - module to determine resolution order
281
+ """
282
+
283
+ if types in self.funcs:
284
+ return self.funcs[types]
285
+
286
+ try:
287
+ return next(self.dispatch_iter(*types))
288
+ except StopIteration:
289
+ return None
290
+
291
+ def dispatch_iter(self, *types):
292
+ n = len(types)
293
+ for signature in self.ordering:
294
+ if len(signature) == n and all(map(issubclass, types, signature)):
295
+ result = self.funcs[signature]
296
+ yield result
297
+
298
+ def resolve(self, types):
299
+ """ Deterimine appropriate implementation for this type signature
300
+
301
+ .. deprecated:: 0.4.4
302
+ Use ``dispatch(*types)`` instead
303
+ """
304
+ warn("resolve() is deprecated, use dispatch(*types)",
305
+ DeprecationWarning)
306
+
307
+ return self.dispatch(*types)
308
+
309
+ def __getstate__(self):
310
+ return {'name': self.name,
311
+ 'funcs': self.funcs}
312
+
313
+ def __setstate__(self, d):
314
+ self.name = d['name']
315
+ self.funcs = d['funcs']
316
+ self.ordering = ordering(self.funcs)
317
+ self._cache = {}
318
+
319
+ @property
320
+ def __doc__(self):
321
+ docs = ["Multiply dispatched method: %s" % self.name]
322
+
323
+ if self.doc:
324
+ docs.append(self.doc)
325
+
326
+ other = []
327
+ for sig in self.ordering[::-1]:
328
+ func = self.funcs[sig]
329
+ if func.__doc__:
330
+ s = 'Inputs: <%s>\n' % str_signature(sig)
331
+ s += '-' * len(s) + '\n'
332
+ s += func.__doc__.strip()
333
+ docs.append(s)
334
+ else:
335
+ other.append(str_signature(sig))
336
+
337
+ if other:
338
+ docs.append('Other signatures:\n ' + '\n '.join(other))
339
+
340
+ return '\n\n'.join(docs)
341
+
342
+ def _help(self, *args):
343
+ return self.dispatch(*map(type, args)).__doc__
344
+
345
+ def help(self, *args, **kwargs):
346
+ """ Print docstring for the function corresponding to inputs """
347
+ print(self._help(*args))
348
+
349
+ def _source(self, *args):
350
+ func = self.dispatch(*map(type, args))
351
+ if not func:
352
+ raise TypeError("No function found")
353
+ return source(func)
354
+
355
+ def source(self, *args, **kwargs):
356
+ """ Print source code for the function corresponding to inputs """
357
+ print(self._source(*args))
358
+
359
+
360
+ def source(func):
361
+ s = 'File: %s\n\n' % inspect.getsourcefile(func)
362
+ s = s + inspect.getsource(func)
363
+ return s
364
+
365
+
366
+ class MethodDispatcher(Dispatcher):
367
+ """ Dispatch methods based on type signature
368
+
369
+ See Also:
370
+ Dispatcher
371
+ """
372
+
373
+ @classmethod
374
+ def get_func_params(cls, func):
375
+ if hasattr(inspect, "signature"):
376
+ sig = inspect.signature(func)
377
+ return itl.islice(sig.parameters.values(), 1, None)
378
+
379
+ def __get__(self, instance, owner):
380
+ self.obj = instance
381
+ self.cls = owner
382
+ return self
383
+
384
+ def __call__(self, *args, **kwargs):
385
+ types = tuple([type(arg) for arg in args])
386
+ func = self.dispatch(*types)
387
+ if not func:
388
+ raise NotImplementedError('Could not find signature for %s: <%s>' %
389
+ (self.name, str_signature(types)))
390
+ return func(self.obj, *args, **kwargs)
391
+
392
+
393
+ def str_signature(sig):
394
+ """ String representation of type signature
395
+
396
+ >>> from sympy.multipledispatch.dispatcher import str_signature
397
+ >>> str_signature((int, float))
398
+ 'int, float'
399
+ """
400
+ return ', '.join(cls.__name__ for cls in sig)
401
+
402
+
403
+ def warning_text(name, amb):
404
+ """ The text for ambiguity warnings """
405
+ text = "\nAmbiguities exist in dispatched function %s\n\n" % (name)
406
+ text += "The following signatures may result in ambiguous behavior:\n"
407
+ for pair in amb:
408
+ text += "\t" + \
409
+ ', '.join('[' + str_signature(s) + ']' for s in pair) + "\n"
410
+ text += "\n\nConsider making the following additions:\n\n"
411
+ text += '\n\n'.join(['@dispatch(' + str_signature(super_signature(s))
412
+ + ')\ndef %s(...)' % name for s in amb])
413
+ return text
llmeval-env/lib/python3.10/site-packages/sympy/multipledispatch/tests/__init__.py ADDED
File without changes
llmeval-env/lib/python3.10/site-packages/sympy/multipledispatch/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (201 Bytes). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/multipledispatch/tests/__pycache__/test_conflict.cpython-310.pyc ADDED
Binary file (2.49 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/multipledispatch/tests/__pycache__/test_core.cpython-310.pyc ADDED
Binary file (7.4 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/multipledispatch/tests/__pycache__/test_dispatcher.cpython-310.pyc ADDED
Binary file (10.3 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/multipledispatch/tests/test_conflict.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.multipledispatch.conflict import (supercedes, ordering, ambiguities,
2
+ ambiguous, super_signature, consistent)
3
+
4
+
5
+ class A: pass
6
+ class B(A): pass
7
+ class C: pass
8
+
9
+
10
+ def test_supercedes():
11
+ assert supercedes([B], [A])
12
+ assert supercedes([B, A], [A, A])
13
+ assert not supercedes([B, A], [A, B])
14
+ assert not supercedes([A], [B])
15
+
16
+
17
+ def test_consistent():
18
+ assert consistent([A], [A])
19
+ assert consistent([B], [B])
20
+ assert not consistent([A], [C])
21
+ assert consistent([A, B], [A, B])
22
+ assert consistent([B, A], [A, B])
23
+ assert not consistent([B, A], [B])
24
+ assert not consistent([B, A], [B, C])
25
+
26
+
27
+ def test_super_signature():
28
+ assert super_signature([[A]]) == [A]
29
+ assert super_signature([[A], [B]]) == [B]
30
+ assert super_signature([[A, B], [B, A]]) == [B, B]
31
+ assert super_signature([[A, A, B], [A, B, A], [B, A, A]]) == [B, B, B]
32
+
33
+
34
+ def test_ambiguous():
35
+ assert not ambiguous([A], [A])
36
+ assert not ambiguous([A], [B])
37
+ assert not ambiguous([B], [B])
38
+ assert not ambiguous([A, B], [B, B])
39
+ assert ambiguous([A, B], [B, A])
40
+
41
+
42
+ def test_ambiguities():
43
+ signatures = [[A], [B], [A, B], [B, A], [A, C]]
44
+ expected = {((A, B), (B, A))}
45
+ result = ambiguities(signatures)
46
+ assert set(map(frozenset, expected)) == set(map(frozenset, result))
47
+
48
+ signatures = [[A], [B], [A, B], [B, A], [A, C], [B, B]]
49
+ expected = set()
50
+ result = ambiguities(signatures)
51
+ assert set(map(frozenset, expected)) == set(map(frozenset, result))
52
+
53
+
54
+ def test_ordering():
55
+ signatures = [[A, A], [A, B], [B, A], [B, B], [A, C]]
56
+ ord = ordering(signatures)
57
+ assert ord[0] == (B, B) or ord[0] == (A, C)
58
+ assert ord[-1] == (A, A) or ord[-1] == (A, C)
59
+
60
+
61
+ def test_type_mro():
62
+ assert super_signature([[object], [type]]) == [type]
llmeval-env/lib/python3.10/site-packages/sympy/multipledispatch/tests/test_core.py ADDED
@@ -0,0 +1,213 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ from typing import Any
3
+
4
+ from sympy.multipledispatch import dispatch
5
+ from sympy.multipledispatch.conflict import AmbiguityWarning
6
+ from sympy.testing.pytest import raises, warns
7
+ from functools import partial
8
+
9
+ test_namespace: dict[str, Any] = {}
10
+
11
+ orig_dispatch = dispatch
12
+ dispatch = partial(dispatch, namespace=test_namespace)
13
+
14
+
15
+ def test_singledispatch():
16
+ @dispatch(int)
17
+ def f(x): # noqa:F811
18
+ return x + 1
19
+
20
+ @dispatch(int)
21
+ def g(x): # noqa:F811
22
+ return x + 2
23
+
24
+ @dispatch(float) # noqa:F811
25
+ def f(x): # noqa:F811
26
+ return x - 1
27
+
28
+ assert f(1) == 2
29
+ assert g(1) == 3
30
+ assert f(1.0) == 0
31
+
32
+ assert raises(NotImplementedError, lambda: f('hello'))
33
+
34
+
35
+ def test_multipledispatch():
36
+ @dispatch(int, int)
37
+ def f(x, y): # noqa:F811
38
+ return x + y
39
+
40
+ @dispatch(float, float) # noqa:F811
41
+ def f(x, y): # noqa:F811
42
+ return x - y
43
+
44
+ assert f(1, 2) == 3
45
+ assert f(1.0, 2.0) == -1.0
46
+
47
+
48
+ class A: pass
49
+ class B: pass
50
+ class C(A): pass
51
+ class D(C): pass
52
+ class E(C): pass
53
+
54
+
55
+ def test_inheritance():
56
+ @dispatch(A)
57
+ def f(x): # noqa:F811
58
+ return 'a'
59
+
60
+ @dispatch(B) # noqa:F811
61
+ def f(x): # noqa:F811
62
+ return 'b'
63
+
64
+ assert f(A()) == 'a'
65
+ assert f(B()) == 'b'
66
+ assert f(C()) == 'a'
67
+
68
+
69
+ def test_inheritance_and_multiple_dispatch():
70
+ @dispatch(A, A)
71
+ def f(x, y): # noqa:F811
72
+ return type(x), type(y)
73
+
74
+ @dispatch(A, B) # noqa:F811
75
+ def f(x, y): # noqa:F811
76
+ return 0
77
+
78
+ assert f(A(), A()) == (A, A)
79
+ assert f(A(), C()) == (A, C)
80
+ assert f(A(), B()) == 0
81
+ assert f(C(), B()) == 0
82
+ assert raises(NotImplementedError, lambda: f(B(), B()))
83
+
84
+
85
+ def test_competing_solutions():
86
+ @dispatch(A)
87
+ def h(x): # noqa:F811
88
+ return 1
89
+
90
+ @dispatch(C) # noqa:F811
91
+ def h(x): # noqa:F811
92
+ return 2
93
+
94
+ assert h(D()) == 2
95
+
96
+
97
+ def test_competing_multiple():
98
+ @dispatch(A, B)
99
+ def h(x, y): # noqa:F811
100
+ return 1
101
+
102
+ @dispatch(C, B) # noqa:F811
103
+ def h(x, y): # noqa:F811
104
+ return 2
105
+
106
+ assert h(D(), B()) == 2
107
+
108
+
109
+ def test_competing_ambiguous():
110
+ test_namespace = {}
111
+ dispatch = partial(orig_dispatch, namespace=test_namespace)
112
+
113
+ @dispatch(A, C)
114
+ def f(x, y): # noqa:F811
115
+ return 2
116
+
117
+ with warns(AmbiguityWarning, test_stacklevel=False):
118
+ @dispatch(C, A) # noqa:F811
119
+ def f(x, y): # noqa:F811
120
+ return 2
121
+
122
+ assert f(A(), C()) == f(C(), A()) == 2
123
+ # assert raises(Warning, lambda : f(C(), C()))
124
+
125
+
126
+ def test_caching_correct_behavior():
127
+ @dispatch(A)
128
+ def f(x): # noqa:F811
129
+ return 1
130
+
131
+ assert f(C()) == 1
132
+
133
+ @dispatch(C)
134
+ def f(x): # noqa:F811
135
+ return 2
136
+
137
+ assert f(C()) == 2
138
+
139
+
140
+ def test_union_types():
141
+ @dispatch((A, C))
142
+ def f(x): # noqa:F811
143
+ return 1
144
+
145
+ assert f(A()) == 1
146
+ assert f(C()) == 1
147
+
148
+
149
+ def test_namespaces():
150
+ ns1 = {}
151
+ ns2 = {}
152
+
153
+ def foo(x):
154
+ return 1
155
+ foo1 = orig_dispatch(int, namespace=ns1)(foo)
156
+
157
+ def foo(x):
158
+ return 2
159
+ foo2 = orig_dispatch(int, namespace=ns2)(foo)
160
+
161
+ assert foo1(0) == 1
162
+ assert foo2(0) == 2
163
+
164
+
165
+ """
166
+ Fails
167
+ def test_dispatch_on_dispatch():
168
+ @dispatch(A)
169
+ @dispatch(C)
170
+ def q(x): # noqa:F811
171
+ return 1
172
+
173
+ assert q(A()) == 1
174
+ assert q(C()) == 1
175
+ """
176
+
177
+
178
+ def test_methods():
179
+ class Foo:
180
+ @dispatch(float)
181
+ def f(self, x): # noqa:F811
182
+ return x - 1
183
+
184
+ @dispatch(int) # noqa:F811
185
+ def f(self, x): # noqa:F811
186
+ return x + 1
187
+
188
+ @dispatch(int)
189
+ def g(self, x): # noqa:F811
190
+ return x + 3
191
+
192
+
193
+ foo = Foo()
194
+ assert foo.f(1) == 2
195
+ assert foo.f(1.0) == 0.0
196
+ assert foo.g(1) == 4
197
+
198
+
199
+ def test_methods_multiple_dispatch():
200
+ class Foo:
201
+ @dispatch(A, A)
202
+ def f(x, y): # noqa:F811
203
+ return 1
204
+
205
+ @dispatch(A, C) # noqa:F811
206
+ def f(x, y): # noqa:F811
207
+ return 2
208
+
209
+
210
+ foo = Foo()
211
+ assert foo.f(A(), A()) == 1
212
+ assert foo.f(A(), C()) == 2
213
+ assert foo.f(C(), C()) == 2
llmeval-env/lib/python3.10/site-packages/sympy/multipledispatch/tests/test_dispatcher.py ADDED
@@ -0,0 +1,284 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.multipledispatch.dispatcher import (Dispatcher, MDNotImplementedError,
2
+ MethodDispatcher, halt_ordering,
3
+ restart_ordering,
4
+ ambiguity_register_error_ignore_dup)
5
+ from sympy.testing.pytest import raises, warns
6
+
7
+
8
+ def identity(x):
9
+ return x
10
+
11
+
12
+ def inc(x):
13
+ return x + 1
14
+
15
+
16
+ def dec(x):
17
+ return x - 1
18
+
19
+
20
+ def test_dispatcher():
21
+ f = Dispatcher('f')
22
+ f.add((int,), inc)
23
+ f.add((float,), dec)
24
+
25
+ with warns(DeprecationWarning, test_stacklevel=False):
26
+ assert f.resolve((int,)) == inc
27
+ assert f.dispatch(int) is inc
28
+
29
+ assert f(1) == 2
30
+ assert f(1.0) == 0.0
31
+
32
+
33
+ def test_union_types():
34
+ f = Dispatcher('f')
35
+ f.register((int, float))(inc)
36
+
37
+ assert f(1) == 2
38
+ assert f(1.0) == 2.0
39
+
40
+
41
+ def test_dispatcher_as_decorator():
42
+ f = Dispatcher('f')
43
+
44
+ @f.register(int)
45
+ def inc(x): # noqa:F811
46
+ return x + 1
47
+
48
+ @f.register(float) # noqa:F811
49
+ def inc(x): # noqa:F811
50
+ return x - 1
51
+
52
+ assert f(1) == 2
53
+ assert f(1.0) == 0.0
54
+
55
+
56
+ def test_register_instance_method():
57
+
58
+ class Test:
59
+ __init__ = MethodDispatcher('f')
60
+
61
+ @__init__.register(list)
62
+ def _init_list(self, data):
63
+ self.data = data
64
+
65
+ @__init__.register(object)
66
+ def _init_obj(self, datum):
67
+ self.data = [datum]
68
+
69
+ a = Test(3)
70
+ b = Test([3])
71
+ assert a.data == b.data
72
+
73
+
74
+ def test_on_ambiguity():
75
+ f = Dispatcher('f')
76
+
77
+ def identity(x): return x
78
+
79
+ ambiguities = [False]
80
+
81
+ def on_ambiguity(dispatcher, amb):
82
+ ambiguities[0] = True
83
+
84
+ f.add((object, object), identity, on_ambiguity=on_ambiguity)
85
+ assert not ambiguities[0]
86
+ f.add((object, float), identity, on_ambiguity=on_ambiguity)
87
+ assert not ambiguities[0]
88
+ f.add((float, object), identity, on_ambiguity=on_ambiguity)
89
+ assert ambiguities[0]
90
+
91
+
92
+ def test_raise_error_on_non_class():
93
+ f = Dispatcher('f')
94
+ assert raises(TypeError, lambda: f.add((1,), inc))
95
+
96
+
97
+ def test_docstring():
98
+
99
+ def one(x, y):
100
+ """ Docstring number one """
101
+ return x + y
102
+
103
+ def two(x, y):
104
+ """ Docstring number two """
105
+ return x + y
106
+
107
+ def three(x, y):
108
+ return x + y
109
+
110
+ master_doc = 'Doc of the multimethod itself'
111
+
112
+ f = Dispatcher('f', doc=master_doc)
113
+ f.add((object, object), one)
114
+ f.add((int, int), two)
115
+ f.add((float, float), three)
116
+
117
+ assert one.__doc__.strip() in f.__doc__
118
+ assert two.__doc__.strip() in f.__doc__
119
+ assert f.__doc__.find(one.__doc__.strip()) < \
120
+ f.__doc__.find(two.__doc__.strip())
121
+ assert 'object, object' in f.__doc__
122
+ assert master_doc in f.__doc__
123
+
124
+
125
+ def test_help():
126
+ def one(x, y):
127
+ """ Docstring number one """
128
+ return x + y
129
+
130
+ def two(x, y):
131
+ """ Docstring number two """
132
+ return x + y
133
+
134
+ def three(x, y):
135
+ """ Docstring number three """
136
+ return x + y
137
+
138
+ master_doc = 'Doc of the multimethod itself'
139
+
140
+ f = Dispatcher('f', doc=master_doc)
141
+ f.add((object, object), one)
142
+ f.add((int, int), two)
143
+ f.add((float, float), three)
144
+
145
+ assert f._help(1, 1) == two.__doc__
146
+ assert f._help(1.0, 2.0) == three.__doc__
147
+
148
+
149
+ def test_source():
150
+ def one(x, y):
151
+ """ Docstring number one """
152
+ return x + y
153
+
154
+ def two(x, y):
155
+ """ Docstring number two """
156
+ return x - y
157
+
158
+ master_doc = 'Doc of the multimethod itself'
159
+
160
+ f = Dispatcher('f', doc=master_doc)
161
+ f.add((int, int), one)
162
+ f.add((float, float), two)
163
+
164
+ assert 'x + y' in f._source(1, 1)
165
+ assert 'x - y' in f._source(1.0, 1.0)
166
+
167
+
168
+ def test_source_raises_on_missing_function():
169
+ f = Dispatcher('f')
170
+
171
+ assert raises(TypeError, lambda: f.source(1))
172
+
173
+
174
+ def test_halt_method_resolution():
175
+ g = [0]
176
+
177
+ def on_ambiguity(a, b):
178
+ g[0] += 1
179
+
180
+ f = Dispatcher('f')
181
+
182
+ halt_ordering()
183
+
184
+ def func(*args):
185
+ pass
186
+
187
+ f.add((int, object), func)
188
+ f.add((object, int), func)
189
+
190
+ assert g == [0]
191
+
192
+ restart_ordering(on_ambiguity=on_ambiguity)
193
+
194
+ assert g == [1]
195
+
196
+ assert set(f.ordering) == {(int, object), (object, int)}
197
+
198
+
199
+ def test_no_implementations():
200
+ f = Dispatcher('f')
201
+ assert raises(NotImplementedError, lambda: f('hello'))
202
+
203
+
204
+ def test_register_stacking():
205
+ f = Dispatcher('f')
206
+
207
+ @f.register(list)
208
+ @f.register(tuple)
209
+ def rev(x):
210
+ return x[::-1]
211
+
212
+ assert f((1, 2, 3)) == (3, 2, 1)
213
+ assert f([1, 2, 3]) == [3, 2, 1]
214
+
215
+ assert raises(NotImplementedError, lambda: f('hello'))
216
+ assert rev('hello') == 'olleh'
217
+
218
+
219
+ def test_dispatch_method():
220
+ f = Dispatcher('f')
221
+
222
+ @f.register(list)
223
+ def rev(x):
224
+ return x[::-1]
225
+
226
+ @f.register(int, int)
227
+ def add(x, y):
228
+ return x + y
229
+
230
+ class MyList(list):
231
+ pass
232
+
233
+ assert f.dispatch(list) is rev
234
+ assert f.dispatch(MyList) is rev
235
+ assert f.dispatch(int, int) is add
236
+
237
+
238
+ def test_not_implemented():
239
+ f = Dispatcher('f')
240
+
241
+ @f.register(object)
242
+ def _(x):
243
+ return 'default'
244
+
245
+ @f.register(int)
246
+ def _(x):
247
+ if x % 2 == 0:
248
+ return 'even'
249
+ else:
250
+ raise MDNotImplementedError()
251
+
252
+ assert f('hello') == 'default' # default behavior
253
+ assert f(2) == 'even' # specialized behavior
254
+ assert f(3) == 'default' # fall bac to default behavior
255
+ assert raises(NotImplementedError, lambda: f(1, 2))
256
+
257
+
258
+ def test_not_implemented_error():
259
+ f = Dispatcher('f')
260
+
261
+ @f.register(float)
262
+ def _(a):
263
+ raise MDNotImplementedError()
264
+
265
+ assert raises(NotImplementedError, lambda: f(1.0))
266
+
267
+ def test_ambiguity_register_error_ignore_dup():
268
+ f = Dispatcher('f')
269
+
270
+ class A:
271
+ pass
272
+ class B(A):
273
+ pass
274
+ class C(A):
275
+ pass
276
+
277
+ # suppress warning for registering ambiguous signal
278
+ f.add((A, B), lambda x,y: None, ambiguity_register_error_ignore_dup)
279
+ f.add((B, A), lambda x,y: None, ambiguity_register_error_ignore_dup)
280
+ f.add((A, C), lambda x,y: None, ambiguity_register_error_ignore_dup)
281
+ f.add((C, A), lambda x,y: None, ambiguity_register_error_ignore_dup)
282
+
283
+ # raises error if ambiguous signal is passed
284
+ assert raises(NotImplementedError, lambda: f(B(), C()))
llmeval-env/lib/python3.10/site-packages/sympy/multipledispatch/utils.py ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections import OrderedDict
2
+
3
+
4
+ def expand_tuples(L):
5
+ """
6
+ >>> from sympy.multipledispatch.utils import expand_tuples
7
+ >>> expand_tuples([1, (2, 3)])
8
+ [(1, 2), (1, 3)]
9
+
10
+ >>> expand_tuples([1, 2])
11
+ [(1, 2)]
12
+ """
13
+ if not L:
14
+ return [()]
15
+ elif not isinstance(L[0], tuple):
16
+ rest = expand_tuples(L[1:])
17
+ return [(L[0],) + t for t in rest]
18
+ else:
19
+ rest = expand_tuples(L[1:])
20
+ return [(item,) + t for t in rest for item in L[0]]
21
+
22
+
23
+ # Taken from theano/theano/gof/sched.py
24
+ # Avoids licensing issues because this was written by Matthew Rocklin
25
+ def _toposort(edges):
26
+ """ Topological sort algorithm by Kahn [1] - O(nodes + vertices)
27
+
28
+ inputs:
29
+ edges - a dict of the form {a: {b, c}} where b and c depend on a
30
+ outputs:
31
+ L - an ordered list of nodes that satisfy the dependencies of edges
32
+
33
+ >>> from sympy.multipledispatch.utils import _toposort
34
+ >>> _toposort({1: (2, 3), 2: (3, )})
35
+ [1, 2, 3]
36
+
37
+ Closely follows the wikipedia page [2]
38
+
39
+ [1] Kahn, Arthur B. (1962), "Topological sorting of large networks",
40
+ Communications of the ACM
41
+ [2] https://en.wikipedia.org/wiki/Toposort#Algorithms
42
+ """
43
+ incoming_edges = reverse_dict(edges)
44
+ incoming_edges = {k: set(val) for k, val in incoming_edges.items()}
45
+ S = OrderedDict.fromkeys(v for v in edges if v not in incoming_edges)
46
+ L = []
47
+
48
+ while S:
49
+ n, _ = S.popitem()
50
+ L.append(n)
51
+ for m in edges.get(n, ()):
52
+ assert n in incoming_edges[m]
53
+ incoming_edges[m].remove(n)
54
+ if not incoming_edges[m]:
55
+ S[m] = None
56
+ if any(incoming_edges.get(v, None) for v in edges):
57
+ raise ValueError("Input has cycles")
58
+ return L
59
+
60
+
61
+ def reverse_dict(d):
62
+ """Reverses direction of dependence dict
63
+
64
+ >>> d = {'a': (1, 2), 'b': (2, 3), 'c':()}
65
+ >>> reverse_dict(d) # doctest: +SKIP
66
+ {1: ('a',), 2: ('a', 'b'), 3: ('b',)}
67
+
68
+ :note: dict order are not deterministic. As we iterate on the
69
+ input dict, it make the output of this function depend on the
70
+ dict order. So this function output order should be considered
71
+ as undeterministic.
72
+
73
+ """
74
+ result = {}
75
+ for key in d:
76
+ for val in d[key]:
77
+ result[val] = result.get(val, ()) + (key, )
78
+ return result
79
+
80
+
81
+ # Taken from toolz
82
+ # Avoids licensing issues because this version was authored by Matthew Rocklin
83
+ def groupby(func, seq):
84
+ """ Group a collection by a key function
85
+
86
+ >>> from sympy.multipledispatch.utils import groupby
87
+ >>> names = ['Alice', 'Bob', 'Charlie', 'Dan', 'Edith', 'Frank']
88
+ >>> groupby(len, names) # doctest: +SKIP
89
+ {3: ['Bob', 'Dan'], 5: ['Alice', 'Edith', 'Frank'], 7: ['Charlie']}
90
+
91
+ >>> iseven = lambda x: x % 2 == 0
92
+ >>> groupby(iseven, [1, 2, 3, 4, 5, 6, 7, 8]) # doctest: +SKIP
93
+ {False: [1, 3, 5, 7], True: [2, 4, 6, 8]}
94
+
95
+ See Also:
96
+ ``countby``
97
+ """
98
+
99
+ d = {}
100
+ for item in seq:
101
+ key = func(item)
102
+ if key not in d:
103
+ d[key] = []
104
+ d[key].append(item)
105
+ return d
llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/__pycache__/anticommutator.cpython-310.pyc ADDED
Binary file (4.74 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/__pycache__/boson.cpython-310.pyc ADDED
Binary file (8.49 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/__pycache__/cartesian.cpython-310.pyc ADDED
Binary file (11.4 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/__pycache__/cg.cpython-310.pyc ADDED
Binary file (22 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/__pycache__/commutator.cpython-310.pyc ADDED
Binary file (6.3 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/__pycache__/constants.cpython-310.pyc ADDED
Binary file (1.79 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/__pycache__/dagger.cpython-310.pyc ADDED
Binary file (2.86 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/__pycache__/density.cpython-310.pyc ADDED
Binary file (10.4 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/__pycache__/gate.cpython-310.pyc ADDED
Binary file (34.6 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/__pycache__/grover.cpython-310.pyc ADDED
Binary file (9.65 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/__pycache__/hilbert.cpython-310.pyc ADDED
Binary file (19.3 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/__pycache__/identitysearch.cpython-310.pyc ADDED
Binary file (21.7 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/__pycache__/innerproduct.cpython-310.pyc ADDED
Binary file (4.3 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/__pycache__/matrixcache.cpython-310.pyc ADDED
Binary file (3.74 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/__pycache__/matrixutils.cpython-310.pyc ADDED
Binary file (7.39 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/physics/quantum/__pycache__/operator.cpython-310.pyc ADDED
Binary file (19.8 kB). View file