applied-ai-018 commited on
Commit
2603e9b
·
verified ·
1 Parent(s): 7c75046

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/calculus/tests/__init__.py +0 -0
  2. llmeval-env/lib/python3.10/site-packages/sympy/calculus/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  3. llmeval-env/lib/python3.10/site-packages/sympy/calculus/tests/__pycache__/test_accumulationbounds.cpython-310.pyc +0 -0
  4. llmeval-env/lib/python3.10/site-packages/sympy/calculus/tests/__pycache__/test_euler.cpython-310.pyc +0 -0
  5. llmeval-env/lib/python3.10/site-packages/sympy/calculus/tests/__pycache__/test_finite_diff.cpython-310.pyc +0 -0
  6. llmeval-env/lib/python3.10/site-packages/sympy/calculus/tests/__pycache__/test_singularities.cpython-310.pyc +0 -0
  7. llmeval-env/lib/python3.10/site-packages/sympy/calculus/tests/__pycache__/test_util.cpython-310.pyc +0 -0
  8. llmeval-env/lib/python3.10/site-packages/sympy/calculus/tests/test_finite_diff.py +168 -0
  9. llmeval-env/lib/python3.10/site-packages/sympy/calculus/tests/test_util.py +331 -0
  10. llmeval-env/lib/python3.10/site-packages/sympy/interactive/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  11. llmeval-env/lib/python3.10/site-packages/sympy/interactive/tests/__pycache__/test_interactive.cpython-310.pyc +0 -0
  12. llmeval-env/lib/python3.10/site-packages/sympy/interactive/tests/__pycache__/test_ipython.cpython-310.pyc +0 -0
  13. llmeval-env/lib/python3.10/site-packages/sympy/interactive/tests/test_interactive.py +10 -0
  14. llmeval-env/lib/python3.10/site-packages/sympy/interactive/tests/test_ipython.py +278 -0
  15. llmeval-env/lib/python3.10/site-packages/sympy/simplify/__init__.py +60 -0
  16. llmeval-env/lib/python3.10/site-packages/sympy/simplify/__pycache__/__init__.cpython-310.pyc +0 -0
  17. llmeval-env/lib/python3.10/site-packages/sympy/simplify/__pycache__/combsimp.cpython-310.pyc +0 -0
  18. llmeval-env/lib/python3.10/site-packages/sympy/simplify/__pycache__/cse_main.cpython-310.pyc +0 -0
  19. llmeval-env/lib/python3.10/site-packages/sympy/simplify/__pycache__/cse_opts.cpython-310.pyc +0 -0
  20. llmeval-env/lib/python3.10/site-packages/sympy/simplify/__pycache__/epathtools.cpython-310.pyc +0 -0
  21. llmeval-env/lib/python3.10/site-packages/sympy/simplify/__pycache__/fu.cpython-310.pyc +0 -0
  22. llmeval-env/lib/python3.10/site-packages/sympy/simplify/__pycache__/gammasimp.cpython-310.pyc +0 -0
  23. llmeval-env/lib/python3.10/site-packages/sympy/simplify/__pycache__/hyperexpand.cpython-310.pyc +0 -0
  24. llmeval-env/lib/python3.10/site-packages/sympy/simplify/__pycache__/hyperexpand_doc.cpython-310.pyc +0 -0
  25. llmeval-env/lib/python3.10/site-packages/sympy/simplify/__pycache__/powsimp.cpython-310.pyc +0 -0
  26. llmeval-env/lib/python3.10/site-packages/sympy/simplify/__pycache__/radsimp.cpython-310.pyc +0 -0
  27. llmeval-env/lib/python3.10/site-packages/sympy/simplify/__pycache__/ratsimp.cpython-310.pyc +0 -0
  28. llmeval-env/lib/python3.10/site-packages/sympy/simplify/__pycache__/simplify.cpython-310.pyc +0 -0
  29. llmeval-env/lib/python3.10/site-packages/sympy/simplify/__pycache__/sqrtdenest.cpython-310.pyc +0 -0
  30. llmeval-env/lib/python3.10/site-packages/sympy/simplify/__pycache__/traversaltools.cpython-310.pyc +0 -0
  31. llmeval-env/lib/python3.10/site-packages/sympy/simplify/__pycache__/trigsimp.cpython-310.pyc +0 -0
  32. llmeval-env/lib/python3.10/site-packages/sympy/simplify/combsimp.py +114 -0
  33. llmeval-env/lib/python3.10/site-packages/sympy/simplify/cse_opts.py +52 -0
  34. llmeval-env/lib/python3.10/site-packages/sympy/simplify/fu.py +2099 -0
  35. llmeval-env/lib/python3.10/site-packages/sympy/simplify/gammasimp.py +497 -0
  36. llmeval-env/lib/python3.10/site-packages/sympy/simplify/hyperexpand.py +2494 -0
  37. llmeval-env/lib/python3.10/site-packages/sympy/simplify/ratsimp.py +222 -0
  38. llmeval-env/lib/python3.10/site-packages/sympy/simplify/tests/__init__.py +0 -0
  39. llmeval-env/lib/python3.10/site-packages/sympy/simplify/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  40. llmeval-env/lib/python3.10/site-packages/sympy/simplify/tests/__pycache__/test_cse.cpython-310.pyc +0 -0
  41. llmeval-env/lib/python3.10/site-packages/sympy/simplify/tests/__pycache__/test_epathtools.cpython-310.pyc +0 -0
  42. llmeval-env/lib/python3.10/site-packages/sympy/simplify/tests/__pycache__/test_fu.cpython-310.pyc +0 -0
  43. llmeval-env/lib/python3.10/site-packages/sympy/simplify/tests/__pycache__/test_function.cpython-310.pyc +0 -0
  44. llmeval-env/lib/python3.10/site-packages/sympy/simplify/tests/__pycache__/test_gammasimp.cpython-310.pyc +0 -0
  45. llmeval-env/lib/python3.10/site-packages/sympy/simplify/tests/__pycache__/test_hyperexpand.cpython-310.pyc +0 -0
  46. llmeval-env/lib/python3.10/site-packages/sympy/simplify/tests/__pycache__/test_powsimp.cpython-310.pyc +0 -0
  47. llmeval-env/lib/python3.10/site-packages/sympy/simplify/tests/__pycache__/test_radsimp.cpython-310.pyc +0 -0
  48. llmeval-env/lib/python3.10/site-packages/sympy/simplify/tests/__pycache__/test_ratsimp.cpython-310.pyc +0 -0
  49. llmeval-env/lib/python3.10/site-packages/sympy/simplify/tests/__pycache__/test_rewrite.cpython-310.pyc +0 -0
  50. llmeval-env/lib/python3.10/site-packages/sympy/simplify/tests/__pycache__/test_simplify.cpython-310.pyc +0 -0
llmeval-env/lib/python3.10/site-packages/sympy/calculus/tests/__init__.py ADDED
File without changes
llmeval-env/lib/python3.10/site-packages/sympy/calculus/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (193 Bytes). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/calculus/tests/__pycache__/test_accumulationbounds.cpython-310.pyc ADDED
Binary file (12.7 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/calculus/tests/__pycache__/test_euler.cpython-310.pyc ADDED
Binary file (3.84 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/calculus/tests/__pycache__/test_finite_diff.cpython-310.pyc ADDED
Binary file (7.48 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/calculus/tests/__pycache__/test_singularities.cpython-310.pyc ADDED
Binary file (4.7 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/calculus/tests/__pycache__/test_util.cpython-310.pyc ADDED
Binary file (15.2 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/calculus/tests/test_finite_diff.py ADDED
@@ -0,0 +1,168 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from itertools import product
2
+
3
+ from sympy.core.function import (Function, diff)
4
+ from sympy.core.numbers import Rational
5
+ from sympy.core.singleton import S
6
+ from sympy.core.symbol import symbols
7
+ from sympy.functions.elementary.exponential import exp
8
+ from sympy.calculus.finite_diff import (
9
+ apply_finite_diff, differentiate_finite, finite_diff_weights,
10
+ _as_finite_diff
11
+ )
12
+ from sympy.testing.pytest import raises, warns_deprecated_sympy
13
+
14
+
15
+ def test_apply_finite_diff():
16
+ x, h = symbols('x h')
17
+ f = Function('f')
18
+ assert (apply_finite_diff(1, [x-h, x+h], [f(x-h), f(x+h)], x) -
19
+ (f(x+h)-f(x-h))/(2*h)).simplify() == 0
20
+
21
+ assert (apply_finite_diff(1, [5, 6, 7], [f(5), f(6), f(7)], 5) -
22
+ (Rational(-3, 2)*f(5) + 2*f(6) - S.Half*f(7))).simplify() == 0
23
+ raises(ValueError, lambda: apply_finite_diff(1, [x, h], [f(x)]))
24
+
25
+
26
+ def test_finite_diff_weights():
27
+
28
+ d = finite_diff_weights(1, [5, 6, 7], 5)
29
+ assert d[1][2] == [Rational(-3, 2), 2, Rational(-1, 2)]
30
+
31
+ # Table 1, p. 702 in doi:10.1090/S0025-5718-1988-0935077-0
32
+ # --------------------------------------------------------
33
+ xl = [0, 1, -1, 2, -2, 3, -3, 4, -4]
34
+
35
+ # d holds all coefficients
36
+ d = finite_diff_weights(4, xl, S.Zero)
37
+
38
+ # Zeroeth derivative
39
+ for i in range(5):
40
+ assert d[0][i] == [S.One] + [S.Zero]*8
41
+
42
+ # First derivative
43
+ assert d[1][0] == [S.Zero]*9
44
+ assert d[1][2] == [S.Zero, S.Half, Rational(-1, 2)] + [S.Zero]*6
45
+ assert d[1][4] == [S.Zero, Rational(2, 3), Rational(-2, 3), Rational(-1, 12), Rational(1, 12)] + [S.Zero]*4
46
+ assert d[1][6] == [S.Zero, Rational(3, 4), Rational(-3, 4), Rational(-3, 20), Rational(3, 20),
47
+ Rational(1, 60), Rational(-1, 60)] + [S.Zero]*2
48
+ assert d[1][8] == [S.Zero, Rational(4, 5), Rational(-4, 5), Rational(-1, 5), Rational(1, 5),
49
+ Rational(4, 105), Rational(-4, 105), Rational(-1, 280), Rational(1, 280)]
50
+
51
+ # Second derivative
52
+ for i in range(2):
53
+ assert d[2][i] == [S.Zero]*9
54
+ assert d[2][2] == [-S(2), S.One, S.One] + [S.Zero]*6
55
+ assert d[2][4] == [Rational(-5, 2), Rational(4, 3), Rational(4, 3), Rational(-1, 12), Rational(-1, 12)] + [S.Zero]*4
56
+ assert d[2][6] == [Rational(-49, 18), Rational(3, 2), Rational(3, 2), Rational(-3, 20), Rational(-3, 20),
57
+ Rational(1, 90), Rational(1, 90)] + [S.Zero]*2
58
+ assert d[2][8] == [Rational(-205, 72), Rational(8, 5), Rational(8, 5), Rational(-1, 5), Rational(-1, 5),
59
+ Rational(8, 315), Rational(8, 315), Rational(-1, 560), Rational(-1, 560)]
60
+
61
+ # Third derivative
62
+ for i in range(3):
63
+ assert d[3][i] == [S.Zero]*9
64
+ assert d[3][4] == [S.Zero, -S.One, S.One, S.Half, Rational(-1, 2)] + [S.Zero]*4
65
+ assert d[3][6] == [S.Zero, Rational(-13, 8), Rational(13, 8), S.One, -S.One,
66
+ Rational(-1, 8), Rational(1, 8)] + [S.Zero]*2
67
+ assert d[3][8] == [S.Zero, Rational(-61, 30), Rational(61, 30), Rational(169, 120), Rational(-169, 120),
68
+ Rational(-3, 10), Rational(3, 10), Rational(7, 240), Rational(-7, 240)]
69
+
70
+ # Fourth derivative
71
+ for i in range(4):
72
+ assert d[4][i] == [S.Zero]*9
73
+ assert d[4][4] == [S(6), -S(4), -S(4), S.One, S.One] + [S.Zero]*4
74
+ assert d[4][6] == [Rational(28, 3), Rational(-13, 2), Rational(-13, 2), S(2), S(2),
75
+ Rational(-1, 6), Rational(-1, 6)] + [S.Zero]*2
76
+ assert d[4][8] == [Rational(91, 8), Rational(-122, 15), Rational(-122, 15), Rational(169, 60), Rational(169, 60),
77
+ Rational(-2, 5), Rational(-2, 5), Rational(7, 240), Rational(7, 240)]
78
+
79
+ # Table 2, p. 703 in doi:10.1090/S0025-5718-1988-0935077-0
80
+ # --------------------------------------------------------
81
+ xl = [[j/S(2) for j in list(range(-i*2+1, 0, 2))+list(range(1, i*2+1, 2))]
82
+ for i in range(1, 5)]
83
+
84
+ # d holds all coefficients
85
+ d = [finite_diff_weights({0: 1, 1: 2, 2: 4, 3: 4}[i], xl[i], 0) for
86
+ i in range(4)]
87
+
88
+ # Zeroth derivative
89
+ assert d[0][0][1] == [S.Half, S.Half]
90
+ assert d[1][0][3] == [Rational(-1, 16), Rational(9, 16), Rational(9, 16), Rational(-1, 16)]
91
+ assert d[2][0][5] == [Rational(3, 256), Rational(-25, 256), Rational(75, 128), Rational(75, 128),
92
+ Rational(-25, 256), Rational(3, 256)]
93
+ assert d[3][0][7] == [Rational(-5, 2048), Rational(49, 2048), Rational(-245, 2048), Rational(1225, 2048),
94
+ Rational(1225, 2048), Rational(-245, 2048), Rational(49, 2048), Rational(-5, 2048)]
95
+
96
+ # First derivative
97
+ assert d[0][1][1] == [-S.One, S.One]
98
+ assert d[1][1][3] == [Rational(1, 24), Rational(-9, 8), Rational(9, 8), Rational(-1, 24)]
99
+ assert d[2][1][5] == [Rational(-3, 640), Rational(25, 384), Rational(-75, 64),
100
+ Rational(75, 64), Rational(-25, 384), Rational(3, 640)]
101
+ assert d[3][1][7] == [Rational(5, 7168), Rational(-49, 5120),
102
+ Rational(245, 3072), Rational(-1225, 1024),
103
+ Rational(1225, 1024), Rational(-245, 3072),
104
+ Rational(49, 5120), Rational(-5, 7168)]
105
+
106
+ # Reasonably the rest of the table is also correct... (testing of that
107
+ # deemed excessive at the moment)
108
+ raises(ValueError, lambda: finite_diff_weights(-1, [1, 2]))
109
+ raises(ValueError, lambda: finite_diff_weights(1.2, [1, 2]))
110
+ x = symbols('x')
111
+ raises(ValueError, lambda: finite_diff_weights(x, [1, 2]))
112
+
113
+
114
+ def test_as_finite_diff():
115
+ x = symbols('x')
116
+ f = Function('f')
117
+ dx = Function('dx')
118
+
119
+ _as_finite_diff(f(x).diff(x), [x-2, x-1, x, x+1, x+2])
120
+
121
+ # Use of undefined functions in ``points``
122
+ df_true = -f(x+dx(x)/2-dx(x+dx(x)/2)/2) / dx(x+dx(x)/2) \
123
+ + f(x+dx(x)/2+dx(x+dx(x)/2)/2) / dx(x+dx(x)/2)
124
+ df_test = diff(f(x), x).as_finite_difference(points=dx(x), x0=x+dx(x)/2)
125
+ assert (df_test - df_true).simplify() == 0
126
+
127
+
128
+ def test_differentiate_finite():
129
+ x, y, h = symbols('x y h')
130
+ f = Function('f')
131
+ with warns_deprecated_sympy():
132
+ res0 = differentiate_finite(f(x, y) + exp(42), x, y, evaluate=True)
133
+ xm, xp, ym, yp = [v + sign*S.Half for v, sign in product([x, y], [-1, 1])]
134
+ ref0 = f(xm, ym) + f(xp, yp) - f(xm, yp) - f(xp, ym)
135
+ assert (res0 - ref0).simplify() == 0
136
+
137
+ g = Function('g')
138
+ with warns_deprecated_sympy():
139
+ res1 = differentiate_finite(f(x)*g(x) + 42, x, evaluate=True)
140
+ ref1 = (-f(x - S.Half) + f(x + S.Half))*g(x) + \
141
+ (-g(x - S.Half) + g(x + S.Half))*f(x)
142
+ assert (res1 - ref1).simplify() == 0
143
+
144
+ res2 = differentiate_finite(f(x) + x**3 + 42, x, points=[x-1, x+1])
145
+ ref2 = (f(x + 1) + (x + 1)**3 - f(x - 1) - (x - 1)**3)/2
146
+ assert (res2 - ref2).simplify() == 0
147
+ raises(TypeError, lambda: differentiate_finite(f(x)*g(x), x,
148
+ pints=[x-1, x+1]))
149
+
150
+ res3 = differentiate_finite(f(x)*g(x).diff(x), x)
151
+ ref3 = (-g(x) + g(x + 1))*f(x + S.Half) - (g(x) - g(x - 1))*f(x - S.Half)
152
+ assert res3 == ref3
153
+
154
+ res4 = differentiate_finite(f(x)*g(x).diff(x).diff(x), x)
155
+ ref4 = -((g(x - Rational(3, 2)) - 2*g(x - S.Half) + g(x + S.Half))*f(x - S.Half)) \
156
+ + (g(x - S.Half) - 2*g(x + S.Half) + g(x + Rational(3, 2)))*f(x + S.Half)
157
+ assert res4 == ref4
158
+
159
+ res5_expr = f(x).diff(x)*g(x).diff(x)
160
+ res5 = differentiate_finite(res5_expr, points=[x-h, x, x+h])
161
+ ref5 = (-2*f(x)/h + f(-h + x)/(2*h) + 3*f(h + x)/(2*h))*(-2*g(x)/h + g(-h + x)/(2*h) \
162
+ + 3*g(h + x)/(2*h))/(2*h) - (2*f(x)/h - 3*f(-h + x)/(2*h) - \
163
+ f(h + x)/(2*h))*(2*g(x)/h - 3*g(-h + x)/(2*h) - g(h + x)/(2*h))/(2*h)
164
+ assert res5 == ref5
165
+
166
+ res6 = res5.limit(h, 0).doit()
167
+ ref6 = diff(res5_expr, x)
168
+ assert res6 == ref6
llmeval-env/lib/python3.10/site-packages/sympy/calculus/tests/test_util.py ADDED
@@ -0,0 +1,331 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.numbers import (E, I, Rational, oo, pi)
2
+ from sympy.core.singleton import S
3
+ from sympy.core.symbol import (Symbol, symbols)
4
+ from sympy.functions.elementary.complexes import (Abs, re)
5
+ from sympy.functions.elementary.exponential import (exp, log)
6
+ from sympy.functions.elementary.miscellaneous import sqrt
7
+ from sympy.functions.elementary.piecewise import Piecewise
8
+ from sympy.functions.elementary.trigonometric import (cos, cot, csc, sec, sin, tan)
9
+ from sympy.functions.special.error_functions import expint
10
+ from sympy.matrices.expressions.matexpr import MatrixSymbol
11
+ from sympy.simplify.simplify import simplify
12
+ from sympy.calculus.util import (function_range, continuous_domain, not_empty_in,
13
+ periodicity, lcim, is_convex,
14
+ stationary_points, minimum, maximum)
15
+ from sympy.sets.sets import (Interval, FiniteSet, Complement, Union)
16
+ from sympy.testing.pytest import raises, _both_exp_pow
17
+ from sympy.abc import x
18
+
19
+ a = Symbol('a', real=True)
20
+
21
+ def test_function_range():
22
+ x, y, a, b = symbols('x y a b')
23
+ assert function_range(sin(x), x, Interval(-pi/2, pi/2)
24
+ ) == Interval(-1, 1)
25
+ assert function_range(sin(x), x, Interval(0, pi)
26
+ ) == Interval(0, 1)
27
+ assert function_range(tan(x), x, Interval(0, pi)
28
+ ) == Interval(-oo, oo)
29
+ assert function_range(tan(x), x, Interval(pi/2, pi)
30
+ ) == Interval(-oo, 0)
31
+ assert function_range((x + 3)/(x - 2), x, Interval(-5, 5)
32
+ ) == Union(Interval(-oo, Rational(2, 7)), Interval(Rational(8, 3), oo))
33
+ assert function_range(1/(x**2), x, Interval(-1, 1)
34
+ ) == Interval(1, oo)
35
+ assert function_range(exp(x), x, Interval(-1, 1)
36
+ ) == Interval(exp(-1), exp(1))
37
+ assert function_range(log(x) - x, x, S.Reals
38
+ ) == Interval(-oo, -1)
39
+ assert function_range(sqrt(3*x - 1), x, Interval(0, 2)
40
+ ) == Interval(0, sqrt(5))
41
+ assert function_range(x*(x - 1) - (x**2 - x), x, S.Reals
42
+ ) == FiniteSet(0)
43
+ assert function_range(x*(x - 1) - (x**2 - x) + y, x, S.Reals
44
+ ) == FiniteSet(y)
45
+ assert function_range(sin(x), x, Union(Interval(-5, -3), FiniteSet(4))
46
+ ) == Union(Interval(-sin(3), 1), FiniteSet(sin(4)))
47
+ assert function_range(cos(x), x, Interval(-oo, -4)
48
+ ) == Interval(-1, 1)
49
+ assert function_range(cos(x), x, S.EmptySet) == S.EmptySet
50
+ assert function_range(x/sqrt(x**2+1), x, S.Reals) == Interval.open(-1,1)
51
+ raises(NotImplementedError, lambda : function_range(
52
+ exp(x)*(sin(x) - cos(x))/2 - x, x, S.Reals))
53
+ raises(NotImplementedError, lambda : function_range(
54
+ sin(x) + x, x, S.Reals)) # issue 13273
55
+ raises(NotImplementedError, lambda : function_range(
56
+ log(x), x, S.Integers))
57
+ raises(NotImplementedError, lambda : function_range(
58
+ sin(x)/2, x, S.Naturals))
59
+
60
+
61
+ def test_continuous_domain():
62
+ x = Symbol('x')
63
+ assert continuous_domain(sin(x), x, Interval(0, 2*pi)) == Interval(0, 2*pi)
64
+ assert continuous_domain(tan(x), x, Interval(0, 2*pi)) == \
65
+ Union(Interval(0, pi/2, False, True), Interval(pi/2, pi*Rational(3, 2), True, True),
66
+ Interval(pi*Rational(3, 2), 2*pi, True, False))
67
+ assert continuous_domain((x - 1)/((x - 1)**2), x, S.Reals) == \
68
+ Union(Interval(-oo, 1, True, True), Interval(1, oo, True, True))
69
+ assert continuous_domain(log(x) + log(4*x - 1), x, S.Reals) == \
70
+ Interval(Rational(1, 4), oo, True, True)
71
+ assert continuous_domain(1/sqrt(x - 3), x, S.Reals) == Interval(3, oo, True, True)
72
+ assert continuous_domain(1/x - 2, x, S.Reals) == \
73
+ Union(Interval.open(-oo, 0), Interval.open(0, oo))
74
+ assert continuous_domain(1/(x**2 - 4) + 2, x, S.Reals) == \
75
+ Union(Interval.open(-oo, -2), Interval.open(-2, 2), Interval.open(2, oo))
76
+ domain = continuous_domain(log(tan(x)**2 + 1), x, S.Reals)
77
+ assert not domain.contains(3*pi/2)
78
+ assert domain.contains(5)
79
+ d = Symbol('d', even=True, zero=False)
80
+ assert continuous_domain(x**(1/d), x, S.Reals) == Interval(0, oo)
81
+
82
+
83
+ def test_not_empty_in():
84
+ assert not_empty_in(FiniteSet(x, 2*x).intersect(Interval(1, 2, True, False)), x) == \
85
+ Interval(S.Half, 2, True, False)
86
+ assert not_empty_in(FiniteSet(x, x**2).intersect(Interval(1, 2)), x) == \
87
+ Union(Interval(-sqrt(2), -1), Interval(1, 2))
88
+ assert not_empty_in(FiniteSet(x**2 + x, x).intersect(Interval(2, 4)), x) == \
89
+ Union(Interval(-sqrt(17)/2 - S.Half, -2),
90
+ Interval(1, Rational(-1, 2) + sqrt(17)/2), Interval(2, 4))
91
+ assert not_empty_in(FiniteSet(x/(x - 1)).intersect(S.Reals), x) == \
92
+ Complement(S.Reals, FiniteSet(1))
93
+ assert not_empty_in(FiniteSet(a/(a - 1)).intersect(S.Reals), a) == \
94
+ Complement(S.Reals, FiniteSet(1))
95
+ assert not_empty_in(FiniteSet((x**2 - 3*x + 2)/(x - 1)).intersect(S.Reals), x) == \
96
+ Complement(S.Reals, FiniteSet(1))
97
+ assert not_empty_in(FiniteSet(3, 4, x/(x - 1)).intersect(Interval(2, 3)), x) == \
98
+ Interval(-oo, oo)
99
+ assert not_empty_in(FiniteSet(4, x/(x - 1)).intersect(Interval(2, 3)), x) == \
100
+ Interval(S(3)/2, 2)
101
+ assert not_empty_in(FiniteSet(x/(x**2 - 1)).intersect(S.Reals), x) == \
102
+ Complement(S.Reals, FiniteSet(-1, 1))
103
+ assert not_empty_in(FiniteSet(x, x**2).intersect(Union(Interval(1, 3, True, True),
104
+ Interval(4, 5))), x) == \
105
+ Union(Interval(-sqrt(5), -2), Interval(-sqrt(3), -1, True, True),
106
+ Interval(1, 3, True, True), Interval(4, 5))
107
+ assert not_empty_in(FiniteSet(1).intersect(Interval(3, 4)), x) == S.EmptySet
108
+ assert not_empty_in(FiniteSet(x**2/(x + 2)).intersect(Interval(1, oo)), x) == \
109
+ Union(Interval(-2, -1, True, False), Interval(2, oo))
110
+ raises(ValueError, lambda: not_empty_in(x))
111
+ raises(ValueError, lambda: not_empty_in(Interval(0, 1), x))
112
+ raises(NotImplementedError,
113
+ lambda: not_empty_in(FiniteSet(x).intersect(S.Reals), x, a))
114
+
115
+
116
+ @_both_exp_pow
117
+ def test_periodicity():
118
+ x = Symbol('x')
119
+ y = Symbol('y')
120
+ z = Symbol('z', real=True)
121
+
122
+ assert periodicity(sin(2*x), x) == pi
123
+ assert periodicity((-2)*tan(4*x), x) == pi/4
124
+ assert periodicity(sin(x)**2, x) == 2*pi
125
+ assert periodicity(3**tan(3*x), x) == pi/3
126
+ assert periodicity(tan(x)*cos(x), x) == 2*pi
127
+ assert periodicity(sin(x)**(tan(x)), x) == 2*pi
128
+ assert periodicity(tan(x)*sec(x), x) == 2*pi
129
+ assert periodicity(sin(2*x)*cos(2*x) - y, x) == pi/2
130
+ assert periodicity(tan(x) + cot(x), x) == pi
131
+ assert periodicity(sin(x) - cos(2*x), x) == 2*pi
132
+ assert periodicity(sin(x) - 1, x) == 2*pi
133
+ assert periodicity(sin(4*x) + sin(x)*cos(x), x) == pi
134
+ assert periodicity(exp(sin(x)), x) == 2*pi
135
+ assert periodicity(log(cot(2*x)) - sin(cos(2*x)), x) == pi
136
+ assert periodicity(sin(2*x)*exp(tan(x) - csc(2*x)), x) == pi
137
+ assert periodicity(cos(sec(x) - csc(2*x)), x) == 2*pi
138
+ assert periodicity(tan(sin(2*x)), x) == pi
139
+ assert periodicity(2*tan(x)**2, x) == pi
140
+ assert periodicity(sin(x%4), x) == 4
141
+ assert periodicity(sin(x)%4, x) == 2*pi
142
+ assert periodicity(tan((3*x-2)%4), x) == Rational(4, 3)
143
+ assert periodicity((sqrt(2)*(x+1)+x) % 3, x) == 3 / (sqrt(2)+1)
144
+ assert periodicity((x**2+1) % x, x) is None
145
+ assert periodicity(sin(re(x)), x) == 2*pi
146
+ assert periodicity(sin(x)**2 + cos(x)**2, x) is S.Zero
147
+ assert periodicity(tan(x), y) is S.Zero
148
+ assert periodicity(sin(x) + I*cos(x), x) == 2*pi
149
+ assert periodicity(x - sin(2*y), y) == pi
150
+
151
+ assert periodicity(exp(x), x) is None
152
+ assert periodicity(exp(I*x), x) == 2*pi
153
+ assert periodicity(exp(I*z), z) == 2*pi
154
+ assert periodicity(exp(z), z) is None
155
+ assert periodicity(exp(log(sin(z) + I*cos(2*z)), evaluate=False), z) == 2*pi
156
+ assert periodicity(exp(log(sin(2*z) + I*cos(z)), evaluate=False), z) == 2*pi
157
+ assert periodicity(exp(sin(z)), z) == 2*pi
158
+ assert periodicity(exp(2*I*z), z) == pi
159
+ assert periodicity(exp(z + I*sin(z)), z) is None
160
+ assert periodicity(exp(cos(z/2) + sin(z)), z) == 4*pi
161
+ assert periodicity(log(x), x) is None
162
+ assert periodicity(exp(x)**sin(x), x) is None
163
+ assert periodicity(sin(x)**y, y) is None
164
+
165
+ assert periodicity(Abs(sin(Abs(sin(x)))), x) == pi
166
+ assert all(periodicity(Abs(f(x)), x) == pi for f in (
167
+ cos, sin, sec, csc, tan, cot))
168
+ assert periodicity(Abs(sin(tan(x))), x) == pi
169
+ assert periodicity(Abs(sin(sin(x) + tan(x))), x) == 2*pi
170
+ assert periodicity(sin(x) > S.Half, x) == 2*pi
171
+
172
+ assert periodicity(x > 2, x) is None
173
+ assert periodicity(x**3 - x**2 + 1, x) is None
174
+ assert periodicity(Abs(x), x) is None
175
+ assert periodicity(Abs(x**2 - 1), x) is None
176
+
177
+ assert periodicity((x**2 + 4)%2, x) is None
178
+ assert periodicity((E**x)%3, x) is None
179
+
180
+ assert periodicity(sin(expint(1, x))/expint(1, x), x) is None
181
+ # returning `None` for any Piecewise
182
+ p = Piecewise((0, x < -1), (x**2, x <= 1), (log(x), True))
183
+ assert periodicity(p, x) is None
184
+
185
+ m = MatrixSymbol('m', 3, 3)
186
+ raises(NotImplementedError, lambda: periodicity(sin(m), m))
187
+ raises(NotImplementedError, lambda: periodicity(sin(m[0, 0]), m))
188
+ raises(NotImplementedError, lambda: periodicity(sin(m), m[0, 0]))
189
+ raises(NotImplementedError, lambda: periodicity(sin(m[0, 0]), m[0, 0]))
190
+
191
+
192
+ def test_periodicity_check():
193
+ x = Symbol('x')
194
+ y = Symbol('y')
195
+
196
+ assert periodicity(tan(x), x, check=True) == pi
197
+ assert periodicity(sin(x) + cos(x), x, check=True) == 2*pi
198
+ assert periodicity(sec(x), x) == 2*pi
199
+ assert periodicity(sin(x*y), x) == 2*pi/abs(y)
200
+ assert periodicity(Abs(sec(sec(x))), x) == pi
201
+
202
+
203
+ def test_lcim():
204
+ assert lcim([S.Half, S(2), S(3)]) == 6
205
+ assert lcim([pi/2, pi/4, pi]) == pi
206
+ assert lcim([2*pi, pi/2]) == 2*pi
207
+ assert lcim([S.One, 2*pi]) is None
208
+ assert lcim([S(2) + 2*E, E/3 + Rational(1, 3), S.One + E]) == S(2) + 2*E
209
+
210
+
211
+ def test_is_convex():
212
+ assert is_convex(1/x, x, domain=Interval.open(0, oo)) == True
213
+ assert is_convex(1/x, x, domain=Interval(-oo, 0)) == False
214
+ assert is_convex(x**2, x, domain=Interval(0, oo)) == True
215
+ assert is_convex(1/x**3, x, domain=Interval.Lopen(0, oo)) == True
216
+ assert is_convex(-1/x**3, x, domain=Interval.Ropen(-oo, 0)) == True
217
+ assert is_convex(log(x), x) == False
218
+ raises(NotImplementedError, lambda: is_convex(log(x), x, a))
219
+
220
+
221
+ def test_stationary_points():
222
+ x, y = symbols('x y')
223
+
224
+ assert stationary_points(sin(x), x, Interval(-pi/2, pi/2)
225
+ ) == {-pi/2, pi/2}
226
+ assert stationary_points(sin(x), x, Interval.Ropen(0, pi/4)
227
+ ) is S.EmptySet
228
+ assert stationary_points(tan(x), x,
229
+ ) is S.EmptySet
230
+ assert stationary_points(sin(x)*cos(x), x, Interval(0, pi)
231
+ ) == {pi/4, pi*Rational(3, 4)}
232
+ assert stationary_points(sec(x), x, Interval(0, pi)
233
+ ) == {0, pi}
234
+ assert stationary_points((x+3)*(x-2), x
235
+ ) == FiniteSet(Rational(-1, 2))
236
+ assert stationary_points((x + 3)/(x - 2), x, Interval(-5, 5)
237
+ ) is S.EmptySet
238
+ assert stationary_points((x**2+3)/(x-2), x
239
+ ) == {2 - sqrt(7), 2 + sqrt(7)}
240
+ assert stationary_points((x**2+3)/(x-2), x, Interval(0, 5)
241
+ ) == {2 + sqrt(7)}
242
+ assert stationary_points(x**4 + x**3 - 5*x**2, x, S.Reals
243
+ ) == FiniteSet(-2, 0, Rational(5, 4))
244
+ assert stationary_points(exp(x), x
245
+ ) is S.EmptySet
246
+ assert stationary_points(log(x) - x, x, S.Reals
247
+ ) == {1}
248
+ assert stationary_points(cos(x), x, Union(Interval(0, 5), Interval(-6, -3))
249
+ ) == {0, -pi, pi}
250
+ assert stationary_points(y, x, S.Reals
251
+ ) == S.Reals
252
+ assert stationary_points(y, x, S.EmptySet) == S.EmptySet
253
+
254
+
255
+ def test_maximum():
256
+ x, y = symbols('x y')
257
+ assert maximum(sin(x), x) is S.One
258
+ assert maximum(sin(x), x, Interval(0, 1)) == sin(1)
259
+ assert maximum(tan(x), x) is oo
260
+ assert maximum(tan(x), x, Interval(-pi/4, pi/4)) is S.One
261
+ assert maximum(sin(x)*cos(x), x, S.Reals) == S.Half
262
+ assert simplify(maximum(sin(x)*cos(x), x, Interval(pi*Rational(3, 8), pi*Rational(5, 8)))
263
+ ) == sqrt(2)/4
264
+ assert maximum((x+3)*(x-2), x) is oo
265
+ assert maximum((x+3)*(x-2), x, Interval(-5, 0)) == S(14)
266
+ assert maximum((x+3)/(x-2), x, Interval(-5, 0)) == Rational(2, 7)
267
+ assert simplify(maximum(-x**4-x**3+x**2+10, x)
268
+ ) == 41*sqrt(41)/512 + Rational(5419, 512)
269
+ assert maximum(exp(x), x, Interval(-oo, 2)) == exp(2)
270
+ assert maximum(log(x) - x, x, S.Reals) is S.NegativeOne
271
+ assert maximum(cos(x), x, Union(Interval(0, 5), Interval(-6, -3))
272
+ ) is S.One
273
+ assert maximum(cos(x)-sin(x), x, S.Reals) == sqrt(2)
274
+ assert maximum(y, x, S.Reals) == y
275
+ assert maximum(abs(a**3 + a), a, Interval(0, 2)) == 10
276
+ assert maximum(abs(60*a**3 + 24*a), a, Interval(0, 2)) == 528
277
+ assert maximum(abs(12*a*(5*a**2 + 2)), a, Interval(0, 2)) == 528
278
+ assert maximum(x/sqrt(x**2+1), x, S.Reals) == 1
279
+
280
+ raises(ValueError, lambda : maximum(sin(x), x, S.EmptySet))
281
+ raises(ValueError, lambda : maximum(log(cos(x)), x, S.EmptySet))
282
+ raises(ValueError, lambda : maximum(1/(x**2 + y**2 + 1), x, S.EmptySet))
283
+ raises(ValueError, lambda : maximum(sin(x), sin(x)))
284
+ raises(ValueError, lambda : maximum(sin(x), x*y, S.EmptySet))
285
+ raises(ValueError, lambda : maximum(sin(x), S.One))
286
+
287
+
288
+ def test_minimum():
289
+ x, y = symbols('x y')
290
+
291
+ assert minimum(sin(x), x) is S.NegativeOne
292
+ assert minimum(sin(x), x, Interval(1, 4)) == sin(4)
293
+ assert minimum(tan(x), x) is -oo
294
+ assert minimum(tan(x), x, Interval(-pi/4, pi/4)) is S.NegativeOne
295
+ assert minimum(sin(x)*cos(x), x, S.Reals) == Rational(-1, 2)
296
+ assert simplify(minimum(sin(x)*cos(x), x, Interval(pi*Rational(3, 8), pi*Rational(5, 8)))
297
+ ) == -sqrt(2)/4
298
+ assert minimum((x+3)*(x-2), x) == Rational(-25, 4)
299
+ assert minimum((x+3)/(x-2), x, Interval(-5, 0)) == Rational(-3, 2)
300
+ assert minimum(x**4-x**3+x**2+10, x) == S(10)
301
+ assert minimum(exp(x), x, Interval(-2, oo)) == exp(-2)
302
+ assert minimum(log(x) - x, x, S.Reals) is -oo
303
+ assert minimum(cos(x), x, Union(Interval(0, 5), Interval(-6, -3))
304
+ ) is S.NegativeOne
305
+ assert minimum(cos(x)-sin(x), x, S.Reals) == -sqrt(2)
306
+ assert minimum(y, x, S.Reals) == y
307
+ assert minimum(x/sqrt(x**2+1), x, S.Reals) == -1
308
+
309
+ raises(ValueError, lambda : minimum(sin(x), x, S.EmptySet))
310
+ raises(ValueError, lambda : minimum(log(cos(x)), x, S.EmptySet))
311
+ raises(ValueError, lambda : minimum(1/(x**2 + y**2 + 1), x, S.EmptySet))
312
+ raises(ValueError, lambda : minimum(sin(x), sin(x)))
313
+ raises(ValueError, lambda : minimum(sin(x), x*y, S.EmptySet))
314
+ raises(ValueError, lambda : minimum(sin(x), S.One))
315
+
316
+
317
+ def test_issue_19869():
318
+ t = symbols('t')
319
+ assert (maximum(sqrt(3)*(t - 1)/(3*sqrt(t**2 + 1)), t)
320
+ ) == sqrt(3)/3
321
+
322
+
323
+ def test_issue_16469():
324
+ x = Symbol("x", real=True)
325
+ f = abs(x)
326
+ assert function_range(f, x, S.Reals) == Interval(0, oo, False, True)
327
+
328
+
329
+ @_both_exp_pow
330
+ def test_issue_18747():
331
+ assert periodicity(exp(pi*I*(x/4+S.Half/2)), x) == 8
llmeval-env/lib/python3.10/site-packages/sympy/interactive/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (196 Bytes). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/interactive/tests/__pycache__/test_interactive.cpython-310.pyc ADDED
Binary file (705 Bytes). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/interactive/tests/__pycache__/test_ipython.cpython-310.pyc ADDED
Binary file (6.67 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/interactive/tests/test_interactive.py ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.interactive.session import int_to_Integer
2
+
3
+
4
+ def test_int_to_Integer():
5
+ assert int_to_Integer("1 + 2.2 + 0x3 + 40") == \
6
+ 'Integer (1 )+2.2 +Integer (0x3 )+Integer (40 )'
7
+ assert int_to_Integer("0b101") == 'Integer (0b101 )'
8
+ assert int_to_Integer("ab1 + 1 + '1 + 2'") == "ab1 +Integer (1 )+'1 + 2'"
9
+ assert int_to_Integer("(2 + \n3)") == '(Integer (2 )+\nInteger (3 ))'
10
+ assert int_to_Integer("2 + 2.0 + 2j + 2e-10") == 'Integer (2 )+2.0 +2j +2e-10 '
llmeval-env/lib/python3.10/site-packages/sympy/interactive/tests/test_ipython.py ADDED
@@ -0,0 +1,278 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests of tools for setting up interactive IPython sessions. """
2
+
3
+ from sympy.interactive.session import (init_ipython_session,
4
+ enable_automatic_symbols, enable_automatic_int_sympification)
5
+
6
+ from sympy.core import Symbol, Rational, Integer
7
+ from sympy.external import import_module
8
+ from sympy.testing.pytest import raises
9
+
10
+ # TODO: The code below could be made more granular with something like:
11
+ #
12
+ # @requires('IPython', version=">=0.11")
13
+ # def test_automatic_symbols(ipython):
14
+
15
+ ipython = import_module("IPython", min_module_version="0.11")
16
+
17
+ if not ipython:
18
+ #bin/test will not execute any tests now
19
+ disabled = True
20
+
21
+ # WARNING: These tests will modify the existing IPython environment. IPython
22
+ # uses a single instance for its interpreter, so there is no way to isolate
23
+ # the test from another IPython session. It also means that if this test is
24
+ # run twice in the same Python session it will fail. This isn't usually a
25
+ # problem because the test suite is run in a subprocess by default, but if the
26
+ # tests are run with subprocess=False it can pollute the current IPython
27
+ # session. See the discussion in issue #15149.
28
+
29
+ def test_automatic_symbols():
30
+ # NOTE: Because of the way the hook works, you have to use run_cell(code,
31
+ # True). This means that the code must have no Out, or it will be printed
32
+ # during the tests.
33
+ app = init_ipython_session()
34
+ app.run_cell("from sympy import *")
35
+
36
+ enable_automatic_symbols(app)
37
+
38
+ symbol = "verylongsymbolname"
39
+ assert symbol not in app.user_ns
40
+ app.run_cell("a = %s" % symbol, True)
41
+ assert symbol not in app.user_ns
42
+ app.run_cell("a = type(%s)" % symbol, True)
43
+ assert app.user_ns['a'] == Symbol
44
+ app.run_cell("%s = Symbol('%s')" % (symbol, symbol), True)
45
+ assert symbol in app.user_ns
46
+
47
+ # Check that built-in names aren't overridden
48
+ app.run_cell("a = all == __builtin__.all", True)
49
+ assert "all" not in app.user_ns
50
+ assert app.user_ns['a'] is True
51
+
52
+ # Check that SymPy names aren't overridden
53
+ app.run_cell("import sympy")
54
+ app.run_cell("a = factorial == sympy.factorial", True)
55
+ assert app.user_ns['a'] is True
56
+
57
+
58
+ def test_int_to_Integer():
59
+ # XXX: Warning, don't test with == here. 0.5 == Rational(1, 2) is True!
60
+ app = init_ipython_session()
61
+ app.run_cell("from sympy import Integer")
62
+ app.run_cell("a = 1")
63
+ assert isinstance(app.user_ns['a'], int)
64
+
65
+ enable_automatic_int_sympification(app)
66
+ app.run_cell("a = 1/2")
67
+ assert isinstance(app.user_ns['a'], Rational)
68
+ app.run_cell("a = 1")
69
+ assert isinstance(app.user_ns['a'], Integer)
70
+ app.run_cell("a = int(1)")
71
+ assert isinstance(app.user_ns['a'], int)
72
+ app.run_cell("a = (1/\n2)")
73
+ assert app.user_ns['a'] == Rational(1, 2)
74
+ # TODO: How can we test that the output of a SyntaxError is the original
75
+ # input, not the transformed input?
76
+
77
+
78
+ def test_ipythonprinting():
79
+ # Initialize and setup IPython session
80
+ app = init_ipython_session()
81
+ app.run_cell("ip = get_ipython()")
82
+ app.run_cell("inst = ip.instance()")
83
+ app.run_cell("format = inst.display_formatter.format")
84
+ app.run_cell("from sympy import Symbol")
85
+
86
+ # Printing without printing extension
87
+ app.run_cell("a = format(Symbol('pi'))")
88
+ app.run_cell("a2 = format(Symbol('pi')**2)")
89
+ # Deal with API change starting at IPython 1.0
90
+ if int(ipython.__version__.split(".")[0]) < 1:
91
+ assert app.user_ns['a']['text/plain'] == "pi"
92
+ assert app.user_ns['a2']['text/plain'] == "pi**2"
93
+ else:
94
+ assert app.user_ns['a'][0]['text/plain'] == "pi"
95
+ assert app.user_ns['a2'][0]['text/plain'] == "pi**2"
96
+
97
+ # Load printing extension
98
+ app.run_cell("from sympy import init_printing")
99
+ app.run_cell("init_printing()")
100
+ # Printing with printing extension
101
+ app.run_cell("a = format(Symbol('pi'))")
102
+ app.run_cell("a2 = format(Symbol('pi')**2)")
103
+ # Deal with API change starting at IPython 1.0
104
+ if int(ipython.__version__.split(".")[0]) < 1:
105
+ assert app.user_ns['a']['text/plain'] in ('\N{GREEK SMALL LETTER PI}', 'pi')
106
+ assert app.user_ns['a2']['text/plain'] in (' 2\n\N{GREEK SMALL LETTER PI} ', ' 2\npi ')
107
+ else:
108
+ assert app.user_ns['a'][0]['text/plain'] in ('\N{GREEK SMALL LETTER PI}', 'pi')
109
+ assert app.user_ns['a2'][0]['text/plain'] in (' 2\n\N{GREEK SMALL LETTER PI} ', ' 2\npi ')
110
+
111
+
112
+ def test_print_builtin_option():
113
+ # Initialize and setup IPython session
114
+ app = init_ipython_session()
115
+ app.run_cell("ip = get_ipython()")
116
+ app.run_cell("inst = ip.instance()")
117
+ app.run_cell("format = inst.display_formatter.format")
118
+ app.run_cell("from sympy import Symbol")
119
+ app.run_cell("from sympy import init_printing")
120
+
121
+ app.run_cell("a = format({Symbol('pi'): 3.14, Symbol('n_i'): 3})")
122
+ # Deal with API change starting at IPython 1.0
123
+ if int(ipython.__version__.split(".")[0]) < 1:
124
+ text = app.user_ns['a']['text/plain']
125
+ raises(KeyError, lambda: app.user_ns['a']['text/latex'])
126
+ else:
127
+ text = app.user_ns['a'][0]['text/plain']
128
+ raises(KeyError, lambda: app.user_ns['a'][0]['text/latex'])
129
+ # XXX: How can we make this ignore the terminal width? This test fails if
130
+ # the terminal is too narrow.
131
+ assert text in ("{pi: 3.14, n_i: 3}",
132
+ '{n\N{LATIN SUBSCRIPT SMALL LETTER I}: 3, \N{GREEK SMALL LETTER PI}: 3.14}',
133
+ "{n_i: 3, pi: 3.14}",
134
+ '{\N{GREEK SMALL LETTER PI}: 3.14, n\N{LATIN SUBSCRIPT SMALL LETTER I}: 3}')
135
+
136
+ # If we enable the default printing, then the dictionary's should render
137
+ # as a LaTeX version of the whole dict: ${\pi: 3.14, n_i: 3}$
138
+ app.run_cell("inst.display_formatter.formatters['text/latex'].enabled = True")
139
+ app.run_cell("init_printing(use_latex=True)")
140
+ app.run_cell("a = format({Symbol('pi'): 3.14, Symbol('n_i'): 3})")
141
+ # Deal with API change starting at IPython 1.0
142
+ if int(ipython.__version__.split(".")[0]) < 1:
143
+ text = app.user_ns['a']['text/plain']
144
+ latex = app.user_ns['a']['text/latex']
145
+ else:
146
+ text = app.user_ns['a'][0]['text/plain']
147
+ latex = app.user_ns['a'][0]['text/latex']
148
+ assert text in ("{pi: 3.14, n_i: 3}",
149
+ '{n\N{LATIN SUBSCRIPT SMALL LETTER I}: 3, \N{GREEK SMALL LETTER PI}: 3.14}',
150
+ "{n_i: 3, pi: 3.14}",
151
+ '{\N{GREEK SMALL LETTER PI}: 3.14, n\N{LATIN SUBSCRIPT SMALL LETTER I}: 3}')
152
+ assert latex == r'$\displaystyle \left\{ n_{i} : 3, \ \pi : 3.14\right\}$'
153
+
154
+ # Objects with an _latex overload should also be handled by our tuple
155
+ # printer.
156
+ app.run_cell("""\
157
+ class WithOverload:
158
+ def _latex(self, printer):
159
+ return r"\\LaTeX"
160
+ """)
161
+ app.run_cell("a = format((WithOverload(),))")
162
+ # Deal with API change starting at IPython 1.0
163
+ if int(ipython.__version__.split(".")[0]) < 1:
164
+ latex = app.user_ns['a']['text/latex']
165
+ else:
166
+ latex = app.user_ns['a'][0]['text/latex']
167
+ assert latex == r'$\displaystyle \left( \LaTeX,\right)$'
168
+
169
+ app.run_cell("inst.display_formatter.formatters['text/latex'].enabled = True")
170
+ app.run_cell("init_printing(use_latex=True, print_builtin=False)")
171
+ app.run_cell("a = format({Symbol('pi'): 3.14, Symbol('n_i'): 3})")
172
+ # Deal with API change starting at IPython 1.0
173
+ if int(ipython.__version__.split(".")[0]) < 1:
174
+ text = app.user_ns['a']['text/plain']
175
+ raises(KeyError, lambda: app.user_ns['a']['text/latex'])
176
+ else:
177
+ text = app.user_ns['a'][0]['text/plain']
178
+ raises(KeyError, lambda: app.user_ns['a'][0]['text/latex'])
179
+ # Note : In Python 3 we have one text type: str which holds Unicode data
180
+ # and two byte types bytes and bytearray.
181
+ # Python 3.3.3 + IPython 0.13.2 gives: '{n_i: 3, pi: 3.14}'
182
+ # Python 3.3.3 + IPython 1.1.0 gives: '{n_i: 3, pi: 3.14}'
183
+ assert text in ("{pi: 3.14, n_i: 3}", "{n_i: 3, pi: 3.14}")
184
+
185
+
186
+ def test_builtin_containers():
187
+ # Initialize and setup IPython session
188
+ app = init_ipython_session()
189
+ app.run_cell("ip = get_ipython()")
190
+ app.run_cell("inst = ip.instance()")
191
+ app.run_cell("format = inst.display_formatter.format")
192
+ app.run_cell("inst.display_formatter.formatters['text/latex'].enabled = True")
193
+ app.run_cell("from sympy import init_printing, Matrix")
194
+ app.run_cell('init_printing(use_latex=True, use_unicode=False)')
195
+
196
+ # Make sure containers that shouldn't pretty print don't.
197
+ app.run_cell('a = format((True, False))')
198
+ app.run_cell('import sys')
199
+ app.run_cell('b = format(sys.flags)')
200
+ app.run_cell('c = format((Matrix([1, 2]),))')
201
+ # Deal with API change starting at IPython 1.0
202
+ if int(ipython.__version__.split(".")[0]) < 1:
203
+ assert app.user_ns['a']['text/plain'] == '(True, False)'
204
+ assert 'text/latex' not in app.user_ns['a']
205
+ assert app.user_ns['b']['text/plain'][:10] == 'sys.flags('
206
+ assert 'text/latex' not in app.user_ns['b']
207
+ assert app.user_ns['c']['text/plain'] == \
208
+ """\
209
+ [1] \n\
210
+ ([ ],)
211
+ [2] \
212
+ """
213
+ assert app.user_ns['c']['text/latex'] == '$\\displaystyle \\left( \\left[\\begin{matrix}1\\\\2\\end{matrix}\\right],\\right)$'
214
+ else:
215
+ assert app.user_ns['a'][0]['text/plain'] == '(True, False)'
216
+ assert 'text/latex' not in app.user_ns['a'][0]
217
+ assert app.user_ns['b'][0]['text/plain'][:10] == 'sys.flags('
218
+ assert 'text/latex' not in app.user_ns['b'][0]
219
+ assert app.user_ns['c'][0]['text/plain'] == \
220
+ """\
221
+ [1] \n\
222
+ ([ ],)
223
+ [2] \
224
+ """
225
+ assert app.user_ns['c'][0]['text/latex'] == '$\\displaystyle \\left( \\left[\\begin{matrix}1\\\\2\\end{matrix}\\right],\\right)$'
226
+
227
+ def test_matplotlib_bad_latex():
228
+ # Initialize and setup IPython session
229
+ app = init_ipython_session()
230
+ app.run_cell("import IPython")
231
+ app.run_cell("ip = get_ipython()")
232
+ app.run_cell("inst = ip.instance()")
233
+ app.run_cell("format = inst.display_formatter.format")
234
+ app.run_cell("from sympy import init_printing, Matrix")
235
+ app.run_cell("init_printing(use_latex='matplotlib')")
236
+
237
+ # The png formatter is not enabled by default in this context
238
+ app.run_cell("inst.display_formatter.formatters['image/png'].enabled = True")
239
+
240
+ # Make sure no warnings are raised by IPython
241
+ app.run_cell("import warnings")
242
+ # IPython.core.formatters.FormatterWarning was introduced in IPython 2.0
243
+ if int(ipython.__version__.split(".")[0]) < 2:
244
+ app.run_cell("warnings.simplefilter('error')")
245
+ else:
246
+ app.run_cell("warnings.simplefilter('error', IPython.core.formatters.FormatterWarning)")
247
+
248
+ # This should not raise an exception
249
+ app.run_cell("a = format(Matrix([1, 2, 3]))")
250
+
251
+ # issue 9799
252
+ app.run_cell("from sympy import Piecewise, Symbol, Eq")
253
+ app.run_cell("x = Symbol('x'); pw = format(Piecewise((1, Eq(x, 0)), (0, True)))")
254
+
255
+
256
+ def test_override_repr_latex():
257
+ # Initialize and setup IPython session
258
+ app = init_ipython_session()
259
+ app.run_cell("import IPython")
260
+ app.run_cell("ip = get_ipython()")
261
+ app.run_cell("inst = ip.instance()")
262
+ app.run_cell("format = inst.display_formatter.format")
263
+ app.run_cell("inst.display_formatter.formatters['text/latex'].enabled = True")
264
+ app.run_cell("from sympy import init_printing")
265
+ app.run_cell("from sympy import Symbol")
266
+ app.run_cell("init_printing(use_latex=True)")
267
+ app.run_cell("""\
268
+ class SymbolWithOverload(Symbol):
269
+ def _repr_latex_(self):
270
+ return r"Hello " + super()._repr_latex_() + " world"
271
+ """)
272
+ app.run_cell("a = format(SymbolWithOverload('s'))")
273
+
274
+ if int(ipython.__version__.split(".")[0]) < 1:
275
+ latex = app.user_ns['a']['text/latex']
276
+ else:
277
+ latex = app.user_ns['a'][0]['text/latex']
278
+ assert latex == r'Hello $\displaystyle s$ world'
llmeval-env/lib/python3.10/site-packages/sympy/simplify/__init__.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The module helps converting SymPy expressions into shorter forms of them.
2
+
3
+ for example:
4
+ the expression E**(pi*I) will be converted into -1
5
+ the expression (x+x)**2 will be converted into 4*x**2
6
+ """
7
+ from .simplify import (simplify, hypersimp, hypersimilar,
8
+ logcombine, separatevars, posify, besselsimp, kroneckersimp,
9
+ signsimp, nsimplify)
10
+
11
+ from .fu import FU, fu
12
+
13
+ from .sqrtdenest import sqrtdenest
14
+
15
+ from .cse_main import cse
16
+
17
+ from .epathtools import epath, EPath
18
+
19
+ from .hyperexpand import hyperexpand
20
+
21
+ from .radsimp import collect, rcollect, radsimp, collect_const, fraction, numer, denom
22
+
23
+ from .trigsimp import trigsimp, exptrigsimp
24
+
25
+ from .powsimp import powsimp, powdenest
26
+
27
+ from .combsimp import combsimp
28
+
29
+ from .gammasimp import gammasimp
30
+
31
+ from .ratsimp import ratsimp, ratsimpmodprime
32
+
33
+ __all__ = [
34
+ 'simplify', 'hypersimp', 'hypersimilar', 'logcombine', 'separatevars',
35
+ 'posify', 'besselsimp', 'kroneckersimp', 'signsimp',
36
+ 'nsimplify',
37
+
38
+ 'FU', 'fu',
39
+
40
+ 'sqrtdenest',
41
+
42
+ 'cse',
43
+
44
+ 'epath', 'EPath',
45
+
46
+ 'hyperexpand',
47
+
48
+ 'collect', 'rcollect', 'radsimp', 'collect_const', 'fraction', 'numer',
49
+ 'denom',
50
+
51
+ 'trigsimp', 'exptrigsimp',
52
+
53
+ 'powsimp', 'powdenest',
54
+
55
+ 'combsimp',
56
+
57
+ 'gammasimp',
58
+
59
+ 'ratsimp', 'ratsimpmodprime',
60
+ ]
llmeval-env/lib/python3.10/site-packages/sympy/simplify/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (1.36 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/simplify/__pycache__/combsimp.cpython-310.pyc ADDED
Binary file (3.7 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/simplify/__pycache__/cse_main.cpython-310.pyc ADDED
Binary file (26 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/simplify/__pycache__/cse_opts.cpython-310.pyc ADDED
Binary file (1.63 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/simplify/__pycache__/epathtools.cpython-310.pyc ADDED
Binary file (8.5 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/simplify/__pycache__/fu.cpython-310.pyc ADDED
Binary file (51.3 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/simplify/__pycache__/gammasimp.cpython-310.pyc ADDED
Binary file (12.4 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/simplify/__pycache__/hyperexpand.cpython-310.pyc ADDED
Binary file (73.5 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/simplify/__pycache__/hyperexpand_doc.cpython-310.pyc ADDED
Binary file (745 Bytes). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/simplify/__pycache__/powsimp.cpython-310.pyc ADDED
Binary file (17.7 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/simplify/__pycache__/radsimp.cpython-310.pyc ADDED
Binary file (34.6 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/simplify/__pycache__/ratsimp.cpython-310.pyc ADDED
Binary file (7.7 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/simplify/__pycache__/simplify.cpython-310.pyc ADDED
Binary file (57.3 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/simplify/__pycache__/sqrtdenest.cpython-310.pyc ADDED
Binary file (19.6 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/simplify/__pycache__/traversaltools.cpython-310.pyc ADDED
Binary file (610 Bytes). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/simplify/__pycache__/trigsimp.cpython-310.pyc ADDED
Binary file (33.9 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/simplify/combsimp.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core import Mul
2
+ from sympy.core.function import count_ops
3
+ from sympy.core.traversal import preorder_traversal, bottom_up
4
+ from sympy.functions.combinatorial.factorials import binomial, factorial
5
+ from sympy.functions import gamma
6
+ from sympy.simplify.gammasimp import gammasimp, _gammasimp
7
+
8
+ from sympy.utilities.timeutils import timethis
9
+
10
+
11
+ @timethis('combsimp')
12
+ def combsimp(expr):
13
+ r"""
14
+ Simplify combinatorial expressions.
15
+
16
+ Explanation
17
+ ===========
18
+
19
+ This function takes as input an expression containing factorials,
20
+ binomials, Pochhammer symbol and other "combinatorial" functions,
21
+ and tries to minimize the number of those functions and reduce
22
+ the size of their arguments.
23
+
24
+ The algorithm works by rewriting all combinatorial functions as
25
+ gamma functions and applying gammasimp() except simplification
26
+ steps that may make an integer argument non-integer. See docstring
27
+ of gammasimp for more information.
28
+
29
+ Then it rewrites expression in terms of factorials and binomials by
30
+ rewriting gammas as factorials and converting (a+b)!/a!b! into
31
+ binomials.
32
+
33
+ If expression has gamma functions or combinatorial functions
34
+ with non-integer argument, it is automatically passed to gammasimp.
35
+
36
+ Examples
37
+ ========
38
+
39
+ >>> from sympy.simplify import combsimp
40
+ >>> from sympy import factorial, binomial, symbols
41
+ >>> n, k = symbols('n k', integer = True)
42
+
43
+ >>> combsimp(factorial(n)/factorial(n - 3))
44
+ n*(n - 2)*(n - 1)
45
+ >>> combsimp(binomial(n+1, k+1)/binomial(n, k))
46
+ (n + 1)/(k + 1)
47
+
48
+ """
49
+
50
+ expr = expr.rewrite(gamma, piecewise=False)
51
+ if any(isinstance(node, gamma) and not node.args[0].is_integer
52
+ for node in preorder_traversal(expr)):
53
+ return gammasimp(expr);
54
+
55
+ expr = _gammasimp(expr, as_comb = True)
56
+ expr = _gamma_as_comb(expr)
57
+ return expr
58
+
59
+
60
+ def _gamma_as_comb(expr):
61
+ """
62
+ Helper function for combsimp.
63
+
64
+ Rewrites expression in terms of factorials and binomials
65
+ """
66
+
67
+ expr = expr.rewrite(factorial)
68
+
69
+ def f(rv):
70
+ if not rv.is_Mul:
71
+ return rv
72
+ rvd = rv.as_powers_dict()
73
+ nd_fact_args = [[], []] # numerator, denominator
74
+
75
+ for k in rvd:
76
+ if isinstance(k, factorial) and rvd[k].is_Integer:
77
+ if rvd[k].is_positive:
78
+ nd_fact_args[0].extend([k.args[0]]*rvd[k])
79
+ else:
80
+ nd_fact_args[1].extend([k.args[0]]*-rvd[k])
81
+ rvd[k] = 0
82
+ if not nd_fact_args[0] or not nd_fact_args[1]:
83
+ return rv
84
+
85
+ hit = False
86
+ for m in range(2):
87
+ i = 0
88
+ while i < len(nd_fact_args[m]):
89
+ ai = nd_fact_args[m][i]
90
+ for j in range(i + 1, len(nd_fact_args[m])):
91
+ aj = nd_fact_args[m][j]
92
+
93
+ sum = ai + aj
94
+ if sum in nd_fact_args[1 - m]:
95
+ hit = True
96
+
97
+ nd_fact_args[1 - m].remove(sum)
98
+ del nd_fact_args[m][j]
99
+ del nd_fact_args[m][i]
100
+
101
+ rvd[binomial(sum, ai if count_ops(ai) <
102
+ count_ops(aj) else aj)] += (
103
+ -1 if m == 0 else 1)
104
+ break
105
+ else:
106
+ i += 1
107
+
108
+ if hit:
109
+ return Mul(*([k**rvd[k] for k in rvd] + [factorial(k)
110
+ for k in nd_fact_args[0]]))/Mul(*[factorial(k)
111
+ for k in nd_fact_args[1]])
112
+ return rv
113
+
114
+ return bottom_up(expr, f)
llmeval-env/lib/python3.10/site-packages/sympy/simplify/cse_opts.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ Optimizations of the expression tree representation for better CSE
2
+ opportunities.
3
+ """
4
+ from sympy.core import Add, Basic, Mul
5
+ from sympy.core.singleton import S
6
+ from sympy.core.sorting import default_sort_key
7
+ from sympy.core.traversal import preorder_traversal
8
+
9
+
10
+ def sub_pre(e):
11
+ """ Replace y - x with -(x - y) if -1 can be extracted from y - x.
12
+ """
13
+ # replacing Add, A, from which -1 can be extracted with -1*-A
14
+ adds = [a for a in e.atoms(Add) if a.could_extract_minus_sign()]
15
+ reps = {}
16
+ ignore = set()
17
+ for a in adds:
18
+ na = -a
19
+ if na.is_Mul: # e.g. MatExpr
20
+ ignore.add(a)
21
+ continue
22
+ reps[a] = Mul._from_args([S.NegativeOne, na])
23
+
24
+ e = e.xreplace(reps)
25
+
26
+ # repeat again for persisting Adds but mark these with a leading 1, -1
27
+ # e.g. y - x -> 1*-1*(x - y)
28
+ if isinstance(e, Basic):
29
+ negs = {}
30
+ for a in sorted(e.atoms(Add), key=default_sort_key):
31
+ if a in ignore:
32
+ continue
33
+ if a in reps:
34
+ negs[a] = reps[a]
35
+ elif a.could_extract_minus_sign():
36
+ negs[a] = Mul._from_args([S.One, S.NegativeOne, -a])
37
+ e = e.xreplace(negs)
38
+ return e
39
+
40
+
41
+ def sub_post(e):
42
+ """ Replace 1*-1*x with -x.
43
+ """
44
+ replacements = []
45
+ for node in preorder_traversal(e):
46
+ if isinstance(node, Mul) and \
47
+ node.args[0] is S.One and node.args[1] is S.NegativeOne:
48
+ replacements.append((node, -Mul._from_args(node.args[2:])))
49
+ for node, replacement in replacements:
50
+ e = e.xreplace({node: replacement})
51
+
52
+ return e
llmeval-env/lib/python3.10/site-packages/sympy/simplify/fu.py ADDED
@@ -0,0 +1,2099 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections import defaultdict
2
+
3
+ from sympy.core.add import Add
4
+ from sympy.core.expr import Expr
5
+ from sympy.core.exprtools import Factors, gcd_terms, factor_terms
6
+ from sympy.core.function import expand_mul
7
+ from sympy.core.mul import Mul
8
+ from sympy.core.numbers import pi, I
9
+ from sympy.core.power import Pow
10
+ from sympy.core.singleton import S
11
+ from sympy.core.sorting import ordered
12
+ from sympy.core.symbol import Dummy
13
+ from sympy.core.sympify import sympify
14
+ from sympy.core.traversal import bottom_up
15
+ from sympy.functions.combinatorial.factorials import binomial
16
+ from sympy.functions.elementary.hyperbolic import (
17
+ cosh, sinh, tanh, coth, sech, csch, HyperbolicFunction)
18
+ from sympy.functions.elementary.trigonometric import (
19
+ cos, sin, tan, cot, sec, csc, sqrt, TrigonometricFunction)
20
+ from sympy.ntheory.factor_ import perfect_power
21
+ from sympy.polys.polytools import factor
22
+ from sympy.strategies.tree import greedy
23
+ from sympy.strategies.core import identity, debug
24
+
25
+ from sympy import SYMPY_DEBUG
26
+
27
+
28
+ # ================== Fu-like tools ===========================
29
+
30
+
31
+ def TR0(rv):
32
+ """Simplification of rational polynomials, trying to simplify
33
+ the expression, e.g. combine things like 3*x + 2*x, etc....
34
+ """
35
+ # although it would be nice to use cancel, it doesn't work
36
+ # with noncommutatives
37
+ return rv.normal().factor().expand()
38
+
39
+
40
+ def TR1(rv):
41
+ """Replace sec, csc with 1/cos, 1/sin
42
+
43
+ Examples
44
+ ========
45
+
46
+ >>> from sympy.simplify.fu import TR1, sec, csc
47
+ >>> from sympy.abc import x
48
+ >>> TR1(2*csc(x) + sec(x))
49
+ 1/cos(x) + 2/sin(x)
50
+ """
51
+
52
+ def f(rv):
53
+ if isinstance(rv, sec):
54
+ a = rv.args[0]
55
+ return S.One/cos(a)
56
+ elif isinstance(rv, csc):
57
+ a = rv.args[0]
58
+ return S.One/sin(a)
59
+ return rv
60
+
61
+ return bottom_up(rv, f)
62
+
63
+
64
+ def TR2(rv):
65
+ """Replace tan and cot with sin/cos and cos/sin
66
+
67
+ Examples
68
+ ========
69
+
70
+ >>> from sympy.simplify.fu import TR2
71
+ >>> from sympy.abc import x
72
+ >>> from sympy import tan, cot, sin, cos
73
+ >>> TR2(tan(x))
74
+ sin(x)/cos(x)
75
+ >>> TR2(cot(x))
76
+ cos(x)/sin(x)
77
+ >>> TR2(tan(tan(x) - sin(x)/cos(x)))
78
+ 0
79
+
80
+ """
81
+
82
+ def f(rv):
83
+ if isinstance(rv, tan):
84
+ a = rv.args[0]
85
+ return sin(a)/cos(a)
86
+ elif isinstance(rv, cot):
87
+ a = rv.args[0]
88
+ return cos(a)/sin(a)
89
+ return rv
90
+
91
+ return bottom_up(rv, f)
92
+
93
+
94
+ def TR2i(rv, half=False):
95
+ """Converts ratios involving sin and cos as follows::
96
+ sin(x)/cos(x) -> tan(x)
97
+ sin(x)/(cos(x) + 1) -> tan(x/2) if half=True
98
+
99
+ Examples
100
+ ========
101
+
102
+ >>> from sympy.simplify.fu import TR2i
103
+ >>> from sympy.abc import x, a
104
+ >>> from sympy import sin, cos
105
+ >>> TR2i(sin(x)/cos(x))
106
+ tan(x)
107
+
108
+ Powers of the numerator and denominator are also recognized
109
+
110
+ >>> TR2i(sin(x)**2/(cos(x) + 1)**2, half=True)
111
+ tan(x/2)**2
112
+
113
+ The transformation does not take place unless assumptions allow
114
+ (i.e. the base must be positive or the exponent must be an integer
115
+ for both numerator and denominator)
116
+
117
+ >>> TR2i(sin(x)**a/(cos(x) + 1)**a)
118
+ sin(x)**a/(cos(x) + 1)**a
119
+
120
+ """
121
+
122
+ def f(rv):
123
+ if not rv.is_Mul:
124
+ return rv
125
+
126
+ n, d = rv.as_numer_denom()
127
+ if n.is_Atom or d.is_Atom:
128
+ return rv
129
+
130
+ def ok(k, e):
131
+ # initial filtering of factors
132
+ return (
133
+ (e.is_integer or k.is_positive) and (
134
+ k.func in (sin, cos) or (half and
135
+ k.is_Add and
136
+ len(k.args) >= 2 and
137
+ any(any(isinstance(ai, cos) or ai.is_Pow and ai.base is cos
138
+ for ai in Mul.make_args(a)) for a in k.args))))
139
+
140
+ n = n.as_powers_dict()
141
+ ndone = [(k, n.pop(k)) for k in list(n.keys()) if not ok(k, n[k])]
142
+ if not n:
143
+ return rv
144
+
145
+ d = d.as_powers_dict()
146
+ ddone = [(k, d.pop(k)) for k in list(d.keys()) if not ok(k, d[k])]
147
+ if not d:
148
+ return rv
149
+
150
+ # factoring if necessary
151
+
152
+ def factorize(d, ddone):
153
+ newk = []
154
+ for k in d:
155
+ if k.is_Add and len(k.args) > 1:
156
+ knew = factor(k) if half else factor_terms(k)
157
+ if knew != k:
158
+ newk.append((k, knew))
159
+ if newk:
160
+ for i, (k, knew) in enumerate(newk):
161
+ del d[k]
162
+ newk[i] = knew
163
+ newk = Mul(*newk).as_powers_dict()
164
+ for k in newk:
165
+ v = d[k] + newk[k]
166
+ if ok(k, v):
167
+ d[k] = v
168
+ else:
169
+ ddone.append((k, v))
170
+ del newk
171
+ factorize(n, ndone)
172
+ factorize(d, ddone)
173
+
174
+ # joining
175
+ t = []
176
+ for k in n:
177
+ if isinstance(k, sin):
178
+ a = cos(k.args[0], evaluate=False)
179
+ if a in d and d[a] == n[k]:
180
+ t.append(tan(k.args[0])**n[k])
181
+ n[k] = d[a] = None
182
+ elif half:
183
+ a1 = 1 + a
184
+ if a1 in d and d[a1] == n[k]:
185
+ t.append((tan(k.args[0]/2))**n[k])
186
+ n[k] = d[a1] = None
187
+ elif isinstance(k, cos):
188
+ a = sin(k.args[0], evaluate=False)
189
+ if a in d and d[a] == n[k]:
190
+ t.append(tan(k.args[0])**-n[k])
191
+ n[k] = d[a] = None
192
+ elif half and k.is_Add and k.args[0] is S.One and \
193
+ isinstance(k.args[1], cos):
194
+ a = sin(k.args[1].args[0], evaluate=False)
195
+ if a in d and d[a] == n[k] and (d[a].is_integer or \
196
+ a.is_positive):
197
+ t.append(tan(a.args[0]/2)**-n[k])
198
+ n[k] = d[a] = None
199
+
200
+ if t:
201
+ rv = Mul(*(t + [b**e for b, e in n.items() if e]))/\
202
+ Mul(*[b**e for b, e in d.items() if e])
203
+ rv *= Mul(*[b**e for b, e in ndone])/Mul(*[b**e for b, e in ddone])
204
+
205
+ return rv
206
+
207
+ return bottom_up(rv, f)
208
+
209
+
210
+ def TR3(rv):
211
+ """Induced formula: example sin(-a) = -sin(a)
212
+
213
+ Examples
214
+ ========
215
+
216
+ >>> from sympy.simplify.fu import TR3
217
+ >>> from sympy.abc import x, y
218
+ >>> from sympy import pi
219
+ >>> from sympy import cos
220
+ >>> TR3(cos(y - x*(y - x)))
221
+ cos(x*(x - y) + y)
222
+ >>> cos(pi/2 + x)
223
+ -sin(x)
224
+ >>> cos(30*pi/2 + x)
225
+ -cos(x)
226
+
227
+ """
228
+ from sympy.simplify.simplify import signsimp
229
+
230
+ # Negative argument (already automatic for funcs like sin(-x) -> -sin(x)
231
+ # but more complicated expressions can use it, too). Also, trig angles
232
+ # between pi/4 and pi/2 are not reduced to an angle between 0 and pi/4.
233
+ # The following are automatically handled:
234
+ # Argument of type: pi/2 +/- angle
235
+ # Argument of type: pi +/- angle
236
+ # Argument of type : 2k*pi +/- angle
237
+
238
+ def f(rv):
239
+ if not isinstance(rv, TrigonometricFunction):
240
+ return rv
241
+ rv = rv.func(signsimp(rv.args[0]))
242
+ if not isinstance(rv, TrigonometricFunction):
243
+ return rv
244
+ if (rv.args[0] - S.Pi/4).is_positive is (S.Pi/2 - rv.args[0]).is_positive is True:
245
+ fmap = {cos: sin, sin: cos, tan: cot, cot: tan, sec: csc, csc: sec}
246
+ rv = fmap[type(rv)](S.Pi/2 - rv.args[0])
247
+ return rv
248
+
249
+ return bottom_up(rv, f)
250
+
251
+
252
+ def TR4(rv):
253
+ """Identify values of special angles.
254
+
255
+ a= 0 pi/6 pi/4 pi/3 pi/2
256
+ ----------------------------------------------------
257
+ sin(a) 0 1/2 sqrt(2)/2 sqrt(3)/2 1
258
+ cos(a) 1 sqrt(3)/2 sqrt(2)/2 1/2 0
259
+ tan(a) 0 sqt(3)/3 1 sqrt(3) --
260
+
261
+ Examples
262
+ ========
263
+
264
+ >>> from sympy import pi
265
+ >>> from sympy import cos, sin, tan, cot
266
+ >>> for s in (0, pi/6, pi/4, pi/3, pi/2):
267
+ ... print('%s %s %s %s' % (cos(s), sin(s), tan(s), cot(s)))
268
+ ...
269
+ 1 0 0 zoo
270
+ sqrt(3)/2 1/2 sqrt(3)/3 sqrt(3)
271
+ sqrt(2)/2 sqrt(2)/2 1 1
272
+ 1/2 sqrt(3)/2 sqrt(3) sqrt(3)/3
273
+ 0 1 zoo 0
274
+ """
275
+ # special values at 0, pi/6, pi/4, pi/3, pi/2 already handled
276
+ return rv
277
+
278
+
279
+ def _TR56(rv, f, g, h, max, pow):
280
+ """Helper for TR5 and TR6 to replace f**2 with h(g**2)
281
+
282
+ Options
283
+ =======
284
+
285
+ max : controls size of exponent that can appear on f
286
+ e.g. if max=4 then f**4 will be changed to h(g**2)**2.
287
+ pow : controls whether the exponent must be a perfect power of 2
288
+ e.g. if pow=True (and max >= 6) then f**6 will not be changed
289
+ but f**8 will be changed to h(g**2)**4
290
+
291
+ >>> from sympy.simplify.fu import _TR56 as T
292
+ >>> from sympy.abc import x
293
+ >>> from sympy import sin, cos
294
+ >>> h = lambda x: 1 - x
295
+ >>> T(sin(x)**3, sin, cos, h, 4, False)
296
+ (1 - cos(x)**2)*sin(x)
297
+ >>> T(sin(x)**6, sin, cos, h, 6, False)
298
+ (1 - cos(x)**2)**3
299
+ >>> T(sin(x)**6, sin, cos, h, 6, True)
300
+ sin(x)**6
301
+ >>> T(sin(x)**8, sin, cos, h, 10, True)
302
+ (1 - cos(x)**2)**4
303
+ """
304
+
305
+ def _f(rv):
306
+ # I'm not sure if this transformation should target all even powers
307
+ # or only those expressible as powers of 2. Also, should it only
308
+ # make the changes in powers that appear in sums -- making an isolated
309
+ # change is not going to allow a simplification as far as I can tell.
310
+ if not (rv.is_Pow and rv.base.func == f):
311
+ return rv
312
+ if not rv.exp.is_real:
313
+ return rv
314
+
315
+ if (rv.exp < 0) == True:
316
+ return rv
317
+ if (rv.exp > max) == True:
318
+ return rv
319
+ if rv.exp == 1:
320
+ return rv
321
+ if rv.exp == 2:
322
+ return h(g(rv.base.args[0])**2)
323
+ else:
324
+ if rv.exp % 2 == 1:
325
+ e = rv.exp//2
326
+ return f(rv.base.args[0])*h(g(rv.base.args[0])**2)**e
327
+ elif rv.exp == 4:
328
+ e = 2
329
+ elif not pow:
330
+ if rv.exp % 2:
331
+ return rv
332
+ e = rv.exp//2
333
+ else:
334
+ p = perfect_power(rv.exp)
335
+ if not p:
336
+ return rv
337
+ e = rv.exp//2
338
+ return h(g(rv.base.args[0])**2)**e
339
+
340
+ return bottom_up(rv, _f)
341
+
342
+
343
+ def TR5(rv, max=4, pow=False):
344
+ """Replacement of sin**2 with 1 - cos(x)**2.
345
+
346
+ See _TR56 docstring for advanced use of ``max`` and ``pow``.
347
+
348
+ Examples
349
+ ========
350
+
351
+ >>> from sympy.simplify.fu import TR5
352
+ >>> from sympy.abc import x
353
+ >>> from sympy import sin
354
+ >>> TR5(sin(x)**2)
355
+ 1 - cos(x)**2
356
+ >>> TR5(sin(x)**-2) # unchanged
357
+ sin(x)**(-2)
358
+ >>> TR5(sin(x)**4)
359
+ (1 - cos(x)**2)**2
360
+ """
361
+ return _TR56(rv, sin, cos, lambda x: 1 - x, max=max, pow=pow)
362
+
363
+
364
+ def TR6(rv, max=4, pow=False):
365
+ """Replacement of cos**2 with 1 - sin(x)**2.
366
+
367
+ See _TR56 docstring for advanced use of ``max`` and ``pow``.
368
+
369
+ Examples
370
+ ========
371
+
372
+ >>> from sympy.simplify.fu import TR6
373
+ >>> from sympy.abc import x
374
+ >>> from sympy import cos
375
+ >>> TR6(cos(x)**2)
376
+ 1 - sin(x)**2
377
+ >>> TR6(cos(x)**-2) #unchanged
378
+ cos(x)**(-2)
379
+ >>> TR6(cos(x)**4)
380
+ (1 - sin(x)**2)**2
381
+ """
382
+ return _TR56(rv, cos, sin, lambda x: 1 - x, max=max, pow=pow)
383
+
384
+
385
+ def TR7(rv):
386
+ """Lowering the degree of cos(x)**2.
387
+
388
+ Examples
389
+ ========
390
+
391
+ >>> from sympy.simplify.fu import TR7
392
+ >>> from sympy.abc import x
393
+ >>> from sympy import cos
394
+ >>> TR7(cos(x)**2)
395
+ cos(2*x)/2 + 1/2
396
+ >>> TR7(cos(x)**2 + 1)
397
+ cos(2*x)/2 + 3/2
398
+
399
+ """
400
+
401
+ def f(rv):
402
+ if not (rv.is_Pow and rv.base.func == cos and rv.exp == 2):
403
+ return rv
404
+ return (1 + cos(2*rv.base.args[0]))/2
405
+
406
+ return bottom_up(rv, f)
407
+
408
+
409
+ def TR8(rv, first=True):
410
+ """Converting products of ``cos`` and/or ``sin`` to a sum or
411
+ difference of ``cos`` and or ``sin`` terms.
412
+
413
+ Examples
414
+ ========
415
+
416
+ >>> from sympy.simplify.fu import TR8
417
+ >>> from sympy import cos, sin
418
+ >>> TR8(cos(2)*cos(3))
419
+ cos(5)/2 + cos(1)/2
420
+ >>> TR8(cos(2)*sin(3))
421
+ sin(5)/2 + sin(1)/2
422
+ >>> TR8(sin(2)*sin(3))
423
+ -cos(5)/2 + cos(1)/2
424
+ """
425
+
426
+ def f(rv):
427
+ if not (
428
+ rv.is_Mul or
429
+ rv.is_Pow and
430
+ rv.base.func in (cos, sin) and
431
+ (rv.exp.is_integer or rv.base.is_positive)):
432
+ return rv
433
+
434
+ if first:
435
+ n, d = [expand_mul(i) for i in rv.as_numer_denom()]
436
+ newn = TR8(n, first=False)
437
+ newd = TR8(d, first=False)
438
+ if newn != n or newd != d:
439
+ rv = gcd_terms(newn/newd)
440
+ if rv.is_Mul and rv.args[0].is_Rational and \
441
+ len(rv.args) == 2 and rv.args[1].is_Add:
442
+ rv = Mul(*rv.as_coeff_Mul())
443
+ return rv
444
+
445
+ args = {cos: [], sin: [], None: []}
446
+ for a in ordered(Mul.make_args(rv)):
447
+ if a.func in (cos, sin):
448
+ args[type(a)].append(a.args[0])
449
+ elif (a.is_Pow and a.exp.is_Integer and a.exp > 0 and \
450
+ a.base.func in (cos, sin)):
451
+ # XXX this is ok but pathological expression could be handled
452
+ # more efficiently as in TRmorrie
453
+ args[type(a.base)].extend([a.base.args[0]]*a.exp)
454
+ else:
455
+ args[None].append(a)
456
+ c = args[cos]
457
+ s = args[sin]
458
+ if not (c and s or len(c) > 1 or len(s) > 1):
459
+ return rv
460
+
461
+ args = args[None]
462
+ n = min(len(c), len(s))
463
+ for i in range(n):
464
+ a1 = s.pop()
465
+ a2 = c.pop()
466
+ args.append((sin(a1 + a2) + sin(a1 - a2))/2)
467
+ while len(c) > 1:
468
+ a1 = c.pop()
469
+ a2 = c.pop()
470
+ args.append((cos(a1 + a2) + cos(a1 - a2))/2)
471
+ if c:
472
+ args.append(cos(c.pop()))
473
+ while len(s) > 1:
474
+ a1 = s.pop()
475
+ a2 = s.pop()
476
+ args.append((-cos(a1 + a2) + cos(a1 - a2))/2)
477
+ if s:
478
+ args.append(sin(s.pop()))
479
+ return TR8(expand_mul(Mul(*args)))
480
+
481
+ return bottom_up(rv, f)
482
+
483
+
484
+ def TR9(rv):
485
+ """Sum of ``cos`` or ``sin`` terms as a product of ``cos`` or ``sin``.
486
+
487
+ Examples
488
+ ========
489
+
490
+ >>> from sympy.simplify.fu import TR9
491
+ >>> from sympy import cos, sin
492
+ >>> TR9(cos(1) + cos(2))
493
+ 2*cos(1/2)*cos(3/2)
494
+ >>> TR9(cos(1) + 2*sin(1) + 2*sin(2))
495
+ cos(1) + 4*sin(3/2)*cos(1/2)
496
+
497
+ If no change is made by TR9, no re-arrangement of the
498
+ expression will be made. For example, though factoring
499
+ of common term is attempted, if the factored expression
500
+ was not changed, the original expression will be returned:
501
+
502
+ >>> TR9(cos(3) + cos(3)*cos(2))
503
+ cos(3) + cos(2)*cos(3)
504
+
505
+ """
506
+
507
+ def f(rv):
508
+ if not rv.is_Add:
509
+ return rv
510
+
511
+ def do(rv, first=True):
512
+ # cos(a)+/-cos(b) can be combined into a product of cosines and
513
+ # sin(a)+/-sin(b) can be combined into a product of cosine and
514
+ # sine.
515
+ #
516
+ # If there are more than two args, the pairs which "work" will
517
+ # have a gcd extractable and the remaining two terms will have
518
+ # the above structure -- all pairs must be checked to find the
519
+ # ones that work. args that don't have a common set of symbols
520
+ # are skipped since this doesn't lead to a simpler formula and
521
+ # also has the arbitrariness of combining, for example, the x
522
+ # and y term instead of the y and z term in something like
523
+ # cos(x) + cos(y) + cos(z).
524
+
525
+ if not rv.is_Add:
526
+ return rv
527
+
528
+ args = list(ordered(rv.args))
529
+ if len(args) != 2:
530
+ hit = False
531
+ for i in range(len(args)):
532
+ ai = args[i]
533
+ if ai is None:
534
+ continue
535
+ for j in range(i + 1, len(args)):
536
+ aj = args[j]
537
+ if aj is None:
538
+ continue
539
+ was = ai + aj
540
+ new = do(was)
541
+ if new != was:
542
+ args[i] = new # update in place
543
+ args[j] = None
544
+ hit = True
545
+ break # go to next i
546
+ if hit:
547
+ rv = Add(*[_f for _f in args if _f])
548
+ if rv.is_Add:
549
+ rv = do(rv)
550
+
551
+ return rv
552
+
553
+ # two-arg Add
554
+ split = trig_split(*args)
555
+ if not split:
556
+ return rv
557
+ gcd, n1, n2, a, b, iscos = split
558
+
559
+ # application of rule if possible
560
+ if iscos:
561
+ if n1 == n2:
562
+ return gcd*n1*2*cos((a + b)/2)*cos((a - b)/2)
563
+ if n1 < 0:
564
+ a, b = b, a
565
+ return -2*gcd*sin((a + b)/2)*sin((a - b)/2)
566
+ else:
567
+ if n1 == n2:
568
+ return gcd*n1*2*sin((a + b)/2)*cos((a - b)/2)
569
+ if n1 < 0:
570
+ a, b = b, a
571
+ return 2*gcd*cos((a + b)/2)*sin((a - b)/2)
572
+
573
+ return process_common_addends(rv, do) # DON'T sift by free symbols
574
+
575
+ return bottom_up(rv, f)
576
+
577
+
578
+ def TR10(rv, first=True):
579
+ """Separate sums in ``cos`` and ``sin``.
580
+
581
+ Examples
582
+ ========
583
+
584
+ >>> from sympy.simplify.fu import TR10
585
+ >>> from sympy.abc import a, b, c
586
+ >>> from sympy import cos, sin
587
+ >>> TR10(cos(a + b))
588
+ -sin(a)*sin(b) + cos(a)*cos(b)
589
+ >>> TR10(sin(a + b))
590
+ sin(a)*cos(b) + sin(b)*cos(a)
591
+ >>> TR10(sin(a + b + c))
592
+ (-sin(a)*sin(b) + cos(a)*cos(b))*sin(c) + \
593
+ (sin(a)*cos(b) + sin(b)*cos(a))*cos(c)
594
+ """
595
+
596
+ def f(rv):
597
+ if rv.func not in (cos, sin):
598
+ return rv
599
+
600
+ f = rv.func
601
+ arg = rv.args[0]
602
+ if arg.is_Add:
603
+ if first:
604
+ args = list(ordered(arg.args))
605
+ else:
606
+ args = list(arg.args)
607
+ a = args.pop()
608
+ b = Add._from_args(args)
609
+ if b.is_Add:
610
+ if f == sin:
611
+ return sin(a)*TR10(cos(b), first=False) + \
612
+ cos(a)*TR10(sin(b), first=False)
613
+ else:
614
+ return cos(a)*TR10(cos(b), first=False) - \
615
+ sin(a)*TR10(sin(b), first=False)
616
+ else:
617
+ if f == sin:
618
+ return sin(a)*cos(b) + cos(a)*sin(b)
619
+ else:
620
+ return cos(a)*cos(b) - sin(a)*sin(b)
621
+ return rv
622
+
623
+ return bottom_up(rv, f)
624
+
625
+
626
+ def TR10i(rv):
627
+ """Sum of products to function of sum.
628
+
629
+ Examples
630
+ ========
631
+
632
+ >>> from sympy.simplify.fu import TR10i
633
+ >>> from sympy import cos, sin, sqrt
634
+ >>> from sympy.abc import x
635
+
636
+ >>> TR10i(cos(1)*cos(3) + sin(1)*sin(3))
637
+ cos(2)
638
+ >>> TR10i(cos(1)*sin(3) + sin(1)*cos(3) + cos(3))
639
+ cos(3) + sin(4)
640
+ >>> TR10i(sqrt(2)*cos(x)*x + sqrt(6)*sin(x)*x)
641
+ 2*sqrt(2)*x*sin(x + pi/6)
642
+
643
+ """
644
+ global _ROOT2, _ROOT3, _invROOT3
645
+ if _ROOT2 is None:
646
+ _roots()
647
+
648
+ def f(rv):
649
+ if not rv.is_Add:
650
+ return rv
651
+
652
+ def do(rv, first=True):
653
+ # args which can be expressed as A*(cos(a)*cos(b)+/-sin(a)*sin(b))
654
+ # or B*(cos(a)*sin(b)+/-cos(b)*sin(a)) can be combined into
655
+ # A*f(a+/-b) where f is either sin or cos.
656
+ #
657
+ # If there are more than two args, the pairs which "work" will have
658
+ # a gcd extractable and the remaining two terms will have the above
659
+ # structure -- all pairs must be checked to find the ones that
660
+ # work.
661
+
662
+ if not rv.is_Add:
663
+ return rv
664
+
665
+ args = list(ordered(rv.args))
666
+ if len(args) != 2:
667
+ hit = False
668
+ for i in range(len(args)):
669
+ ai = args[i]
670
+ if ai is None:
671
+ continue
672
+ for j in range(i + 1, len(args)):
673
+ aj = args[j]
674
+ if aj is None:
675
+ continue
676
+ was = ai + aj
677
+ new = do(was)
678
+ if new != was:
679
+ args[i] = new # update in place
680
+ args[j] = None
681
+ hit = True
682
+ break # go to next i
683
+ if hit:
684
+ rv = Add(*[_f for _f in args if _f])
685
+ if rv.is_Add:
686
+ rv = do(rv)
687
+
688
+ return rv
689
+
690
+ # two-arg Add
691
+ split = trig_split(*args, two=True)
692
+ if not split:
693
+ return rv
694
+ gcd, n1, n2, a, b, same = split
695
+
696
+ # identify and get c1 to be cos then apply rule if possible
697
+ if same: # coscos, sinsin
698
+ gcd = n1*gcd
699
+ if n1 == n2:
700
+ return gcd*cos(a - b)
701
+ return gcd*cos(a + b)
702
+ else: #cossin, cossin
703
+ gcd = n1*gcd
704
+ if n1 == n2:
705
+ return gcd*sin(a + b)
706
+ return gcd*sin(b - a)
707
+
708
+ rv = process_common_addends(
709
+ rv, do, lambda x: tuple(ordered(x.free_symbols)))
710
+
711
+ # need to check for inducible pairs in ratio of sqrt(3):1 that
712
+ # appeared in different lists when sorting by coefficient
713
+ while rv.is_Add:
714
+ byrad = defaultdict(list)
715
+ for a in rv.args:
716
+ hit = 0
717
+ if a.is_Mul:
718
+ for ai in a.args:
719
+ if ai.is_Pow and ai.exp is S.Half and \
720
+ ai.base.is_Integer:
721
+ byrad[ai].append(a)
722
+ hit = 1
723
+ break
724
+ if not hit:
725
+ byrad[S.One].append(a)
726
+
727
+ # no need to check all pairs -- just check for the onees
728
+ # that have the right ratio
729
+ args = []
730
+ for a in byrad:
731
+ for b in [_ROOT3*a, _invROOT3]:
732
+ if b in byrad:
733
+ for i in range(len(byrad[a])):
734
+ if byrad[a][i] is None:
735
+ continue
736
+ for j in range(len(byrad[b])):
737
+ if byrad[b][j] is None:
738
+ continue
739
+ was = Add(byrad[a][i] + byrad[b][j])
740
+ new = do(was)
741
+ if new != was:
742
+ args.append(new)
743
+ byrad[a][i] = None
744
+ byrad[b][j] = None
745
+ break
746
+ if args:
747
+ rv = Add(*(args + [Add(*[_f for _f in v if _f])
748
+ for v in byrad.values()]))
749
+ else:
750
+ rv = do(rv) # final pass to resolve any new inducible pairs
751
+ break
752
+
753
+ return rv
754
+
755
+ return bottom_up(rv, f)
756
+
757
+
758
+ def TR11(rv, base=None):
759
+ """Function of double angle to product. The ``base`` argument can be used
760
+ to indicate what is the un-doubled argument, e.g. if 3*pi/7 is the base
761
+ then cosine and sine functions with argument 6*pi/7 will be replaced.
762
+
763
+ Examples
764
+ ========
765
+
766
+ >>> from sympy.simplify.fu import TR11
767
+ >>> from sympy import cos, sin, pi
768
+ >>> from sympy.abc import x
769
+ >>> TR11(sin(2*x))
770
+ 2*sin(x)*cos(x)
771
+ >>> TR11(cos(2*x))
772
+ -sin(x)**2 + cos(x)**2
773
+ >>> TR11(sin(4*x))
774
+ 4*(-sin(x)**2 + cos(x)**2)*sin(x)*cos(x)
775
+ >>> TR11(sin(4*x/3))
776
+ 4*(-sin(x/3)**2 + cos(x/3)**2)*sin(x/3)*cos(x/3)
777
+
778
+ If the arguments are simply integers, no change is made
779
+ unless a base is provided:
780
+
781
+ >>> TR11(cos(2))
782
+ cos(2)
783
+ >>> TR11(cos(4), 2)
784
+ -sin(2)**2 + cos(2)**2
785
+
786
+ There is a subtle issue here in that autosimplification will convert
787
+ some higher angles to lower angles
788
+
789
+ >>> cos(6*pi/7) + cos(3*pi/7)
790
+ -cos(pi/7) + cos(3*pi/7)
791
+
792
+ The 6*pi/7 angle is now pi/7 but can be targeted with TR11 by supplying
793
+ the 3*pi/7 base:
794
+
795
+ >>> TR11(_, 3*pi/7)
796
+ -sin(3*pi/7)**2 + cos(3*pi/7)**2 + cos(3*pi/7)
797
+
798
+ """
799
+
800
+ def f(rv):
801
+ if rv.func not in (cos, sin):
802
+ return rv
803
+
804
+ if base:
805
+ f = rv.func
806
+ t = f(base*2)
807
+ co = S.One
808
+ if t.is_Mul:
809
+ co, t = t.as_coeff_Mul()
810
+ if t.func not in (cos, sin):
811
+ return rv
812
+ if rv.args[0] == t.args[0]:
813
+ c = cos(base)
814
+ s = sin(base)
815
+ if f is cos:
816
+ return (c**2 - s**2)/co
817
+ else:
818
+ return 2*c*s/co
819
+ return rv
820
+
821
+ elif not rv.args[0].is_Number:
822
+ # make a change if the leading coefficient's numerator is
823
+ # divisible by 2
824
+ c, m = rv.args[0].as_coeff_Mul(rational=True)
825
+ if c.p % 2 == 0:
826
+ arg = c.p//2*m/c.q
827
+ c = TR11(cos(arg))
828
+ s = TR11(sin(arg))
829
+ if rv.func == sin:
830
+ rv = 2*s*c
831
+ else:
832
+ rv = c**2 - s**2
833
+ return rv
834
+
835
+ return bottom_up(rv, f)
836
+
837
+
838
+ def _TR11(rv):
839
+ """
840
+ Helper for TR11 to find half-arguments for sin in factors of
841
+ num/den that appear in cos or sin factors in the den/num.
842
+
843
+ Examples
844
+ ========
845
+
846
+ >>> from sympy.simplify.fu import TR11, _TR11
847
+ >>> from sympy import cos, sin
848
+ >>> from sympy.abc import x
849
+ >>> TR11(sin(x/3)/(cos(x/6)))
850
+ sin(x/3)/cos(x/6)
851
+ >>> _TR11(sin(x/3)/(cos(x/6)))
852
+ 2*sin(x/6)
853
+ >>> TR11(sin(x/6)/(sin(x/3)))
854
+ sin(x/6)/sin(x/3)
855
+ >>> _TR11(sin(x/6)/(sin(x/3)))
856
+ 1/(2*cos(x/6))
857
+
858
+ """
859
+ def f(rv):
860
+ if not isinstance(rv, Expr):
861
+ return rv
862
+
863
+ def sincos_args(flat):
864
+ # find arguments of sin and cos that
865
+ # appears as bases in args of flat
866
+ # and have Integer exponents
867
+ args = defaultdict(set)
868
+ for fi in Mul.make_args(flat):
869
+ b, e = fi.as_base_exp()
870
+ if e.is_Integer and e > 0:
871
+ if b.func in (cos, sin):
872
+ args[type(b)].add(b.args[0])
873
+ return args
874
+ num_args, den_args = map(sincos_args, rv.as_numer_denom())
875
+ def handle_match(rv, num_args, den_args):
876
+ # for arg in sin args of num_args, look for arg/2
877
+ # in den_args and pass this half-angle to TR11
878
+ # for handling in rv
879
+ for narg in num_args[sin]:
880
+ half = narg/2
881
+ if half in den_args[cos]:
882
+ func = cos
883
+ elif half in den_args[sin]:
884
+ func = sin
885
+ else:
886
+ continue
887
+ rv = TR11(rv, half)
888
+ den_args[func].remove(half)
889
+ return rv
890
+ # sin in num, sin or cos in den
891
+ rv = handle_match(rv, num_args, den_args)
892
+ # sin in den, sin or cos in num
893
+ rv = handle_match(rv, den_args, num_args)
894
+ return rv
895
+
896
+ return bottom_up(rv, f)
897
+
898
+
899
+ def TR12(rv, first=True):
900
+ """Separate sums in ``tan``.
901
+
902
+ Examples
903
+ ========
904
+
905
+ >>> from sympy.abc import x, y
906
+ >>> from sympy import tan
907
+ >>> from sympy.simplify.fu import TR12
908
+ >>> TR12(tan(x + y))
909
+ (tan(x) + tan(y))/(-tan(x)*tan(y) + 1)
910
+ """
911
+
912
+ def f(rv):
913
+ if not rv.func == tan:
914
+ return rv
915
+
916
+ arg = rv.args[0]
917
+ if arg.is_Add:
918
+ if first:
919
+ args = list(ordered(arg.args))
920
+ else:
921
+ args = list(arg.args)
922
+ a = args.pop()
923
+ b = Add._from_args(args)
924
+ if b.is_Add:
925
+ tb = TR12(tan(b), first=False)
926
+ else:
927
+ tb = tan(b)
928
+ return (tan(a) + tb)/(1 - tan(a)*tb)
929
+ return rv
930
+
931
+ return bottom_up(rv, f)
932
+
933
+
934
+ def TR12i(rv):
935
+ """Combine tan arguments as
936
+ (tan(y) + tan(x))/(tan(x)*tan(y) - 1) -> -tan(x + y).
937
+
938
+ Examples
939
+ ========
940
+
941
+ >>> from sympy.simplify.fu import TR12i
942
+ >>> from sympy import tan
943
+ >>> from sympy.abc import a, b, c
944
+ >>> ta, tb, tc = [tan(i) for i in (a, b, c)]
945
+ >>> TR12i((ta + tb)/(-ta*tb + 1))
946
+ tan(a + b)
947
+ >>> TR12i((ta + tb)/(ta*tb - 1))
948
+ -tan(a + b)
949
+ >>> TR12i((-ta - tb)/(ta*tb - 1))
950
+ tan(a + b)
951
+ >>> eq = (ta + tb)/(-ta*tb + 1)**2*(-3*ta - 3*tc)/(2*(ta*tc - 1))
952
+ >>> TR12i(eq.expand())
953
+ -3*tan(a + b)*tan(a + c)/(2*(tan(a) + tan(b) - 1))
954
+ """
955
+ def f(rv):
956
+ if not (rv.is_Add or rv.is_Mul or rv.is_Pow):
957
+ return rv
958
+
959
+ n, d = rv.as_numer_denom()
960
+ if not d.args or not n.args:
961
+ return rv
962
+
963
+ dok = {}
964
+
965
+ def ok(di):
966
+ m = as_f_sign_1(di)
967
+ if m:
968
+ g, f, s = m
969
+ if s is S.NegativeOne and f.is_Mul and len(f.args) == 2 and \
970
+ all(isinstance(fi, tan) for fi in f.args):
971
+ return g, f
972
+
973
+ d_args = list(Mul.make_args(d))
974
+ for i, di in enumerate(d_args):
975
+ m = ok(di)
976
+ if m:
977
+ g, t = m
978
+ s = Add(*[_.args[0] for _ in t.args])
979
+ dok[s] = S.One
980
+ d_args[i] = g
981
+ continue
982
+ if di.is_Add:
983
+ di = factor(di)
984
+ if di.is_Mul:
985
+ d_args.extend(di.args)
986
+ d_args[i] = S.One
987
+ elif di.is_Pow and (di.exp.is_integer or di.base.is_positive):
988
+ m = ok(di.base)
989
+ if m:
990
+ g, t = m
991
+ s = Add(*[_.args[0] for _ in t.args])
992
+ dok[s] = di.exp
993
+ d_args[i] = g**di.exp
994
+ else:
995
+ di = factor(di)
996
+ if di.is_Mul:
997
+ d_args.extend(di.args)
998
+ d_args[i] = S.One
999
+ if not dok:
1000
+ return rv
1001
+
1002
+ def ok(ni):
1003
+ if ni.is_Add and len(ni.args) == 2:
1004
+ a, b = ni.args
1005
+ if isinstance(a, tan) and isinstance(b, tan):
1006
+ return a, b
1007
+ n_args = list(Mul.make_args(factor_terms(n)))
1008
+ hit = False
1009
+ for i, ni in enumerate(n_args):
1010
+ m = ok(ni)
1011
+ if not m:
1012
+ m = ok(-ni)
1013
+ if m:
1014
+ n_args[i] = S.NegativeOne
1015
+ else:
1016
+ if ni.is_Add:
1017
+ ni = factor(ni)
1018
+ if ni.is_Mul:
1019
+ n_args.extend(ni.args)
1020
+ n_args[i] = S.One
1021
+ continue
1022
+ elif ni.is_Pow and (
1023
+ ni.exp.is_integer or ni.base.is_positive):
1024
+ m = ok(ni.base)
1025
+ if m:
1026
+ n_args[i] = S.One
1027
+ else:
1028
+ ni = factor(ni)
1029
+ if ni.is_Mul:
1030
+ n_args.extend(ni.args)
1031
+ n_args[i] = S.One
1032
+ continue
1033
+ else:
1034
+ continue
1035
+ else:
1036
+ n_args[i] = S.One
1037
+ hit = True
1038
+ s = Add(*[_.args[0] for _ in m])
1039
+ ed = dok[s]
1040
+ newed = ed.extract_additively(S.One)
1041
+ if newed is not None:
1042
+ if newed:
1043
+ dok[s] = newed
1044
+ else:
1045
+ dok.pop(s)
1046
+ n_args[i] *= -tan(s)
1047
+
1048
+ if hit:
1049
+ rv = Mul(*n_args)/Mul(*d_args)/Mul(*[(Add(*[
1050
+ tan(a) for a in i.args]) - 1)**e for i, e in dok.items()])
1051
+
1052
+ return rv
1053
+
1054
+ return bottom_up(rv, f)
1055
+
1056
+
1057
+ def TR13(rv):
1058
+ """Change products of ``tan`` or ``cot``.
1059
+
1060
+ Examples
1061
+ ========
1062
+
1063
+ >>> from sympy.simplify.fu import TR13
1064
+ >>> from sympy import tan, cot
1065
+ >>> TR13(tan(3)*tan(2))
1066
+ -tan(2)/tan(5) - tan(3)/tan(5) + 1
1067
+ >>> TR13(cot(3)*cot(2))
1068
+ cot(2)*cot(5) + 1 + cot(3)*cot(5)
1069
+ """
1070
+
1071
+ def f(rv):
1072
+ if not rv.is_Mul:
1073
+ return rv
1074
+
1075
+ # XXX handle products of powers? or let power-reducing handle it?
1076
+ args = {tan: [], cot: [], None: []}
1077
+ for a in ordered(Mul.make_args(rv)):
1078
+ if a.func in (tan, cot):
1079
+ args[type(a)].append(a.args[0])
1080
+ else:
1081
+ args[None].append(a)
1082
+ t = args[tan]
1083
+ c = args[cot]
1084
+ if len(t) < 2 and len(c) < 2:
1085
+ return rv
1086
+ args = args[None]
1087
+ while len(t) > 1:
1088
+ t1 = t.pop()
1089
+ t2 = t.pop()
1090
+ args.append(1 - (tan(t1)/tan(t1 + t2) + tan(t2)/tan(t1 + t2)))
1091
+ if t:
1092
+ args.append(tan(t.pop()))
1093
+ while len(c) > 1:
1094
+ t1 = c.pop()
1095
+ t2 = c.pop()
1096
+ args.append(1 + cot(t1)*cot(t1 + t2) + cot(t2)*cot(t1 + t2))
1097
+ if c:
1098
+ args.append(cot(c.pop()))
1099
+ return Mul(*args)
1100
+
1101
+ return bottom_up(rv, f)
1102
+
1103
+
1104
+ def TRmorrie(rv):
1105
+ """Returns cos(x)*cos(2*x)*...*cos(2**(k-1)*x) -> sin(2**k*x)/(2**k*sin(x))
1106
+
1107
+ Examples
1108
+ ========
1109
+
1110
+ >>> from sympy.simplify.fu import TRmorrie, TR8, TR3
1111
+ >>> from sympy.abc import x
1112
+ >>> from sympy import Mul, cos, pi
1113
+ >>> TRmorrie(cos(x)*cos(2*x))
1114
+ sin(4*x)/(4*sin(x))
1115
+ >>> TRmorrie(7*Mul(*[cos(x) for x in range(10)]))
1116
+ 7*sin(12)*sin(16)*cos(5)*cos(7)*cos(9)/(64*sin(1)*sin(3))
1117
+
1118
+ Sometimes autosimplification will cause a power to be
1119
+ not recognized. e.g. in the following, cos(4*pi/7) automatically
1120
+ simplifies to -cos(3*pi/7) so only 2 of the 3 terms are
1121
+ recognized:
1122
+
1123
+ >>> TRmorrie(cos(pi/7)*cos(2*pi/7)*cos(4*pi/7))
1124
+ -sin(3*pi/7)*cos(3*pi/7)/(4*sin(pi/7))
1125
+
1126
+ A touch by TR8 resolves the expression to a Rational
1127
+
1128
+ >>> TR8(_)
1129
+ -1/8
1130
+
1131
+ In this case, if eq is unsimplified, the answer is obtained
1132
+ directly:
1133
+
1134
+ >>> eq = cos(pi/9)*cos(2*pi/9)*cos(3*pi/9)*cos(4*pi/9)
1135
+ >>> TRmorrie(eq)
1136
+ 1/16
1137
+
1138
+ But if angles are made canonical with TR3 then the answer
1139
+ is not simplified without further work:
1140
+
1141
+ >>> TR3(eq)
1142
+ sin(pi/18)*cos(pi/9)*cos(2*pi/9)/2
1143
+ >>> TRmorrie(_)
1144
+ sin(pi/18)*sin(4*pi/9)/(8*sin(pi/9))
1145
+ >>> TR8(_)
1146
+ cos(7*pi/18)/(16*sin(pi/9))
1147
+ >>> TR3(_)
1148
+ 1/16
1149
+
1150
+ The original expression would have resolve to 1/16 directly with TR8,
1151
+ however:
1152
+
1153
+ >>> TR8(eq)
1154
+ 1/16
1155
+
1156
+ References
1157
+ ==========
1158
+
1159
+ .. [1] https://en.wikipedia.org/wiki/Morrie%27s_law
1160
+
1161
+ """
1162
+
1163
+ def f(rv, first=True):
1164
+ if not rv.is_Mul:
1165
+ return rv
1166
+ if first:
1167
+ n, d = rv.as_numer_denom()
1168
+ return f(n, 0)/f(d, 0)
1169
+
1170
+ args = defaultdict(list)
1171
+ coss = {}
1172
+ other = []
1173
+ for c in rv.args:
1174
+ b, e = c.as_base_exp()
1175
+ if e.is_Integer and isinstance(b, cos):
1176
+ co, a = b.args[0].as_coeff_Mul()
1177
+ args[a].append(co)
1178
+ coss[b] = e
1179
+ else:
1180
+ other.append(c)
1181
+
1182
+ new = []
1183
+ for a in args:
1184
+ c = args[a]
1185
+ c.sort()
1186
+ while c:
1187
+ k = 0
1188
+ cc = ci = c[0]
1189
+ while cc in c:
1190
+ k += 1
1191
+ cc *= 2
1192
+ if k > 1:
1193
+ newarg = sin(2**k*ci*a)/2**k/sin(ci*a)
1194
+ # see how many times this can be taken
1195
+ take = None
1196
+ ccs = []
1197
+ for i in range(k):
1198
+ cc /= 2
1199
+ key = cos(a*cc, evaluate=False)
1200
+ ccs.append(cc)
1201
+ take = min(coss[key], take or coss[key])
1202
+ # update exponent counts
1203
+ for i in range(k):
1204
+ cc = ccs.pop()
1205
+ key = cos(a*cc, evaluate=False)
1206
+ coss[key] -= take
1207
+ if not coss[key]:
1208
+ c.remove(cc)
1209
+ new.append(newarg**take)
1210
+ else:
1211
+ b = cos(c.pop(0)*a)
1212
+ other.append(b**coss[b])
1213
+
1214
+ if new:
1215
+ rv = Mul(*(new + other + [
1216
+ cos(k*a, evaluate=False) for a in args for k in args[a]]))
1217
+
1218
+ return rv
1219
+
1220
+ return bottom_up(rv, f)
1221
+
1222
+
1223
+ def TR14(rv, first=True):
1224
+ """Convert factored powers of sin and cos identities into simpler
1225
+ expressions.
1226
+
1227
+ Examples
1228
+ ========
1229
+
1230
+ >>> from sympy.simplify.fu import TR14
1231
+ >>> from sympy.abc import x, y
1232
+ >>> from sympy import cos, sin
1233
+ >>> TR14((cos(x) - 1)*(cos(x) + 1))
1234
+ -sin(x)**2
1235
+ >>> TR14((sin(x) - 1)*(sin(x) + 1))
1236
+ -cos(x)**2
1237
+ >>> p1 = (cos(x) + 1)*(cos(x) - 1)
1238
+ >>> p2 = (cos(y) - 1)*2*(cos(y) + 1)
1239
+ >>> p3 = (3*(cos(y) - 1))*(3*(cos(y) + 1))
1240
+ >>> TR14(p1*p2*p3*(x - 1))
1241
+ -18*(x - 1)*sin(x)**2*sin(y)**4
1242
+
1243
+ """
1244
+
1245
+ def f(rv):
1246
+ if not rv.is_Mul:
1247
+ return rv
1248
+
1249
+ if first:
1250
+ # sort them by location in numerator and denominator
1251
+ # so the code below can just deal with positive exponents
1252
+ n, d = rv.as_numer_denom()
1253
+ if d is not S.One:
1254
+ newn = TR14(n, first=False)
1255
+ newd = TR14(d, first=False)
1256
+ if newn != n or newd != d:
1257
+ rv = newn/newd
1258
+ return rv
1259
+
1260
+ other = []
1261
+ process = []
1262
+ for a in rv.args:
1263
+ if a.is_Pow:
1264
+ b, e = a.as_base_exp()
1265
+ if not (e.is_integer or b.is_positive):
1266
+ other.append(a)
1267
+ continue
1268
+ a = b
1269
+ else:
1270
+ e = S.One
1271
+ m = as_f_sign_1(a)
1272
+ if not m or m[1].func not in (cos, sin):
1273
+ if e is S.One:
1274
+ other.append(a)
1275
+ else:
1276
+ other.append(a**e)
1277
+ continue
1278
+ g, f, si = m
1279
+ process.append((g, e.is_Number, e, f, si, a))
1280
+
1281
+ # sort them to get like terms next to each other
1282
+ process = list(ordered(process))
1283
+
1284
+ # keep track of whether there was any change
1285
+ nother = len(other)
1286
+
1287
+ # access keys
1288
+ keys = (g, t, e, f, si, a) = list(range(6))
1289
+
1290
+ while process:
1291
+ A = process.pop(0)
1292
+ if process:
1293
+ B = process[0]
1294
+
1295
+ if A[e].is_Number and B[e].is_Number:
1296
+ # both exponents are numbers
1297
+ if A[f] == B[f]:
1298
+ if A[si] != B[si]:
1299
+ B = process.pop(0)
1300
+ take = min(A[e], B[e])
1301
+
1302
+ # reinsert any remainder
1303
+ # the B will likely sort after A so check it first
1304
+ if B[e] != take:
1305
+ rem = [B[i] for i in keys]
1306
+ rem[e] -= take
1307
+ process.insert(0, rem)
1308
+ elif A[e] != take:
1309
+ rem = [A[i] for i in keys]
1310
+ rem[e] -= take
1311
+ process.insert(0, rem)
1312
+
1313
+ if isinstance(A[f], cos):
1314
+ t = sin
1315
+ else:
1316
+ t = cos
1317
+ other.append((-A[g]*B[g]*t(A[f].args[0])**2)**take)
1318
+ continue
1319
+
1320
+ elif A[e] == B[e]:
1321
+ # both exponents are equal symbols
1322
+ if A[f] == B[f]:
1323
+ if A[si] != B[si]:
1324
+ B = process.pop(0)
1325
+ take = A[e]
1326
+ if isinstance(A[f], cos):
1327
+ t = sin
1328
+ else:
1329
+ t = cos
1330
+ other.append((-A[g]*B[g]*t(A[f].args[0])**2)**take)
1331
+ continue
1332
+
1333
+ # either we are done or neither condition above applied
1334
+ other.append(A[a]**A[e])
1335
+
1336
+ if len(other) != nother:
1337
+ rv = Mul(*other)
1338
+
1339
+ return rv
1340
+
1341
+ return bottom_up(rv, f)
1342
+
1343
+
1344
+ def TR15(rv, max=4, pow=False):
1345
+ """Convert sin(x)**-2 to 1 + cot(x)**2.
1346
+
1347
+ See _TR56 docstring for advanced use of ``max`` and ``pow``.
1348
+
1349
+ Examples
1350
+ ========
1351
+
1352
+ >>> from sympy.simplify.fu import TR15
1353
+ >>> from sympy.abc import x
1354
+ >>> from sympy import sin
1355
+ >>> TR15(1 - 1/sin(x)**2)
1356
+ -cot(x)**2
1357
+
1358
+ """
1359
+
1360
+ def f(rv):
1361
+ if not (isinstance(rv, Pow) and isinstance(rv.base, sin)):
1362
+ return rv
1363
+
1364
+ e = rv.exp
1365
+ if e % 2 == 1:
1366
+ return TR15(rv.base**(e + 1))/rv.base
1367
+
1368
+ ia = 1/rv
1369
+ a = _TR56(ia, sin, cot, lambda x: 1 + x, max=max, pow=pow)
1370
+ if a != ia:
1371
+ rv = a
1372
+ return rv
1373
+
1374
+ return bottom_up(rv, f)
1375
+
1376
+
1377
+ def TR16(rv, max=4, pow=False):
1378
+ """Convert cos(x)**-2 to 1 + tan(x)**2.
1379
+
1380
+ See _TR56 docstring for advanced use of ``max`` and ``pow``.
1381
+
1382
+ Examples
1383
+ ========
1384
+
1385
+ >>> from sympy.simplify.fu import TR16
1386
+ >>> from sympy.abc import x
1387
+ >>> from sympy import cos
1388
+ >>> TR16(1 - 1/cos(x)**2)
1389
+ -tan(x)**2
1390
+
1391
+ """
1392
+
1393
+ def f(rv):
1394
+ if not (isinstance(rv, Pow) and isinstance(rv.base, cos)):
1395
+ return rv
1396
+
1397
+ e = rv.exp
1398
+ if e % 2 == 1:
1399
+ return TR15(rv.base**(e + 1))/rv.base
1400
+
1401
+ ia = 1/rv
1402
+ a = _TR56(ia, cos, tan, lambda x: 1 + x, max=max, pow=pow)
1403
+ if a != ia:
1404
+ rv = a
1405
+ return rv
1406
+
1407
+ return bottom_up(rv, f)
1408
+
1409
+
1410
+ def TR111(rv):
1411
+ """Convert f(x)**-i to g(x)**i where either ``i`` is an integer
1412
+ or the base is positive and f, g are: tan, cot; sin, csc; or cos, sec.
1413
+
1414
+ Examples
1415
+ ========
1416
+
1417
+ >>> from sympy.simplify.fu import TR111
1418
+ >>> from sympy.abc import x
1419
+ >>> from sympy import tan
1420
+ >>> TR111(1 - 1/tan(x)**2)
1421
+ 1 - cot(x)**2
1422
+
1423
+ """
1424
+
1425
+ def f(rv):
1426
+ if not (
1427
+ isinstance(rv, Pow) and
1428
+ (rv.base.is_positive or rv.exp.is_integer and rv.exp.is_negative)):
1429
+ return rv
1430
+
1431
+ if isinstance(rv.base, tan):
1432
+ return cot(rv.base.args[0])**-rv.exp
1433
+ elif isinstance(rv.base, sin):
1434
+ return csc(rv.base.args[0])**-rv.exp
1435
+ elif isinstance(rv.base, cos):
1436
+ return sec(rv.base.args[0])**-rv.exp
1437
+ return rv
1438
+
1439
+ return bottom_up(rv, f)
1440
+
1441
+
1442
+ def TR22(rv, max=4, pow=False):
1443
+ """Convert tan(x)**2 to sec(x)**2 - 1 and cot(x)**2 to csc(x)**2 - 1.
1444
+
1445
+ See _TR56 docstring for advanced use of ``max`` and ``pow``.
1446
+
1447
+ Examples
1448
+ ========
1449
+
1450
+ >>> from sympy.simplify.fu import TR22
1451
+ >>> from sympy.abc import x
1452
+ >>> from sympy import tan, cot
1453
+ >>> TR22(1 + tan(x)**2)
1454
+ sec(x)**2
1455
+ >>> TR22(1 + cot(x)**2)
1456
+ csc(x)**2
1457
+
1458
+ """
1459
+
1460
+ def f(rv):
1461
+ if not (isinstance(rv, Pow) and rv.base.func in (cot, tan)):
1462
+ return rv
1463
+
1464
+ rv = _TR56(rv, tan, sec, lambda x: x - 1, max=max, pow=pow)
1465
+ rv = _TR56(rv, cot, csc, lambda x: x - 1, max=max, pow=pow)
1466
+ return rv
1467
+
1468
+ return bottom_up(rv, f)
1469
+
1470
+
1471
+ def TRpower(rv):
1472
+ """Convert sin(x)**n and cos(x)**n with positive n to sums.
1473
+
1474
+ Examples
1475
+ ========
1476
+
1477
+ >>> from sympy.simplify.fu import TRpower
1478
+ >>> from sympy.abc import x
1479
+ >>> from sympy import cos, sin
1480
+ >>> TRpower(sin(x)**6)
1481
+ -15*cos(2*x)/32 + 3*cos(4*x)/16 - cos(6*x)/32 + 5/16
1482
+ >>> TRpower(sin(x)**3*cos(2*x)**4)
1483
+ (3*sin(x)/4 - sin(3*x)/4)*(cos(4*x)/2 + cos(8*x)/8 + 3/8)
1484
+
1485
+ References
1486
+ ==========
1487
+
1488
+ .. [1] https://en.wikipedia.org/wiki/List_of_trigonometric_identities#Power-reduction_formulae
1489
+
1490
+ """
1491
+
1492
+ def f(rv):
1493
+ if not (isinstance(rv, Pow) and isinstance(rv.base, (sin, cos))):
1494
+ return rv
1495
+ b, n = rv.as_base_exp()
1496
+ x = b.args[0]
1497
+ if n.is_Integer and n.is_positive:
1498
+ if n.is_odd and isinstance(b, cos):
1499
+ rv = 2**(1-n)*Add(*[binomial(n, k)*cos((n - 2*k)*x)
1500
+ for k in range((n + 1)/2)])
1501
+ elif n.is_odd and isinstance(b, sin):
1502
+ rv = 2**(1-n)*S.NegativeOne**((n-1)/2)*Add(*[binomial(n, k)*
1503
+ S.NegativeOne**k*sin((n - 2*k)*x) for k in range((n + 1)/2)])
1504
+ elif n.is_even and isinstance(b, cos):
1505
+ rv = 2**(1-n)*Add(*[binomial(n, k)*cos((n - 2*k)*x)
1506
+ for k in range(n/2)])
1507
+ elif n.is_even and isinstance(b, sin):
1508
+ rv = 2**(1-n)*S.NegativeOne**(n/2)*Add(*[binomial(n, k)*
1509
+ S.NegativeOne**k*cos((n - 2*k)*x) for k in range(n/2)])
1510
+ if n.is_even:
1511
+ rv += 2**(-n)*binomial(n, n/2)
1512
+ return rv
1513
+
1514
+ return bottom_up(rv, f)
1515
+
1516
+
1517
+ def L(rv):
1518
+ """Return count of trigonometric functions in expression.
1519
+
1520
+ Examples
1521
+ ========
1522
+
1523
+ >>> from sympy.simplify.fu import L
1524
+ >>> from sympy.abc import x
1525
+ >>> from sympy import cos, sin
1526
+ >>> L(cos(x)+sin(x))
1527
+ 2
1528
+ """
1529
+ return S(rv.count(TrigonometricFunction))
1530
+
1531
+
1532
+ # ============== end of basic Fu-like tools =====================
1533
+
1534
+ if SYMPY_DEBUG:
1535
+ (TR0, TR1, TR2, TR3, TR4, TR5, TR6, TR7, TR8, TR9, TR10, TR11, TR12, TR13,
1536
+ TR2i, TRmorrie, TR14, TR15, TR16, TR12i, TR111, TR22
1537
+ )= list(map(debug,
1538
+ (TR0, TR1, TR2, TR3, TR4, TR5, TR6, TR7, TR8, TR9, TR10, TR11, TR12, TR13,
1539
+ TR2i, TRmorrie, TR14, TR15, TR16, TR12i, TR111, TR22)))
1540
+
1541
+
1542
+ # tuples are chains -- (f, g) -> lambda x: g(f(x))
1543
+ # lists are choices -- [f, g] -> lambda x: min(f(x), g(x), key=objective)
1544
+
1545
+ CTR1 = [(TR5, TR0), (TR6, TR0), identity]
1546
+
1547
+ CTR2 = (TR11, [(TR5, TR0), (TR6, TR0), TR0])
1548
+
1549
+ CTR3 = [(TRmorrie, TR8, TR0), (TRmorrie, TR8, TR10i, TR0), identity]
1550
+
1551
+ CTR4 = [(TR4, TR10i), identity]
1552
+
1553
+ RL1 = (TR4, TR3, TR4, TR12, TR4, TR13, TR4, TR0)
1554
+
1555
+
1556
+ # XXX it's a little unclear how this one is to be implemented
1557
+ # see Fu paper of reference, page 7. What is the Union symbol referring to?
1558
+ # The diagram shows all these as one chain of transformations, but the
1559
+ # text refers to them being applied independently. Also, a break
1560
+ # if L starts to increase has not been implemented.
1561
+ RL2 = [
1562
+ (TR4, TR3, TR10, TR4, TR3, TR11),
1563
+ (TR5, TR7, TR11, TR4),
1564
+ (CTR3, CTR1, TR9, CTR2, TR4, TR9, TR9, CTR4),
1565
+ identity,
1566
+ ]
1567
+
1568
+
1569
+ def fu(rv, measure=lambda x: (L(x), x.count_ops())):
1570
+ """Attempt to simplify expression by using transformation rules given
1571
+ in the algorithm by Fu et al.
1572
+
1573
+ :func:`fu` will try to minimize the objective function ``measure``.
1574
+ By default this first minimizes the number of trig terms and then minimizes
1575
+ the number of total operations.
1576
+
1577
+ Examples
1578
+ ========
1579
+
1580
+ >>> from sympy.simplify.fu import fu
1581
+ >>> from sympy import cos, sin, tan, pi, S, sqrt
1582
+ >>> from sympy.abc import x, y, a, b
1583
+
1584
+ >>> fu(sin(50)**2 + cos(50)**2 + sin(pi/6))
1585
+ 3/2
1586
+ >>> fu(sqrt(6)*cos(x) + sqrt(2)*sin(x))
1587
+ 2*sqrt(2)*sin(x + pi/3)
1588
+
1589
+ CTR1 example
1590
+
1591
+ >>> eq = sin(x)**4 - cos(y)**2 + sin(y)**2 + 2*cos(x)**2
1592
+ >>> fu(eq)
1593
+ cos(x)**4 - 2*cos(y)**2 + 2
1594
+
1595
+ CTR2 example
1596
+
1597
+ >>> fu(S.Half - cos(2*x)/2)
1598
+ sin(x)**2
1599
+
1600
+ CTR3 example
1601
+
1602
+ >>> fu(sin(a)*(cos(b) - sin(b)) + cos(a)*(sin(b) + cos(b)))
1603
+ sqrt(2)*sin(a + b + pi/4)
1604
+
1605
+ CTR4 example
1606
+
1607
+ >>> fu(sqrt(3)*cos(x)/2 + sin(x)/2)
1608
+ sin(x + pi/3)
1609
+
1610
+ Example 1
1611
+
1612
+ >>> fu(1-sin(2*x)**2/4-sin(y)**2-cos(x)**4)
1613
+ -cos(x)**2 + cos(y)**2
1614
+
1615
+ Example 2
1616
+
1617
+ >>> fu(cos(4*pi/9))
1618
+ sin(pi/18)
1619
+ >>> fu(cos(pi/9)*cos(2*pi/9)*cos(3*pi/9)*cos(4*pi/9))
1620
+ 1/16
1621
+
1622
+ Example 3
1623
+
1624
+ >>> fu(tan(7*pi/18)+tan(5*pi/18)-sqrt(3)*tan(5*pi/18)*tan(7*pi/18))
1625
+ -sqrt(3)
1626
+
1627
+ Objective function example
1628
+
1629
+ >>> fu(sin(x)/cos(x)) # default objective function
1630
+ tan(x)
1631
+ >>> fu(sin(x)/cos(x), measure=lambda x: -x.count_ops()) # maximize op count
1632
+ sin(x)/cos(x)
1633
+
1634
+ References
1635
+ ==========
1636
+
1637
+ .. [1] https://www.sciencedirect.com/science/article/pii/S0895717706001609
1638
+ """
1639
+ fRL1 = greedy(RL1, measure)
1640
+ fRL2 = greedy(RL2, measure)
1641
+
1642
+ was = rv
1643
+ rv = sympify(rv)
1644
+ if not isinstance(rv, Expr):
1645
+ return rv.func(*[fu(a, measure=measure) for a in rv.args])
1646
+ rv = TR1(rv)
1647
+ if rv.has(tan, cot):
1648
+ rv1 = fRL1(rv)
1649
+ if (measure(rv1) < measure(rv)):
1650
+ rv = rv1
1651
+ if rv.has(tan, cot):
1652
+ rv = TR2(rv)
1653
+ if rv.has(sin, cos):
1654
+ rv1 = fRL2(rv)
1655
+ rv2 = TR8(TRmorrie(rv1))
1656
+ rv = min([was, rv, rv1, rv2], key=measure)
1657
+ return min(TR2i(rv), rv, key=measure)
1658
+
1659
+
1660
+ def process_common_addends(rv, do, key2=None, key1=True):
1661
+ """Apply ``do`` to addends of ``rv`` that (if ``key1=True``) share at least
1662
+ a common absolute value of their coefficient and the value of ``key2`` when
1663
+ applied to the argument. If ``key1`` is False ``key2`` must be supplied and
1664
+ will be the only key applied.
1665
+ """
1666
+
1667
+ # collect by absolute value of coefficient and key2
1668
+ absc = defaultdict(list)
1669
+ if key1:
1670
+ for a in rv.args:
1671
+ c, a = a.as_coeff_Mul()
1672
+ if c < 0:
1673
+ c = -c
1674
+ a = -a # put the sign on `a`
1675
+ absc[(c, key2(a) if key2 else 1)].append(a)
1676
+ elif key2:
1677
+ for a in rv.args:
1678
+ absc[(S.One, key2(a))].append(a)
1679
+ else:
1680
+ raise ValueError('must have at least one key')
1681
+
1682
+ args = []
1683
+ hit = False
1684
+ for k in absc:
1685
+ v = absc[k]
1686
+ c, _ = k
1687
+ if len(v) > 1:
1688
+ e = Add(*v, evaluate=False)
1689
+ new = do(e)
1690
+ if new != e:
1691
+ e = new
1692
+ hit = True
1693
+ args.append(c*e)
1694
+ else:
1695
+ args.append(c*v[0])
1696
+ if hit:
1697
+ rv = Add(*args)
1698
+
1699
+ return rv
1700
+
1701
+
1702
+ fufuncs = '''
1703
+ TR0 TR1 TR2 TR3 TR4 TR5 TR6 TR7 TR8 TR9 TR10 TR10i TR11
1704
+ TR12 TR13 L TR2i TRmorrie TR12i
1705
+ TR14 TR15 TR16 TR111 TR22'''.split()
1706
+ FU = dict(list(zip(fufuncs, list(map(locals().get, fufuncs)))))
1707
+
1708
+
1709
+ def _roots():
1710
+ global _ROOT2, _ROOT3, _invROOT3
1711
+ _ROOT2, _ROOT3 = sqrt(2), sqrt(3)
1712
+ _invROOT3 = 1/_ROOT3
1713
+ _ROOT2 = None
1714
+
1715
+
1716
+ def trig_split(a, b, two=False):
1717
+ """Return the gcd, s1, s2, a1, a2, bool where
1718
+
1719
+ If two is False (default) then::
1720
+ a + b = gcd*(s1*f(a1) + s2*f(a2)) where f = cos if bool else sin
1721
+ else:
1722
+ if bool, a + b was +/- cos(a1)*cos(a2) +/- sin(a1)*sin(a2) and equals
1723
+ n1*gcd*cos(a - b) if n1 == n2 else
1724
+ n1*gcd*cos(a + b)
1725
+ else a + b was +/- cos(a1)*sin(a2) +/- sin(a1)*cos(a2) and equals
1726
+ n1*gcd*sin(a + b) if n1 = n2 else
1727
+ n1*gcd*sin(b - a)
1728
+
1729
+ Examples
1730
+ ========
1731
+
1732
+ >>> from sympy.simplify.fu import trig_split
1733
+ >>> from sympy.abc import x, y, z
1734
+ >>> from sympy import cos, sin, sqrt
1735
+
1736
+ >>> trig_split(cos(x), cos(y))
1737
+ (1, 1, 1, x, y, True)
1738
+ >>> trig_split(2*cos(x), -2*cos(y))
1739
+ (2, 1, -1, x, y, True)
1740
+ >>> trig_split(cos(x)*sin(y), cos(y)*sin(y))
1741
+ (sin(y), 1, 1, x, y, True)
1742
+
1743
+ >>> trig_split(cos(x), -sqrt(3)*sin(x), two=True)
1744
+ (2, 1, -1, x, pi/6, False)
1745
+ >>> trig_split(cos(x), sin(x), two=True)
1746
+ (sqrt(2), 1, 1, x, pi/4, False)
1747
+ >>> trig_split(cos(x), -sin(x), two=True)
1748
+ (sqrt(2), 1, -1, x, pi/4, False)
1749
+ >>> trig_split(sqrt(2)*cos(x), -sqrt(6)*sin(x), two=True)
1750
+ (2*sqrt(2), 1, -1, x, pi/6, False)
1751
+ >>> trig_split(-sqrt(6)*cos(x), -sqrt(2)*sin(x), two=True)
1752
+ (-2*sqrt(2), 1, 1, x, pi/3, False)
1753
+ >>> trig_split(cos(x)/sqrt(6), sin(x)/sqrt(2), two=True)
1754
+ (sqrt(6)/3, 1, 1, x, pi/6, False)
1755
+ >>> trig_split(-sqrt(6)*cos(x)*sin(y), -sqrt(2)*sin(x)*sin(y), two=True)
1756
+ (-2*sqrt(2)*sin(y), 1, 1, x, pi/3, False)
1757
+
1758
+ >>> trig_split(cos(x), sin(x))
1759
+ >>> trig_split(cos(x), sin(z))
1760
+ >>> trig_split(2*cos(x), -sin(x))
1761
+ >>> trig_split(cos(x), -sqrt(3)*sin(x))
1762
+ >>> trig_split(cos(x)*cos(y), sin(x)*sin(z))
1763
+ >>> trig_split(cos(x)*cos(y), sin(x)*sin(y))
1764
+ >>> trig_split(-sqrt(6)*cos(x), sqrt(2)*sin(x)*sin(y), two=True)
1765
+ """
1766
+ global _ROOT2, _ROOT3, _invROOT3
1767
+ if _ROOT2 is None:
1768
+ _roots()
1769
+
1770
+ a, b = [Factors(i) for i in (a, b)]
1771
+ ua, ub = a.normal(b)
1772
+ gcd = a.gcd(b).as_expr()
1773
+ n1 = n2 = 1
1774
+ if S.NegativeOne in ua.factors:
1775
+ ua = ua.quo(S.NegativeOne)
1776
+ n1 = -n1
1777
+ elif S.NegativeOne in ub.factors:
1778
+ ub = ub.quo(S.NegativeOne)
1779
+ n2 = -n2
1780
+ a, b = [i.as_expr() for i in (ua, ub)]
1781
+
1782
+ def pow_cos_sin(a, two):
1783
+ """Return ``a`` as a tuple (r, c, s) such that
1784
+ ``a = (r or 1)*(c or 1)*(s or 1)``.
1785
+
1786
+ Three arguments are returned (radical, c-factor, s-factor) as
1787
+ long as the conditions set by ``two`` are met; otherwise None is
1788
+ returned. If ``two`` is True there will be one or two non-None
1789
+ values in the tuple: c and s or c and r or s and r or s or c with c
1790
+ being a cosine function (if possible) else a sine, and s being a sine
1791
+ function (if possible) else oosine. If ``two`` is False then there
1792
+ will only be a c or s term in the tuple.
1793
+
1794
+ ``two`` also require that either two cos and/or sin be present (with
1795
+ the condition that if the functions are the same the arguments are
1796
+ different or vice versa) or that a single cosine or a single sine
1797
+ be present with an optional radical.
1798
+
1799
+ If the above conditions dictated by ``two`` are not met then None
1800
+ is returned.
1801
+ """
1802
+ c = s = None
1803
+ co = S.One
1804
+ if a.is_Mul:
1805
+ co, a = a.as_coeff_Mul()
1806
+ if len(a.args) > 2 or not two:
1807
+ return None
1808
+ if a.is_Mul:
1809
+ args = list(a.args)
1810
+ else:
1811
+ args = [a]
1812
+ a = args.pop(0)
1813
+ if isinstance(a, cos):
1814
+ c = a
1815
+ elif isinstance(a, sin):
1816
+ s = a
1817
+ elif a.is_Pow and a.exp is S.Half: # autoeval doesn't allow -1/2
1818
+ co *= a
1819
+ else:
1820
+ return None
1821
+ if args:
1822
+ b = args[0]
1823
+ if isinstance(b, cos):
1824
+ if c:
1825
+ s = b
1826
+ else:
1827
+ c = b
1828
+ elif isinstance(b, sin):
1829
+ if s:
1830
+ c = b
1831
+ else:
1832
+ s = b
1833
+ elif b.is_Pow and b.exp is S.Half:
1834
+ co *= b
1835
+ else:
1836
+ return None
1837
+ return co if co is not S.One else None, c, s
1838
+ elif isinstance(a, cos):
1839
+ c = a
1840
+ elif isinstance(a, sin):
1841
+ s = a
1842
+ if c is None and s is None:
1843
+ return
1844
+ co = co if co is not S.One else None
1845
+ return co, c, s
1846
+
1847
+ # get the parts
1848
+ m = pow_cos_sin(a, two)
1849
+ if m is None:
1850
+ return
1851
+ coa, ca, sa = m
1852
+ m = pow_cos_sin(b, two)
1853
+ if m is None:
1854
+ return
1855
+ cob, cb, sb = m
1856
+
1857
+ # check them
1858
+ if (not ca) and cb or ca and isinstance(ca, sin):
1859
+ coa, ca, sa, cob, cb, sb = cob, cb, sb, coa, ca, sa
1860
+ n1, n2 = n2, n1
1861
+ if not two: # need cos(x) and cos(y) or sin(x) and sin(y)
1862
+ c = ca or sa
1863
+ s = cb or sb
1864
+ if not isinstance(c, s.func):
1865
+ return None
1866
+ return gcd, n1, n2, c.args[0], s.args[0], isinstance(c, cos)
1867
+ else:
1868
+ if not coa and not cob:
1869
+ if (ca and cb and sa and sb):
1870
+ if isinstance(ca, sa.func) is not isinstance(cb, sb.func):
1871
+ return
1872
+ args = {j.args for j in (ca, sa)}
1873
+ if not all(i.args in args for i in (cb, sb)):
1874
+ return
1875
+ return gcd, n1, n2, ca.args[0], sa.args[0], isinstance(ca, sa.func)
1876
+ if ca and sa or cb and sb or \
1877
+ two and (ca is None and sa is None or cb is None and sb is None):
1878
+ return
1879
+ c = ca or sa
1880
+ s = cb or sb
1881
+ if c.args != s.args:
1882
+ return
1883
+ if not coa:
1884
+ coa = S.One
1885
+ if not cob:
1886
+ cob = S.One
1887
+ if coa is cob:
1888
+ gcd *= _ROOT2
1889
+ return gcd, n1, n2, c.args[0], pi/4, False
1890
+ elif coa/cob == _ROOT3:
1891
+ gcd *= 2*cob
1892
+ return gcd, n1, n2, c.args[0], pi/3, False
1893
+ elif coa/cob == _invROOT3:
1894
+ gcd *= 2*coa
1895
+ return gcd, n1, n2, c.args[0], pi/6, False
1896
+
1897
+
1898
+ def as_f_sign_1(e):
1899
+ """If ``e`` is a sum that can be written as ``g*(a + s)`` where
1900
+ ``s`` is ``+/-1``, return ``g``, ``a``, and ``s`` where ``a`` does
1901
+ not have a leading negative coefficient.
1902
+
1903
+ Examples
1904
+ ========
1905
+
1906
+ >>> from sympy.simplify.fu import as_f_sign_1
1907
+ >>> from sympy.abc import x
1908
+ >>> as_f_sign_1(x + 1)
1909
+ (1, x, 1)
1910
+ >>> as_f_sign_1(x - 1)
1911
+ (1, x, -1)
1912
+ >>> as_f_sign_1(-x + 1)
1913
+ (-1, x, -1)
1914
+ >>> as_f_sign_1(-x - 1)
1915
+ (-1, x, 1)
1916
+ >>> as_f_sign_1(2*x + 2)
1917
+ (2, x, 1)
1918
+ """
1919
+ if not e.is_Add or len(e.args) != 2:
1920
+ return
1921
+ # exact match
1922
+ a, b = e.args
1923
+ if a in (S.NegativeOne, S.One):
1924
+ g = S.One
1925
+ if b.is_Mul and b.args[0].is_Number and b.args[0] < 0:
1926
+ a, b = -a, -b
1927
+ g = -g
1928
+ return g, b, a
1929
+ # gcd match
1930
+ a, b = [Factors(i) for i in e.args]
1931
+ ua, ub = a.normal(b)
1932
+ gcd = a.gcd(b).as_expr()
1933
+ if S.NegativeOne in ua.factors:
1934
+ ua = ua.quo(S.NegativeOne)
1935
+ n1 = -1
1936
+ n2 = 1
1937
+ elif S.NegativeOne in ub.factors:
1938
+ ub = ub.quo(S.NegativeOne)
1939
+ n1 = 1
1940
+ n2 = -1
1941
+ else:
1942
+ n1 = n2 = 1
1943
+ a, b = [i.as_expr() for i in (ua, ub)]
1944
+ if a is S.One:
1945
+ a, b = b, a
1946
+ n1, n2 = n2, n1
1947
+ if n1 == -1:
1948
+ gcd = -gcd
1949
+ n2 = -n2
1950
+
1951
+ if b is S.One:
1952
+ return gcd, a, n2
1953
+
1954
+
1955
+ def _osborne(e, d):
1956
+ """Replace all hyperbolic functions with trig functions using
1957
+ the Osborne rule.
1958
+
1959
+ Notes
1960
+ =====
1961
+
1962
+ ``d`` is a dummy variable to prevent automatic evaluation
1963
+ of trigonometric/hyperbolic functions.
1964
+
1965
+
1966
+ References
1967
+ ==========
1968
+
1969
+ .. [1] https://en.wikipedia.org/wiki/Hyperbolic_function
1970
+ """
1971
+
1972
+ def f(rv):
1973
+ if not isinstance(rv, HyperbolicFunction):
1974
+ return rv
1975
+ a = rv.args[0]
1976
+ a = a*d if not a.is_Add else Add._from_args([i*d for i in a.args])
1977
+ if isinstance(rv, sinh):
1978
+ return I*sin(a)
1979
+ elif isinstance(rv, cosh):
1980
+ return cos(a)
1981
+ elif isinstance(rv, tanh):
1982
+ return I*tan(a)
1983
+ elif isinstance(rv, coth):
1984
+ return cot(a)/I
1985
+ elif isinstance(rv, sech):
1986
+ return sec(a)
1987
+ elif isinstance(rv, csch):
1988
+ return csc(a)/I
1989
+ else:
1990
+ raise NotImplementedError('unhandled %s' % rv.func)
1991
+
1992
+ return bottom_up(e, f)
1993
+
1994
+
1995
+ def _osbornei(e, d):
1996
+ """Replace all trig functions with hyperbolic functions using
1997
+ the Osborne rule.
1998
+
1999
+ Notes
2000
+ =====
2001
+
2002
+ ``d`` is a dummy variable to prevent automatic evaluation
2003
+ of trigonometric/hyperbolic functions.
2004
+
2005
+ References
2006
+ ==========
2007
+
2008
+ .. [1] https://en.wikipedia.org/wiki/Hyperbolic_function
2009
+ """
2010
+
2011
+ def f(rv):
2012
+ if not isinstance(rv, TrigonometricFunction):
2013
+ return rv
2014
+ const, x = rv.args[0].as_independent(d, as_Add=True)
2015
+ a = x.xreplace({d: S.One}) + const*I
2016
+ if isinstance(rv, sin):
2017
+ return sinh(a)/I
2018
+ elif isinstance(rv, cos):
2019
+ return cosh(a)
2020
+ elif isinstance(rv, tan):
2021
+ return tanh(a)/I
2022
+ elif isinstance(rv, cot):
2023
+ return coth(a)*I
2024
+ elif isinstance(rv, sec):
2025
+ return sech(a)
2026
+ elif isinstance(rv, csc):
2027
+ return csch(a)*I
2028
+ else:
2029
+ raise NotImplementedError('unhandled %s' % rv.func)
2030
+
2031
+ return bottom_up(e, f)
2032
+
2033
+
2034
+ def hyper_as_trig(rv):
2035
+ """Return an expression containing hyperbolic functions in terms
2036
+ of trigonometric functions. Any trigonometric functions initially
2037
+ present are replaced with Dummy symbols and the function to undo
2038
+ the masking and the conversion back to hyperbolics is also returned. It
2039
+ should always be true that::
2040
+
2041
+ t, f = hyper_as_trig(expr)
2042
+ expr == f(t)
2043
+
2044
+ Examples
2045
+ ========
2046
+
2047
+ >>> from sympy.simplify.fu import hyper_as_trig, fu
2048
+ >>> from sympy.abc import x
2049
+ >>> from sympy import cosh, sinh
2050
+ >>> eq = sinh(x)**2 + cosh(x)**2
2051
+ >>> t, f = hyper_as_trig(eq)
2052
+ >>> f(fu(t))
2053
+ cosh(2*x)
2054
+
2055
+ References
2056
+ ==========
2057
+
2058
+ .. [1] https://en.wikipedia.org/wiki/Hyperbolic_function
2059
+ """
2060
+ from sympy.simplify.simplify import signsimp
2061
+ from sympy.simplify.radsimp import collect
2062
+
2063
+ # mask off trig functions
2064
+ trigs = rv.atoms(TrigonometricFunction)
2065
+ reps = [(t, Dummy()) for t in trigs]
2066
+ masked = rv.xreplace(dict(reps))
2067
+
2068
+ # get inversion substitutions in place
2069
+ reps = [(v, k) for k, v in reps]
2070
+
2071
+ d = Dummy()
2072
+
2073
+ return _osborne(masked, d), lambda x: collect(signsimp(
2074
+ _osbornei(x, d).xreplace(dict(reps))), S.ImaginaryUnit)
2075
+
2076
+
2077
+ def sincos_to_sum(expr):
2078
+ """Convert products and powers of sin and cos to sums.
2079
+
2080
+ Explanation
2081
+ ===========
2082
+
2083
+ Applied power reduction TRpower first, then expands products, and
2084
+ converts products to sums with TR8.
2085
+
2086
+ Examples
2087
+ ========
2088
+
2089
+ >>> from sympy.simplify.fu import sincos_to_sum
2090
+ >>> from sympy.abc import x
2091
+ >>> from sympy import cos, sin
2092
+ >>> sincos_to_sum(16*sin(x)**3*cos(2*x)**2)
2093
+ 7*sin(x) - 5*sin(3*x) + 3*sin(5*x) - sin(7*x)
2094
+ """
2095
+
2096
+ if not expr.has(cos, sin):
2097
+ return expr
2098
+ else:
2099
+ return TR8(expand_mul(TRpower(expr)))
llmeval-env/lib/python3.10/site-packages/sympy/simplify/gammasimp.py ADDED
@@ -0,0 +1,497 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core import Function, S, Mul, Pow, Add
2
+ from sympy.core.sorting import ordered, default_sort_key
3
+ from sympy.core.function import expand_func
4
+ from sympy.core.symbol import Dummy
5
+ from sympy.functions import gamma, sqrt, sin
6
+ from sympy.polys import factor, cancel
7
+ from sympy.utilities.iterables import sift, uniq
8
+
9
+
10
+ def gammasimp(expr):
11
+ r"""
12
+ Simplify expressions with gamma functions.
13
+
14
+ Explanation
15
+ ===========
16
+
17
+ This function takes as input an expression containing gamma
18
+ functions or functions that can be rewritten in terms of gamma
19
+ functions and tries to minimize the number of those functions and
20
+ reduce the size of their arguments.
21
+
22
+ The algorithm works by rewriting all gamma functions as expressions
23
+ involving rising factorials (Pochhammer symbols) and applies
24
+ recurrence relations and other transformations applicable to rising
25
+ factorials, to reduce their arguments, possibly letting the resulting
26
+ rising factorial to cancel. Rising factorials with the second argument
27
+ being an integer are expanded into polynomial forms and finally all
28
+ other rising factorial are rewritten in terms of gamma functions.
29
+
30
+ Then the following two steps are performed.
31
+
32
+ 1. Reduce the number of gammas by applying the reflection theorem
33
+ gamma(x)*gamma(1-x) == pi/sin(pi*x).
34
+ 2. Reduce the number of gammas by applying the multiplication theorem
35
+ gamma(x)*gamma(x+1/n)*...*gamma(x+(n-1)/n) == C*gamma(n*x).
36
+
37
+ It then reduces the number of prefactors by absorbing them into gammas
38
+ where possible and expands gammas with rational argument.
39
+
40
+ All transformation rules can be found (or were derived from) here:
41
+
42
+ .. [1] https://functions.wolfram.com/GammaBetaErf/Pochhammer/17/01/02/
43
+ .. [2] https://functions.wolfram.com/GammaBetaErf/Pochhammer/27/01/0005/
44
+
45
+ Examples
46
+ ========
47
+
48
+ >>> from sympy.simplify import gammasimp
49
+ >>> from sympy import gamma, Symbol
50
+ >>> from sympy.abc import x
51
+ >>> n = Symbol('n', integer = True)
52
+
53
+ >>> gammasimp(gamma(x)/gamma(x - 3))
54
+ (x - 3)*(x - 2)*(x - 1)
55
+ >>> gammasimp(gamma(n + 3))
56
+ gamma(n + 3)
57
+
58
+ """
59
+
60
+ expr = expr.rewrite(gamma)
61
+
62
+ # compute_ST will be looking for Functions and we don't want
63
+ # it looking for non-gamma functions: issue 22606
64
+ # so we mask free, non-gamma functions
65
+ f = expr.atoms(Function)
66
+ # take out gammas
67
+ gammas = {i for i in f if isinstance(i, gamma)}
68
+ if not gammas:
69
+ return expr # avoid side effects like factoring
70
+ f -= gammas
71
+ # keep only those without bound symbols
72
+ f = f & expr.as_dummy().atoms(Function)
73
+ if f:
74
+ dum, fun, simp = zip(*[
75
+ (Dummy(), fi, fi.func(*[
76
+ _gammasimp(a, as_comb=False) for a in fi.args]))
77
+ for fi in ordered(f)])
78
+ d = expr.xreplace(dict(zip(fun, dum)))
79
+ return _gammasimp(d, as_comb=False).xreplace(dict(zip(dum, simp)))
80
+
81
+ return _gammasimp(expr, as_comb=False)
82
+
83
+
84
+ def _gammasimp(expr, as_comb):
85
+ """
86
+ Helper function for gammasimp and combsimp.
87
+
88
+ Explanation
89
+ ===========
90
+
91
+ Simplifies expressions written in terms of gamma function. If
92
+ as_comb is True, it tries to preserve integer arguments. See
93
+ docstring of gammasimp for more information. This was part of
94
+ combsimp() in combsimp.py.
95
+ """
96
+ expr = expr.replace(gamma,
97
+ lambda n: _rf(1, (n - 1).expand()))
98
+
99
+ if as_comb:
100
+ expr = expr.replace(_rf,
101
+ lambda a, b: gamma(b + 1))
102
+ else:
103
+ expr = expr.replace(_rf,
104
+ lambda a, b: gamma(a + b)/gamma(a))
105
+
106
+ def rule_gamma(expr, level=0):
107
+ """ Simplify products of gamma functions further. """
108
+
109
+ if expr.is_Atom:
110
+ return expr
111
+
112
+ def gamma_rat(x):
113
+ # helper to simplify ratios of gammas
114
+ was = x.count(gamma)
115
+ xx = x.replace(gamma, lambda n: _rf(1, (n - 1).expand()
116
+ ).replace(_rf, lambda a, b: gamma(a + b)/gamma(a)))
117
+ if xx.count(gamma) < was:
118
+ x = xx
119
+ return x
120
+
121
+ def gamma_factor(x):
122
+ # return True if there is a gamma factor in shallow args
123
+ if isinstance(x, gamma):
124
+ return True
125
+ if x.is_Add or x.is_Mul:
126
+ return any(gamma_factor(xi) for xi in x.args)
127
+ if x.is_Pow and (x.exp.is_integer or x.base.is_positive):
128
+ return gamma_factor(x.base)
129
+ return False
130
+
131
+ # recursion step
132
+ if level == 0:
133
+ expr = expr.func(*[rule_gamma(x, level + 1) for x in expr.args])
134
+ level += 1
135
+
136
+ if not expr.is_Mul:
137
+ return expr
138
+
139
+ # non-commutative step
140
+ if level == 1:
141
+ args, nc = expr.args_cnc()
142
+ if not args:
143
+ return expr
144
+ if nc:
145
+ return rule_gamma(Mul._from_args(args), level + 1)*Mul._from_args(nc)
146
+ level += 1
147
+
148
+ # pure gamma handling, not factor absorption
149
+ if level == 2:
150
+ T, F = sift(expr.args, gamma_factor, binary=True)
151
+ gamma_ind = Mul(*F)
152
+ d = Mul(*T)
153
+
154
+ nd, dd = d.as_numer_denom()
155
+ for ipass in range(2):
156
+ args = list(ordered(Mul.make_args(nd)))
157
+ for i, ni in enumerate(args):
158
+ if ni.is_Add:
159
+ ni, dd = Add(*[
160
+ rule_gamma(gamma_rat(a/dd), level + 1) for a in ni.args]
161
+ ).as_numer_denom()
162
+ args[i] = ni
163
+ if not dd.has(gamma):
164
+ break
165
+ nd = Mul(*args)
166
+ if ipass == 0 and not gamma_factor(nd):
167
+ break
168
+ nd, dd = dd, nd # now process in reversed order
169
+ expr = gamma_ind*nd/dd
170
+ if not (expr.is_Mul and (gamma_factor(dd) or gamma_factor(nd))):
171
+ return expr
172
+ level += 1
173
+
174
+ # iteration until constant
175
+ if level == 3:
176
+ while True:
177
+ was = expr
178
+ expr = rule_gamma(expr, 4)
179
+ if expr == was:
180
+ return expr
181
+
182
+ numer_gammas = []
183
+ denom_gammas = []
184
+ numer_others = []
185
+ denom_others = []
186
+ def explicate(p):
187
+ if p is S.One:
188
+ return None, []
189
+ b, e = p.as_base_exp()
190
+ if e.is_Integer:
191
+ if isinstance(b, gamma):
192
+ return True, [b.args[0]]*e
193
+ else:
194
+ return False, [b]*e
195
+ else:
196
+ return False, [p]
197
+
198
+ newargs = list(ordered(expr.args))
199
+ while newargs:
200
+ n, d = newargs.pop().as_numer_denom()
201
+ isg, l = explicate(n)
202
+ if isg:
203
+ numer_gammas.extend(l)
204
+ elif isg is False:
205
+ numer_others.extend(l)
206
+ isg, l = explicate(d)
207
+ if isg:
208
+ denom_gammas.extend(l)
209
+ elif isg is False:
210
+ denom_others.extend(l)
211
+
212
+ # =========== level 2 work: pure gamma manipulation =========
213
+
214
+ if not as_comb:
215
+ # Try to reduce the number of gamma factors by applying the
216
+ # reflection formula gamma(x)*gamma(1-x) = pi/sin(pi*x)
217
+ for gammas, numer, denom in [(
218
+ numer_gammas, numer_others, denom_others),
219
+ (denom_gammas, denom_others, numer_others)]:
220
+ new = []
221
+ while gammas:
222
+ g1 = gammas.pop()
223
+ if g1.is_integer:
224
+ new.append(g1)
225
+ continue
226
+ for i, g2 in enumerate(gammas):
227
+ n = g1 + g2 - 1
228
+ if not n.is_Integer:
229
+ continue
230
+ numer.append(S.Pi)
231
+ denom.append(sin(S.Pi*g1))
232
+ gammas.pop(i)
233
+ if n > 0:
234
+ for k in range(n):
235
+ numer.append(1 - g1 + k)
236
+ elif n < 0:
237
+ for k in range(-n):
238
+ denom.append(-g1 - k)
239
+ break
240
+ else:
241
+ new.append(g1)
242
+ # /!\ updating IN PLACE
243
+ gammas[:] = new
244
+
245
+ # Try to reduce the number of gammas by using the duplication
246
+ # theorem to cancel an upper and lower: gamma(2*s)/gamma(s) =
247
+ # 2**(2*s + 1)/(4*sqrt(pi))*gamma(s + 1/2). Although this could
248
+ # be done with higher argument ratios like gamma(3*x)/gamma(x),
249
+ # this would not reduce the number of gammas as in this case.
250
+ for ng, dg, no, do in [(numer_gammas, denom_gammas, numer_others,
251
+ denom_others),
252
+ (denom_gammas, numer_gammas, denom_others,
253
+ numer_others)]:
254
+
255
+ while True:
256
+ for x in ng:
257
+ for y in dg:
258
+ n = x - 2*y
259
+ if n.is_Integer:
260
+ break
261
+ else:
262
+ continue
263
+ break
264
+ else:
265
+ break
266
+ ng.remove(x)
267
+ dg.remove(y)
268
+ if n > 0:
269
+ for k in range(n):
270
+ no.append(2*y + k)
271
+ elif n < 0:
272
+ for k in range(-n):
273
+ do.append(2*y - 1 - k)
274
+ ng.append(y + S.Half)
275
+ no.append(2**(2*y - 1))
276
+ do.append(sqrt(S.Pi))
277
+
278
+ # Try to reduce the number of gamma factors by applying the
279
+ # multiplication theorem (used when n gammas with args differing
280
+ # by 1/n mod 1 are encountered).
281
+ #
282
+ # run of 2 with args differing by 1/2
283
+ #
284
+ # >>> gammasimp(gamma(x)*gamma(x+S.Half))
285
+ # 2*sqrt(2)*2**(-2*x - 1/2)*sqrt(pi)*gamma(2*x)
286
+ #
287
+ # run of 3 args differing by 1/3 (mod 1)
288
+ #
289
+ # >>> gammasimp(gamma(x)*gamma(x+S(1)/3)*gamma(x+S(2)/3))
290
+ # 6*3**(-3*x - 1/2)*pi*gamma(3*x)
291
+ # >>> gammasimp(gamma(x)*gamma(x+S(1)/3)*gamma(x+S(5)/3))
292
+ # 2*3**(-3*x - 1/2)*pi*(3*x + 2)*gamma(3*x)
293
+ #
294
+ def _run(coeffs):
295
+ # find runs in coeffs such that the difference in terms (mod 1)
296
+ # of t1, t2, ..., tn is 1/n
297
+ u = list(uniq(coeffs))
298
+ for i in range(len(u)):
299
+ dj = ([((u[j] - u[i]) % 1, j) for j in range(i + 1, len(u))])
300
+ for one, j in dj:
301
+ if one.p == 1 and one.q != 1:
302
+ n = one.q
303
+ got = [i]
304
+ get = list(range(1, n))
305
+ for d, j in dj:
306
+ m = n*d
307
+ if m.is_Integer and m in get:
308
+ get.remove(m)
309
+ got.append(j)
310
+ if not get:
311
+ break
312
+ else:
313
+ continue
314
+ for i, j in enumerate(got):
315
+ c = u[j]
316
+ coeffs.remove(c)
317
+ got[i] = c
318
+ return one.q, got[0], got[1:]
319
+
320
+ def _mult_thm(gammas, numer, denom):
321
+ # pull off and analyze the leading coefficient from each gamma arg
322
+ # looking for runs in those Rationals
323
+
324
+ # expr -> coeff + resid -> rats[resid] = coeff
325
+ rats = {}
326
+ for g in gammas:
327
+ c, resid = g.as_coeff_Add()
328
+ rats.setdefault(resid, []).append(c)
329
+
330
+ # look for runs in Rationals for each resid
331
+ keys = sorted(rats, key=default_sort_key)
332
+ for resid in keys:
333
+ coeffs = sorted(rats[resid])
334
+ new = []
335
+ while True:
336
+ run = _run(coeffs)
337
+ if run is None:
338
+ break
339
+
340
+ # process the sequence that was found:
341
+ # 1) convert all the gamma functions to have the right
342
+ # argument (could be off by an integer)
343
+ # 2) append the factors corresponding to the theorem
344
+ # 3) append the new gamma function
345
+
346
+ n, ui, other = run
347
+
348
+ # (1)
349
+ for u in other:
350
+ con = resid + u - 1
351
+ for k in range(int(u - ui)):
352
+ numer.append(con - k)
353
+
354
+ con = n*(resid + ui) # for (2) and (3)
355
+
356
+ # (2)
357
+ numer.append((2*S.Pi)**(S(n - 1)/2)*
358
+ n**(S.Half - con))
359
+ # (3)
360
+ new.append(con)
361
+
362
+ # restore resid to coeffs
363
+ rats[resid] = [resid + c for c in coeffs] + new
364
+
365
+ # rebuild the gamma arguments
366
+ g = []
367
+ for resid in keys:
368
+ g += rats[resid]
369
+ # /!\ updating IN PLACE
370
+ gammas[:] = g
371
+
372
+ for l, numer, denom in [(numer_gammas, numer_others, denom_others),
373
+ (denom_gammas, denom_others, numer_others)]:
374
+ _mult_thm(l, numer, denom)
375
+
376
+ # =========== level >= 2 work: factor absorption =========
377
+
378
+ if level >= 2:
379
+ # Try to absorb factors into the gammas: x*gamma(x) -> gamma(x + 1)
380
+ # and gamma(x)/(x - 1) -> gamma(x - 1)
381
+ # This code (in particular repeated calls to find_fuzzy) can be very
382
+ # slow.
383
+ def find_fuzzy(l, x):
384
+ if not l:
385
+ return
386
+ S1, T1 = compute_ST(x)
387
+ for y in l:
388
+ S2, T2 = inv[y]
389
+ if T1 != T2 or (not S1.intersection(S2) and
390
+ (S1 != set() or S2 != set())):
391
+ continue
392
+ # XXX we want some simplification (e.g. cancel or
393
+ # simplify) but no matter what it's slow.
394
+ a = len(cancel(x/y).free_symbols)
395
+ b = len(x.free_symbols)
396
+ c = len(y.free_symbols)
397
+ # TODO is there a better heuristic?
398
+ if a == 0 and (b > 0 or c > 0):
399
+ return y
400
+
401
+ # We thus try to avoid expensive calls by building the following
402
+ # "invariants": For every factor or gamma function argument
403
+ # - the set of free symbols S
404
+ # - the set of functional components T
405
+ # We will only try to absorb if T1==T2 and (S1 intersect S2 != emptyset
406
+ # or S1 == S2 == emptyset)
407
+ inv = {}
408
+
409
+ def compute_ST(expr):
410
+ if expr in inv:
411
+ return inv[expr]
412
+ return (expr.free_symbols, expr.atoms(Function).union(
413
+ {e.exp for e in expr.atoms(Pow)}))
414
+
415
+ def update_ST(expr):
416
+ inv[expr] = compute_ST(expr)
417
+ for expr in numer_gammas + denom_gammas + numer_others + denom_others:
418
+ update_ST(expr)
419
+
420
+ for gammas, numer, denom in [(
421
+ numer_gammas, numer_others, denom_others),
422
+ (denom_gammas, denom_others, numer_others)]:
423
+ new = []
424
+ while gammas:
425
+ g = gammas.pop()
426
+ cont = True
427
+ while cont:
428
+ cont = False
429
+ y = find_fuzzy(numer, g)
430
+ if y is not None:
431
+ numer.remove(y)
432
+ if y != g:
433
+ numer.append(y/g)
434
+ update_ST(y/g)
435
+ g += 1
436
+ cont = True
437
+ y = find_fuzzy(denom, g - 1)
438
+ if y is not None:
439
+ denom.remove(y)
440
+ if y != g - 1:
441
+ numer.append((g - 1)/y)
442
+ update_ST((g - 1)/y)
443
+ g -= 1
444
+ cont = True
445
+ new.append(g)
446
+ # /!\ updating IN PLACE
447
+ gammas[:] = new
448
+
449
+ # =========== rebuild expr ==================================
450
+
451
+ return Mul(*[gamma(g) for g in numer_gammas]) \
452
+ / Mul(*[gamma(g) for g in denom_gammas]) \
453
+ * Mul(*numer_others) / Mul(*denom_others)
454
+
455
+ was = factor(expr)
456
+ # (for some reason we cannot use Basic.replace in this case)
457
+ expr = rule_gamma(was)
458
+ if expr != was:
459
+ expr = factor(expr)
460
+
461
+ expr = expr.replace(gamma,
462
+ lambda n: expand_func(gamma(n)) if n.is_Rational else gamma(n))
463
+
464
+ return expr
465
+
466
+
467
+ class _rf(Function):
468
+ @classmethod
469
+ def eval(cls, a, b):
470
+ if b.is_Integer:
471
+ if not b:
472
+ return S.One
473
+
474
+ n = int(b)
475
+
476
+ if n > 0:
477
+ return Mul(*[a + i for i in range(n)])
478
+ elif n < 0:
479
+ return 1/Mul(*[a - i for i in range(1, -n + 1)])
480
+ else:
481
+ if b.is_Add:
482
+ c, _b = b.as_coeff_Add()
483
+
484
+ if c.is_Integer:
485
+ if c > 0:
486
+ return _rf(a, _b)*_rf(a + _b, c)
487
+ elif c < 0:
488
+ return _rf(a, _b)/_rf(a + _b + c, -c)
489
+
490
+ if a.is_Add:
491
+ c, _a = a.as_coeff_Add()
492
+
493
+ if c.is_Integer:
494
+ if c > 0:
495
+ return _rf(_a, b)*_rf(_a + b, c)/_rf(_a, c)
496
+ elif c < 0:
497
+ return _rf(_a, b)*_rf(_a + c, -c)/_rf(_a + b + c, -c)
llmeval-env/lib/python3.10/site-packages/sympy/simplify/hyperexpand.py ADDED
@@ -0,0 +1,2494 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Expand Hypergeometric (and Meijer G) functions into named
3
+ special functions.
4
+
5
+ The algorithm for doing this uses a collection of lookup tables of
6
+ hypergeometric functions, and various of their properties, to expand
7
+ many hypergeometric functions in terms of special functions.
8
+
9
+ It is based on the following paper:
10
+ Kelly B. Roach. Meijer G Function Representations.
11
+ In: Proceedings of the 1997 International Symposium on Symbolic and
12
+ Algebraic Computation, pages 205-211, New York, 1997. ACM.
13
+
14
+ It is described in great(er) detail in the Sphinx documentation.
15
+ """
16
+ # SUMMARY OF EXTENSIONS FOR MEIJER G FUNCTIONS
17
+ #
18
+ # o z**rho G(ap, bq; z) = G(ap + rho, bq + rho; z)
19
+ #
20
+ # o denote z*d/dz by D
21
+ #
22
+ # o It is helpful to keep in mind that ap and bq play essentially symmetric
23
+ # roles: G(1/z) has slightly altered parameters, with ap and bq interchanged.
24
+ #
25
+ # o There are four shift operators:
26
+ # A_J = b_J - D, J = 1, ..., n
27
+ # B_J = 1 - a_j + D, J = 1, ..., m
28
+ # C_J = -b_J + D, J = m+1, ..., q
29
+ # D_J = a_J - 1 - D, J = n+1, ..., p
30
+ #
31
+ # A_J, C_J increment b_J
32
+ # B_J, D_J decrement a_J
33
+ #
34
+ # o The corresponding four inverse-shift operators are defined if there
35
+ # is no cancellation. Thus e.g. an index a_J (upper or lower) can be
36
+ # incremented if a_J != b_i for i = 1, ..., q.
37
+ #
38
+ # o Order reduction: if b_j - a_i is a non-negative integer, where
39
+ # j <= m and i > n, the corresponding quotient of gamma functions reduces
40
+ # to a polynomial. Hence the G function can be expressed using a G-function
41
+ # of lower order.
42
+ # Similarly if j > m and i <= n.
43
+ #
44
+ # Secondly, there are paired index theorems [Adamchik, The evaluation of
45
+ # integrals of Bessel functions via G-function identities]. Suppose there
46
+ # are three parameters a, b, c, where a is an a_i, i <= n, b is a b_j,
47
+ # j <= m and c is a denominator parameter (i.e. a_i, i > n or b_j, j > m).
48
+ # Suppose further all three differ by integers.
49
+ # Then the order can be reduced.
50
+ # TODO work this out in detail.
51
+ #
52
+ # o An index quadruple is called suitable if its order cannot be reduced.
53
+ # If there exists a sequence of shift operators transforming one index
54
+ # quadruple into another, we say one is reachable from the other.
55
+ #
56
+ # o Deciding if one index quadruple is reachable from another is tricky. For
57
+ # this reason, we use hand-built routines to match and instantiate formulas.
58
+ #
59
+ from collections import defaultdict
60
+ from itertools import product
61
+ from functools import reduce
62
+ from math import prod
63
+
64
+ from sympy import SYMPY_DEBUG
65
+ from sympy.core import (S, Dummy, symbols, sympify, Tuple, expand, I, pi, Mul,
66
+ EulerGamma, oo, zoo, expand_func, Add, nan, Expr, Rational)
67
+ from sympy.core.mod import Mod
68
+ from sympy.core.sorting import default_sort_key
69
+ from sympy.functions import (exp, sqrt, root, log, lowergamma, cos,
70
+ besseli, gamma, uppergamma, expint, erf, sin, besselj, Ei, Ci, Si, Shi,
71
+ sinh, cosh, Chi, fresnels, fresnelc, polar_lift, exp_polar, floor, ceiling,
72
+ rf, factorial, lerchphi, Piecewise, re, elliptic_k, elliptic_e)
73
+ from sympy.functions.elementary.complexes import polarify, unpolarify
74
+ from sympy.functions.special.hyper import (hyper, HyperRep_atanh,
75
+ HyperRep_power1, HyperRep_power2, HyperRep_log1, HyperRep_asin1,
76
+ HyperRep_asin2, HyperRep_sqrts1, HyperRep_sqrts2, HyperRep_log2,
77
+ HyperRep_cosasin, HyperRep_sinasin, meijerg)
78
+ from sympy.matrices import Matrix, eye, zeros
79
+ from sympy.polys import apart, poly, Poly
80
+ from sympy.series import residue
81
+ from sympy.simplify.powsimp import powdenest
82
+ from sympy.utilities.iterables import sift
83
+
84
+ # function to define "buckets"
85
+ def _mod1(x):
86
+ # TODO see if this can work as Mod(x, 1); this will require
87
+ # different handling of the "buckets" since these need to
88
+ # be sorted and that fails when there is a mixture of
89
+ # integers and expressions with parameters. With the current
90
+ # Mod behavior, Mod(k, 1) == Mod(1, 1) == 0 if k is an integer.
91
+ # Although the sorting can be done with Basic.compare, this may
92
+ # still require different handling of the sorted buckets.
93
+ if x.is_Number:
94
+ return Mod(x, 1)
95
+ c, x = x.as_coeff_Add()
96
+ return Mod(c, 1) + x
97
+
98
+
99
+ # leave add formulae at the top for easy reference
100
+ def add_formulae(formulae):
101
+ """ Create our knowledge base. """
102
+ a, b, c, z = symbols('a b c, z', cls=Dummy)
103
+
104
+ def add(ap, bq, res):
105
+ func = Hyper_Function(ap, bq)
106
+ formulae.append(Formula(func, z, res, (a, b, c)))
107
+
108
+ def addb(ap, bq, B, C, M):
109
+ func = Hyper_Function(ap, bq)
110
+ formulae.append(Formula(func, z, None, (a, b, c), B, C, M))
111
+
112
+ # Luke, Y. L. (1969), The Special Functions and Their Approximations,
113
+ # Volume 1, section 6.2
114
+
115
+ # 0F0
116
+ add((), (), exp(z))
117
+
118
+ # 1F0
119
+ add((a, ), (), HyperRep_power1(-a, z))
120
+
121
+ # 2F1
122
+ addb((a, a - S.Half), (2*a, ),
123
+ Matrix([HyperRep_power2(a, z),
124
+ HyperRep_power2(a + S.Half, z)/2]),
125
+ Matrix([[1, 0]]),
126
+ Matrix([[(a - S.Half)*z/(1 - z), (S.Half - a)*z/(1 - z)],
127
+ [a/(1 - z), a*(z - 2)/(1 - z)]]))
128
+ addb((1, 1), (2, ),
129
+ Matrix([HyperRep_log1(z), 1]), Matrix([[-1/z, 0]]),
130
+ Matrix([[0, z/(z - 1)], [0, 0]]))
131
+ addb((S.Half, 1), (S('3/2'), ),
132
+ Matrix([HyperRep_atanh(z), 1]),
133
+ Matrix([[1, 0]]),
134
+ Matrix([[Rational(-1, 2), 1/(1 - z)/2], [0, 0]]))
135
+ addb((S.Half, S.Half), (S('3/2'), ),
136
+ Matrix([HyperRep_asin1(z), HyperRep_power1(Rational(-1, 2), z)]),
137
+ Matrix([[1, 0]]),
138
+ Matrix([[Rational(-1, 2), S.Half], [0, z/(1 - z)/2]]))
139
+ addb((a, S.Half + a), (S.Half, ),
140
+ Matrix([HyperRep_sqrts1(-a, z), -HyperRep_sqrts2(-a - S.Half, z)]),
141
+ Matrix([[1, 0]]),
142
+ Matrix([[0, -a],
143
+ [z*(-2*a - 1)/2/(1 - z), S.Half - z*(-2*a - 1)/(1 - z)]]))
144
+
145
+ # A. P. Prudnikov, Yu. A. Brychkov and O. I. Marichev (1990).
146
+ # Integrals and Series: More Special Functions, Vol. 3,.
147
+ # Gordon and Breach Science Publisher
148
+ addb([a, -a], [S.Half],
149
+ Matrix([HyperRep_cosasin(a, z), HyperRep_sinasin(a, z)]),
150
+ Matrix([[1, 0]]),
151
+ Matrix([[0, -a], [a*z/(1 - z), 1/(1 - z)/2]]))
152
+ addb([1, 1], [3*S.Half],
153
+ Matrix([HyperRep_asin2(z), 1]), Matrix([[1, 0]]),
154
+ Matrix([[(z - S.Half)/(1 - z), 1/(1 - z)/2], [0, 0]]))
155
+
156
+ # Complete elliptic integrals K(z) and E(z), both a 2F1 function
157
+ addb([S.Half, S.Half], [S.One],
158
+ Matrix([elliptic_k(z), elliptic_e(z)]),
159
+ Matrix([[2/pi, 0]]),
160
+ Matrix([[Rational(-1, 2), -1/(2*z-2)],
161
+ [Rational(-1, 2), S.Half]]))
162
+ addb([Rational(-1, 2), S.Half], [S.One],
163
+ Matrix([elliptic_k(z), elliptic_e(z)]),
164
+ Matrix([[0, 2/pi]]),
165
+ Matrix([[Rational(-1, 2), -1/(2*z-2)],
166
+ [Rational(-1, 2), S.Half]]))
167
+
168
+ # 3F2
169
+ addb([Rational(-1, 2), 1, 1], [S.Half, 2],
170
+ Matrix([z*HyperRep_atanh(z), HyperRep_log1(z), 1]),
171
+ Matrix([[Rational(-2, 3), -S.One/(3*z), Rational(2, 3)]]),
172
+ Matrix([[S.Half, 0, z/(1 - z)/2],
173
+ [0, 0, z/(z - 1)],
174
+ [0, 0, 0]]))
175
+ # actually the formula for 3/2 is much nicer ...
176
+ addb([Rational(-1, 2), 1, 1], [2, 2],
177
+ Matrix([HyperRep_power1(S.Half, z), HyperRep_log2(z), 1]),
178
+ Matrix([[Rational(4, 9) - 16/(9*z), 4/(3*z), 16/(9*z)]]),
179
+ Matrix([[z/2/(z - 1), 0, 0], [1/(2*(z - 1)), 0, S.Half], [0, 0, 0]]))
180
+
181
+ # 1F1
182
+ addb([1], [b], Matrix([z**(1 - b) * exp(z) * lowergamma(b - 1, z), 1]),
183
+ Matrix([[b - 1, 0]]), Matrix([[1 - b + z, 1], [0, 0]]))
184
+ addb([a], [2*a],
185
+ Matrix([z**(S.Half - a)*exp(z/2)*besseli(a - S.Half, z/2)
186
+ * gamma(a + S.Half)/4**(S.Half - a),
187
+ z**(S.Half - a)*exp(z/2)*besseli(a + S.Half, z/2)
188
+ * gamma(a + S.Half)/4**(S.Half - a)]),
189
+ Matrix([[1, 0]]),
190
+ Matrix([[z/2, z/2], [z/2, (z/2 - 2*a)]]))
191
+ mz = polar_lift(-1)*z
192
+ addb([a], [a + 1],
193
+ Matrix([mz**(-a)*a*lowergamma(a, mz), a*exp(z)]),
194
+ Matrix([[1, 0]]),
195
+ Matrix([[-a, 1], [0, z]]))
196
+ # This one is redundant.
197
+ add([Rational(-1, 2)], [S.Half], exp(z) - sqrt(pi*z)*(-I)*erf(I*sqrt(z)))
198
+
199
+ # Added to get nice results for Laplace transform of Fresnel functions
200
+ # https://functions.wolfram.com/07.22.03.6437.01
201
+ # Basic rule
202
+ #add([1], [Rational(3, 4), Rational(5, 4)],
203
+ # sqrt(pi) * (cos(2*sqrt(polar_lift(-1)*z))*fresnelc(2*root(polar_lift(-1)*z,4)/sqrt(pi)) +
204
+ # sin(2*sqrt(polar_lift(-1)*z))*fresnels(2*root(polar_lift(-1)*z,4)/sqrt(pi)))
205
+ # / (2*root(polar_lift(-1)*z,4)))
206
+ # Manually tuned rule
207
+ addb([1], [Rational(3, 4), Rational(5, 4)],
208
+ Matrix([ sqrt(pi)*(I*sinh(2*sqrt(z))*fresnels(2*root(z, 4)*exp(I*pi/4)/sqrt(pi))
209
+ + cosh(2*sqrt(z))*fresnelc(2*root(z, 4)*exp(I*pi/4)/sqrt(pi)))
210
+ * exp(-I*pi/4)/(2*root(z, 4)),
211
+ sqrt(pi)*root(z, 4)*(sinh(2*sqrt(z))*fresnelc(2*root(z, 4)*exp(I*pi/4)/sqrt(pi))
212
+ + I*cosh(2*sqrt(z))*fresnels(2*root(z, 4)*exp(I*pi/4)/sqrt(pi)))
213
+ *exp(-I*pi/4)/2,
214
+ 1 ]),
215
+ Matrix([[1, 0, 0]]),
216
+ Matrix([[Rational(-1, 4), 1, Rational(1, 4)],
217
+ [ z, Rational(1, 4), 0],
218
+ [ 0, 0, 0]]))
219
+
220
+ # 2F2
221
+ addb([S.Half, a], [Rational(3, 2), a + 1],
222
+ Matrix([a/(2*a - 1)*(-I)*sqrt(pi/z)*erf(I*sqrt(z)),
223
+ a/(2*a - 1)*(polar_lift(-1)*z)**(-a)*
224
+ lowergamma(a, polar_lift(-1)*z),
225
+ a/(2*a - 1)*exp(z)]),
226
+ Matrix([[1, -1, 0]]),
227
+ Matrix([[Rational(-1, 2), 0, 1], [0, -a, 1], [0, 0, z]]))
228
+ # We make a "basis" of four functions instead of three, and give EulerGamma
229
+ # an extra slot (it could just be a coefficient to 1). The advantage is
230
+ # that this way Polys will not see multivariate polynomials (it treats
231
+ # EulerGamma as an indeterminate), which is *way* faster.
232
+ addb([1, 1], [2, 2],
233
+ Matrix([Ei(z) - log(z), exp(z), 1, EulerGamma]),
234
+ Matrix([[1/z, 0, 0, -1/z]]),
235
+ Matrix([[0, 1, -1, 0], [0, z, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]))
236
+
237
+ # 0F1
238
+ add((), (S.Half, ), cosh(2*sqrt(z)))
239
+ addb([], [b],
240
+ Matrix([gamma(b)*z**((1 - b)/2)*besseli(b - 1, 2*sqrt(z)),
241
+ gamma(b)*z**(1 - b/2)*besseli(b, 2*sqrt(z))]),
242
+ Matrix([[1, 0]]), Matrix([[0, 1], [z, (1 - b)]]))
243
+
244
+ # 0F3
245
+ x = 4*z**Rational(1, 4)
246
+
247
+ def fp(a, z):
248
+ return besseli(a, x) + besselj(a, x)
249
+
250
+ def fm(a, z):
251
+ return besseli(a, x) - besselj(a, x)
252
+
253
+ # TODO branching
254
+ addb([], [S.Half, a, a + S.Half],
255
+ Matrix([fp(2*a - 1, z), fm(2*a, z)*z**Rational(1, 4),
256
+ fm(2*a - 1, z)*sqrt(z), fp(2*a, z)*z**Rational(3, 4)])
257
+ * 2**(-2*a)*gamma(2*a)*z**((1 - 2*a)/4),
258
+ Matrix([[1, 0, 0, 0]]),
259
+ Matrix([[0, 1, 0, 0],
260
+ [0, S.Half - a, 1, 0],
261
+ [0, 0, S.Half, 1],
262
+ [z, 0, 0, 1 - a]]))
263
+ x = 2*(4*z)**Rational(1, 4)*exp_polar(I*pi/4)
264
+ addb([], [a, a + S.Half, 2*a],
265
+ (2*sqrt(polar_lift(-1)*z))**(1 - 2*a)*gamma(2*a)**2 *
266
+ Matrix([besselj(2*a - 1, x)*besseli(2*a - 1, x),
267
+ x*(besseli(2*a, x)*besselj(2*a - 1, x)
268
+ - besseli(2*a - 1, x)*besselj(2*a, x)),
269
+ x**2*besseli(2*a, x)*besselj(2*a, x),
270
+ x**3*(besseli(2*a, x)*besselj(2*a - 1, x)
271
+ + besseli(2*a - 1, x)*besselj(2*a, x))]),
272
+ Matrix([[1, 0, 0, 0]]),
273
+ Matrix([[0, Rational(1, 4), 0, 0],
274
+ [0, (1 - 2*a)/2, Rational(-1, 2), 0],
275
+ [0, 0, 1 - 2*a, Rational(1, 4)],
276
+ [-32*z, 0, 0, 1 - a]]))
277
+
278
+ # 1F2
279
+ addb([a], [a - S.Half, 2*a],
280
+ Matrix([z**(S.Half - a)*besseli(a - S.Half, sqrt(z))**2,
281
+ z**(1 - a)*besseli(a - S.Half, sqrt(z))
282
+ *besseli(a - Rational(3, 2), sqrt(z)),
283
+ z**(Rational(3, 2) - a)*besseli(a - Rational(3, 2), sqrt(z))**2]),
284
+ Matrix([[-gamma(a + S.Half)**2/4**(S.Half - a),
285
+ 2*gamma(a - S.Half)*gamma(a + S.Half)/4**(1 - a),
286
+ 0]]),
287
+ Matrix([[1 - 2*a, 1, 0], [z/2, S.Half - a, S.Half], [0, z, 0]]))
288
+ addb([S.Half], [b, 2 - b],
289
+ pi*(1 - b)/sin(pi*b)*
290
+ Matrix([besseli(1 - b, sqrt(z))*besseli(b - 1, sqrt(z)),
291
+ sqrt(z)*(besseli(-b, sqrt(z))*besseli(b - 1, sqrt(z))
292
+ + besseli(1 - b, sqrt(z))*besseli(b, sqrt(z))),
293
+ besseli(-b, sqrt(z))*besseli(b, sqrt(z))]),
294
+ Matrix([[1, 0, 0]]),
295
+ Matrix([[b - 1, S.Half, 0],
296
+ [z, 0, z],
297
+ [0, S.Half, -b]]))
298
+ addb([S.Half], [Rational(3, 2), Rational(3, 2)],
299
+ Matrix([Shi(2*sqrt(z))/2/sqrt(z), sinh(2*sqrt(z))/2/sqrt(z),
300
+ cosh(2*sqrt(z))]),
301
+ Matrix([[1, 0, 0]]),
302
+ Matrix([[Rational(-1, 2), S.Half, 0], [0, Rational(-1, 2), S.Half], [0, 2*z, 0]]))
303
+
304
+ # FresnelS
305
+ # Basic rule
306
+ #add([Rational(3, 4)], [Rational(3, 2),Rational(7, 4)], 6*fresnels( exp(pi*I/4)*root(z,4)*2/sqrt(pi) ) / ( pi * (exp(pi*I/4)*root(z,4)*2/sqrt(pi))**3 ) )
307
+ # Manually tuned rule
308
+ addb([Rational(3, 4)], [Rational(3, 2), Rational(7, 4)],
309
+ Matrix(
310
+ [ fresnels(
311
+ exp(
312
+ pi*I/4)*root(
313
+ z, 4)*2/sqrt(
314
+ pi) ) / (
315
+ pi * (exp(pi*I/4)*root(z, 4)*2/sqrt(pi))**3 ),
316
+ sinh(2*sqrt(z))/sqrt(z),
317
+ cosh(2*sqrt(z)) ]),
318
+ Matrix([[6, 0, 0]]),
319
+ Matrix([[Rational(-3, 4), Rational(1, 16), 0],
320
+ [ 0, Rational(-1, 2), 1],
321
+ [ 0, z, 0]]))
322
+
323
+ # FresnelC
324
+ # Basic rule
325
+ #add([Rational(1, 4)], [S.Half,Rational(5, 4)], fresnelc( exp(pi*I/4)*root(z,4)*2/sqrt(pi) ) / ( exp(pi*I/4)*root(z,4)*2/sqrt(pi) ) )
326
+ # Manually tuned rule
327
+ addb([Rational(1, 4)], [S.Half, Rational(5, 4)],
328
+ Matrix(
329
+ [ sqrt(
330
+ pi)*exp(
331
+ -I*pi/4)*fresnelc(
332
+ 2*root(z, 4)*exp(I*pi/4)/sqrt(pi))/(2*root(z, 4)),
333
+ cosh(2*sqrt(z)),
334
+ sinh(2*sqrt(z))*sqrt(z) ]),
335
+ Matrix([[1, 0, 0]]),
336
+ Matrix([[Rational(-1, 4), Rational(1, 4), 0 ],
337
+ [ 0, 0, 1 ],
338
+ [ 0, z, S.Half]]))
339
+
340
+ # 2F3
341
+ # XXX with this five-parameter formula is pretty slow with the current
342
+ # Formula.find_instantiations (creates 2!*3!*3**(2+3) ~ 3000
343
+ # instantiations ... But it's not too bad.
344
+ addb([a, a + S.Half], [2*a, b, 2*a - b + 1],
345
+ gamma(b)*gamma(2*a - b + 1) * (sqrt(z)/2)**(1 - 2*a) *
346
+ Matrix([besseli(b - 1, sqrt(z))*besseli(2*a - b, sqrt(z)),
347
+ sqrt(z)*besseli(b, sqrt(z))*besseli(2*a - b, sqrt(z)),
348
+ sqrt(z)*besseli(b - 1, sqrt(z))*besseli(2*a - b + 1, sqrt(z)),
349
+ besseli(b, sqrt(z))*besseli(2*a - b + 1, sqrt(z))]),
350
+ Matrix([[1, 0, 0, 0]]),
351
+ Matrix([[0, S.Half, S.Half, 0],
352
+ [z/2, 1 - b, 0, z/2],
353
+ [z/2, 0, b - 2*a, z/2],
354
+ [0, S.Half, S.Half, -2*a]]))
355
+ # (C/f above comment about eulergamma in the basis).
356
+ addb([1, 1], [2, 2, Rational(3, 2)],
357
+ Matrix([Chi(2*sqrt(z)) - log(2*sqrt(z)),
358
+ cosh(2*sqrt(z)), sqrt(z)*sinh(2*sqrt(z)), 1, EulerGamma]),
359
+ Matrix([[1/z, 0, 0, 0, -1/z]]),
360
+ Matrix([[0, S.Half, 0, Rational(-1, 2), 0],
361
+ [0, 0, 1, 0, 0],
362
+ [0, z, S.Half, 0, 0],
363
+ [0, 0, 0, 0, 0],
364
+ [0, 0, 0, 0, 0]]))
365
+
366
+ # 3F3
367
+ # This is rule: https://functions.wolfram.com/07.31.03.0134.01
368
+ # Initial reason to add it was a nice solution for
369
+ # integrate(erf(a*z)/z**2, z) and same for erfc and erfi.
370
+ # Basic rule
371
+ # add([1, 1, a], [2, 2, a+1], (a/(z*(a-1)**2)) *
372
+ # (1 - (-z)**(1-a) * (gamma(a) - uppergamma(a,-z))
373
+ # - (a-1) * (EulerGamma + uppergamma(0,-z) + log(-z))
374
+ # - exp(z)))
375
+ # Manually tuned rule
376
+ addb([1, 1, a], [2, 2, a+1],
377
+ Matrix([a*(log(-z) + expint(1, -z) + EulerGamma)/(z*(a**2 - 2*a + 1)),
378
+ a*(-z)**(-a)*(gamma(a) - uppergamma(a, -z))/(a - 1)**2,
379
+ a*exp(z)/(a**2 - 2*a + 1),
380
+ a/(z*(a**2 - 2*a + 1))]),
381
+ Matrix([[1-a, 1, -1/z, 1]]),
382
+ Matrix([[-1,0,-1/z,1],
383
+ [0,-a,1,0],
384
+ [0,0,z,0],
385
+ [0,0,0,-1]]))
386
+
387
+
388
+ def add_meijerg_formulae(formulae):
389
+ a, b, c, z = list(map(Dummy, 'abcz'))
390
+ rho = Dummy('rho')
391
+
392
+ def add(an, ap, bm, bq, B, C, M, matcher):
393
+ formulae.append(MeijerFormula(an, ap, bm, bq, z, [a, b, c, rho],
394
+ B, C, M, matcher))
395
+
396
+ def detect_uppergamma(func):
397
+ x = func.an[0]
398
+ y, z = func.bm
399
+ swapped = False
400
+ if not _mod1((x - y).simplify()):
401
+ swapped = True
402
+ (y, z) = (z, y)
403
+ if _mod1((x - z).simplify()) or x - z > 0:
404
+ return None
405
+ l = [y, x]
406
+ if swapped:
407
+ l = [x, y]
408
+ return {rho: y, a: x - y}, G_Function([x], [], l, [])
409
+
410
+ add([a + rho], [], [rho, a + rho], [],
411
+ Matrix([gamma(1 - a)*z**rho*exp(z)*uppergamma(a, z),
412
+ gamma(1 - a)*z**(a + rho)]),
413
+ Matrix([[1, 0]]),
414
+ Matrix([[rho + z, -1], [0, a + rho]]),
415
+ detect_uppergamma)
416
+
417
+ def detect_3113(func):
418
+ """https://functions.wolfram.com/07.34.03.0984.01"""
419
+ x = func.an[0]
420
+ u, v, w = func.bm
421
+ if _mod1((u - v).simplify()) == 0:
422
+ if _mod1((v - w).simplify()) == 0:
423
+ return
424
+ sig = (S.Half, S.Half, S.Zero)
425
+ x1, x2, y = u, v, w
426
+ else:
427
+ if _mod1((x - u).simplify()) == 0:
428
+ sig = (S.Half, S.Zero, S.Half)
429
+ x1, y, x2 = u, v, w
430
+ else:
431
+ sig = (S.Zero, S.Half, S.Half)
432
+ y, x1, x2 = u, v, w
433
+
434
+ if (_mod1((x - x1).simplify()) != 0 or
435
+ _mod1((x - x2).simplify()) != 0 or
436
+ _mod1((x - y).simplify()) != S.Half or
437
+ x - x1 > 0 or x - x2 > 0):
438
+ return
439
+
440
+ return {a: x}, G_Function([x], [], [x - S.Half + t for t in sig], [])
441
+
442
+ s = sin(2*sqrt(z))
443
+ c_ = cos(2*sqrt(z))
444
+ S_ = Si(2*sqrt(z)) - pi/2
445
+ C = Ci(2*sqrt(z))
446
+ add([a], [], [a, a, a - S.Half], [],
447
+ Matrix([sqrt(pi)*z**(a - S.Half)*(c_*S_ - s*C),
448
+ sqrt(pi)*z**a*(s*S_ + c_*C),
449
+ sqrt(pi)*z**a]),
450
+ Matrix([[-2, 0, 0]]),
451
+ Matrix([[a - S.Half, -1, 0], [z, a, S.Half], [0, 0, a]]),
452
+ detect_3113)
453
+
454
+
455
+ def make_simp(z):
456
+ """ Create a function that simplifies rational functions in ``z``. """
457
+
458
+ def simp(expr):
459
+ """ Efficiently simplify the rational function ``expr``. """
460
+ numer, denom = expr.as_numer_denom()
461
+ numer = numer.expand()
462
+ # denom = denom.expand() # is this needed?
463
+ c, numer, denom = poly(numer, z).cancel(poly(denom, z))
464
+ return c * numer.as_expr() / denom.as_expr()
465
+
466
+ return simp
467
+
468
+
469
+ def debug(*args):
470
+ if SYMPY_DEBUG:
471
+ for a in args:
472
+ print(a, end="")
473
+ print()
474
+
475
+
476
+ class Hyper_Function(Expr):
477
+ """ A generalized hypergeometric function. """
478
+
479
+ def __new__(cls, ap, bq):
480
+ obj = super().__new__(cls)
481
+ obj.ap = Tuple(*list(map(expand, ap)))
482
+ obj.bq = Tuple(*list(map(expand, bq)))
483
+ return obj
484
+
485
+ @property
486
+ def args(self):
487
+ return (self.ap, self.bq)
488
+
489
+ @property
490
+ def sizes(self):
491
+ return (len(self.ap), len(self.bq))
492
+
493
+ @property
494
+ def gamma(self):
495
+ """
496
+ Number of upper parameters that are negative integers
497
+
498
+ This is a transformation invariant.
499
+ """
500
+ return sum(bool(x.is_integer and x.is_negative) for x in self.ap)
501
+
502
+ def _hashable_content(self):
503
+ return super()._hashable_content() + (self.ap,
504
+ self.bq)
505
+
506
+ def __call__(self, arg):
507
+ return hyper(self.ap, self.bq, arg)
508
+
509
+ def build_invariants(self):
510
+ """
511
+ Compute the invariant vector.
512
+
513
+ Explanation
514
+ ===========
515
+
516
+ The invariant vector is:
517
+ (gamma, ((s1, n1), ..., (sk, nk)), ((t1, m1), ..., (tr, mr)))
518
+ where gamma is the number of integer a < 0,
519
+ s1 < ... < sk
520
+ nl is the number of parameters a_i congruent to sl mod 1
521
+ t1 < ... < tr
522
+ ml is the number of parameters b_i congruent to tl mod 1
523
+
524
+ If the index pair contains parameters, then this is not truly an
525
+ invariant, since the parameters cannot be sorted uniquely mod1.
526
+
527
+ Examples
528
+ ========
529
+
530
+ >>> from sympy.simplify.hyperexpand import Hyper_Function
531
+ >>> from sympy import S
532
+ >>> ap = (S.Half, S.One/3, S(-1)/2, -2)
533
+ >>> bq = (1, 2)
534
+
535
+ Here gamma = 1,
536
+ k = 3, s1 = 0, s2 = 1/3, s3 = 1/2
537
+ n1 = 1, n2 = 1, n2 = 2
538
+ r = 1, t1 = 0
539
+ m1 = 2:
540
+
541
+ >>> Hyper_Function(ap, bq).build_invariants()
542
+ (1, ((0, 1), (1/3, 1), (1/2, 2)), ((0, 2),))
543
+ """
544
+ abuckets, bbuckets = sift(self.ap, _mod1), sift(self.bq, _mod1)
545
+
546
+ def tr(bucket):
547
+ bucket = list(bucket.items())
548
+ if not any(isinstance(x[0], Mod) for x in bucket):
549
+ bucket.sort(key=lambda x: default_sort_key(x[0]))
550
+ bucket = tuple([(mod, len(values)) for mod, values in bucket if
551
+ values])
552
+ return bucket
553
+
554
+ return (self.gamma, tr(abuckets), tr(bbuckets))
555
+
556
+ def difficulty(self, func):
557
+ """ Estimate how many steps it takes to reach ``func`` from self.
558
+ Return -1 if impossible. """
559
+ if self.gamma != func.gamma:
560
+ return -1
561
+ oabuckets, obbuckets, abuckets, bbuckets = [sift(params, _mod1) for
562
+ params in (self.ap, self.bq, func.ap, func.bq)]
563
+
564
+ diff = 0
565
+ for bucket, obucket in [(abuckets, oabuckets), (bbuckets, obbuckets)]:
566
+ for mod in set(list(bucket.keys()) + list(obucket.keys())):
567
+ if (mod not in bucket) or (mod not in obucket) \
568
+ or len(bucket[mod]) != len(obucket[mod]):
569
+ return -1
570
+ l1 = list(bucket[mod])
571
+ l2 = list(obucket[mod])
572
+ l1.sort()
573
+ l2.sort()
574
+ for i, j in zip(l1, l2):
575
+ diff += abs(i - j)
576
+
577
+ return diff
578
+
579
+ def _is_suitable_origin(self):
580
+ """
581
+ Decide if ``self`` is a suitable origin.
582
+
583
+ Explanation
584
+ ===========
585
+
586
+ A function is a suitable origin iff:
587
+ * none of the ai equals bj + n, with n a non-negative integer
588
+ * none of the ai is zero
589
+ * none of the bj is a non-positive integer
590
+
591
+ Note that this gives meaningful results only when none of the indices
592
+ are symbolic.
593
+
594
+ """
595
+ for a in self.ap:
596
+ for b in self.bq:
597
+ if (a - b).is_integer and (a - b).is_negative is False:
598
+ return False
599
+ for a in self.ap:
600
+ if a == 0:
601
+ return False
602
+ for b in self.bq:
603
+ if b.is_integer and b.is_nonpositive:
604
+ return False
605
+ return True
606
+
607
+
608
+ class G_Function(Expr):
609
+ """ A Meijer G-function. """
610
+
611
+ def __new__(cls, an, ap, bm, bq):
612
+ obj = super().__new__(cls)
613
+ obj.an = Tuple(*list(map(expand, an)))
614
+ obj.ap = Tuple(*list(map(expand, ap)))
615
+ obj.bm = Tuple(*list(map(expand, bm)))
616
+ obj.bq = Tuple(*list(map(expand, bq)))
617
+ return obj
618
+
619
+ @property
620
+ def args(self):
621
+ return (self.an, self.ap, self.bm, self.bq)
622
+
623
+ def _hashable_content(self):
624
+ return super()._hashable_content() + self.args
625
+
626
+ def __call__(self, z):
627
+ return meijerg(self.an, self.ap, self.bm, self.bq, z)
628
+
629
+ def compute_buckets(self):
630
+ """
631
+ Compute buckets for the fours sets of parameters.
632
+
633
+ Explanation
634
+ ===========
635
+
636
+ We guarantee that any two equal Mod objects returned are actually the
637
+ same, and that the buckets are sorted by real part (an and bq
638
+ descendending, bm and ap ascending).
639
+
640
+ Examples
641
+ ========
642
+
643
+ >>> from sympy.simplify.hyperexpand import G_Function
644
+ >>> from sympy.abc import y
645
+ >>> from sympy import S
646
+
647
+ >>> a, b = [1, 3, 2, S(3)/2], [1 + y, y, 2, y + 3]
648
+ >>> G_Function(a, b, [2], [y]).compute_buckets()
649
+ ({0: [3, 2, 1], 1/2: [3/2]},
650
+ {0: [2], y: [y, y + 1, y + 3]}, {0: [2]}, {y: [y]})
651
+
652
+ """
653
+ dicts = pan, pap, pbm, pbq = [defaultdict(list) for i in range(4)]
654
+ for dic, lis in zip(dicts, (self.an, self.ap, self.bm, self.bq)):
655
+ for x in lis:
656
+ dic[_mod1(x)].append(x)
657
+
658
+ for dic, flip in zip(dicts, (True, False, False, True)):
659
+ for m, items in dic.items():
660
+ x0 = items[0]
661
+ items.sort(key=lambda x: x - x0, reverse=flip)
662
+ dic[m] = items
663
+
664
+ return tuple([dict(w) for w in dicts])
665
+
666
+ @property
667
+ def signature(self):
668
+ return (len(self.an), len(self.ap), len(self.bm), len(self.bq))
669
+
670
+
671
+ # Dummy variable.
672
+ _x = Dummy('x')
673
+
674
+ class Formula:
675
+ """
676
+ This class represents hypergeometric formulae.
677
+
678
+ Explanation
679
+ ===========
680
+
681
+ Its data members are:
682
+ - z, the argument
683
+ - closed_form, the closed form expression
684
+ - symbols, the free symbols (parameters) in the formula
685
+ - func, the function
686
+ - B, C, M (see _compute_basis)
687
+
688
+ Examples
689
+ ========
690
+
691
+ >>> from sympy.abc import a, b, z
692
+ >>> from sympy.simplify.hyperexpand import Formula, Hyper_Function
693
+ >>> func = Hyper_Function((a/2, a/3 + b, (1+a)/2), (a, b, (a+b)/7))
694
+ >>> f = Formula(func, z, None, [a, b])
695
+
696
+ """
697
+
698
+ def _compute_basis(self, closed_form):
699
+ """
700
+ Compute a set of functions B=(f1, ..., fn), a nxn matrix M
701
+ and a 1xn matrix C such that:
702
+ closed_form = C B
703
+ z d/dz B = M B.
704
+ """
705
+ afactors = [_x + a for a in self.func.ap]
706
+ bfactors = [_x + b - 1 for b in self.func.bq]
707
+ expr = _x*Mul(*bfactors) - self.z*Mul(*afactors)
708
+ poly = Poly(expr, _x)
709
+
710
+ n = poly.degree() - 1
711
+ b = [closed_form]
712
+ for _ in range(n):
713
+ b.append(self.z*b[-1].diff(self.z))
714
+
715
+ self.B = Matrix(b)
716
+ self.C = Matrix([[1] + [0]*n])
717
+
718
+ m = eye(n)
719
+ m = m.col_insert(0, zeros(n, 1))
720
+ l = poly.all_coeffs()[1:]
721
+ l.reverse()
722
+ self.M = m.row_insert(n, -Matrix([l])/poly.all_coeffs()[0])
723
+
724
+ def __init__(self, func, z, res, symbols, B=None, C=None, M=None):
725
+ z = sympify(z)
726
+ res = sympify(res)
727
+ symbols = [x for x in sympify(symbols) if func.has(x)]
728
+
729
+ self.z = z
730
+ self.symbols = symbols
731
+ self.B = B
732
+ self.C = C
733
+ self.M = M
734
+ self.func = func
735
+
736
+ # TODO with symbolic parameters, it could be advantageous
737
+ # (for prettier answers) to compute a basis only *after*
738
+ # instantiation
739
+ if res is not None:
740
+ self._compute_basis(res)
741
+
742
+ @property
743
+ def closed_form(self):
744
+ return reduce(lambda s,m: s+m[0]*m[1], zip(self.C, self.B), S.Zero)
745
+
746
+ def find_instantiations(self, func):
747
+ """
748
+ Find substitutions of the free symbols that match ``func``.
749
+
750
+ Return the substitution dictionaries as a list. Note that the returned
751
+ instantiations need not actually match, or be valid!
752
+
753
+ """
754
+ from sympy.solvers import solve
755
+ ap = func.ap
756
+ bq = func.bq
757
+ if len(ap) != len(self.func.ap) or len(bq) != len(self.func.bq):
758
+ raise TypeError('Cannot instantiate other number of parameters')
759
+ symbol_values = []
760
+ for a in self.symbols:
761
+ if a in self.func.ap.args:
762
+ symbol_values.append(ap)
763
+ elif a in self.func.bq.args:
764
+ symbol_values.append(bq)
765
+ else:
766
+ raise ValueError("At least one of the parameters of the "
767
+ "formula must be equal to %s" % (a,))
768
+ base_repl = [dict(list(zip(self.symbols, values)))
769
+ for values in product(*symbol_values)]
770
+ abuckets, bbuckets = [sift(params, _mod1) for params in [ap, bq]]
771
+ a_inv, b_inv = [{a: len(vals) for a, vals in bucket.items()}
772
+ for bucket in [abuckets, bbuckets]]
773
+ critical_values = [[0] for _ in self.symbols]
774
+ result = []
775
+ _n = Dummy()
776
+ for repl in base_repl:
777
+ symb_a, symb_b = [sift(params, lambda x: _mod1(x.xreplace(repl)))
778
+ for params in [self.func.ap, self.func.bq]]
779
+ for bucket, obucket in [(abuckets, symb_a), (bbuckets, symb_b)]:
780
+ for mod in set(list(bucket.keys()) + list(obucket.keys())):
781
+ if (mod not in bucket) or (mod not in obucket) \
782
+ or len(bucket[mod]) != len(obucket[mod]):
783
+ break
784
+ for a, vals in zip(self.symbols, critical_values):
785
+ if repl[a].free_symbols:
786
+ continue
787
+ exprs = [expr for expr in obucket[mod] if expr.has(a)]
788
+ repl0 = repl.copy()
789
+ repl0[a] += _n
790
+ for expr in exprs:
791
+ for target in bucket[mod]:
792
+ n0, = solve(expr.xreplace(repl0) - target, _n)
793
+ if n0.free_symbols:
794
+ raise ValueError("Value should not be true")
795
+ vals.append(n0)
796
+ else:
797
+ values = []
798
+ for a, vals in zip(self.symbols, critical_values):
799
+ a0 = repl[a]
800
+ min_ = floor(min(vals))
801
+ max_ = ceiling(max(vals))
802
+ values.append([a0 + n for n in range(min_, max_ + 1)])
803
+ result.extend(dict(list(zip(self.symbols, l))) for l in product(*values))
804
+ return result
805
+
806
+
807
+
808
+
809
+ class FormulaCollection:
810
+ """ A collection of formulae to use as origins. """
811
+
812
+ def __init__(self):
813
+ """ Doing this globally at module init time is a pain ... """
814
+ self.symbolic_formulae = {}
815
+ self.concrete_formulae = {}
816
+ self.formulae = []
817
+
818
+ add_formulae(self.formulae)
819
+
820
+ # Now process the formulae into a helpful form.
821
+ # These dicts are indexed by (p, q).
822
+
823
+ for f in self.formulae:
824
+ sizes = f.func.sizes
825
+ if len(f.symbols) > 0:
826
+ self.symbolic_formulae.setdefault(sizes, []).append(f)
827
+ else:
828
+ inv = f.func.build_invariants()
829
+ self.concrete_formulae.setdefault(sizes, {})[inv] = f
830
+
831
+ def lookup_origin(self, func):
832
+ """
833
+ Given the suitable target ``func``, try to find an origin in our
834
+ knowledge base.
835
+
836
+ Examples
837
+ ========
838
+
839
+ >>> from sympy.simplify.hyperexpand import (FormulaCollection,
840
+ ... Hyper_Function)
841
+ >>> f = FormulaCollection()
842
+ >>> f.lookup_origin(Hyper_Function((), ())).closed_form
843
+ exp(_z)
844
+ >>> f.lookup_origin(Hyper_Function([1], ())).closed_form
845
+ HyperRep_power1(-1, _z)
846
+
847
+ >>> from sympy import S
848
+ >>> i = Hyper_Function([S('1/4'), S('3/4 + 4')], [S.Half])
849
+ >>> f.lookup_origin(i).closed_form
850
+ HyperRep_sqrts1(-1/4, _z)
851
+ """
852
+ inv = func.build_invariants()
853
+ sizes = func.sizes
854
+ if sizes in self.concrete_formulae and \
855
+ inv in self.concrete_formulae[sizes]:
856
+ return self.concrete_formulae[sizes][inv]
857
+
858
+ # We don't have a concrete formula. Try to instantiate.
859
+ if sizes not in self.symbolic_formulae:
860
+ return None # Too bad...
861
+
862
+ possible = []
863
+ for f in self.symbolic_formulae[sizes]:
864
+ repls = f.find_instantiations(func)
865
+ for repl in repls:
866
+ func2 = f.func.xreplace(repl)
867
+ if not func2._is_suitable_origin():
868
+ continue
869
+ diff = func2.difficulty(func)
870
+ if diff == -1:
871
+ continue
872
+ possible.append((diff, repl, f, func2))
873
+
874
+ # find the nearest origin
875
+ possible.sort(key=lambda x: x[0])
876
+ for _, repl, f, func2 in possible:
877
+ f2 = Formula(func2, f.z, None, [], f.B.subs(repl),
878
+ f.C.subs(repl), f.M.subs(repl))
879
+ if not any(e.has(S.NaN, oo, -oo, zoo) for e in [f2.B, f2.M, f2.C]):
880
+ return f2
881
+
882
+ return None
883
+
884
+
885
+ class MeijerFormula:
886
+ """
887
+ This class represents a Meijer G-function formula.
888
+
889
+ Its data members are:
890
+ - z, the argument
891
+ - symbols, the free symbols (parameters) in the formula
892
+ - func, the function
893
+ - B, C, M (c/f ordinary Formula)
894
+ """
895
+
896
+ def __init__(self, an, ap, bm, bq, z, symbols, B, C, M, matcher):
897
+ an, ap, bm, bq = [Tuple(*list(map(expand, w))) for w in [an, ap, bm, bq]]
898
+ self.func = G_Function(an, ap, bm, bq)
899
+ self.z = z
900
+ self.symbols = symbols
901
+ self._matcher = matcher
902
+ self.B = B
903
+ self.C = C
904
+ self.M = M
905
+
906
+ @property
907
+ def closed_form(self):
908
+ return reduce(lambda s,m: s+m[0]*m[1], zip(self.C, self.B), S.Zero)
909
+
910
+ def try_instantiate(self, func):
911
+ """
912
+ Try to instantiate the current formula to (almost) match func.
913
+ This uses the _matcher passed on init.
914
+ """
915
+ if func.signature != self.func.signature:
916
+ return None
917
+ res = self._matcher(func)
918
+ if res is not None:
919
+ subs, newfunc = res
920
+ return MeijerFormula(newfunc.an, newfunc.ap, newfunc.bm, newfunc.bq,
921
+ self.z, [],
922
+ self.B.subs(subs), self.C.subs(subs),
923
+ self.M.subs(subs), None)
924
+
925
+
926
+ class MeijerFormulaCollection:
927
+ """
928
+ This class holds a collection of meijer g formulae.
929
+ """
930
+
931
+ def __init__(self):
932
+ formulae = []
933
+ add_meijerg_formulae(formulae)
934
+ self.formulae = defaultdict(list)
935
+ for formula in formulae:
936
+ self.formulae[formula.func.signature].append(formula)
937
+ self.formulae = dict(self.formulae)
938
+
939
+ def lookup_origin(self, func):
940
+ """ Try to find a formula that matches func. """
941
+ if func.signature not in self.formulae:
942
+ return None
943
+ for formula in self.formulae[func.signature]:
944
+ res = formula.try_instantiate(func)
945
+ if res is not None:
946
+ return res
947
+
948
+
949
+ class Operator:
950
+ """
951
+ Base class for operators to be applied to our functions.
952
+
953
+ Explanation
954
+ ===========
955
+
956
+ These operators are differential operators. They are by convention
957
+ expressed in the variable D = z*d/dz (although this base class does
958
+ not actually care).
959
+ Note that when the operator is applied to an object, we typically do
960
+ *not* blindly differentiate but instead use a different representation
961
+ of the z*d/dz operator (see make_derivative_operator).
962
+
963
+ To subclass from this, define a __init__ method that initializes a
964
+ self._poly variable. This variable stores a polynomial. By convention
965
+ the generator is z*d/dz, and acts to the right of all coefficients.
966
+
967
+ Thus this poly
968
+ x**2 + 2*z*x + 1
969
+ represents the differential operator
970
+ (z*d/dz)**2 + 2*z**2*d/dz.
971
+
972
+ This class is used only in the implementation of the hypergeometric
973
+ function expansion algorithm.
974
+ """
975
+
976
+ def apply(self, obj, op):
977
+ """
978
+ Apply ``self`` to the object ``obj``, where the generator is ``op``.
979
+
980
+ Examples
981
+ ========
982
+
983
+ >>> from sympy.simplify.hyperexpand import Operator
984
+ >>> from sympy.polys.polytools import Poly
985
+ >>> from sympy.abc import x, y, z
986
+ >>> op = Operator()
987
+ >>> op._poly = Poly(x**2 + z*x + y, x)
988
+ >>> op.apply(z**7, lambda f: f.diff(z))
989
+ y*z**7 + 7*z**7 + 42*z**5
990
+ """
991
+ coeffs = self._poly.all_coeffs()
992
+ coeffs.reverse()
993
+ diffs = [obj]
994
+ for c in coeffs[1:]:
995
+ diffs.append(op(diffs[-1]))
996
+ r = coeffs[0]*diffs[0]
997
+ for c, d in zip(coeffs[1:], diffs[1:]):
998
+ r += c*d
999
+ return r
1000
+
1001
+
1002
+ class MultOperator(Operator):
1003
+ """ Simply multiply by a "constant" """
1004
+
1005
+ def __init__(self, p):
1006
+ self._poly = Poly(p, _x)
1007
+
1008
+
1009
+ class ShiftA(Operator):
1010
+ """ Increment an upper index. """
1011
+
1012
+ def __init__(self, ai):
1013
+ ai = sympify(ai)
1014
+ if ai == 0:
1015
+ raise ValueError('Cannot increment zero upper index.')
1016
+ self._poly = Poly(_x/ai + 1, _x)
1017
+
1018
+ def __str__(self):
1019
+ return '<Increment upper %s.>' % (1/self._poly.all_coeffs()[0])
1020
+
1021
+
1022
+ class ShiftB(Operator):
1023
+ """ Decrement a lower index. """
1024
+
1025
+ def __init__(self, bi):
1026
+ bi = sympify(bi)
1027
+ if bi == 1:
1028
+ raise ValueError('Cannot decrement unit lower index.')
1029
+ self._poly = Poly(_x/(bi - 1) + 1, _x)
1030
+
1031
+ def __str__(self):
1032
+ return '<Decrement lower %s.>' % (1/self._poly.all_coeffs()[0] + 1)
1033
+
1034
+
1035
+ class UnShiftA(Operator):
1036
+ """ Decrement an upper index. """
1037
+
1038
+ def __init__(self, ap, bq, i, z):
1039
+ """ Note: i counts from zero! """
1040
+ ap, bq, i = list(map(sympify, [ap, bq, i]))
1041
+
1042
+ self._ap = ap
1043
+ self._bq = bq
1044
+ self._i = i
1045
+
1046
+ ap = list(ap)
1047
+ bq = list(bq)
1048
+ ai = ap.pop(i) - 1
1049
+
1050
+ if ai == 0:
1051
+ raise ValueError('Cannot decrement unit upper index.')
1052
+
1053
+ m = Poly(z*ai, _x)
1054
+ for a in ap:
1055
+ m *= Poly(_x + a, _x)
1056
+
1057
+ A = Dummy('A')
1058
+ n = D = Poly(ai*A - ai, A)
1059
+ for b in bq:
1060
+ n *= D + (b - 1).as_poly(A)
1061
+
1062
+ b0 = -n.nth(0)
1063
+ if b0 == 0:
1064
+ raise ValueError('Cannot decrement upper index: '
1065
+ 'cancels with lower')
1066
+
1067
+ n = Poly(Poly(n.all_coeffs()[:-1], A).as_expr().subs(A, _x/ai + 1), _x)
1068
+
1069
+ self._poly = Poly((n - m)/b0, _x)
1070
+
1071
+ def __str__(self):
1072
+ return '<Decrement upper index #%s of %s, %s.>' % (self._i,
1073
+ self._ap, self._bq)
1074
+
1075
+
1076
+ class UnShiftB(Operator):
1077
+ """ Increment a lower index. """
1078
+
1079
+ def __init__(self, ap, bq, i, z):
1080
+ """ Note: i counts from zero! """
1081
+ ap, bq, i = list(map(sympify, [ap, bq, i]))
1082
+
1083
+ self._ap = ap
1084
+ self._bq = bq
1085
+ self._i = i
1086
+
1087
+ ap = list(ap)
1088
+ bq = list(bq)
1089
+ bi = bq.pop(i) + 1
1090
+
1091
+ if bi == 0:
1092
+ raise ValueError('Cannot increment -1 lower index.')
1093
+
1094
+ m = Poly(_x*(bi - 1), _x)
1095
+ for b in bq:
1096
+ m *= Poly(_x + b - 1, _x)
1097
+
1098
+ B = Dummy('B')
1099
+ D = Poly((bi - 1)*B - bi + 1, B)
1100
+ n = Poly(z, B)
1101
+ for a in ap:
1102
+ n *= (D + a.as_poly(B))
1103
+
1104
+ b0 = n.nth(0)
1105
+ if b0 == 0:
1106
+ raise ValueError('Cannot increment index: cancels with upper')
1107
+
1108
+ n = Poly(Poly(n.all_coeffs()[:-1], B).as_expr().subs(
1109
+ B, _x/(bi - 1) + 1), _x)
1110
+
1111
+ self._poly = Poly((m - n)/b0, _x)
1112
+
1113
+ def __str__(self):
1114
+ return '<Increment lower index #%s of %s, %s.>' % (self._i,
1115
+ self._ap, self._bq)
1116
+
1117
+
1118
+ class MeijerShiftA(Operator):
1119
+ """ Increment an upper b index. """
1120
+
1121
+ def __init__(self, bi):
1122
+ bi = sympify(bi)
1123
+ self._poly = Poly(bi - _x, _x)
1124
+
1125
+ def __str__(self):
1126
+ return '<Increment upper b=%s.>' % (self._poly.all_coeffs()[1])
1127
+
1128
+
1129
+ class MeijerShiftB(Operator):
1130
+ """ Decrement an upper a index. """
1131
+
1132
+ def __init__(self, bi):
1133
+ bi = sympify(bi)
1134
+ self._poly = Poly(1 - bi + _x, _x)
1135
+
1136
+ def __str__(self):
1137
+ return '<Decrement upper a=%s.>' % (1 - self._poly.all_coeffs()[1])
1138
+
1139
+
1140
+ class MeijerShiftC(Operator):
1141
+ """ Increment a lower b index. """
1142
+
1143
+ def __init__(self, bi):
1144
+ bi = sympify(bi)
1145
+ self._poly = Poly(-bi + _x, _x)
1146
+
1147
+ def __str__(self):
1148
+ return '<Increment lower b=%s.>' % (-self._poly.all_coeffs()[1])
1149
+
1150
+
1151
+ class MeijerShiftD(Operator):
1152
+ """ Decrement a lower a index. """
1153
+
1154
+ def __init__(self, bi):
1155
+ bi = sympify(bi)
1156
+ self._poly = Poly(bi - 1 - _x, _x)
1157
+
1158
+ def __str__(self):
1159
+ return '<Decrement lower a=%s.>' % (self._poly.all_coeffs()[1] + 1)
1160
+
1161
+
1162
+ class MeijerUnShiftA(Operator):
1163
+ """ Decrement an upper b index. """
1164
+
1165
+ def __init__(self, an, ap, bm, bq, i, z):
1166
+ """ Note: i counts from zero! """
1167
+ an, ap, bm, bq, i = list(map(sympify, [an, ap, bm, bq, i]))
1168
+
1169
+ self._an = an
1170
+ self._ap = ap
1171
+ self._bm = bm
1172
+ self._bq = bq
1173
+ self._i = i
1174
+
1175
+ an = list(an)
1176
+ ap = list(ap)
1177
+ bm = list(bm)
1178
+ bq = list(bq)
1179
+ bi = bm.pop(i) - 1
1180
+
1181
+ m = Poly(1, _x) * prod(Poly(b - _x, _x) for b in bm) * prod(Poly(_x - b, _x) for b in bq)
1182
+
1183
+ A = Dummy('A')
1184
+ D = Poly(bi - A, A)
1185
+ n = Poly(z, A) * prod((D + 1 - a) for a in an) * prod((-D + a - 1) for a in ap)
1186
+
1187
+ b0 = n.nth(0)
1188
+ if b0 == 0:
1189
+ raise ValueError('Cannot decrement upper b index (cancels)')
1190
+
1191
+ n = Poly(Poly(n.all_coeffs()[:-1], A).as_expr().subs(A, bi - _x), _x)
1192
+
1193
+ self._poly = Poly((m - n)/b0, _x)
1194
+
1195
+ def __str__(self):
1196
+ return '<Decrement upper b index #%s of %s, %s, %s, %s.>' % (self._i,
1197
+ self._an, self._ap, self._bm, self._bq)
1198
+
1199
+
1200
+ class MeijerUnShiftB(Operator):
1201
+ """ Increment an upper a index. """
1202
+
1203
+ def __init__(self, an, ap, bm, bq, i, z):
1204
+ """ Note: i counts from zero! """
1205
+ an, ap, bm, bq, i = list(map(sympify, [an, ap, bm, bq, i]))
1206
+
1207
+ self._an = an
1208
+ self._ap = ap
1209
+ self._bm = bm
1210
+ self._bq = bq
1211
+ self._i = i
1212
+
1213
+ an = list(an)
1214
+ ap = list(ap)
1215
+ bm = list(bm)
1216
+ bq = list(bq)
1217
+ ai = an.pop(i) + 1
1218
+
1219
+ m = Poly(z, _x)
1220
+ for a in an:
1221
+ m *= Poly(1 - a + _x, _x)
1222
+ for a in ap:
1223
+ m *= Poly(a - 1 - _x, _x)
1224
+
1225
+ B = Dummy('B')
1226
+ D = Poly(B + ai - 1, B)
1227
+ n = Poly(1, B)
1228
+ for b in bm:
1229
+ n *= (-D + b)
1230
+ for b in bq:
1231
+ n *= (D - b)
1232
+
1233
+ b0 = n.nth(0)
1234
+ if b0 == 0:
1235
+ raise ValueError('Cannot increment upper a index (cancels)')
1236
+
1237
+ n = Poly(Poly(n.all_coeffs()[:-1], B).as_expr().subs(
1238
+ B, 1 - ai + _x), _x)
1239
+
1240
+ self._poly = Poly((m - n)/b0, _x)
1241
+
1242
+ def __str__(self):
1243
+ return '<Increment upper a index #%s of %s, %s, %s, %s.>' % (self._i,
1244
+ self._an, self._ap, self._bm, self._bq)
1245
+
1246
+
1247
+ class MeijerUnShiftC(Operator):
1248
+ """ Decrement a lower b index. """
1249
+ # XXX this is "essentially" the same as MeijerUnShiftA. This "essentially"
1250
+ # can be made rigorous using the functional equation G(1/z) = G'(z),
1251
+ # where G' denotes a G function of slightly altered parameters.
1252
+ # However, sorting out the details seems harder than just coding it
1253
+ # again.
1254
+
1255
+ def __init__(self, an, ap, bm, bq, i, z):
1256
+ """ Note: i counts from zero! """
1257
+ an, ap, bm, bq, i = list(map(sympify, [an, ap, bm, bq, i]))
1258
+
1259
+ self._an = an
1260
+ self._ap = ap
1261
+ self._bm = bm
1262
+ self._bq = bq
1263
+ self._i = i
1264
+
1265
+ an = list(an)
1266
+ ap = list(ap)
1267
+ bm = list(bm)
1268
+ bq = list(bq)
1269
+ bi = bq.pop(i) - 1
1270
+
1271
+ m = Poly(1, _x)
1272
+ for b in bm:
1273
+ m *= Poly(b - _x, _x)
1274
+ for b in bq:
1275
+ m *= Poly(_x - b, _x)
1276
+
1277
+ C = Dummy('C')
1278
+ D = Poly(bi + C, C)
1279
+ n = Poly(z, C)
1280
+ for a in an:
1281
+ n *= (D + 1 - a)
1282
+ for a in ap:
1283
+ n *= (-D + a - 1)
1284
+
1285
+ b0 = n.nth(0)
1286
+ if b0 == 0:
1287
+ raise ValueError('Cannot decrement lower b index (cancels)')
1288
+
1289
+ n = Poly(Poly(n.all_coeffs()[:-1], C).as_expr().subs(C, _x - bi), _x)
1290
+
1291
+ self._poly = Poly((m - n)/b0, _x)
1292
+
1293
+ def __str__(self):
1294
+ return '<Decrement lower b index #%s of %s, %s, %s, %s.>' % (self._i,
1295
+ self._an, self._ap, self._bm, self._bq)
1296
+
1297
+
1298
+ class MeijerUnShiftD(Operator):
1299
+ """ Increment a lower a index. """
1300
+ # XXX This is essentially the same as MeijerUnShiftA.
1301
+ # See comment at MeijerUnShiftC.
1302
+
1303
+ def __init__(self, an, ap, bm, bq, i, z):
1304
+ """ Note: i counts from zero! """
1305
+ an, ap, bm, bq, i = list(map(sympify, [an, ap, bm, bq, i]))
1306
+
1307
+ self._an = an
1308
+ self._ap = ap
1309
+ self._bm = bm
1310
+ self._bq = bq
1311
+ self._i = i
1312
+
1313
+ an = list(an)
1314
+ ap = list(ap)
1315
+ bm = list(bm)
1316
+ bq = list(bq)
1317
+ ai = ap.pop(i) + 1
1318
+
1319
+ m = Poly(z, _x)
1320
+ for a in an:
1321
+ m *= Poly(1 - a + _x, _x)
1322
+ for a in ap:
1323
+ m *= Poly(a - 1 - _x, _x)
1324
+
1325
+ B = Dummy('B') # - this is the shift operator `D_I`
1326
+ D = Poly(ai - 1 - B, B)
1327
+ n = Poly(1, B)
1328
+ for b in bm:
1329
+ n *= (-D + b)
1330
+ for b in bq:
1331
+ n *= (D - b)
1332
+
1333
+ b0 = n.nth(0)
1334
+ if b0 == 0:
1335
+ raise ValueError('Cannot increment lower a index (cancels)')
1336
+
1337
+ n = Poly(Poly(n.all_coeffs()[:-1], B).as_expr().subs(
1338
+ B, ai - 1 - _x), _x)
1339
+
1340
+ self._poly = Poly((m - n)/b0, _x)
1341
+
1342
+ def __str__(self):
1343
+ return '<Increment lower a index #%s of %s, %s, %s, %s.>' % (self._i,
1344
+ self._an, self._ap, self._bm, self._bq)
1345
+
1346
+
1347
+ class ReduceOrder(Operator):
1348
+ """ Reduce Order by cancelling an upper and a lower index. """
1349
+
1350
+ def __new__(cls, ai, bj):
1351
+ """ For convenience if reduction is not possible, return None. """
1352
+ ai = sympify(ai)
1353
+ bj = sympify(bj)
1354
+ n = ai - bj
1355
+ if not n.is_Integer or n < 0:
1356
+ return None
1357
+ if bj.is_integer and bj.is_nonpositive:
1358
+ return None
1359
+
1360
+ expr = Operator.__new__(cls)
1361
+
1362
+ p = S.One
1363
+ for k in range(n):
1364
+ p *= (_x + bj + k)/(bj + k)
1365
+
1366
+ expr._poly = Poly(p, _x)
1367
+ expr._a = ai
1368
+ expr._b = bj
1369
+
1370
+ return expr
1371
+
1372
+ @classmethod
1373
+ def _meijer(cls, b, a, sign):
1374
+ """ Cancel b + sign*s and a + sign*s
1375
+ This is for meijer G functions. """
1376
+ b = sympify(b)
1377
+ a = sympify(a)
1378
+ n = b - a
1379
+ if n.is_negative or not n.is_Integer:
1380
+ return None
1381
+
1382
+ expr = Operator.__new__(cls)
1383
+
1384
+ p = S.One
1385
+ for k in range(n):
1386
+ p *= (sign*_x + a + k)
1387
+
1388
+ expr._poly = Poly(p, _x)
1389
+ if sign == -1:
1390
+ expr._a = b
1391
+ expr._b = a
1392
+ else:
1393
+ expr._b = Add(1, a - 1, evaluate=False)
1394
+ expr._a = Add(1, b - 1, evaluate=False)
1395
+
1396
+ return expr
1397
+
1398
+ @classmethod
1399
+ def meijer_minus(cls, b, a):
1400
+ return cls._meijer(b, a, -1)
1401
+
1402
+ @classmethod
1403
+ def meijer_plus(cls, a, b):
1404
+ return cls._meijer(1 - a, 1 - b, 1)
1405
+
1406
+ def __str__(self):
1407
+ return '<Reduce order by cancelling upper %s with lower %s.>' % \
1408
+ (self._a, self._b)
1409
+
1410
+
1411
+ def _reduce_order(ap, bq, gen, key):
1412
+ """ Order reduction algorithm used in Hypergeometric and Meijer G """
1413
+ ap = list(ap)
1414
+ bq = list(bq)
1415
+
1416
+ ap.sort(key=key)
1417
+ bq.sort(key=key)
1418
+
1419
+ nap = []
1420
+ # we will edit bq in place
1421
+ operators = []
1422
+ for a in ap:
1423
+ op = None
1424
+ for i in range(len(bq)):
1425
+ op = gen(a, bq[i])
1426
+ if op is not None:
1427
+ bq.pop(i)
1428
+ break
1429
+ if op is None:
1430
+ nap.append(a)
1431
+ else:
1432
+ operators.append(op)
1433
+
1434
+ return nap, bq, operators
1435
+
1436
+
1437
+ def reduce_order(func):
1438
+ """
1439
+ Given the hypergeometric function ``func``, find a sequence of operators to
1440
+ reduces order as much as possible.
1441
+
1442
+ Explanation
1443
+ ===========
1444
+
1445
+ Return (newfunc, [operators]), where applying the operators to the
1446
+ hypergeometric function newfunc yields func.
1447
+
1448
+ Examples
1449
+ ========
1450
+
1451
+ >>> from sympy.simplify.hyperexpand import reduce_order, Hyper_Function
1452
+ >>> reduce_order(Hyper_Function((1, 2), (3, 4)))
1453
+ (Hyper_Function((1, 2), (3, 4)), [])
1454
+ >>> reduce_order(Hyper_Function((1,), (1,)))
1455
+ (Hyper_Function((), ()), [<Reduce order by cancelling upper 1 with lower 1.>])
1456
+ >>> reduce_order(Hyper_Function((2, 4), (3, 3)))
1457
+ (Hyper_Function((2,), (3,)), [<Reduce order by cancelling
1458
+ upper 4 with lower 3.>])
1459
+ """
1460
+ nap, nbq, operators = _reduce_order(func.ap, func.bq, ReduceOrder, default_sort_key)
1461
+
1462
+ return Hyper_Function(Tuple(*nap), Tuple(*nbq)), operators
1463
+
1464
+
1465
+ def reduce_order_meijer(func):
1466
+ """
1467
+ Given the Meijer G function parameters, ``func``, find a sequence of
1468
+ operators that reduces order as much as possible.
1469
+
1470
+ Return newfunc, [operators].
1471
+
1472
+ Examples
1473
+ ========
1474
+
1475
+ >>> from sympy.simplify.hyperexpand import (reduce_order_meijer,
1476
+ ... G_Function)
1477
+ >>> reduce_order_meijer(G_Function([3, 4], [5, 6], [3, 4], [1, 2]))[0]
1478
+ G_Function((4, 3), (5, 6), (3, 4), (2, 1))
1479
+ >>> reduce_order_meijer(G_Function([3, 4], [5, 6], [3, 4], [1, 8]))[0]
1480
+ G_Function((3,), (5, 6), (3, 4), (1,))
1481
+ >>> reduce_order_meijer(G_Function([3, 4], [5, 6], [7, 5], [1, 5]))[0]
1482
+ G_Function((3,), (), (), (1,))
1483
+ >>> reduce_order_meijer(G_Function([3, 4], [5, 6], [7, 5], [5, 3]))[0]
1484
+ G_Function((), (), (), ())
1485
+ """
1486
+
1487
+ nan, nbq, ops1 = _reduce_order(func.an, func.bq, ReduceOrder.meijer_plus,
1488
+ lambda x: default_sort_key(-x))
1489
+ nbm, nap, ops2 = _reduce_order(func.bm, func.ap, ReduceOrder.meijer_minus,
1490
+ default_sort_key)
1491
+
1492
+ return G_Function(nan, nap, nbm, nbq), ops1 + ops2
1493
+
1494
+
1495
+ def make_derivative_operator(M, z):
1496
+ """ Create a derivative operator, to be passed to Operator.apply. """
1497
+ def doit(C):
1498
+ r = z*C.diff(z) + C*M
1499
+ r = r.applyfunc(make_simp(z))
1500
+ return r
1501
+ return doit
1502
+
1503
+
1504
+ def apply_operators(obj, ops, op):
1505
+ """
1506
+ Apply the list of operators ``ops`` to object ``obj``, substituting
1507
+ ``op`` for the generator.
1508
+ """
1509
+ res = obj
1510
+ for o in reversed(ops):
1511
+ res = o.apply(res, op)
1512
+ return res
1513
+
1514
+
1515
+ def devise_plan(target, origin, z):
1516
+ """
1517
+ Devise a plan (consisting of shift and un-shift operators) to be applied
1518
+ to the hypergeometric function ``target`` to yield ``origin``.
1519
+ Returns a list of operators.
1520
+
1521
+ Examples
1522
+ ========
1523
+
1524
+ >>> from sympy.simplify.hyperexpand import devise_plan, Hyper_Function
1525
+ >>> from sympy.abc import z
1526
+
1527
+ Nothing to do:
1528
+
1529
+ >>> devise_plan(Hyper_Function((1, 2), ()), Hyper_Function((1, 2), ()), z)
1530
+ []
1531
+ >>> devise_plan(Hyper_Function((), (1, 2)), Hyper_Function((), (1, 2)), z)
1532
+ []
1533
+
1534
+ Very simple plans:
1535
+
1536
+ >>> devise_plan(Hyper_Function((2,), ()), Hyper_Function((1,), ()), z)
1537
+ [<Increment upper 1.>]
1538
+ >>> devise_plan(Hyper_Function((), (2,)), Hyper_Function((), (1,)), z)
1539
+ [<Increment lower index #0 of [], [1].>]
1540
+
1541
+ Several buckets:
1542
+
1543
+ >>> from sympy import S
1544
+ >>> devise_plan(Hyper_Function((1, S.Half), ()),
1545
+ ... Hyper_Function((2, S('3/2')), ()), z) #doctest: +NORMALIZE_WHITESPACE
1546
+ [<Decrement upper index #0 of [3/2, 1], [].>,
1547
+ <Decrement upper index #0 of [2, 3/2], [].>]
1548
+
1549
+ A slightly more complicated plan:
1550
+
1551
+ >>> devise_plan(Hyper_Function((1, 3), ()), Hyper_Function((2, 2), ()), z)
1552
+ [<Increment upper 2.>, <Decrement upper index #0 of [2, 2], [].>]
1553
+
1554
+ Another more complicated plan: (note that the ap have to be shifted first!)
1555
+
1556
+ >>> devise_plan(Hyper_Function((1, -1), (2,)), Hyper_Function((3, -2), (4,)), z)
1557
+ [<Decrement lower 3.>, <Decrement lower 4.>,
1558
+ <Decrement upper index #1 of [-1, 2], [4].>,
1559
+ <Decrement upper index #1 of [-1, 3], [4].>, <Increment upper -2.>]
1560
+ """
1561
+ abuckets, bbuckets, nabuckets, nbbuckets = [sift(params, _mod1) for
1562
+ params in (target.ap, target.bq, origin.ap, origin.bq)]
1563
+
1564
+ if len(list(abuckets.keys())) != len(list(nabuckets.keys())) or \
1565
+ len(list(bbuckets.keys())) != len(list(nbbuckets.keys())):
1566
+ raise ValueError('%s not reachable from %s' % (target, origin))
1567
+
1568
+ ops = []
1569
+
1570
+ def do_shifts(fro, to, inc, dec):
1571
+ ops = []
1572
+ for i in range(len(fro)):
1573
+ if to[i] - fro[i] > 0:
1574
+ sh = inc
1575
+ ch = 1
1576
+ else:
1577
+ sh = dec
1578
+ ch = -1
1579
+
1580
+ while to[i] != fro[i]:
1581
+ ops += [sh(fro, i)]
1582
+ fro[i] += ch
1583
+
1584
+ return ops
1585
+
1586
+ def do_shifts_a(nal, nbk, al, aother, bother):
1587
+ """ Shift us from (nal, nbk) to (al, nbk). """
1588
+ return do_shifts(nal, al, lambda p, i: ShiftA(p[i]),
1589
+ lambda p, i: UnShiftA(p + aother, nbk + bother, i, z))
1590
+
1591
+ def do_shifts_b(nal, nbk, bk, aother, bother):
1592
+ """ Shift us from (nal, nbk) to (nal, bk). """
1593
+ return do_shifts(nbk, bk,
1594
+ lambda p, i: UnShiftB(nal + aother, p + bother, i, z),
1595
+ lambda p, i: ShiftB(p[i]))
1596
+
1597
+ for r in sorted(list(abuckets.keys()) + list(bbuckets.keys()), key=default_sort_key):
1598
+ al = ()
1599
+ nal = ()
1600
+ bk = ()
1601
+ nbk = ()
1602
+ if r in abuckets:
1603
+ al = abuckets[r]
1604
+ nal = nabuckets[r]
1605
+ if r in bbuckets:
1606
+ bk = bbuckets[r]
1607
+ nbk = nbbuckets[r]
1608
+ if len(al) != len(nal) or len(bk) != len(nbk):
1609
+ raise ValueError('%s not reachable from %s' % (target, origin))
1610
+
1611
+ al, nal, bk, nbk = [sorted(w, key=default_sort_key)
1612
+ for w in [al, nal, bk, nbk]]
1613
+
1614
+ def others(dic, key):
1615
+ l = []
1616
+ for k, value in dic.items():
1617
+ if k != key:
1618
+ l += list(dic[k])
1619
+ return l
1620
+ aother = others(nabuckets, r)
1621
+ bother = others(nbbuckets, r)
1622
+
1623
+ if len(al) == 0:
1624
+ # there can be no complications, just shift the bs as we please
1625
+ ops += do_shifts_b([], nbk, bk, aother, bother)
1626
+ elif len(bk) == 0:
1627
+ # there can be no complications, just shift the as as we please
1628
+ ops += do_shifts_a(nal, [], al, aother, bother)
1629
+ else:
1630
+ namax = nal[-1]
1631
+ amax = al[-1]
1632
+
1633
+ if nbk[0] - namax <= 0 or bk[0] - amax <= 0:
1634
+ raise ValueError('Non-suitable parameters.')
1635
+
1636
+ if namax - amax > 0:
1637
+ # we are going to shift down - first do the as, then the bs
1638
+ ops += do_shifts_a(nal, nbk, al, aother, bother)
1639
+ ops += do_shifts_b(al, nbk, bk, aother, bother)
1640
+ else:
1641
+ # we are going to shift up - first do the bs, then the as
1642
+ ops += do_shifts_b(nal, nbk, bk, aother, bother)
1643
+ ops += do_shifts_a(nal, bk, al, aother, bother)
1644
+
1645
+ nabuckets[r] = al
1646
+ nbbuckets[r] = bk
1647
+
1648
+ ops.reverse()
1649
+ return ops
1650
+
1651
+
1652
+ def try_shifted_sum(func, z):
1653
+ """ Try to recognise a hypergeometric sum that starts from k > 0. """
1654
+ abuckets, bbuckets = sift(func.ap, _mod1), sift(func.bq, _mod1)
1655
+ if len(abuckets[S.Zero]) != 1:
1656
+ return None
1657
+ r = abuckets[S.Zero][0]
1658
+ if r <= 0:
1659
+ return None
1660
+ if S.Zero not in bbuckets:
1661
+ return None
1662
+ l = list(bbuckets[S.Zero])
1663
+ l.sort()
1664
+ k = l[0]
1665
+ if k <= 0:
1666
+ return None
1667
+
1668
+ nap = list(func.ap)
1669
+ nap.remove(r)
1670
+ nbq = list(func.bq)
1671
+ nbq.remove(k)
1672
+ k -= 1
1673
+ nap = [x - k for x in nap]
1674
+ nbq = [x - k for x in nbq]
1675
+
1676
+ ops = []
1677
+ for n in range(r - 1):
1678
+ ops.append(ShiftA(n + 1))
1679
+ ops.reverse()
1680
+
1681
+ fac = factorial(k)/z**k
1682
+ fac *= Mul(*[rf(b, k) for b in nbq])
1683
+ fac /= Mul(*[rf(a, k) for a in nap])
1684
+
1685
+ ops += [MultOperator(fac)]
1686
+
1687
+ p = 0
1688
+ for n in range(k):
1689
+ m = z**n/factorial(n)
1690
+ m *= Mul(*[rf(a, n) for a in nap])
1691
+ m /= Mul(*[rf(b, n) for b in nbq])
1692
+ p += m
1693
+
1694
+ return Hyper_Function(nap, nbq), ops, -p
1695
+
1696
+
1697
+ def try_polynomial(func, z):
1698
+ """ Recognise polynomial cases. Returns None if not such a case.
1699
+ Requires order to be fully reduced. """
1700
+ abuckets, bbuckets = sift(func.ap, _mod1), sift(func.bq, _mod1)
1701
+ a0 = abuckets[S.Zero]
1702
+ b0 = bbuckets[S.Zero]
1703
+ a0.sort()
1704
+ b0.sort()
1705
+ al0 = [x for x in a0 if x <= 0]
1706
+ bl0 = [x for x in b0 if x <= 0]
1707
+
1708
+ if bl0 and all(a < bl0[-1] for a in al0):
1709
+ return oo
1710
+ if not al0:
1711
+ return None
1712
+
1713
+ a = al0[-1]
1714
+ fac = 1
1715
+ res = S.One
1716
+ for n in Tuple(*list(range(-a))):
1717
+ fac *= z
1718
+ fac /= n + 1
1719
+ fac *= Mul(*[a + n for a in func.ap])
1720
+ fac /= Mul(*[b + n for b in func.bq])
1721
+ res += fac
1722
+ return res
1723
+
1724
+
1725
+ def try_lerchphi(func):
1726
+ """
1727
+ Try to find an expression for Hyper_Function ``func`` in terms of Lerch
1728
+ Transcendents.
1729
+
1730
+ Return None if no such expression can be found.
1731
+ """
1732
+ # This is actually quite simple, and is described in Roach's paper,
1733
+ # section 18.
1734
+ # We don't need to implement the reduction to polylog here, this
1735
+ # is handled by expand_func.
1736
+
1737
+ # First we need to figure out if the summation coefficient is a rational
1738
+ # function of the summation index, and construct that rational function.
1739
+ abuckets, bbuckets = sift(func.ap, _mod1), sift(func.bq, _mod1)
1740
+
1741
+ paired = {}
1742
+ for key, value in abuckets.items():
1743
+ if key != 0 and key not in bbuckets:
1744
+ return None
1745
+ bvalue = bbuckets[key]
1746
+ paired[key] = (list(value), list(bvalue))
1747
+ bbuckets.pop(key, None)
1748
+ if bbuckets != {}:
1749
+ return None
1750
+ if S.Zero not in abuckets:
1751
+ return None
1752
+ aints, bints = paired[S.Zero]
1753
+ # Account for the additional n! in denominator
1754
+ paired[S.Zero] = (aints, bints + [1])
1755
+
1756
+ t = Dummy('t')
1757
+ numer = S.One
1758
+ denom = S.One
1759
+ for key, (avalue, bvalue) in paired.items():
1760
+ if len(avalue) != len(bvalue):
1761
+ return None
1762
+ # Note that since order has been reduced fully, all the b are
1763
+ # bigger than all the a they differ from by an integer. In particular
1764
+ # if there are any negative b left, this function is not well-defined.
1765
+ for a, b in zip(avalue, bvalue):
1766
+ if (a - b).is_positive:
1767
+ k = a - b
1768
+ numer *= rf(b + t, k)
1769
+ denom *= rf(b, k)
1770
+ else:
1771
+ k = b - a
1772
+ numer *= rf(a, k)
1773
+ denom *= rf(a + t, k)
1774
+
1775
+ # Now do a partial fraction decomposition.
1776
+ # We assemble two structures: a list monomials of pairs (a, b) representing
1777
+ # a*t**b (b a non-negative integer), and a dict terms, where
1778
+ # terms[a] = [(b, c)] means that there is a term b/(t-a)**c.
1779
+ part = apart(numer/denom, t)
1780
+ args = Add.make_args(part)
1781
+ monomials = []
1782
+ terms = {}
1783
+ for arg in args:
1784
+ numer, denom = arg.as_numer_denom()
1785
+ if not denom.has(t):
1786
+ p = Poly(numer, t)
1787
+ if not p.is_monomial:
1788
+ raise TypeError("p should be monomial")
1789
+ ((b, ), a) = p.LT()
1790
+ monomials += [(a/denom, b)]
1791
+ continue
1792
+ if numer.has(t):
1793
+ raise NotImplementedError('Need partial fraction decomposition'
1794
+ ' with linear denominators')
1795
+ indep, [dep] = denom.as_coeff_mul(t)
1796
+ n = 1
1797
+ if dep.is_Pow:
1798
+ n = dep.exp
1799
+ dep = dep.base
1800
+ if dep == t:
1801
+ a == 0
1802
+ elif dep.is_Add:
1803
+ a, tmp = dep.as_independent(t)
1804
+ b = 1
1805
+ if tmp != t:
1806
+ b, _ = tmp.as_independent(t)
1807
+ if dep != b*t + a:
1808
+ raise NotImplementedError('unrecognised form %s' % dep)
1809
+ a /= b
1810
+ indep *= b**n
1811
+ else:
1812
+ raise NotImplementedError('unrecognised form of partial fraction')
1813
+ terms.setdefault(a, []).append((numer/indep, n))
1814
+
1815
+ # Now that we have this information, assemble our formula. All the
1816
+ # monomials yield rational functions and go into one basis element.
1817
+ # The terms[a] are related by differentiation. If the largest exponent is
1818
+ # n, we need lerchphi(z, k, a) for k = 1, 2, ..., n.
1819
+ # deriv maps a basis to its derivative, expressed as a C(z)-linear
1820
+ # combination of other basis elements.
1821
+ deriv = {}
1822
+ coeffs = {}
1823
+ z = Dummy('z')
1824
+ monomials.sort(key=lambda x: x[1])
1825
+ mon = {0: 1/(1 - z)}
1826
+ if monomials:
1827
+ for k in range(monomials[-1][1]):
1828
+ mon[k + 1] = z*mon[k].diff(z)
1829
+ for a, n in monomials:
1830
+ coeffs.setdefault(S.One, []).append(a*mon[n])
1831
+ for a, l in terms.items():
1832
+ for c, k in l:
1833
+ coeffs.setdefault(lerchphi(z, k, a), []).append(c)
1834
+ l.sort(key=lambda x: x[1])
1835
+ for k in range(2, l[-1][1] + 1):
1836
+ deriv[lerchphi(z, k, a)] = [(-a, lerchphi(z, k, a)),
1837
+ (1, lerchphi(z, k - 1, a))]
1838
+ deriv[lerchphi(z, 1, a)] = [(-a, lerchphi(z, 1, a)),
1839
+ (1/(1 - z), S.One)]
1840
+ trans = {}
1841
+ for n, b in enumerate([S.One] + list(deriv.keys())):
1842
+ trans[b] = n
1843
+ basis = [expand_func(b) for (b, _) in sorted(trans.items(),
1844
+ key=lambda x:x[1])]
1845
+ B = Matrix(basis)
1846
+ C = Matrix([[0]*len(B)])
1847
+ for b, c in coeffs.items():
1848
+ C[trans[b]] = Add(*c)
1849
+ M = zeros(len(B))
1850
+ for b, l in deriv.items():
1851
+ for c, b2 in l:
1852
+ M[trans[b], trans[b2]] = c
1853
+ return Formula(func, z, None, [], B, C, M)
1854
+
1855
+
1856
+ def build_hypergeometric_formula(func):
1857
+ """
1858
+ Create a formula object representing the hypergeometric function ``func``.
1859
+
1860
+ """
1861
+ # We know that no `ap` are negative integers, otherwise "detect poly"
1862
+ # would have kicked in. However, `ap` could be empty. In this case we can
1863
+ # use a different basis.
1864
+ # I'm not aware of a basis that works in all cases.
1865
+ z = Dummy('z')
1866
+ if func.ap:
1867
+ afactors = [_x + a for a in func.ap]
1868
+ bfactors = [_x + b - 1 for b in func.bq]
1869
+ expr = _x*Mul(*bfactors) - z*Mul(*afactors)
1870
+ poly = Poly(expr, _x)
1871
+ n = poly.degree()
1872
+ basis = []
1873
+ M = zeros(n)
1874
+ for k in range(n):
1875
+ a = func.ap[0] + k
1876
+ basis += [hyper([a] + list(func.ap[1:]), func.bq, z)]
1877
+ if k < n - 1:
1878
+ M[k, k] = -a
1879
+ M[k, k + 1] = a
1880
+ B = Matrix(basis)
1881
+ C = Matrix([[1] + [0]*(n - 1)])
1882
+ derivs = [eye(n)]
1883
+ for k in range(n):
1884
+ derivs.append(M*derivs[k])
1885
+ l = poly.all_coeffs()
1886
+ l.reverse()
1887
+ res = [0]*n
1888
+ for k, c in enumerate(l):
1889
+ for r, d in enumerate(C*derivs[k]):
1890
+ res[r] += c*d
1891
+ for k, c in enumerate(res):
1892
+ M[n - 1, k] = -c/derivs[n - 1][0, n - 1]/poly.all_coeffs()[0]
1893
+ return Formula(func, z, None, [], B, C, M)
1894
+ else:
1895
+ # Since there are no `ap`, none of the `bq` can be non-positive
1896
+ # integers.
1897
+ basis = []
1898
+ bq = list(func.bq[:])
1899
+ for i in range(len(bq)):
1900
+ basis += [hyper([], bq, z)]
1901
+ bq[i] += 1
1902
+ basis += [hyper([], bq, z)]
1903
+ B = Matrix(basis)
1904
+ n = len(B)
1905
+ C = Matrix([[1] + [0]*(n - 1)])
1906
+ M = zeros(n)
1907
+ M[0, n - 1] = z/Mul(*func.bq)
1908
+ for k in range(1, n):
1909
+ M[k, k - 1] = func.bq[k - 1]
1910
+ M[k, k] = -func.bq[k - 1]
1911
+ return Formula(func, z, None, [], B, C, M)
1912
+
1913
+
1914
+ def hyperexpand_special(ap, bq, z):
1915
+ """
1916
+ Try to find a closed-form expression for hyper(ap, bq, z), where ``z``
1917
+ is supposed to be a "special" value, e.g. 1.
1918
+
1919
+ This function tries various of the classical summation formulae
1920
+ (Gauss, Saalschuetz, etc).
1921
+ """
1922
+ # This code is very ad-hoc. There are many clever algorithms
1923
+ # (notably Zeilberger's) related to this problem.
1924
+ # For now we just want a few simple cases to work.
1925
+ p, q = len(ap), len(bq)
1926
+ z_ = z
1927
+ z = unpolarify(z)
1928
+ if z == 0:
1929
+ return S.One
1930
+ from sympy.simplify.simplify import simplify
1931
+ if p == 2 and q == 1:
1932
+ # 2F1
1933
+ a, b, c = ap + bq
1934
+ if z == 1:
1935
+ # Gauss
1936
+ return gamma(c - a - b)*gamma(c)/gamma(c - a)/gamma(c - b)
1937
+ if z == -1 and simplify(b - a + c) == 1:
1938
+ b, a = a, b
1939
+ if z == -1 and simplify(a - b + c) == 1:
1940
+ # Kummer
1941
+ if b.is_integer and b.is_negative:
1942
+ return 2*cos(pi*b/2)*gamma(-b)*gamma(b - a + 1) \
1943
+ /gamma(-b/2)/gamma(b/2 - a + 1)
1944
+ else:
1945
+ return gamma(b/2 + 1)*gamma(b - a + 1) \
1946
+ /gamma(b + 1)/gamma(b/2 - a + 1)
1947
+ # TODO tons of more formulae
1948
+ # investigate what algorithms exist
1949
+ return hyper(ap, bq, z_)
1950
+
1951
+ _collection = None
1952
+
1953
+
1954
+ def _hyperexpand(func, z, ops0=[], z0=Dummy('z0'), premult=1, prem=0,
1955
+ rewrite='default'):
1956
+ """
1957
+ Try to find an expression for the hypergeometric function ``func``.
1958
+
1959
+ Explanation
1960
+ ===========
1961
+
1962
+ The result is expressed in terms of a dummy variable ``z0``. Then it
1963
+ is multiplied by ``premult``. Then ``ops0`` is applied.
1964
+ ``premult`` must be a*z**prem for some a independent of ``z``.
1965
+ """
1966
+
1967
+ if z.is_zero:
1968
+ return S.One
1969
+
1970
+ from sympy.simplify.simplify import simplify
1971
+
1972
+ z = polarify(z, subs=False)
1973
+ if rewrite == 'default':
1974
+ rewrite = 'nonrepsmall'
1975
+
1976
+ def carryout_plan(f, ops):
1977
+ C = apply_operators(f.C.subs(f.z, z0), ops,
1978
+ make_derivative_operator(f.M.subs(f.z, z0), z0))
1979
+ C = apply_operators(C, ops0,
1980
+ make_derivative_operator(f.M.subs(f.z, z0)
1981
+ + prem*eye(f.M.shape[0]), z0))
1982
+
1983
+ if premult == 1:
1984
+ C = C.applyfunc(make_simp(z0))
1985
+ r = reduce(lambda s,m: s+m[0]*m[1], zip(C, f.B.subs(f.z, z0)), S.Zero)*premult
1986
+ res = r.subs(z0, z)
1987
+ if rewrite:
1988
+ res = res.rewrite(rewrite)
1989
+ return res
1990
+
1991
+ # TODO
1992
+ # The following would be possible:
1993
+ # *) PFD Duplication (see Kelly Roach's paper)
1994
+ # *) In a similar spirit, try_lerchphi() can be generalised considerably.
1995
+
1996
+ global _collection
1997
+ if _collection is None:
1998
+ _collection = FormulaCollection()
1999
+
2000
+ debug('Trying to expand hypergeometric function ', func)
2001
+
2002
+ # First reduce order as much as possible.
2003
+ func, ops = reduce_order(func)
2004
+ if ops:
2005
+ debug(' Reduced order to ', func)
2006
+ else:
2007
+ debug(' Could not reduce order.')
2008
+
2009
+ # Now try polynomial cases
2010
+ res = try_polynomial(func, z0)
2011
+ if res is not None:
2012
+ debug(' Recognised polynomial.')
2013
+ p = apply_operators(res, ops, lambda f: z0*f.diff(z0))
2014
+ p = apply_operators(p*premult, ops0, lambda f: z0*f.diff(z0))
2015
+ return unpolarify(simplify(p).subs(z0, z))
2016
+
2017
+ # Try to recognise a shifted sum.
2018
+ p = S.Zero
2019
+ res = try_shifted_sum(func, z0)
2020
+ if res is not None:
2021
+ func, nops, p = res
2022
+ debug(' Recognised shifted sum, reduced order to ', func)
2023
+ ops += nops
2024
+
2025
+ # apply the plan for poly
2026
+ p = apply_operators(p, ops, lambda f: z0*f.diff(z0))
2027
+ p = apply_operators(p*premult, ops0, lambda f: z0*f.diff(z0))
2028
+ p = simplify(p).subs(z0, z)
2029
+
2030
+ # Try special expansions early.
2031
+ if unpolarify(z) in [1, -1] and (len(func.ap), len(func.bq)) == (2, 1):
2032
+ f = build_hypergeometric_formula(func)
2033
+ r = carryout_plan(f, ops).replace(hyper, hyperexpand_special)
2034
+ if not r.has(hyper):
2035
+ return r + p
2036
+
2037
+ # Try to find a formula in our collection
2038
+ formula = _collection.lookup_origin(func)
2039
+
2040
+ # Now try a lerch phi formula
2041
+ if formula is None:
2042
+ formula = try_lerchphi(func)
2043
+
2044
+ if formula is None:
2045
+ debug(' Could not find an origin. ',
2046
+ 'Will return answer in terms of '
2047
+ 'simpler hypergeometric functions.')
2048
+ formula = build_hypergeometric_formula(func)
2049
+
2050
+ debug(' Found an origin: ', formula.closed_form, ' ', formula.func)
2051
+
2052
+ # We need to find the operators that convert formula into func.
2053
+ ops += devise_plan(func, formula.func, z0)
2054
+
2055
+ # Now carry out the plan.
2056
+ r = carryout_plan(formula, ops) + p
2057
+
2058
+ return powdenest(r, polar=True).replace(hyper, hyperexpand_special)
2059
+
2060
+
2061
+ def devise_plan_meijer(fro, to, z):
2062
+ """
2063
+ Find operators to convert G-function ``fro`` into G-function ``to``.
2064
+
2065
+ Explanation
2066
+ ===========
2067
+
2068
+ It is assumed that ``fro`` and ``to`` have the same signatures, and that in fact
2069
+ any corresponding pair of parameters differs by integers, and a direct path
2070
+ is possible. I.e. if there are parameters a1 b1 c1 and a2 b2 c2 it is
2071
+ assumed that a1 can be shifted to a2, etc. The only thing this routine
2072
+ determines is the order of shifts to apply, nothing clever will be tried.
2073
+ It is also assumed that ``fro`` is suitable.
2074
+
2075
+ Examples
2076
+ ========
2077
+
2078
+ >>> from sympy.simplify.hyperexpand import (devise_plan_meijer,
2079
+ ... G_Function)
2080
+ >>> from sympy.abc import z
2081
+
2082
+ Empty plan:
2083
+
2084
+ >>> devise_plan_meijer(G_Function([1], [2], [3], [4]),
2085
+ ... G_Function([1], [2], [3], [4]), z)
2086
+ []
2087
+
2088
+ Very simple plans:
2089
+
2090
+ >>> devise_plan_meijer(G_Function([0], [], [], []),
2091
+ ... G_Function([1], [], [], []), z)
2092
+ [<Increment upper a index #0 of [0], [], [], [].>]
2093
+ >>> devise_plan_meijer(G_Function([0], [], [], []),
2094
+ ... G_Function([-1], [], [], []), z)
2095
+ [<Decrement upper a=0.>]
2096
+ >>> devise_plan_meijer(G_Function([], [1], [], []),
2097
+ ... G_Function([], [2], [], []), z)
2098
+ [<Increment lower a index #0 of [], [1], [], [].>]
2099
+
2100
+ Slightly more complicated plans:
2101
+
2102
+ >>> devise_plan_meijer(G_Function([0], [], [], []),
2103
+ ... G_Function([2], [], [], []), z)
2104
+ [<Increment upper a index #0 of [1], [], [], [].>,
2105
+ <Increment upper a index #0 of [0], [], [], [].>]
2106
+ >>> devise_plan_meijer(G_Function([0], [], [0], []),
2107
+ ... G_Function([-1], [], [1], []), z)
2108
+ [<Increment upper b=0.>, <Decrement upper a=0.>]
2109
+
2110
+ Order matters:
2111
+
2112
+ >>> devise_plan_meijer(G_Function([0], [], [0], []),
2113
+ ... G_Function([1], [], [1], []), z)
2114
+ [<Increment upper a index #0 of [0], [], [1], [].>, <Increment upper b=0.>]
2115
+ """
2116
+ # TODO for now, we use the following simple heuristic: inverse-shift
2117
+ # when possible, shift otherwise. Give up if we cannot make progress.
2118
+
2119
+ def try_shift(f, t, shifter, diff, counter):
2120
+ """ Try to apply ``shifter`` in order to bring some element in ``f``
2121
+ nearer to its counterpart in ``to``. ``diff`` is +/- 1 and
2122
+ determines the effect of ``shifter``. Counter is a list of elements
2123
+ blocking the shift.
2124
+
2125
+ Return an operator if change was possible, else None.
2126
+ """
2127
+ for idx, (a, b) in enumerate(zip(f, t)):
2128
+ if (
2129
+ (a - b).is_integer and (b - a)/diff > 0 and
2130
+ all(a != x for x in counter)):
2131
+ sh = shifter(idx)
2132
+ f[idx] += diff
2133
+ return sh
2134
+ fan = list(fro.an)
2135
+ fap = list(fro.ap)
2136
+ fbm = list(fro.bm)
2137
+ fbq = list(fro.bq)
2138
+ ops = []
2139
+ change = True
2140
+ while change:
2141
+ change = False
2142
+ op = try_shift(fan, to.an,
2143
+ lambda i: MeijerUnShiftB(fan, fap, fbm, fbq, i, z),
2144
+ 1, fbm + fbq)
2145
+ if op is not None:
2146
+ ops += [op]
2147
+ change = True
2148
+ continue
2149
+ op = try_shift(fap, to.ap,
2150
+ lambda i: MeijerUnShiftD(fan, fap, fbm, fbq, i, z),
2151
+ 1, fbm + fbq)
2152
+ if op is not None:
2153
+ ops += [op]
2154
+ change = True
2155
+ continue
2156
+ op = try_shift(fbm, to.bm,
2157
+ lambda i: MeijerUnShiftA(fan, fap, fbm, fbq, i, z),
2158
+ -1, fan + fap)
2159
+ if op is not None:
2160
+ ops += [op]
2161
+ change = True
2162
+ continue
2163
+ op = try_shift(fbq, to.bq,
2164
+ lambda i: MeijerUnShiftC(fan, fap, fbm, fbq, i, z),
2165
+ -1, fan + fap)
2166
+ if op is not None:
2167
+ ops += [op]
2168
+ change = True
2169
+ continue
2170
+ op = try_shift(fan, to.an, lambda i: MeijerShiftB(fan[i]), -1, [])
2171
+ if op is not None:
2172
+ ops += [op]
2173
+ change = True
2174
+ continue
2175
+ op = try_shift(fap, to.ap, lambda i: MeijerShiftD(fap[i]), -1, [])
2176
+ if op is not None:
2177
+ ops += [op]
2178
+ change = True
2179
+ continue
2180
+ op = try_shift(fbm, to.bm, lambda i: MeijerShiftA(fbm[i]), 1, [])
2181
+ if op is not None:
2182
+ ops += [op]
2183
+ change = True
2184
+ continue
2185
+ op = try_shift(fbq, to.bq, lambda i: MeijerShiftC(fbq[i]), 1, [])
2186
+ if op is not None:
2187
+ ops += [op]
2188
+ change = True
2189
+ continue
2190
+ if fan != list(to.an) or fap != list(to.ap) or fbm != list(to.bm) or \
2191
+ fbq != list(to.bq):
2192
+ raise NotImplementedError('Could not devise plan.')
2193
+ ops.reverse()
2194
+ return ops
2195
+
2196
+ _meijercollection = None
2197
+
2198
+
2199
+ def _meijergexpand(func, z0, allow_hyper=False, rewrite='default',
2200
+ place=None):
2201
+ """
2202
+ Try to find an expression for the Meijer G function specified
2203
+ by the G_Function ``func``. If ``allow_hyper`` is True, then returning
2204
+ an expression in terms of hypergeometric functions is allowed.
2205
+
2206
+ Currently this just does Slater's theorem.
2207
+ If expansions exist both at zero and at infinity, ``place``
2208
+ can be set to ``0`` or ``zoo`` for the preferred choice.
2209
+ """
2210
+ global _meijercollection
2211
+ if _meijercollection is None:
2212
+ _meijercollection = MeijerFormulaCollection()
2213
+ if rewrite == 'default':
2214
+ rewrite = None
2215
+
2216
+ func0 = func
2217
+ debug('Try to expand Meijer G function corresponding to ', func)
2218
+
2219
+ # We will play games with analytic continuation - rather use a fresh symbol
2220
+ z = Dummy('z')
2221
+
2222
+ func, ops = reduce_order_meijer(func)
2223
+ if ops:
2224
+ debug(' Reduced order to ', func)
2225
+ else:
2226
+ debug(' Could not reduce order.')
2227
+
2228
+ # Try to find a direct formula
2229
+ f = _meijercollection.lookup_origin(func)
2230
+ if f is not None:
2231
+ debug(' Found a Meijer G formula: ', f.func)
2232
+ ops += devise_plan_meijer(f.func, func, z)
2233
+
2234
+ # Now carry out the plan.
2235
+ C = apply_operators(f.C.subs(f.z, z), ops,
2236
+ make_derivative_operator(f.M.subs(f.z, z), z))
2237
+
2238
+ C = C.applyfunc(make_simp(z))
2239
+ r = C*f.B.subs(f.z, z)
2240
+ r = r[0].subs(z, z0)
2241
+ return powdenest(r, polar=True)
2242
+
2243
+ debug(" Could not find a direct formula. Trying Slater's theorem.")
2244
+
2245
+ # TODO the following would be possible:
2246
+ # *) Paired Index Theorems
2247
+ # *) PFD Duplication
2248
+ # (See Kelly Roach's paper for details on either.)
2249
+ #
2250
+ # TODO Also, we tend to create combinations of gamma functions that can be
2251
+ # simplified.
2252
+
2253
+ def can_do(pbm, pap):
2254
+ """ Test if slater applies. """
2255
+ for i in pbm:
2256
+ if len(pbm[i]) > 1:
2257
+ l = 0
2258
+ if i in pap:
2259
+ l = len(pap[i])
2260
+ if l + 1 < len(pbm[i]):
2261
+ return False
2262
+ return True
2263
+
2264
+ def do_slater(an, bm, ap, bq, z, zfinal):
2265
+ # zfinal is the value that will eventually be substituted for z.
2266
+ # We pass it to _hyperexpand to improve performance.
2267
+ func = G_Function(an, bm, ap, bq)
2268
+ _, pbm, pap, _ = func.compute_buckets()
2269
+ if not can_do(pbm, pap):
2270
+ return S.Zero, False
2271
+
2272
+ cond = len(an) + len(ap) < len(bm) + len(bq)
2273
+ if len(an) + len(ap) == len(bm) + len(bq):
2274
+ cond = abs(z) < 1
2275
+ if cond is False:
2276
+ return S.Zero, False
2277
+
2278
+ res = S.Zero
2279
+ for m in pbm:
2280
+ if len(pbm[m]) == 1:
2281
+ bh = pbm[m][0]
2282
+ fac = 1
2283
+ bo = list(bm)
2284
+ bo.remove(bh)
2285
+ for bj in bo:
2286
+ fac *= gamma(bj - bh)
2287
+ for aj in an:
2288
+ fac *= gamma(1 + bh - aj)
2289
+ for bj in bq:
2290
+ fac /= gamma(1 + bh - bj)
2291
+ for aj in ap:
2292
+ fac /= gamma(aj - bh)
2293
+ nap = [1 + bh - a for a in list(an) + list(ap)]
2294
+ nbq = [1 + bh - b for b in list(bo) + list(bq)]
2295
+
2296
+ k = polar_lift(S.NegativeOne**(len(ap) - len(bm)))
2297
+ harg = k*zfinal
2298
+ # NOTE even though k "is" +-1, this has to be t/k instead of
2299
+ # t*k ... we are using polar numbers for consistency!
2300
+ premult = (t/k)**bh
2301
+ hyp = _hyperexpand(Hyper_Function(nap, nbq), harg, ops,
2302
+ t, premult, bh, rewrite=None)
2303
+ res += fac * hyp
2304
+ else:
2305
+ b_ = pbm[m][0]
2306
+ ki = [bi - b_ for bi in pbm[m][1:]]
2307
+ u = len(ki)
2308
+ li = [ai - b_ for ai in pap[m][:u + 1]]
2309
+ bo = list(bm)
2310
+ for b in pbm[m]:
2311
+ bo.remove(b)
2312
+ ao = list(ap)
2313
+ for a in pap[m][:u]:
2314
+ ao.remove(a)
2315
+ lu = li[-1]
2316
+ di = [l - k for (l, k) in zip(li, ki)]
2317
+
2318
+ # We first work out the integrand:
2319
+ s = Dummy('s')
2320
+ integrand = z**s
2321
+ for b in bm:
2322
+ if not Mod(b, 1) and b.is_Number:
2323
+ b = int(round(b))
2324
+ integrand *= gamma(b - s)
2325
+ for a in an:
2326
+ integrand *= gamma(1 - a + s)
2327
+ for b in bq:
2328
+ integrand /= gamma(1 - b + s)
2329
+ for a in ap:
2330
+ integrand /= gamma(a - s)
2331
+
2332
+ # Now sum the finitely many residues:
2333
+ # XXX This speeds up some cases - is it a good idea?
2334
+ integrand = expand_func(integrand)
2335
+ for r in range(int(round(lu))):
2336
+ resid = residue(integrand, s, b_ + r)
2337
+ resid = apply_operators(resid, ops, lambda f: z*f.diff(z))
2338
+ res -= resid
2339
+
2340
+ # Now the hypergeometric term.
2341
+ au = b_ + lu
2342
+ k = polar_lift(S.NegativeOne**(len(ao) + len(bo) + 1))
2343
+ harg = k*zfinal
2344
+ premult = (t/k)**au
2345
+ nap = [1 + au - a for a in list(an) + list(ap)] + [1]
2346
+ nbq = [1 + au - b for b in list(bm) + list(bq)]
2347
+
2348
+ hyp = _hyperexpand(Hyper_Function(nap, nbq), harg, ops,
2349
+ t, premult, au, rewrite=None)
2350
+
2351
+ C = S.NegativeOne**(lu)/factorial(lu)
2352
+ for i in range(u):
2353
+ C *= S.NegativeOne**di[i]/rf(lu - li[i] + 1, di[i])
2354
+ for a in an:
2355
+ C *= gamma(1 - a + au)
2356
+ for b in bo:
2357
+ C *= gamma(b - au)
2358
+ for a in ao:
2359
+ C /= gamma(a - au)
2360
+ for b in bq:
2361
+ C /= gamma(1 - b + au)
2362
+
2363
+ res += C*hyp
2364
+
2365
+ return res, cond
2366
+
2367
+ t = Dummy('t')
2368
+ slater1, cond1 = do_slater(func.an, func.bm, func.ap, func.bq, z, z0)
2369
+
2370
+ def tr(l):
2371
+ return [1 - x for x in l]
2372
+
2373
+ for op in ops:
2374
+ op._poly = Poly(op._poly.subs({z: 1/t, _x: -_x}), _x)
2375
+ slater2, cond2 = do_slater(tr(func.bm), tr(func.an), tr(func.bq), tr(func.ap),
2376
+ t, 1/z0)
2377
+
2378
+ slater1 = powdenest(slater1.subs(z, z0), polar=True)
2379
+ slater2 = powdenest(slater2.subs(t, 1/z0), polar=True)
2380
+ if not isinstance(cond2, bool):
2381
+ cond2 = cond2.subs(t, 1/z)
2382
+
2383
+ m = func(z)
2384
+ if m.delta > 0 or \
2385
+ (m.delta == 0 and len(m.ap) == len(m.bq) and
2386
+ (re(m.nu) < -1) is not False and polar_lift(z0) == polar_lift(1)):
2387
+ # The condition delta > 0 means that the convergence region is
2388
+ # connected. Any expression we find can be continued analytically
2389
+ # to the entire convergence region.
2390
+ # The conditions delta==0, p==q, re(nu) < -1 imply that G is continuous
2391
+ # on the positive reals, so the values at z=1 agree.
2392
+ if cond1 is not False:
2393
+ cond1 = True
2394
+ if cond2 is not False:
2395
+ cond2 = True
2396
+
2397
+ if cond1 is True:
2398
+ slater1 = slater1.rewrite(rewrite or 'nonrep')
2399
+ else:
2400
+ slater1 = slater1.rewrite(rewrite or 'nonrepsmall')
2401
+ if cond2 is True:
2402
+ slater2 = slater2.rewrite(rewrite or 'nonrep')
2403
+ else:
2404
+ slater2 = slater2.rewrite(rewrite or 'nonrepsmall')
2405
+
2406
+ if cond1 is not False and cond2 is not False:
2407
+ # If one condition is False, there is no choice.
2408
+ if place == 0:
2409
+ cond2 = False
2410
+ if place == zoo:
2411
+ cond1 = False
2412
+
2413
+ if not isinstance(cond1, bool):
2414
+ cond1 = cond1.subs(z, z0)
2415
+ if not isinstance(cond2, bool):
2416
+ cond2 = cond2.subs(z, z0)
2417
+
2418
+ def weight(expr, cond):
2419
+ if cond is True:
2420
+ c0 = 0
2421
+ elif cond is False:
2422
+ c0 = 1
2423
+ else:
2424
+ c0 = 2
2425
+ if expr.has(oo, zoo, -oo, nan):
2426
+ # XXX this actually should not happen, but consider
2427
+ # S('meijerg(((0, -1/2, 0, -1/2, 1/2), ()), ((0,),
2428
+ # (-1/2, -1/2, -1/2, -1)), exp_polar(I*pi))/4')
2429
+ c0 = 3
2430
+ return (c0, expr.count(hyper), expr.count_ops())
2431
+
2432
+ w1 = weight(slater1, cond1)
2433
+ w2 = weight(slater2, cond2)
2434
+ if min(w1, w2) <= (0, 1, oo):
2435
+ if w1 < w2:
2436
+ return slater1
2437
+ else:
2438
+ return slater2
2439
+ if max(w1[0], w2[0]) <= 1 and max(w1[1], w2[1]) <= 1:
2440
+ return Piecewise((slater1, cond1), (slater2, cond2), (func0(z0), True))
2441
+
2442
+ # We couldn't find an expression without hypergeometric functions.
2443
+ # TODO it would be helpful to give conditions under which the integral
2444
+ # is known to diverge.
2445
+ r = Piecewise((slater1, cond1), (slater2, cond2), (func0(z0), True))
2446
+ if r.has(hyper) and not allow_hyper:
2447
+ debug(' Could express using hypergeometric functions, '
2448
+ 'but not allowed.')
2449
+ if not r.has(hyper) or allow_hyper:
2450
+ return r
2451
+
2452
+ return func0(z0)
2453
+
2454
+
2455
+ def hyperexpand(f, allow_hyper=False, rewrite='default', place=None):
2456
+ """
2457
+ Expand hypergeometric functions. If allow_hyper is True, allow partial
2458
+ simplification (that is a result different from input,
2459
+ but still containing hypergeometric functions).
2460
+
2461
+ If a G-function has expansions both at zero and at infinity,
2462
+ ``place`` can be set to ``0`` or ``zoo`` to indicate the
2463
+ preferred choice.
2464
+
2465
+ Examples
2466
+ ========
2467
+
2468
+ >>> from sympy.simplify.hyperexpand import hyperexpand
2469
+ >>> from sympy.functions import hyper
2470
+ >>> from sympy.abc import z
2471
+ >>> hyperexpand(hyper([], [], z))
2472
+ exp(z)
2473
+
2474
+ Non-hyperegeometric parts of the expression and hypergeometric expressions
2475
+ that are not recognised are left unchanged:
2476
+
2477
+ >>> hyperexpand(1 + hyper([1, 1, 1], [], z))
2478
+ hyper((1, 1, 1), (), z) + 1
2479
+ """
2480
+ f = sympify(f)
2481
+
2482
+ def do_replace(ap, bq, z):
2483
+ r = _hyperexpand(Hyper_Function(ap, bq), z, rewrite=rewrite)
2484
+ if r is None:
2485
+ return hyper(ap, bq, z)
2486
+ else:
2487
+ return r
2488
+
2489
+ def do_meijer(ap, bq, z):
2490
+ r = _meijergexpand(G_Function(ap[0], ap[1], bq[0], bq[1]), z,
2491
+ allow_hyper, rewrite=rewrite, place=place)
2492
+ if not r.has(nan, zoo, oo, -oo):
2493
+ return r
2494
+ return f.replace(hyper, do_replace).replace(meijerg, do_meijer)
llmeval-env/lib/python3.10/site-packages/sympy/simplify/ratsimp.py ADDED
@@ -0,0 +1,222 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from itertools import combinations_with_replacement
2
+ from sympy.core import symbols, Add, Dummy
3
+ from sympy.core.numbers import Rational
4
+ from sympy.polys import cancel, ComputationFailed, parallel_poly_from_expr, reduced, Poly
5
+ from sympy.polys.monomials import Monomial, monomial_div
6
+ from sympy.polys.polyerrors import DomainError, PolificationFailed
7
+ from sympy.utilities.misc import debug, debugf
8
+
9
+ def ratsimp(expr):
10
+ """
11
+ Put an expression over a common denominator, cancel and reduce.
12
+
13
+ Examples
14
+ ========
15
+
16
+ >>> from sympy import ratsimp
17
+ >>> from sympy.abc import x, y
18
+ >>> ratsimp(1/x + 1/y)
19
+ (x + y)/(x*y)
20
+ """
21
+
22
+ f, g = cancel(expr).as_numer_denom()
23
+ try:
24
+ Q, r = reduced(f, [g], field=True, expand=False)
25
+ except ComputationFailed:
26
+ return f/g
27
+
28
+ return Add(*Q) + cancel(r/g)
29
+
30
+
31
+ def ratsimpmodprime(expr, G, *gens, quick=True, polynomial=False, **args):
32
+ """
33
+ Simplifies a rational expression ``expr`` modulo the prime ideal
34
+ generated by ``G``. ``G`` should be a Groebner basis of the
35
+ ideal.
36
+
37
+ Examples
38
+ ========
39
+
40
+ >>> from sympy.simplify.ratsimp import ratsimpmodprime
41
+ >>> from sympy.abc import x, y
42
+ >>> eq = (x + y**5 + y)/(x - y)
43
+ >>> ratsimpmodprime(eq, [x*y**5 - x - y], x, y, order='lex')
44
+ (-x**2 - x*y - x - y)/(-x**2 + x*y)
45
+
46
+ If ``polynomial`` is ``False``, the algorithm computes a rational
47
+ simplification which minimizes the sum of the total degrees of
48
+ the numerator and the denominator.
49
+
50
+ If ``polynomial`` is ``True``, this function just brings numerator and
51
+ denominator into a canonical form. This is much faster, but has
52
+ potentially worse results.
53
+
54
+ References
55
+ ==========
56
+
57
+ .. [1] M. Monagan, R. Pearce, Rational Simplification Modulo a Polynomial
58
+ Ideal, https://dl.acm.org/doi/pdf/10.1145/1145768.1145809
59
+ (specifically, the second algorithm)
60
+ """
61
+ from sympy.solvers.solvers import solve
62
+
63
+ debug('ratsimpmodprime', expr)
64
+
65
+ # usual preparation of polynomials:
66
+
67
+ num, denom = cancel(expr).as_numer_denom()
68
+
69
+ try:
70
+ polys, opt = parallel_poly_from_expr([num, denom] + G, *gens, **args)
71
+ except PolificationFailed:
72
+ return expr
73
+
74
+ domain = opt.domain
75
+
76
+ if domain.has_assoc_Field:
77
+ opt.domain = domain.get_field()
78
+ else:
79
+ raise DomainError(
80
+ "Cannot compute rational simplification over %s" % domain)
81
+
82
+ # compute only once
83
+ leading_monomials = [g.LM(opt.order) for g in polys[2:]]
84
+ tested = set()
85
+
86
+ def staircase(n):
87
+ """
88
+ Compute all monomials with degree less than ``n`` that are
89
+ not divisible by any element of ``leading_monomials``.
90
+ """
91
+ if n == 0:
92
+ return [1]
93
+ S = []
94
+ for mi in combinations_with_replacement(range(len(opt.gens)), n):
95
+ m = [0]*len(opt.gens)
96
+ for i in mi:
97
+ m[i] += 1
98
+ if all(monomial_div(m, lmg) is None for lmg in
99
+ leading_monomials):
100
+ S.append(m)
101
+
102
+ return [Monomial(s).as_expr(*opt.gens) for s in S] + staircase(n - 1)
103
+
104
+ def _ratsimpmodprime(a, b, allsol, N=0, D=0):
105
+ r"""
106
+ Computes a rational simplification of ``a/b`` which minimizes
107
+ the sum of the total degrees of the numerator and the denominator.
108
+
109
+ Explanation
110
+ ===========
111
+
112
+ The algorithm proceeds by looking at ``a * d - b * c`` modulo
113
+ the ideal generated by ``G`` for some ``c`` and ``d`` with degree
114
+ less than ``a`` and ``b`` respectively.
115
+ The coefficients of ``c`` and ``d`` are indeterminates and thus
116
+ the coefficients of the normalform of ``a * d - b * c`` are
117
+ linear polynomials in these indeterminates.
118
+ If these linear polynomials, considered as system of
119
+ equations, have a nontrivial solution, then `\frac{a}{b}
120
+ \equiv \frac{c}{d}` modulo the ideal generated by ``G``. So,
121
+ by construction, the degree of ``c`` and ``d`` is less than
122
+ the degree of ``a`` and ``b``, so a simpler representation
123
+ has been found.
124
+ After a simpler representation has been found, the algorithm
125
+ tries to reduce the degree of the numerator and denominator
126
+ and returns the result afterwards.
127
+
128
+ As an extension, if quick=False, we look at all possible degrees such
129
+ that the total degree is less than *or equal to* the best current
130
+ solution. We retain a list of all solutions of minimal degree, and try
131
+ to find the best one at the end.
132
+ """
133
+ c, d = a, b
134
+ steps = 0
135
+
136
+ maxdeg = a.total_degree() + b.total_degree()
137
+ if quick:
138
+ bound = maxdeg - 1
139
+ else:
140
+ bound = maxdeg
141
+ while N + D <= bound:
142
+ if (N, D) in tested:
143
+ break
144
+ tested.add((N, D))
145
+
146
+ M1 = staircase(N)
147
+ M2 = staircase(D)
148
+ debugf('%s / %s: %s, %s', (N, D, M1, M2))
149
+
150
+ Cs = symbols("c:%d" % len(M1), cls=Dummy)
151
+ Ds = symbols("d:%d" % len(M2), cls=Dummy)
152
+ ng = Cs + Ds
153
+
154
+ c_hat = Poly(
155
+ sum([Cs[i] * M1[i] for i in range(len(M1))]), opt.gens + ng)
156
+ d_hat = Poly(
157
+ sum([Ds[i] * M2[i] for i in range(len(M2))]), opt.gens + ng)
158
+
159
+ r = reduced(a * d_hat - b * c_hat, G, opt.gens + ng,
160
+ order=opt.order, polys=True)[1]
161
+
162
+ S = Poly(r, gens=opt.gens).coeffs()
163
+ sol = solve(S, Cs + Ds, particular=True, quick=True)
164
+
165
+ if sol and not all(s == 0 for s in sol.values()):
166
+ c = c_hat.subs(sol)
167
+ d = d_hat.subs(sol)
168
+
169
+ # The "free" variables occurring before as parameters
170
+ # might still be in the substituted c, d, so set them
171
+ # to the value chosen before:
172
+ c = c.subs(dict(list(zip(Cs + Ds, [1] * (len(Cs) + len(Ds))))))
173
+ d = d.subs(dict(list(zip(Cs + Ds, [1] * (len(Cs) + len(Ds))))))
174
+
175
+ c = Poly(c, opt.gens)
176
+ d = Poly(d, opt.gens)
177
+ if d == 0:
178
+ raise ValueError('Ideal not prime?')
179
+
180
+ allsol.append((c_hat, d_hat, S, Cs + Ds))
181
+ if N + D != maxdeg:
182
+ allsol = [allsol[-1]]
183
+
184
+ break
185
+
186
+ steps += 1
187
+ N += 1
188
+ D += 1
189
+
190
+ if steps > 0:
191
+ c, d, allsol = _ratsimpmodprime(c, d, allsol, N, D - steps)
192
+ c, d, allsol = _ratsimpmodprime(c, d, allsol, N - steps, D)
193
+
194
+ return c, d, allsol
195
+
196
+ # preprocessing. this improves performance a bit when deg(num)
197
+ # and deg(denom) are large:
198
+ num = reduced(num, G, opt.gens, order=opt.order)[1]
199
+ denom = reduced(denom, G, opt.gens, order=opt.order)[1]
200
+
201
+ if polynomial:
202
+ return (num/denom).cancel()
203
+
204
+ c, d, allsol = _ratsimpmodprime(
205
+ Poly(num, opt.gens, domain=opt.domain), Poly(denom, opt.gens, domain=opt.domain), [])
206
+ if not quick and allsol:
207
+ debugf('Looking for best minimal solution. Got: %s', len(allsol))
208
+ newsol = []
209
+ for c_hat, d_hat, S, ng in allsol:
210
+ sol = solve(S, ng, particular=True, quick=False)
211
+ # all values of sol should be numbers; if not, solve is broken
212
+ newsol.append((c_hat.subs(sol), d_hat.subs(sol)))
213
+ c, d = min(newsol, key=lambda x: len(x[0].terms()) + len(x[1].terms()))
214
+
215
+ if not domain.is_Field:
216
+ cn, c = c.clear_denoms(convert=True)
217
+ dn, d = d.clear_denoms(convert=True)
218
+ r = Rational(cn, dn)
219
+ else:
220
+ r = Rational(1)
221
+
222
+ return (c*r.q)/(d*r.p)
llmeval-env/lib/python3.10/site-packages/sympy/simplify/tests/__init__.py ADDED
File without changes
llmeval-env/lib/python3.10/site-packages/sympy/simplify/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (193 Bytes). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/simplify/tests/__pycache__/test_cse.cpython-310.pyc ADDED
Binary file (29 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/simplify/tests/__pycache__/test_epathtools.cpython-310.pyc ADDED
Binary file (3.96 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/simplify/tests/__pycache__/test_fu.cpython-310.pyc ADDED
Binary file (21.1 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/simplify/tests/__pycache__/test_function.cpython-310.pyc ADDED
Binary file (2.39 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/simplify/tests/__pycache__/test_gammasimp.cpython-310.pyc ADDED
Binary file (4.86 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/simplify/tests/__pycache__/test_hyperexpand.cpython-310.pyc ADDED
Binary file (36.1 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/simplify/tests/__pycache__/test_powsimp.cpython-310.pyc ADDED
Binary file (14.6 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/simplify/tests/__pycache__/test_radsimp.cpython-310.pyc ADDED
Binary file (19.8 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/simplify/tests/__pycache__/test_ratsimp.cpython-310.pyc ADDED
Binary file (2.68 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/simplify/tests/__pycache__/test_rewrite.cpython-310.pyc ADDED
Binary file (1.33 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/simplify/tests/__pycache__/test_simplify.cpython-310.pyc ADDED
Binary file (44 kB). View file