applied-ai-018 commited on
Commit
24091ef
·
verified ·
1 Parent(s): 18481c2

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. env-llmeval/lib/python3.10/site-packages/sympy/concrete/tests/__init__.py +0 -0
  2. env-llmeval/lib/python3.10/site-packages/sympy/concrete/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  3. env-llmeval/lib/python3.10/site-packages/sympy/concrete/tests/__pycache__/test_gosper.cpython-310.pyc +0 -0
  4. env-llmeval/lib/python3.10/site-packages/sympy/concrete/tests/__pycache__/test_sums_products.cpython-310.pyc +0 -0
  5. env-llmeval/lib/python3.10/site-packages/sympy/concrete/tests/test_delta.py +499 -0
  6. env-llmeval/lib/python3.10/site-packages/sympy/concrete/tests/test_gosper.py +204 -0
  7. env-llmeval/lib/python3.10/site-packages/sympy/concrete/tests/test_guess.py +82 -0
  8. env-llmeval/lib/python3.10/site-packages/sympy/concrete/tests/test_products.py +410 -0
  9. env-llmeval/lib/python3.10/site-packages/sympy/concrete/tests/test_sums_products.py +1646 -0
  10. env-llmeval/lib/python3.10/site-packages/sympy/printing/aesaracode.py +539 -0
  11. env-llmeval/lib/python3.10/site-packages/sympy/printing/c.py +747 -0
  12. env-llmeval/lib/python3.10/site-packages/sympy/printing/conventions.py +88 -0
  13. env-llmeval/lib/python3.10/site-packages/sympy/printing/dot.py +294 -0
  14. env-llmeval/lib/python3.10/site-packages/sympy/printing/precedence.py +177 -0
  15. env-llmeval/lib/python3.10/site-packages/sympy/printing/rcode.py +410 -0
  16. env-llmeval/lib/python3.10/site-packages/sympy/printing/rust.py +625 -0
  17. env-llmeval/lib/python3.10/site-packages/sympy/printing/smtlib.py +526 -0
  18. env-llmeval/lib/python3.10/site-packages/sympy/printing/tableform.py +366 -0
  19. env-llmeval/lib/python3.10/site-packages/sympy/printing/tensorflow.py +216 -0
  20. env-llmeval/lib/python3.10/site-packages/sympy/utilities/__pycache__/autowrap.cpython-310.pyc +0 -0
  21. env-llmeval/lib/python3.10/site-packages/sympy/utilities/__pycache__/decorator.cpython-310.pyc +0 -0
  22. env-llmeval/lib/python3.10/site-packages/sympy/utilities/__pycache__/lambdify.cpython-310.pyc +0 -0
  23. env-llmeval/lib/python3.10/site-packages/sympy/utilities/__pycache__/magic.cpython-310.pyc +0 -0
  24. env-llmeval/lib/python3.10/site-packages/sympy/utilities/__pycache__/misc.cpython-310.pyc +0 -0
  25. env-llmeval/lib/python3.10/site-packages/sympy/utilities/__pycache__/pytest.cpython-310.pyc +0 -0
  26. env-llmeval/lib/python3.10/site-packages/sympy/utilities/__pycache__/runtests.cpython-310.pyc +0 -0
  27. env-llmeval/lib/python3.10/site-packages/sympy/utilities/_compilation/__init__.py +22 -0
  28. env-llmeval/lib/python3.10/site-packages/sympy/utilities/_compilation/__pycache__/__init__.cpython-310.pyc +0 -0
  29. env-llmeval/lib/python3.10/site-packages/sympy/utilities/_compilation/__pycache__/availability.cpython-310.pyc +0 -0
  30. env-llmeval/lib/python3.10/site-packages/sympy/utilities/_compilation/__pycache__/compilation.cpython-310.pyc +0 -0
  31. env-llmeval/lib/python3.10/site-packages/sympy/utilities/_compilation/__pycache__/runners.cpython-310.pyc +0 -0
  32. env-llmeval/lib/python3.10/site-packages/sympy/utilities/_compilation/__pycache__/util.cpython-310.pyc +0 -0
  33. env-llmeval/lib/python3.10/site-packages/sympy/utilities/_compilation/availability.py +77 -0
  34. env-llmeval/lib/python3.10/site-packages/sympy/utilities/_compilation/compilation.py +648 -0
  35. env-llmeval/lib/python3.10/site-packages/sympy/utilities/_compilation/tests/__init__.py +0 -0
  36. env-llmeval/lib/python3.10/site-packages/sympy/utilities/_compilation/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  37. env-llmeval/lib/python3.10/site-packages/sympy/utilities/_compilation/tests/__pycache__/test_compilation.cpython-310.pyc +0 -0
  38. env-llmeval/lib/python3.10/site-packages/sympy/utilities/_compilation/tests/test_compilation.py +62 -0
  39. env-llmeval/lib/python3.10/site-packages/sympy/utilities/_compilation/util.py +287 -0
  40. env-llmeval/lib/python3.10/site-packages/sympy/utilities/mathml/__init__.py +79 -0
  41. env-llmeval/lib/python3.10/site-packages/sympy/utilities/mathml/__pycache__/__init__.cpython-310.pyc +0 -0
  42. env-llmeval/lib/python3.10/site-packages/sympy/utilities/mathml/data/mmlctop.xsl +0 -0
  43. env-llmeval/lib/python3.10/site-packages/sympy/utilities/mathml/data/mmltex.xsl +0 -0
  44. env-llmeval/lib/python3.10/site-packages/sympy/utilities/mathml/data/simple_mmlctop.xsl +0 -0
  45. env-llmeval/lib/python3.10/site-packages/sympy/utilities/pytest.py +12 -0
  46. env-llmeval/lib/python3.10/site-packages/sympy/utilities/tests/__init__.py +0 -0
  47. env-llmeval/lib/python3.10/site-packages/sympy/utilities/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  48. env-llmeval/lib/python3.10/site-packages/sympy/utilities/tests/__pycache__/test_autowrap.cpython-310.pyc +0 -0
  49. env-llmeval/lib/python3.10/site-packages/sympy/utilities/tests/__pycache__/test_codegen.cpython-310.pyc +0 -0
  50. env-llmeval/lib/python3.10/site-packages/sympy/utilities/tests/__pycache__/test_codegen_julia.cpython-310.pyc +0 -0
env-llmeval/lib/python3.10/site-packages/sympy/concrete/tests/__init__.py ADDED
File without changes
env-llmeval/lib/python3.10/site-packages/sympy/concrete/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (185 Bytes). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/concrete/tests/__pycache__/test_gosper.cpython-310.pyc ADDED
Binary file (8.37 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/concrete/tests/__pycache__/test_sums_products.cpython-310.pyc ADDED
Binary file (62.1 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/concrete/tests/test_delta.py ADDED
@@ -0,0 +1,499 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.concrete import Sum
2
+ from sympy.concrete.delta import deltaproduct as dp, deltasummation as ds, _extract_delta
3
+ from sympy.core import Eq, S, symbols, oo
4
+ from sympy.functions import KroneckerDelta as KD, Piecewise, piecewise_fold
5
+ from sympy.logic import And
6
+ from sympy.testing.pytest import raises
7
+
8
+ i, j, k, l, m = symbols("i j k l m", integer=True, finite=True)
9
+ x, y = symbols("x y", commutative=False)
10
+
11
+
12
+ def test_deltaproduct_trivial():
13
+ assert dp(x, (j, 1, 0)) == 1
14
+ assert dp(x, (j, 1, 3)) == x**3
15
+ assert dp(x + y, (j, 1, 3)) == (x + y)**3
16
+ assert dp(x*y, (j, 1, 3)) == (x*y)**3
17
+ assert dp(KD(i, j), (k, 1, 3)) == KD(i, j)
18
+ assert dp(x*KD(i, j), (k, 1, 3)) == x**3*KD(i, j)
19
+ assert dp(x*y*KD(i, j), (k, 1, 3)) == (x*y)**3*KD(i, j)
20
+
21
+
22
+ def test_deltaproduct_basic():
23
+ assert dp(KD(i, j), (j, 1, 3)) == 0
24
+ assert dp(KD(i, j), (j, 1, 1)) == KD(i, 1)
25
+ assert dp(KD(i, j), (j, 2, 2)) == KD(i, 2)
26
+ assert dp(KD(i, j), (j, 3, 3)) == KD(i, 3)
27
+ assert dp(KD(i, j), (j, 1, k)) == KD(i, 1)*KD(k, 1) + KD(k, 0)
28
+ assert dp(KD(i, j), (j, k, 3)) == KD(i, 3)*KD(k, 3) + KD(k, 4)
29
+ assert dp(KD(i, j), (j, k, l)) == KD(i, l)*KD(k, l) + KD(k, l + 1)
30
+
31
+
32
+ def test_deltaproduct_mul_x_kd():
33
+ assert dp(x*KD(i, j), (j, 1, 3)) == 0
34
+ assert dp(x*KD(i, j), (j, 1, 1)) == x*KD(i, 1)
35
+ assert dp(x*KD(i, j), (j, 2, 2)) == x*KD(i, 2)
36
+ assert dp(x*KD(i, j), (j, 3, 3)) == x*KD(i, 3)
37
+ assert dp(x*KD(i, j), (j, 1, k)) == x*KD(i, 1)*KD(k, 1) + KD(k, 0)
38
+ assert dp(x*KD(i, j), (j, k, 3)) == x*KD(i, 3)*KD(k, 3) + KD(k, 4)
39
+ assert dp(x*KD(i, j), (j, k, l)) == x*KD(i, l)*KD(k, l) + KD(k, l + 1)
40
+
41
+
42
+ def test_deltaproduct_mul_add_x_y_kd():
43
+ assert dp((x + y)*KD(i, j), (j, 1, 3)) == 0
44
+ assert dp((x + y)*KD(i, j), (j, 1, 1)) == (x + y)*KD(i, 1)
45
+ assert dp((x + y)*KD(i, j), (j, 2, 2)) == (x + y)*KD(i, 2)
46
+ assert dp((x + y)*KD(i, j), (j, 3, 3)) == (x + y)*KD(i, 3)
47
+ assert dp((x + y)*KD(i, j), (j, 1, k)) == \
48
+ (x + y)*KD(i, 1)*KD(k, 1) + KD(k, 0)
49
+ assert dp((x + y)*KD(i, j), (j, k, 3)) == \
50
+ (x + y)*KD(i, 3)*KD(k, 3) + KD(k, 4)
51
+ assert dp((x + y)*KD(i, j), (j, k, l)) == \
52
+ (x + y)*KD(i, l)*KD(k, l) + KD(k, l + 1)
53
+
54
+
55
+ def test_deltaproduct_add_kd_kd():
56
+ assert dp(KD(i, k) + KD(j, k), (k, 1, 3)) == 0
57
+ assert dp(KD(i, k) + KD(j, k), (k, 1, 1)) == KD(i, 1) + KD(j, 1)
58
+ assert dp(KD(i, k) + KD(j, k), (k, 2, 2)) == KD(i, 2) + KD(j, 2)
59
+ assert dp(KD(i, k) + KD(j, k), (k, 3, 3)) == KD(i, 3) + KD(j, 3)
60
+ assert dp(KD(i, k) + KD(j, k), (k, 1, l)) == KD(l, 0) + \
61
+ KD(i, 1)*KD(l, 1) + KD(j, 1)*KD(l, 1) + \
62
+ KD(i, 1)*KD(j, 2)*KD(l, 2) + KD(j, 1)*KD(i, 2)*KD(l, 2)
63
+ assert dp(KD(i, k) + KD(j, k), (k, l, 3)) == KD(l, 4) + \
64
+ KD(i, 3)*KD(l, 3) + KD(j, 3)*KD(l, 3) + \
65
+ KD(i, 2)*KD(j, 3)*KD(l, 2) + KD(i, 3)*KD(j, 2)*KD(l, 2)
66
+ assert dp(KD(i, k) + KD(j, k), (k, l, m)) == KD(l, m + 1) + \
67
+ KD(i, m)*KD(l, m) + KD(j, m)*KD(l, m) + \
68
+ KD(i, m)*KD(j, m - 1)*KD(l, m - 1) + KD(i, m - 1)*KD(j, m)*KD(l, m - 1)
69
+
70
+
71
+ def test_deltaproduct_mul_x_add_kd_kd():
72
+ assert dp(x*(KD(i, k) + KD(j, k)), (k, 1, 3)) == 0
73
+ assert dp(x*(KD(i, k) + KD(j, k)), (k, 1, 1)) == x*(KD(i, 1) + KD(j, 1))
74
+ assert dp(x*(KD(i, k) + KD(j, k)), (k, 2, 2)) == x*(KD(i, 2) + KD(j, 2))
75
+ assert dp(x*(KD(i, k) + KD(j, k)), (k, 3, 3)) == x*(KD(i, 3) + KD(j, 3))
76
+ assert dp(x*(KD(i, k) + KD(j, k)), (k, 1, l)) == KD(l, 0) + \
77
+ x*KD(i, 1)*KD(l, 1) + x*KD(j, 1)*KD(l, 1) + \
78
+ x**2*KD(i, 1)*KD(j, 2)*KD(l, 2) + x**2*KD(j, 1)*KD(i, 2)*KD(l, 2)
79
+ assert dp(x*(KD(i, k) + KD(j, k)), (k, l, 3)) == KD(l, 4) + \
80
+ x*KD(i, 3)*KD(l, 3) + x*KD(j, 3)*KD(l, 3) + \
81
+ x**2*KD(i, 2)*KD(j, 3)*KD(l, 2) + x**2*KD(i, 3)*KD(j, 2)*KD(l, 2)
82
+ assert dp(x*(KD(i, k) + KD(j, k)), (k, l, m)) == KD(l, m + 1) + \
83
+ x*KD(i, m)*KD(l, m) + x*KD(j, m)*KD(l, m) + \
84
+ x**2*KD(i, m - 1)*KD(j, m)*KD(l, m - 1) + \
85
+ x**2*KD(i, m)*KD(j, m - 1)*KD(l, m - 1)
86
+
87
+
88
+ def test_deltaproduct_mul_add_x_y_add_kd_kd():
89
+ assert dp((x + y)*(KD(i, k) + KD(j, k)), (k, 1, 3)) == 0
90
+ assert dp((x + y)*(KD(i, k) + KD(j, k)), (k, 1, 1)) == \
91
+ (x + y)*(KD(i, 1) + KD(j, 1))
92
+ assert dp((x + y)*(KD(i, k) + KD(j, k)), (k, 2, 2)) == \
93
+ (x + y)*(KD(i, 2) + KD(j, 2))
94
+ assert dp((x + y)*(KD(i, k) + KD(j, k)), (k, 3, 3)) == \
95
+ (x + y)*(KD(i, 3) + KD(j, 3))
96
+ assert dp((x + y)*(KD(i, k) + KD(j, k)), (k, 1, l)) == KD(l, 0) + \
97
+ (x + y)*KD(i, 1)*KD(l, 1) + (x + y)*KD(j, 1)*KD(l, 1) + \
98
+ (x + y)**2*KD(i, 1)*KD(j, 2)*KD(l, 2) + \
99
+ (x + y)**2*KD(j, 1)*KD(i, 2)*KD(l, 2)
100
+ assert dp((x + y)*(KD(i, k) + KD(j, k)), (k, l, 3)) == KD(l, 4) + \
101
+ (x + y)*KD(i, 3)*KD(l, 3) + (x + y)*KD(j, 3)*KD(l, 3) + \
102
+ (x + y)**2*KD(i, 2)*KD(j, 3)*KD(l, 2) + \
103
+ (x + y)**2*KD(i, 3)*KD(j, 2)*KD(l, 2)
104
+ assert dp((x + y)*(KD(i, k) + KD(j, k)), (k, l, m)) == KD(l, m + 1) + \
105
+ (x + y)*KD(i, m)*KD(l, m) + (x + y)*KD(j, m)*KD(l, m) + \
106
+ (x + y)**2*KD(i, m - 1)*KD(j, m)*KD(l, m - 1) + \
107
+ (x + y)**2*KD(i, m)*KD(j, m - 1)*KD(l, m - 1)
108
+
109
+
110
+ def test_deltaproduct_add_mul_x_y_mul_x_kd():
111
+ assert dp(x*y + x*KD(i, j), (j, 1, 3)) == (x*y)**3 + \
112
+ x*(x*y)**2*KD(i, 1) + (x*y)*x*(x*y)*KD(i, 2) + (x*y)**2*x*KD(i, 3)
113
+ assert dp(x*y + x*KD(i, j), (j, 1, 1)) == x*y + x*KD(i, 1)
114
+ assert dp(x*y + x*KD(i, j), (j, 2, 2)) == x*y + x*KD(i, 2)
115
+ assert dp(x*y + x*KD(i, j), (j, 3, 3)) == x*y + x*KD(i, 3)
116
+ assert dp(x*y + x*KD(i, j), (j, 1, k)) == \
117
+ (x*y)**k + Piecewise(
118
+ ((x*y)**(i - 1)*x*(x*y)**(k - i), And(1 <= i, i <= k)),
119
+ (0, True)
120
+ )
121
+ assert dp(x*y + x*KD(i, j), (j, k, 3)) == \
122
+ (x*y)**(-k + 4) + Piecewise(
123
+ ((x*y)**(i - k)*x*(x*y)**(3 - i), And(k <= i, i <= 3)),
124
+ (0, True)
125
+ )
126
+ assert dp(x*y + x*KD(i, j), (j, k, l)) == \
127
+ (x*y)**(-k + l + 1) + Piecewise(
128
+ ((x*y)**(i - k)*x*(x*y)**(l - i), And(k <= i, i <= l)),
129
+ (0, True)
130
+ )
131
+
132
+
133
+ def test_deltaproduct_mul_x_add_y_kd():
134
+ assert dp(x*(y + KD(i, j)), (j, 1, 3)) == (x*y)**3 + \
135
+ x*(x*y)**2*KD(i, 1) + (x*y)*x*(x*y)*KD(i, 2) + (x*y)**2*x*KD(i, 3)
136
+ assert dp(x*(y + KD(i, j)), (j, 1, 1)) == x*(y + KD(i, 1))
137
+ assert dp(x*(y + KD(i, j)), (j, 2, 2)) == x*(y + KD(i, 2))
138
+ assert dp(x*(y + KD(i, j)), (j, 3, 3)) == x*(y + KD(i, 3))
139
+ assert dp(x*(y + KD(i, j)), (j, 1, k)) == \
140
+ (x*y)**k + Piecewise(
141
+ ((x*y)**(i - 1)*x*(x*y)**(k - i), And(1 <= i, i <= k)),
142
+ (0, True)
143
+ ).expand()
144
+ assert dp(x*(y + KD(i, j)), (j, k, 3)) == \
145
+ ((x*y)**(-k + 4) + Piecewise(
146
+ ((x*y)**(i - k)*x*(x*y)**(3 - i), And(k <= i, i <= 3)),
147
+ (0, True)
148
+ )).expand()
149
+ assert dp(x*(y + KD(i, j)), (j, k, l)) == \
150
+ ((x*y)**(-k + l + 1) + Piecewise(
151
+ ((x*y)**(i - k)*x*(x*y)**(l - i), And(k <= i, i <= l)),
152
+ (0, True)
153
+ )).expand()
154
+
155
+
156
+ def test_deltaproduct_mul_x_add_y_twokd():
157
+ assert dp(x*(y + 2*KD(i, j)), (j, 1, 3)) == (x*y)**3 + \
158
+ 2*x*(x*y)**2*KD(i, 1) + 2*x*y*x*x*y*KD(i, 2) + 2*(x*y)**2*x*KD(i, 3)
159
+ assert dp(x*(y + 2*KD(i, j)), (j, 1, 1)) == x*(y + 2*KD(i, 1))
160
+ assert dp(x*(y + 2*KD(i, j)), (j, 2, 2)) == x*(y + 2*KD(i, 2))
161
+ assert dp(x*(y + 2*KD(i, j)), (j, 3, 3)) == x*(y + 2*KD(i, 3))
162
+ assert dp(x*(y + 2*KD(i, j)), (j, 1, k)) == \
163
+ (x*y)**k + Piecewise(
164
+ (2*(x*y)**(i - 1)*x*(x*y)**(k - i), And(1 <= i, i <= k)),
165
+ (0, True)
166
+ ).expand()
167
+ assert dp(x*(y + 2*KD(i, j)), (j, k, 3)) == \
168
+ ((x*y)**(-k + 4) + Piecewise(
169
+ (2*(x*y)**(i - k)*x*(x*y)**(3 - i), And(k <= i, i <= 3)),
170
+ (0, True)
171
+ )).expand()
172
+ assert dp(x*(y + 2*KD(i, j)), (j, k, l)) == \
173
+ ((x*y)**(-k + l + 1) + Piecewise(
174
+ (2*(x*y)**(i - k)*x*(x*y)**(l - i), And(k <= i, i <= l)),
175
+ (0, True)
176
+ )).expand()
177
+
178
+
179
+ def test_deltaproduct_mul_add_x_y_add_y_kd():
180
+ assert dp((x + y)*(y + KD(i, j)), (j, 1, 3)) == ((x + y)*y)**3 + \
181
+ (x + y)*((x + y)*y)**2*KD(i, 1) + \
182
+ (x + y)*y*(x + y)**2*y*KD(i, 2) + \
183
+ ((x + y)*y)**2*(x + y)*KD(i, 3)
184
+ assert dp((x + y)*(y + KD(i, j)), (j, 1, 1)) == (x + y)*(y + KD(i, 1))
185
+ assert dp((x + y)*(y + KD(i, j)), (j, 2, 2)) == (x + y)*(y + KD(i, 2))
186
+ assert dp((x + y)*(y + KD(i, j)), (j, 3, 3)) == (x + y)*(y + KD(i, 3))
187
+ assert dp((x + y)*(y + KD(i, j)), (j, 1, k)) == \
188
+ ((x + y)*y)**k + Piecewise(
189
+ (((x + y)*y)**(-1)*((x + y)*y)**i*(x + y)*((x + y)*y
190
+ )**k*((x + y)*y)**(-i), (i >= 1) & (i <= k)), (0, True))
191
+ assert dp((x + y)*(y + KD(i, j)), (j, k, 3)) == (
192
+ (x + y)*y)**4*((x + y)*y)**(-k) + Piecewise((((x + y)*y)**i*(
193
+ (x + y)*y)**(-k)*(x + y)*((x + y)*y)**3*((x + y)*y)**(-i),
194
+ (i >= k) & (i <= 3)), (0, True))
195
+ assert dp((x + y)*(y + KD(i, j)), (j, k, l)) == \
196
+ (x + y)*y*((x + y)*y)**l*((x + y)*y)**(-k) + Piecewise(
197
+ (((x + y)*y)**i*((x + y)*y)**(-k)*(x + y)*((x + y)*y
198
+ )**l*((x + y)*y)**(-i), (i >= k) & (i <= l)), (0, True))
199
+
200
+
201
+ def test_deltaproduct_mul_add_x_kd_add_y_kd():
202
+ assert dp((x + KD(i, k))*(y + KD(i, j)), (j, 1, 3)) == \
203
+ KD(i, 1)*(KD(i, k) + x)*((KD(i, k) + x)*y)**2 + \
204
+ KD(i, 2)*(KD(i, k) + x)*y*(KD(i, k) + x)**2*y + \
205
+ KD(i, 3)*((KD(i, k) + x)*y)**2*(KD(i, k) + x) + \
206
+ ((KD(i, k) + x)*y)**3
207
+ assert dp((x + KD(i, k))*(y + KD(i, j)), (j, 1, 1)) == \
208
+ (x + KD(i, k))*(y + KD(i, 1))
209
+ assert dp((x + KD(i, k))*(y + KD(i, j)), (j, 2, 2)) == \
210
+ (x + KD(i, k))*(y + KD(i, 2))
211
+ assert dp((x + KD(i, k))*(y + KD(i, j)), (j, 3, 3)) == \
212
+ (x + KD(i, k))*(y + KD(i, 3))
213
+ assert dp((x + KD(i, k))*(y + KD(i, j)), (j, 1, k)) == \
214
+ ((KD(i, k) + x)*y)**k + Piecewise(
215
+ (((KD(i, k) + x)*y)**(-1)*((KD(i, k) + x)*y)**i*(KD(i, k) + x
216
+ )*((KD(i, k) + x)*y)**k*((KD(i, k) + x)*y)**(-i), (i >= 1
217
+ ) & (i <= k)), (0, True))
218
+ assert dp((x + KD(i, k))*(y + KD(i, j)), (j, k, 3)) == (
219
+ (KD(i, k) + x)*y)**4*((KD(i, k) + x)*y)**(-k) + Piecewise(
220
+ (((KD(i, k) + x)*y)**i*((KD(i, k) + x)*y)**(-k)*(KD(i, k)
221
+ + x)*((KD(i, k) + x)*y)**3*((KD(i, k) + x)*y)**(-i),
222
+ (i >= k) & (i <= 3)), (0, True))
223
+ assert dp((x + KD(i, k))*(y + KD(i, j)), (j, k, l)) == (
224
+ KD(i, k) + x)*y*((KD(i, k) + x)*y)**l*((KD(i, k) + x)*y
225
+ )**(-k) + Piecewise((((KD(i, k) + x)*y)**i*((KD(i, k) + x
226
+ )*y)**(-k)*(KD(i, k) + x)*((KD(i, k) + x)*y)**l*((KD(i, k) + x
227
+ )*y)**(-i), (i >= k) & (i <= l)), (0, True))
228
+
229
+
230
+ def test_deltasummation_trivial():
231
+ assert ds(x, (j, 1, 0)) == 0
232
+ assert ds(x, (j, 1, 3)) == 3*x
233
+ assert ds(x + y, (j, 1, 3)) == 3*(x + y)
234
+ assert ds(x*y, (j, 1, 3)) == 3*x*y
235
+ assert ds(KD(i, j), (k, 1, 3)) == 3*KD(i, j)
236
+ assert ds(x*KD(i, j), (k, 1, 3)) == 3*x*KD(i, j)
237
+ assert ds(x*y*KD(i, j), (k, 1, 3)) == 3*x*y*KD(i, j)
238
+
239
+
240
+ def test_deltasummation_basic_numerical():
241
+ n = symbols('n', integer=True, nonzero=True)
242
+ assert ds(KD(n, 0), (n, 1, 3)) == 0
243
+
244
+ # return unevaluated, until it gets implemented
245
+ assert ds(KD(i**2, j**2), (j, -oo, oo)) == \
246
+ Sum(KD(i**2, j**2), (j, -oo, oo))
247
+
248
+ assert Piecewise((KD(i, k), And(1 <= i, i <= 3)), (0, True)) == \
249
+ ds(KD(i, j)*KD(j, k), (j, 1, 3)) == \
250
+ ds(KD(j, k)*KD(i, j), (j, 1, 3))
251
+
252
+ assert ds(KD(i, k), (k, -oo, oo)) == 1
253
+ assert ds(KD(i, k), (k, 0, oo)) == Piecewise((1, S.Zero <= i), (0, True))
254
+ assert ds(KD(i, k), (k, 1, 3)) == \
255
+ Piecewise((1, And(1 <= i, i <= 3)), (0, True))
256
+ assert ds(k*KD(i, j)*KD(j, k), (k, -oo, oo)) == j*KD(i, j)
257
+ assert ds(j*KD(i, j), (j, -oo, oo)) == i
258
+ assert ds(i*KD(i, j), (i, -oo, oo)) == j
259
+ assert ds(x, (i, 1, 3)) == 3*x
260
+ assert ds((i + j)*KD(i, j), (j, -oo, oo)) == 2*i
261
+
262
+
263
+ def test_deltasummation_basic_symbolic():
264
+ assert ds(KD(i, j), (j, 1, 3)) == \
265
+ Piecewise((1, And(1 <= i, i <= 3)), (0, True))
266
+ assert ds(KD(i, j), (j, 1, 1)) == Piecewise((1, Eq(i, 1)), (0, True))
267
+ assert ds(KD(i, j), (j, 2, 2)) == Piecewise((1, Eq(i, 2)), (0, True))
268
+ assert ds(KD(i, j), (j, 3, 3)) == Piecewise((1, Eq(i, 3)), (0, True))
269
+ assert ds(KD(i, j), (j, 1, k)) == \
270
+ Piecewise((1, And(1 <= i, i <= k)), (0, True))
271
+ assert ds(KD(i, j), (j, k, 3)) == \
272
+ Piecewise((1, And(k <= i, i <= 3)), (0, True))
273
+ assert ds(KD(i, j), (j, k, l)) == \
274
+ Piecewise((1, And(k <= i, i <= l)), (0, True))
275
+
276
+
277
+ def test_deltasummation_mul_x_kd():
278
+ assert ds(x*KD(i, j), (j, 1, 3)) == \
279
+ Piecewise((x, And(1 <= i, i <= 3)), (0, True))
280
+ assert ds(x*KD(i, j), (j, 1, 1)) == Piecewise((x, Eq(i, 1)), (0, True))
281
+ assert ds(x*KD(i, j), (j, 2, 2)) == Piecewise((x, Eq(i, 2)), (0, True))
282
+ assert ds(x*KD(i, j), (j, 3, 3)) == Piecewise((x, Eq(i, 3)), (0, True))
283
+ assert ds(x*KD(i, j), (j, 1, k)) == \
284
+ Piecewise((x, And(1 <= i, i <= k)), (0, True))
285
+ assert ds(x*KD(i, j), (j, k, 3)) == \
286
+ Piecewise((x, And(k <= i, i <= 3)), (0, True))
287
+ assert ds(x*KD(i, j), (j, k, l)) == \
288
+ Piecewise((x, And(k <= i, i <= l)), (0, True))
289
+
290
+
291
+ def test_deltasummation_mul_add_x_y_kd():
292
+ assert ds((x + y)*KD(i, j), (j, 1, 3)) == \
293
+ Piecewise((x + y, And(1 <= i, i <= 3)), (0, True))
294
+ assert ds((x + y)*KD(i, j), (j, 1, 1)) == \
295
+ Piecewise((x + y, Eq(i, 1)), (0, True))
296
+ assert ds((x + y)*KD(i, j), (j, 2, 2)) == \
297
+ Piecewise((x + y, Eq(i, 2)), (0, True))
298
+ assert ds((x + y)*KD(i, j), (j, 3, 3)) == \
299
+ Piecewise((x + y, Eq(i, 3)), (0, True))
300
+ assert ds((x + y)*KD(i, j), (j, 1, k)) == \
301
+ Piecewise((x + y, And(1 <= i, i <= k)), (0, True))
302
+ assert ds((x + y)*KD(i, j), (j, k, 3)) == \
303
+ Piecewise((x + y, And(k <= i, i <= 3)), (0, True))
304
+ assert ds((x + y)*KD(i, j), (j, k, l)) == \
305
+ Piecewise((x + y, And(k <= i, i <= l)), (0, True))
306
+
307
+
308
+ def test_deltasummation_add_kd_kd():
309
+ assert ds(KD(i, k) + KD(j, k), (k, 1, 3)) == piecewise_fold(
310
+ Piecewise((1, And(1 <= i, i <= 3)), (0, True)) +
311
+ Piecewise((1, And(1 <= j, j <= 3)), (0, True)))
312
+ assert ds(KD(i, k) + KD(j, k), (k, 1, 1)) == piecewise_fold(
313
+ Piecewise((1, Eq(i, 1)), (0, True)) +
314
+ Piecewise((1, Eq(j, 1)), (0, True)))
315
+ assert ds(KD(i, k) + KD(j, k), (k, 2, 2)) == piecewise_fold(
316
+ Piecewise((1, Eq(i, 2)), (0, True)) +
317
+ Piecewise((1, Eq(j, 2)), (0, True)))
318
+ assert ds(KD(i, k) + KD(j, k), (k, 3, 3)) == piecewise_fold(
319
+ Piecewise((1, Eq(i, 3)), (0, True)) +
320
+ Piecewise((1, Eq(j, 3)), (0, True)))
321
+ assert ds(KD(i, k) + KD(j, k), (k, 1, l)) == piecewise_fold(
322
+ Piecewise((1, And(1 <= i, i <= l)), (0, True)) +
323
+ Piecewise((1, And(1 <= j, j <= l)), (0, True)))
324
+ assert ds(KD(i, k) + KD(j, k), (k, l, 3)) == piecewise_fold(
325
+ Piecewise((1, And(l <= i, i <= 3)), (0, True)) +
326
+ Piecewise((1, And(l <= j, j <= 3)), (0, True)))
327
+ assert ds(KD(i, k) + KD(j, k), (k, l, m)) == piecewise_fold(
328
+ Piecewise((1, And(l <= i, i <= m)), (0, True)) +
329
+ Piecewise((1, And(l <= j, j <= m)), (0, True)))
330
+
331
+
332
+ def test_deltasummation_add_mul_x_kd_kd():
333
+ assert ds(x*KD(i, k) + KD(j, k), (k, 1, 3)) == piecewise_fold(
334
+ Piecewise((x, And(1 <= i, i <= 3)), (0, True)) +
335
+ Piecewise((1, And(1 <= j, j <= 3)), (0, True)))
336
+ assert ds(x*KD(i, k) + KD(j, k), (k, 1, 1)) == piecewise_fold(
337
+ Piecewise((x, Eq(i, 1)), (0, True)) +
338
+ Piecewise((1, Eq(j, 1)), (0, True)))
339
+ assert ds(x*KD(i, k) + KD(j, k), (k, 2, 2)) == piecewise_fold(
340
+ Piecewise((x, Eq(i, 2)), (0, True)) +
341
+ Piecewise((1, Eq(j, 2)), (0, True)))
342
+ assert ds(x*KD(i, k) + KD(j, k), (k, 3, 3)) == piecewise_fold(
343
+ Piecewise((x, Eq(i, 3)), (0, True)) +
344
+ Piecewise((1, Eq(j, 3)), (0, True)))
345
+ assert ds(x*KD(i, k) + KD(j, k), (k, 1, l)) == piecewise_fold(
346
+ Piecewise((x, And(1 <= i, i <= l)), (0, True)) +
347
+ Piecewise((1, And(1 <= j, j <= l)), (0, True)))
348
+ assert ds(x*KD(i, k) + KD(j, k), (k, l, 3)) == piecewise_fold(
349
+ Piecewise((x, And(l <= i, i <= 3)), (0, True)) +
350
+ Piecewise((1, And(l <= j, j <= 3)), (0, True)))
351
+ assert ds(x*KD(i, k) + KD(j, k), (k, l, m)) == piecewise_fold(
352
+ Piecewise((x, And(l <= i, i <= m)), (0, True)) +
353
+ Piecewise((1, And(l <= j, j <= m)), (0, True)))
354
+
355
+
356
+ def test_deltasummation_mul_x_add_kd_kd():
357
+ assert ds(x*(KD(i, k) + KD(j, k)), (k, 1, 3)) == piecewise_fold(
358
+ Piecewise((x, And(1 <= i, i <= 3)), (0, True)) +
359
+ Piecewise((x, And(1 <= j, j <= 3)), (0, True)))
360
+ assert ds(x*(KD(i, k) + KD(j, k)), (k, 1, 1)) == piecewise_fold(
361
+ Piecewise((x, Eq(i, 1)), (0, True)) +
362
+ Piecewise((x, Eq(j, 1)), (0, True)))
363
+ assert ds(x*(KD(i, k) + KD(j, k)), (k, 2, 2)) == piecewise_fold(
364
+ Piecewise((x, Eq(i, 2)), (0, True)) +
365
+ Piecewise((x, Eq(j, 2)), (0, True)))
366
+ assert ds(x*(KD(i, k) + KD(j, k)), (k, 3, 3)) == piecewise_fold(
367
+ Piecewise((x, Eq(i, 3)), (0, True)) +
368
+ Piecewise((x, Eq(j, 3)), (0, True)))
369
+ assert ds(x*(KD(i, k) + KD(j, k)), (k, 1, l)) == piecewise_fold(
370
+ Piecewise((x, And(1 <= i, i <= l)), (0, True)) +
371
+ Piecewise((x, And(1 <= j, j <= l)), (0, True)))
372
+ assert ds(x*(KD(i, k) + KD(j, k)), (k, l, 3)) == piecewise_fold(
373
+ Piecewise((x, And(l <= i, i <= 3)), (0, True)) +
374
+ Piecewise((x, And(l <= j, j <= 3)), (0, True)))
375
+ assert ds(x*(KD(i, k) + KD(j, k)), (k, l, m)) == piecewise_fold(
376
+ Piecewise((x, And(l <= i, i <= m)), (0, True)) +
377
+ Piecewise((x, And(l <= j, j <= m)), (0, True)))
378
+
379
+
380
+ def test_deltasummation_mul_add_x_y_add_kd_kd():
381
+ assert ds((x + y)*(KD(i, k) + KD(j, k)), (k, 1, 3)) == piecewise_fold(
382
+ Piecewise((x + y, And(1 <= i, i <= 3)), (0, True)) +
383
+ Piecewise((x + y, And(1 <= j, j <= 3)), (0, True)))
384
+ assert ds((x + y)*(KD(i, k) + KD(j, k)), (k, 1, 1)) == piecewise_fold(
385
+ Piecewise((x + y, Eq(i, 1)), (0, True)) +
386
+ Piecewise((x + y, Eq(j, 1)), (0, True)))
387
+ assert ds((x + y)*(KD(i, k) + KD(j, k)), (k, 2, 2)) == piecewise_fold(
388
+ Piecewise((x + y, Eq(i, 2)), (0, True)) +
389
+ Piecewise((x + y, Eq(j, 2)), (0, True)))
390
+ assert ds((x + y)*(KD(i, k) + KD(j, k)), (k, 3, 3)) == piecewise_fold(
391
+ Piecewise((x + y, Eq(i, 3)), (0, True)) +
392
+ Piecewise((x + y, Eq(j, 3)), (0, True)))
393
+ assert ds((x + y)*(KD(i, k) + KD(j, k)), (k, 1, l)) == piecewise_fold(
394
+ Piecewise((x + y, And(1 <= i, i <= l)), (0, True)) +
395
+ Piecewise((x + y, And(1 <= j, j <= l)), (0, True)))
396
+ assert ds((x + y)*(KD(i, k) + KD(j, k)), (k, l, 3)) == piecewise_fold(
397
+ Piecewise((x + y, And(l <= i, i <= 3)), (0, True)) +
398
+ Piecewise((x + y, And(l <= j, j <= 3)), (0, True)))
399
+ assert ds((x + y)*(KD(i, k) + KD(j, k)), (k, l, m)) == piecewise_fold(
400
+ Piecewise((x + y, And(l <= i, i <= m)), (0, True)) +
401
+ Piecewise((x + y, And(l <= j, j <= m)), (0, True)))
402
+
403
+
404
+ def test_deltasummation_add_mul_x_y_mul_x_kd():
405
+ assert ds(x*y + x*KD(i, j), (j, 1, 3)) == \
406
+ Piecewise((3*x*y + x, And(1 <= i, i <= 3)), (3*x*y, True))
407
+ assert ds(x*y + x*KD(i, j), (j, 1, 1)) == \
408
+ Piecewise((x*y + x, Eq(i, 1)), (x*y, True))
409
+ assert ds(x*y + x*KD(i, j), (j, 2, 2)) == \
410
+ Piecewise((x*y + x, Eq(i, 2)), (x*y, True))
411
+ assert ds(x*y + x*KD(i, j), (j, 3, 3)) == \
412
+ Piecewise((x*y + x, Eq(i, 3)), (x*y, True))
413
+ assert ds(x*y + x*KD(i, j), (j, 1, k)) == \
414
+ Piecewise((k*x*y + x, And(1 <= i, i <= k)), (k*x*y, True))
415
+ assert ds(x*y + x*KD(i, j), (j, k, 3)) == \
416
+ Piecewise(((4 - k)*x*y + x, And(k <= i, i <= 3)), ((4 - k)*x*y, True))
417
+ assert ds(x*y + x*KD(i, j), (j, k, l)) == Piecewise(
418
+ ((l - k + 1)*x*y + x, And(k <= i, i <= l)), ((l - k + 1)*x*y, True))
419
+
420
+
421
+ def test_deltasummation_mul_x_add_y_kd():
422
+ assert ds(x*(y + KD(i, j)), (j, 1, 3)) == \
423
+ Piecewise((3*x*y + x, And(1 <= i, i <= 3)), (3*x*y, True))
424
+ assert ds(x*(y + KD(i, j)), (j, 1, 1)) == \
425
+ Piecewise((x*y + x, Eq(i, 1)), (x*y, True))
426
+ assert ds(x*(y + KD(i, j)), (j, 2, 2)) == \
427
+ Piecewise((x*y + x, Eq(i, 2)), (x*y, True))
428
+ assert ds(x*(y + KD(i, j)), (j, 3, 3)) == \
429
+ Piecewise((x*y + x, Eq(i, 3)), (x*y, True))
430
+ assert ds(x*(y + KD(i, j)), (j, 1, k)) == \
431
+ Piecewise((k*x*y + x, And(1 <= i, i <= k)), (k*x*y, True))
432
+ assert ds(x*(y + KD(i, j)), (j, k, 3)) == \
433
+ Piecewise(((4 - k)*x*y + x, And(k <= i, i <= 3)), ((4 - k)*x*y, True))
434
+ assert ds(x*(y + KD(i, j)), (j, k, l)) == Piecewise(
435
+ ((l - k + 1)*x*y + x, And(k <= i, i <= l)), ((l - k + 1)*x*y, True))
436
+
437
+
438
+ def test_deltasummation_mul_x_add_y_twokd():
439
+ assert ds(x*(y + 2*KD(i, j)), (j, 1, 3)) == \
440
+ Piecewise((3*x*y + 2*x, And(1 <= i, i <= 3)), (3*x*y, True))
441
+ assert ds(x*(y + 2*KD(i, j)), (j, 1, 1)) == \
442
+ Piecewise((x*y + 2*x, Eq(i, 1)), (x*y, True))
443
+ assert ds(x*(y + 2*KD(i, j)), (j, 2, 2)) == \
444
+ Piecewise((x*y + 2*x, Eq(i, 2)), (x*y, True))
445
+ assert ds(x*(y + 2*KD(i, j)), (j, 3, 3)) == \
446
+ Piecewise((x*y + 2*x, Eq(i, 3)), (x*y, True))
447
+ assert ds(x*(y + 2*KD(i, j)), (j, 1, k)) == \
448
+ Piecewise((k*x*y + 2*x, And(1 <= i, i <= k)), (k*x*y, True))
449
+ assert ds(x*(y + 2*KD(i, j)), (j, k, 3)) == Piecewise(
450
+ ((4 - k)*x*y + 2*x, And(k <= i, i <= 3)), ((4 - k)*x*y, True))
451
+ assert ds(x*(y + 2*KD(i, j)), (j, k, l)) == Piecewise(
452
+ ((l - k + 1)*x*y + 2*x, And(k <= i, i <= l)), ((l - k + 1)*x*y, True))
453
+
454
+
455
+ def test_deltasummation_mul_add_x_y_add_y_kd():
456
+ assert ds((x + y)*(y + KD(i, j)), (j, 1, 3)) == Piecewise(
457
+ (3*(x + y)*y + x + y, And(1 <= i, i <= 3)), (3*(x + y)*y, True))
458
+ assert ds((x + y)*(y + KD(i, j)), (j, 1, 1)) == \
459
+ Piecewise(((x + y)*y + x + y, Eq(i, 1)), ((x + y)*y, True))
460
+ assert ds((x + y)*(y + KD(i, j)), (j, 2, 2)) == \
461
+ Piecewise(((x + y)*y + x + y, Eq(i, 2)), ((x + y)*y, True))
462
+ assert ds((x + y)*(y + KD(i, j)), (j, 3, 3)) == \
463
+ Piecewise(((x + y)*y + x + y, Eq(i, 3)), ((x + y)*y, True))
464
+ assert ds((x + y)*(y + KD(i, j)), (j, 1, k)) == Piecewise(
465
+ (k*(x + y)*y + x + y, And(1 <= i, i <= k)), (k*(x + y)*y, True))
466
+ assert ds((x + y)*(y + KD(i, j)), (j, k, 3)) == Piecewise(
467
+ ((4 - k)*(x + y)*y + x + y, And(k <= i, i <= 3)),
468
+ ((4 - k)*(x + y)*y, True))
469
+ assert ds((x + y)*(y + KD(i, j)), (j, k, l)) == Piecewise(
470
+ ((l - k + 1)*(x + y)*y + x + y, And(k <= i, i <= l)),
471
+ ((l - k + 1)*(x + y)*y, True))
472
+
473
+
474
+ def test_deltasummation_mul_add_x_kd_add_y_kd():
475
+ assert ds((x + KD(i, k))*(y + KD(i, j)), (j, 1, 3)) == piecewise_fold(
476
+ Piecewise((KD(i, k) + x, And(1 <= i, i <= 3)), (0, True)) +
477
+ 3*(KD(i, k) + x)*y)
478
+ assert ds((x + KD(i, k))*(y + KD(i, j)), (j, 1, 1)) == piecewise_fold(
479
+ Piecewise((KD(i, k) + x, Eq(i, 1)), (0, True)) +
480
+ (KD(i, k) + x)*y)
481
+ assert ds((x + KD(i, k))*(y + KD(i, j)), (j, 2, 2)) == piecewise_fold(
482
+ Piecewise((KD(i, k) + x, Eq(i, 2)), (0, True)) +
483
+ (KD(i, k) + x)*y)
484
+ assert ds((x + KD(i, k))*(y + KD(i, j)), (j, 3, 3)) == piecewise_fold(
485
+ Piecewise((KD(i, k) + x, Eq(i, 3)), (0, True)) +
486
+ (KD(i, k) + x)*y)
487
+ assert ds((x + KD(i, k))*(y + KD(i, j)), (j, 1, k)) == piecewise_fold(
488
+ Piecewise((KD(i, k) + x, And(1 <= i, i <= k)), (0, True)) +
489
+ k*(KD(i, k) + x)*y)
490
+ assert ds((x + KD(i, k))*(y + KD(i, j)), (j, k, 3)) == piecewise_fold(
491
+ Piecewise((KD(i, k) + x, And(k <= i, i <= 3)), (0, True)) +
492
+ (4 - k)*(KD(i, k) + x)*y)
493
+ assert ds((x + KD(i, k))*(y + KD(i, j)), (j, k, l)) == piecewise_fold(
494
+ Piecewise((KD(i, k) + x, And(k <= i, i <= l)), (0, True)) +
495
+ (l - k + 1)*(KD(i, k) + x)*y)
496
+
497
+
498
+ def test_extract_delta():
499
+ raises(ValueError, lambda: _extract_delta(KD(i, j) + KD(k, l), i))
env-llmeval/lib/python3.10/site-packages/sympy/concrete/tests/test_gosper.py ADDED
@@ -0,0 +1,204 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for Gosper's algorithm for hypergeometric summation. """
2
+
3
+ from sympy.core.numbers import (Rational, pi)
4
+ from sympy.core.singleton import S
5
+ from sympy.core.symbol import Symbol
6
+ from sympy.functions.combinatorial.factorials import (binomial, factorial)
7
+ from sympy.functions.elementary.exponential import (exp, log)
8
+ from sympy.functions.elementary.miscellaneous import sqrt
9
+ from sympy.functions.special.gamma_functions import gamma
10
+ from sympy.polys.polytools import Poly
11
+ from sympy.simplify.simplify import simplify
12
+ from sympy.concrete.gosper import gosper_normal, gosper_sum, gosper_term
13
+ from sympy.abc import a, b, j, k, m, n, r, x
14
+
15
+
16
+ def test_gosper_normal():
17
+ eq = 4*n + 5, 2*(4*n + 1)*(2*n + 3), n
18
+ assert gosper_normal(*eq) == \
19
+ (Poly(Rational(1, 4), n), Poly(n + Rational(3, 2)), Poly(n + Rational(1, 4)))
20
+ assert gosper_normal(*eq, polys=False) == \
21
+ (Rational(1, 4), n + Rational(3, 2), n + Rational(1, 4))
22
+
23
+
24
+ def test_gosper_term():
25
+ assert gosper_term((4*k + 1)*factorial(
26
+ k)/factorial(2*k + 1), k) == (-k - S.Half)/(k + Rational(1, 4))
27
+
28
+
29
+ def test_gosper_sum():
30
+ assert gosper_sum(1, (k, 0, n)) == 1 + n
31
+ assert gosper_sum(k, (k, 0, n)) == n*(1 + n)/2
32
+ assert gosper_sum(k**2, (k, 0, n)) == n*(1 + n)*(1 + 2*n)/6
33
+ assert gosper_sum(k**3, (k, 0, n)) == n**2*(1 + n)**2/4
34
+
35
+ assert gosper_sum(2**k, (k, 0, n)) == 2*2**n - 1
36
+
37
+ assert gosper_sum(factorial(k), (k, 0, n)) is None
38
+ assert gosper_sum(binomial(n, k), (k, 0, n)) is None
39
+
40
+ assert gosper_sum(factorial(k)/k**2, (k, 0, n)) is None
41
+ assert gosper_sum((k - 3)*factorial(k), (k, 0, n)) is None
42
+
43
+ assert gosper_sum(k*factorial(k), k) == factorial(k)
44
+ assert gosper_sum(
45
+ k*factorial(k), (k, 0, n)) == n*factorial(n) + factorial(n) - 1
46
+
47
+ assert gosper_sum((-1)**k*binomial(n, k), (k, 0, n)) == 0
48
+ assert gosper_sum((
49
+ -1)**k*binomial(n, k), (k, 0, m)) == -(-1)**m*(m - n)*binomial(n, m)/n
50
+
51
+ assert gosper_sum((4*k + 1)*factorial(k)/factorial(2*k + 1), (k, 0, n)) == \
52
+ (2*factorial(2*n + 1) - factorial(n))/factorial(2*n + 1)
53
+
54
+ # issue 6033:
55
+ assert gosper_sum(
56
+ n*(n + a + b)*a**n*b**n/(factorial(n + a)*factorial(n + b)), \
57
+ (n, 0, m)).simplify() == -exp(m*log(a) + m*log(b))*gamma(a + 1) \
58
+ *gamma(b + 1)/(gamma(a)*gamma(b)*gamma(a + m + 1)*gamma(b + m + 1)) \
59
+ + 1/(gamma(a)*gamma(b))
60
+
61
+
62
+ def test_gosper_sum_indefinite():
63
+ assert gosper_sum(k, k) == k*(k - 1)/2
64
+ assert gosper_sum(k**2, k) == k*(k - 1)*(2*k - 1)/6
65
+
66
+ assert gosper_sum(1/(k*(k + 1)), k) == -1/k
67
+ assert gosper_sum(-(27*k**4 + 158*k**3 + 430*k**2 + 678*k + 445)*gamma(2*k
68
+ + 4)/(3*(3*k + 7)*gamma(3*k + 6)), k) == \
69
+ (3*k + 5)*(k**2 + 2*k + 5)*gamma(2*k + 4)/gamma(3*k + 6)
70
+
71
+
72
+ def test_gosper_sum_parametric():
73
+ assert gosper_sum(binomial(S.Half, m - j + 1)*binomial(S.Half, m + j), (j, 1, n)) == \
74
+ n*(1 + m - n)*(-1 + 2*m + 2*n)*binomial(S.Half, 1 + m - n)* \
75
+ binomial(S.Half, m + n)/(m*(1 + 2*m))
76
+
77
+
78
+ def test_gosper_sum_algebraic():
79
+ assert gosper_sum(
80
+ n**2 + sqrt(2), (n, 0, m)) == (m + 1)*(2*m**2 + m + 6*sqrt(2))/6
81
+
82
+
83
+ def test_gosper_sum_iterated():
84
+ f1 = binomial(2*k, k)/4**k
85
+ f2 = (1 + 2*n)*binomial(2*n, n)/4**n
86
+ f3 = (1 + 2*n)*(3 + 2*n)*binomial(2*n, n)/(3*4**n)
87
+ f4 = (1 + 2*n)*(3 + 2*n)*(5 + 2*n)*binomial(2*n, n)/(15*4**n)
88
+ f5 = (1 + 2*n)*(3 + 2*n)*(5 + 2*n)*(7 + 2*n)*binomial(2*n, n)/(105*4**n)
89
+
90
+ assert gosper_sum(f1, (k, 0, n)) == f2
91
+ assert gosper_sum(f2, (n, 0, n)) == f3
92
+ assert gosper_sum(f3, (n, 0, n)) == f4
93
+ assert gosper_sum(f4, (n, 0, n)) == f5
94
+
95
+ # the AeqB tests test expressions given in
96
+ # www.math.upenn.edu/~wilf/AeqB.pdf
97
+
98
+
99
+ def test_gosper_sum_AeqB_part1():
100
+ f1a = n**4
101
+ f1b = n**3*2**n
102
+ f1c = 1/(n**2 + sqrt(5)*n - 1)
103
+ f1d = n**4*4**n/binomial(2*n, n)
104
+ f1e = factorial(3*n)/(factorial(n)*factorial(n + 1)*factorial(n + 2)*27**n)
105
+ f1f = binomial(2*n, n)**2/((n + 1)*4**(2*n))
106
+ f1g = (4*n - 1)*binomial(2*n, n)**2/((2*n - 1)**2*4**(2*n))
107
+ f1h = n*factorial(n - S.Half)**2/factorial(n + 1)**2
108
+
109
+ g1a = m*(m + 1)*(2*m + 1)*(3*m**2 + 3*m - 1)/30
110
+ g1b = 26 + 2**(m + 1)*(m**3 - 3*m**2 + 9*m - 13)
111
+ g1c = (m + 1)*(m*(m**2 - 7*m + 3)*sqrt(5) - (
112
+ 3*m**3 - 7*m**2 + 19*m - 6))/(2*m**3*sqrt(5) + m**4 + 5*m**2 - 1)/6
113
+ g1d = Rational(-2, 231) + 2*4**m*(m + 1)*(63*m**4 + 112*m**3 + 18*m**2 -
114
+ 22*m + 3)/(693*binomial(2*m, m))
115
+ g1e = Rational(-9, 2) + (81*m**2 + 261*m + 200)*factorial(
116
+ 3*m + 2)/(40*27**m*factorial(m)*factorial(m + 1)*factorial(m + 2))
117
+ g1f = (2*m + 1)**2*binomial(2*m, m)**2/(4**(2*m)*(m + 1))
118
+ g1g = -binomial(2*m, m)**2/4**(2*m)
119
+ g1h = 4*pi -(2*m + 1)**2*(3*m + 4)*factorial(m - S.Half)**2/factorial(m + 1)**2
120
+
121
+ g = gosper_sum(f1a, (n, 0, m))
122
+ assert g is not None and simplify(g - g1a) == 0
123
+ g = gosper_sum(f1b, (n, 0, m))
124
+ assert g is not None and simplify(g - g1b) == 0
125
+ g = gosper_sum(f1c, (n, 0, m))
126
+ assert g is not None and simplify(g - g1c) == 0
127
+ g = gosper_sum(f1d, (n, 0, m))
128
+ assert g is not None and simplify(g - g1d) == 0
129
+ g = gosper_sum(f1e, (n, 0, m))
130
+ assert g is not None and simplify(g - g1e) == 0
131
+ g = gosper_sum(f1f, (n, 0, m))
132
+ assert g is not None and simplify(g - g1f) == 0
133
+ g = gosper_sum(f1g, (n, 0, m))
134
+ assert g is not None and simplify(g - g1g) == 0
135
+ g = gosper_sum(f1h, (n, 0, m))
136
+ # need to call rewrite(gamma) here because we have terms involving
137
+ # factorial(1/2)
138
+ assert g is not None and simplify(g - g1h).rewrite(gamma) == 0
139
+
140
+
141
+ def test_gosper_sum_AeqB_part2():
142
+ f2a = n**2*a**n
143
+ f2b = (n - r/2)*binomial(r, n)
144
+ f2c = factorial(n - 1)**2/(factorial(n - x)*factorial(n + x))
145
+
146
+ g2a = -a*(a + 1)/(a - 1)**3 + a**(
147
+ m + 1)*(a**2*m**2 - 2*a*m**2 + m**2 - 2*a*m + 2*m + a + 1)/(a - 1)**3
148
+ g2b = (m - r)*binomial(r, m)/2
149
+ ff = factorial(1 - x)*factorial(1 + x)
150
+ g2c = 1/ff*(
151
+ 1 - 1/x**2) + factorial(m)**2/(x**2*factorial(m - x)*factorial(m + x))
152
+
153
+ g = gosper_sum(f2a, (n, 0, m))
154
+ assert g is not None and simplify(g - g2a) == 0
155
+ g = gosper_sum(f2b, (n, 0, m))
156
+ assert g is not None and simplify(g - g2b) == 0
157
+ g = gosper_sum(f2c, (n, 1, m))
158
+ assert g is not None and simplify(g - g2c) == 0
159
+
160
+
161
+ def test_gosper_nan():
162
+ a = Symbol('a', positive=True)
163
+ b = Symbol('b', positive=True)
164
+ n = Symbol('n', integer=True)
165
+ m = Symbol('m', integer=True)
166
+ f2d = n*(n + a + b)*a**n*b**n/(factorial(n + a)*factorial(n + b))
167
+ g2d = 1/(factorial(a - 1)*factorial(
168
+ b - 1)) - a**(m + 1)*b**(m + 1)/(factorial(a + m)*factorial(b + m))
169
+ g = gosper_sum(f2d, (n, 0, m))
170
+ assert simplify(g - g2d) == 0
171
+
172
+
173
+ def test_gosper_sum_AeqB_part3():
174
+ f3a = 1/n**4
175
+ f3b = (6*n + 3)/(4*n**4 + 8*n**3 + 8*n**2 + 4*n + 3)
176
+ f3c = 2**n*(n**2 - 2*n - 1)/(n**2*(n + 1)**2)
177
+ f3d = n**2*4**n/((n + 1)*(n + 2))
178
+ f3e = 2**n/(n + 1)
179
+ f3f = 4*(n - 1)*(n**2 - 2*n - 1)/(n**2*(n + 1)**2*(n - 2)**2*(n - 3)**2)
180
+ f3g = (n**4 - 14*n**2 - 24*n - 9)*2**n/(n**2*(n + 1)**2*(n + 2)**2*
181
+ (n + 3)**2)
182
+
183
+ # g3a -> no closed form
184
+ g3b = m*(m + 2)/(2*m**2 + 4*m + 3)
185
+ g3c = 2**m/m**2 - 2
186
+ g3d = Rational(2, 3) + 4**(m + 1)*(m - 1)/(m + 2)/3
187
+ # g3e -> no closed form
188
+ g3f = -(Rational(-1, 16) + 1/((m - 2)**2*(m + 1)**2)) # the AeqB key is wrong
189
+ g3g = Rational(-2, 9) + 2**(m + 1)/((m + 1)**2*(m + 3)**2)
190
+
191
+ g = gosper_sum(f3a, (n, 1, m))
192
+ assert g is None
193
+ g = gosper_sum(f3b, (n, 1, m))
194
+ assert g is not None and simplify(g - g3b) == 0
195
+ g = gosper_sum(f3c, (n, 1, m - 1))
196
+ assert g is not None and simplify(g - g3c) == 0
197
+ g = gosper_sum(f3d, (n, 1, m))
198
+ assert g is not None and simplify(g - g3d) == 0
199
+ g = gosper_sum(f3e, (n, 0, m - 1))
200
+ assert g is None
201
+ g = gosper_sum(f3f, (n, 4, m))
202
+ assert g is not None and simplify(g - g3f) == 0
203
+ g = gosper_sum(f3g, (n, 1, m))
204
+ assert g is not None and simplify(g - g3g) == 0
env-llmeval/lib/python3.10/site-packages/sympy/concrete/tests/test_guess.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.concrete.guess import (
2
+ find_simple_recurrence_vector,
3
+ find_simple_recurrence,
4
+ rationalize,
5
+ guess_generating_function_rational,
6
+ guess_generating_function,
7
+ guess
8
+ )
9
+ from sympy.concrete.products import Product
10
+ from sympy.core.function import Function
11
+ from sympy.core.numbers import Rational
12
+ from sympy.core.singleton import S
13
+ from sympy.core.symbol import (Symbol, symbols)
14
+ from sympy.core.sympify import sympify
15
+ from sympy.functions.combinatorial.factorials import (RisingFactorial, factorial)
16
+ from sympy.functions.combinatorial.numbers import fibonacci
17
+ from sympy.functions.elementary.exponential import exp
18
+
19
+
20
+ def test_find_simple_recurrence_vector():
21
+ assert find_simple_recurrence_vector(
22
+ [fibonacci(k) for k in range(12)]) == [1, -1, -1]
23
+
24
+
25
+ def test_find_simple_recurrence():
26
+ a = Function('a')
27
+ n = Symbol('n')
28
+ assert find_simple_recurrence([fibonacci(k) for k in range(12)]) == (
29
+ -a(n) - a(n + 1) + a(n + 2))
30
+
31
+ f = Function('a')
32
+ i = Symbol('n')
33
+ a = [1, 1, 1]
34
+ for k in range(15): a.append(5*a[-1]-3*a[-2]+8*a[-3])
35
+ assert find_simple_recurrence(a, A=f, N=i) == (
36
+ -8*f(i) + 3*f(i + 1) - 5*f(i + 2) + f(i + 3))
37
+ assert find_simple_recurrence([0, 2, 15, 74, 12, 3, 0,
38
+ 1, 2, 85, 4, 5, 63]) == 0
39
+
40
+
41
+ def test_rationalize():
42
+ from mpmath import cos, pi, mpf
43
+ assert rationalize(cos(pi/3)) == S.Half
44
+ assert rationalize(mpf("0.333333333333333")) == Rational(1, 3)
45
+ assert rationalize(mpf("-0.333333333333333")) == Rational(-1, 3)
46
+ assert rationalize(pi, maxcoeff = 250) == Rational(355, 113)
47
+
48
+
49
+ def test_guess_generating_function_rational():
50
+ x = Symbol('x')
51
+ assert guess_generating_function_rational([fibonacci(k)
52
+ for k in range(5, 15)]) == ((3*x + 5)/(-x**2 - x + 1))
53
+
54
+
55
+ def test_guess_generating_function():
56
+ x = Symbol('x')
57
+ assert guess_generating_function([fibonacci(k)
58
+ for k in range(5, 15)])['ogf'] == ((3*x + 5)/(-x**2 - x + 1))
59
+ assert guess_generating_function(
60
+ [1, 2, 5, 14, 41, 124, 383, 1200, 3799, 12122, 38919])['ogf'] == (
61
+ (1/(x**4 + 2*x**2 - 4*x + 1))**S.Half)
62
+ assert guess_generating_function(sympify(
63
+ "[3/2, 11/2, 0, -121/2, -363/2, 121, 4719/2, 11495/2, -8712, -178717/2]")
64
+ )['ogf'] == (x + Rational(3, 2))/(11*x**2 - 3*x + 1)
65
+ assert guess_generating_function([factorial(k) for k in range(12)],
66
+ types=['egf'])['egf'] == 1/(-x + 1)
67
+ assert guess_generating_function([k+1 for k in range(12)],
68
+ types=['egf']) == {'egf': (x + 1)*exp(x), 'lgdegf': (x + 2)/(x + 1)}
69
+
70
+
71
+ def test_guess():
72
+ i0, i1 = symbols('i0 i1')
73
+ assert guess([1, 2, 6, 24, 120], evaluate=False) == [Product(i1 + 1, (i1, 1, i0 - 1))]
74
+ assert guess([1, 2, 6, 24, 120]) == [RisingFactorial(2, i0 - 1)]
75
+ assert guess([1, 2, 7, 42, 429, 7436, 218348, 10850216], niter=4) == [
76
+ 2**(i0 - 1)*(Rational(27, 16))**(i0**2/2 - 3*i0/2 +
77
+ 1)*Product(RisingFactorial(Rational(5, 3), i1 - 1)*RisingFactorial(Rational(7, 3), i1
78
+ - 1)/(RisingFactorial(Rational(3, 2), i1 - 1)*RisingFactorial(Rational(5, 2), i1 -
79
+ 1)), (i1, 1, i0 - 1))]
80
+ assert guess([1, 0, 2]) == []
81
+ x, y = symbols('x y')
82
+ assert guess([1, 2, 6, 24, 120], variables=[x, y]) == [RisingFactorial(2, x - 1)]
env-llmeval/lib/python3.10/site-packages/sympy/concrete/tests/test_products.py ADDED
@@ -0,0 +1,410 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.concrete.products import (Product, product)
2
+ from sympy.concrete.summations import Sum
3
+ from sympy.core.function import (Derivative, Function, diff)
4
+ from sympy.core.numbers import (Rational, oo, pi)
5
+ from sympy.core.singleton import S
6
+ from sympy.core.symbol import (Dummy, Symbol, symbols)
7
+ from sympy.functions.combinatorial.factorials import (rf, factorial)
8
+ from sympy.functions.elementary.exponential import (exp, log)
9
+ from sympy.functions.elementary.miscellaneous import sqrt
10
+ from sympy.functions.elementary.trigonometric import (cos, sin)
11
+ from sympy.functions.special.tensor_functions import KroneckerDelta
12
+ from sympy.simplify.combsimp import combsimp
13
+ from sympy.simplify.simplify import simplify
14
+ from sympy.testing.pytest import raises
15
+
16
+ a, k, n, m, x = symbols('a,k,n,m,x', integer=True)
17
+ f = Function('f')
18
+
19
+
20
+ def test_karr_convention():
21
+ # Test the Karr product convention that we want to hold.
22
+ # See his paper "Summation in Finite Terms" for a detailed
23
+ # reasoning why we really want exactly this definition.
24
+ # The convention is described for sums on page 309 and
25
+ # essentially in section 1.4, definition 3. For products
26
+ # we can find in analogy:
27
+ #
28
+ # \prod_{m <= i < n} f(i) 'has the obvious meaning' for m < n
29
+ # \prod_{m <= i < n} f(i) = 0 for m = n
30
+ # \prod_{m <= i < n} f(i) = 1 / \prod_{n <= i < m} f(i) for m > n
31
+ #
32
+ # It is important to note that he defines all products with
33
+ # the upper limit being *exclusive*.
34
+ # In contrast, SymPy and the usual mathematical notation has:
35
+ #
36
+ # prod_{i = a}^b f(i) = f(a) * f(a+1) * ... * f(b-1) * f(b)
37
+ #
38
+ # with the upper limit *inclusive*. So translating between
39
+ # the two we find that:
40
+ #
41
+ # \prod_{m <= i < n} f(i) = \prod_{i = m}^{n-1} f(i)
42
+ #
43
+ # where we intentionally used two different ways to typeset the
44
+ # products and its limits.
45
+
46
+ i = Symbol("i", integer=True)
47
+ k = Symbol("k", integer=True)
48
+ j = Symbol("j", integer=True, positive=True)
49
+
50
+ # A simple example with a concrete factors and symbolic limits.
51
+
52
+ # The normal product: m = k and n = k + j and therefore m < n:
53
+ m = k
54
+ n = k + j
55
+
56
+ a = m
57
+ b = n - 1
58
+ S1 = Product(i**2, (i, a, b)).doit()
59
+
60
+ # The reversed product: m = k + j and n = k and therefore m > n:
61
+ m = k + j
62
+ n = k
63
+
64
+ a = m
65
+ b = n - 1
66
+ S2 = Product(i**2, (i, a, b)).doit()
67
+
68
+ assert S1 * S2 == 1
69
+
70
+ # Test the empty product: m = k and n = k and therefore m = n:
71
+ m = k
72
+ n = k
73
+
74
+ a = m
75
+ b = n - 1
76
+ Sz = Product(i**2, (i, a, b)).doit()
77
+
78
+ assert Sz == 1
79
+
80
+ # Another example this time with an unspecified factor and
81
+ # numeric limits. (We can not do both tests in the same example.)
82
+ f = Function("f")
83
+
84
+ # The normal product with m < n:
85
+ m = 2
86
+ n = 11
87
+
88
+ a = m
89
+ b = n - 1
90
+ S1 = Product(f(i), (i, a, b)).doit()
91
+
92
+ # The reversed product with m > n:
93
+ m = 11
94
+ n = 2
95
+
96
+ a = m
97
+ b = n - 1
98
+ S2 = Product(f(i), (i, a, b)).doit()
99
+
100
+ assert simplify(S1 * S2) == 1
101
+
102
+ # Test the empty product with m = n:
103
+ m = 5
104
+ n = 5
105
+
106
+ a = m
107
+ b = n - 1
108
+ Sz = Product(f(i), (i, a, b)).doit()
109
+
110
+ assert Sz == 1
111
+
112
+
113
+ def test_karr_proposition_2a():
114
+ # Test Karr, page 309, proposition 2, part a
115
+ i, u, v = symbols('i u v', integer=True)
116
+
117
+ def test_the_product(m, n):
118
+ # g
119
+ g = i**3 + 2*i**2 - 3*i
120
+ # f = Delta g
121
+ f = simplify(g.subs(i, i+1) / g)
122
+ # The product
123
+ a = m
124
+ b = n - 1
125
+ P = Product(f, (i, a, b)).doit()
126
+ # Test if Product_{m <= i < n} f(i) = g(n) / g(m)
127
+ assert combsimp(P / (g.subs(i, n) / g.subs(i, m))) == 1
128
+
129
+ # m < n
130
+ test_the_product(u, u + v)
131
+ # m = n
132
+ test_the_product(u, u)
133
+ # m > n
134
+ test_the_product(u + v, u)
135
+
136
+
137
+ def test_karr_proposition_2b():
138
+ # Test Karr, page 309, proposition 2, part b
139
+ i, u, v, w = symbols('i u v w', integer=True)
140
+
141
+ def test_the_product(l, n, m):
142
+ # Productmand
143
+ s = i**3
144
+ # First product
145
+ a = l
146
+ b = n - 1
147
+ S1 = Product(s, (i, a, b)).doit()
148
+ # Second product
149
+ a = l
150
+ b = m - 1
151
+ S2 = Product(s, (i, a, b)).doit()
152
+ # Third product
153
+ a = m
154
+ b = n - 1
155
+ S3 = Product(s, (i, a, b)).doit()
156
+ # Test if S1 = S2 * S3 as required
157
+ assert combsimp(S1 / (S2 * S3)) == 1
158
+
159
+ # l < m < n
160
+ test_the_product(u, u + v, u + v + w)
161
+ # l < m = n
162
+ test_the_product(u, u + v, u + v)
163
+ # l < m > n
164
+ test_the_product(u, u + v + w, v)
165
+ # l = m < n
166
+ test_the_product(u, u, u + v)
167
+ # l = m = n
168
+ test_the_product(u, u, u)
169
+ # l = m > n
170
+ test_the_product(u + v, u + v, u)
171
+ # l > m < n
172
+ test_the_product(u + v, u, u + w)
173
+ # l > m = n
174
+ test_the_product(u + v, u, u)
175
+ # l > m > n
176
+ test_the_product(u + v + w, u + v, u)
177
+
178
+
179
+ def test_simple_products():
180
+ assert product(2, (k, a, n)) == 2**(n - a + 1)
181
+ assert product(k, (k, 1, n)) == factorial(n)
182
+ assert product(k**3, (k, 1, n)) == factorial(n)**3
183
+
184
+ assert product(k + 1, (k, 0, n - 1)) == factorial(n)
185
+ assert product(k + 1, (k, a, n - 1)) == rf(1 + a, n - a)
186
+
187
+ assert product(cos(k), (k, 0, 5)) == cos(1)*cos(2)*cos(3)*cos(4)*cos(5)
188
+ assert product(cos(k), (k, 3, 5)) == cos(3)*cos(4)*cos(5)
189
+ assert product(cos(k), (k, 1, Rational(5, 2))) != cos(1)*cos(2)
190
+
191
+ assert isinstance(product(k**k, (k, 1, n)), Product)
192
+
193
+ assert Product(x**k, (k, 1, n)).variables == [k]
194
+
195
+ raises(ValueError, lambda: Product(n))
196
+ raises(ValueError, lambda: Product(n, k))
197
+ raises(ValueError, lambda: Product(n, k, 1))
198
+ raises(ValueError, lambda: Product(n, k, 1, 10))
199
+ raises(ValueError, lambda: Product(n, (k, 1)))
200
+
201
+ assert product(1, (n, 1, oo)) == 1 # issue 8301
202
+ assert product(2, (n, 1, oo)) is oo
203
+ assert product(-1, (n, 1, oo)).func is Product
204
+
205
+
206
+ def test_multiple_products():
207
+ assert product(x, (n, 1, k), (k, 1, m)) == x**(m**2/2 + m/2)
208
+ assert product(f(n), (
209
+ n, 1, m), (m, 1, k)) == Product(f(n), (n, 1, m), (m, 1, k)).doit()
210
+ assert Product(f(n), (m, 1, k), (n, 1, k)).doit() == \
211
+ Product(Product(f(n), (m, 1, k)), (n, 1, k)).doit() == \
212
+ product(f(n), (m, 1, k), (n, 1, k)) == \
213
+ product(product(f(n), (m, 1, k)), (n, 1, k)) == \
214
+ Product(f(n)**k, (n, 1, k))
215
+ assert Product(
216
+ x, (x, 1, k), (k, 1, n)).doit() == Product(factorial(k), (k, 1, n))
217
+
218
+ assert Product(x**k, (n, 1, k), (k, 1, m)).variables == [n, k]
219
+
220
+
221
+ def test_rational_products():
222
+ assert product(1 + 1/k, (k, 1, n)) == rf(2, n)/factorial(n)
223
+
224
+
225
+ def test_special_products():
226
+ # Wallis product
227
+ assert product((4*k)**2 / (4*k**2 - 1), (k, 1, n)) == \
228
+ 4**n*factorial(n)**2/rf(S.Half, n)/rf(Rational(3, 2), n)
229
+
230
+ # Euler's product formula for sin
231
+ assert product(1 + a/k**2, (k, 1, n)) == \
232
+ rf(1 - sqrt(-a), n)*rf(1 + sqrt(-a), n)/factorial(n)**2
233
+
234
+
235
+ def test__eval_product():
236
+ from sympy.abc import i, n
237
+ # issue 4809
238
+ a = Function('a')
239
+ assert product(2*a(i), (i, 1, n)) == 2**n * Product(a(i), (i, 1, n))
240
+ # issue 4810
241
+ assert product(2**i, (i, 1, n)) == 2**(n*(n + 1)/2)
242
+ k, m = symbols('k m', integer=True)
243
+ assert product(2**i, (i, k, m)) == 2**(-k**2/2 + k/2 + m**2/2 + m/2)
244
+ n = Symbol('n', negative=True, integer=True)
245
+ p = Symbol('p', positive=True, integer=True)
246
+ assert product(2**i, (i, n, p)) == 2**(-n**2/2 + n/2 + p**2/2 + p/2)
247
+ assert product(2**i, (i, p, n)) == 2**(n**2/2 + n/2 - p**2/2 + p/2)
248
+
249
+
250
+ def test_product_pow():
251
+ # issue 4817
252
+ assert product(2**f(k), (k, 1, n)) == 2**Sum(f(k), (k, 1, n))
253
+ assert product(2**(2*f(k)), (k, 1, n)) == 2**Sum(2*f(k), (k, 1, n))
254
+
255
+
256
+ def test_infinite_product():
257
+ # issue 5737
258
+ assert isinstance(Product(2**(1/factorial(n)), (n, 0, oo)), Product)
259
+
260
+
261
+ def test_conjugate_transpose():
262
+ p = Product(x**k, (k, 1, 3))
263
+ assert p.adjoint().doit() == p.doit().adjoint()
264
+ assert p.conjugate().doit() == p.doit().conjugate()
265
+ assert p.transpose().doit() == p.doit().transpose()
266
+
267
+ A, B = symbols("A B", commutative=False)
268
+ p = Product(A*B**k, (k, 1, 3))
269
+ assert p.adjoint().doit() == p.doit().adjoint()
270
+ assert p.conjugate().doit() == p.doit().conjugate()
271
+ assert p.transpose().doit() == p.doit().transpose()
272
+
273
+ p = Product(B**k*A, (k, 1, 3))
274
+ assert p.adjoint().doit() == p.doit().adjoint()
275
+ assert p.conjugate().doit() == p.doit().conjugate()
276
+ assert p.transpose().doit() == p.doit().transpose()
277
+
278
+
279
+ def test_simplify_prod():
280
+ y, t, b, c, v, d = symbols('y, t, b, c, v, d', integer = True)
281
+
282
+ _simplify = lambda e: simplify(e, doit=False)
283
+ assert _simplify(Product(x*y, (x, n, m), (y, a, k)) * \
284
+ Product(y, (x, n, m), (y, a, k))) == \
285
+ Product(x*y**2, (x, n, m), (y, a, k))
286
+ assert _simplify(3 * y* Product(x, (x, n, m)) * Product(x, (x, m + 1, a))) \
287
+ == 3 * y * Product(x, (x, n, a))
288
+ assert _simplify(Product(x, (x, k + 1, a)) * Product(x, (x, n, k))) == \
289
+ Product(x, (x, n, a))
290
+ assert _simplify(Product(x, (x, k + 1, a)) * Product(x + 1, (x, n, k))) == \
291
+ Product(x, (x, k + 1, a)) * Product(x + 1, (x, n, k))
292
+ assert _simplify(Product(x, (t, a, b)) * Product(y, (t, a, b)) * \
293
+ Product(x, (t, b+1, c))) == Product(x*y, (t, a, b)) * \
294
+ Product(x, (t, b+1, c))
295
+ assert _simplify(Product(x, (t, a, b)) * Product(x, (t, b+1, c)) * \
296
+ Product(y, (t, a, b))) == Product(x*y, (t, a, b)) * \
297
+ Product(x, (t, b+1, c))
298
+ assert _simplify(Product(sin(t)**2 + cos(t)**2 + 1, (t, a, b))) == \
299
+ Product(2, (t, a, b))
300
+ assert _simplify(Product(sin(t)**2 + cos(t)**2 - 1, (t, a, b))) == \
301
+ Product(0, (t, a, b))
302
+ assert _simplify(Product(v*Product(sin(t)**2 + cos(t)**2, (t, a, b)),
303
+ (v, c, d))) == Product(v*Product(1, (t, a, b)), (v, c, d))
304
+
305
+
306
+ def test_change_index():
307
+ b, y, c, d, z = symbols('b, y, c, d, z', integer = True)
308
+
309
+ assert Product(x, (x, a, b)).change_index(x, x + 1, y) == \
310
+ Product(y - 1, (y, a + 1, b + 1))
311
+ assert Product(x**2, (x, a, b)).change_index(x, x - 1) == \
312
+ Product((x + 1)**2, (x, a - 1, b - 1))
313
+ assert Product(x**2, (x, a, b)).change_index(x, -x, y) == \
314
+ Product((-y)**2, (y, -b, -a))
315
+ assert Product(x, (x, a, b)).change_index(x, -x - 1) == \
316
+ Product(-x - 1, (x, - b - 1, -a - 1))
317
+ assert Product(x*y, (x, a, b), (y, c, d)).change_index(x, x - 1, z) == \
318
+ Product((z + 1)*y, (z, a - 1, b - 1), (y, c, d))
319
+
320
+
321
+ def test_reorder():
322
+ b, y, c, d, z = symbols('b, y, c, d, z', integer = True)
323
+
324
+ assert Product(x*y, (x, a, b), (y, c, d)).reorder((0, 1)) == \
325
+ Product(x*y, (y, c, d), (x, a, b))
326
+ assert Product(x, (x, a, b), (x, c, d)).reorder((0, 1)) == \
327
+ Product(x, (x, c, d), (x, a, b))
328
+ assert Product(x*y + z, (x, a, b), (z, m, n), (y, c, d)).reorder(\
329
+ (2, 0), (0, 1)) == Product(x*y + z, (z, m, n), (y, c, d), (x, a, b))
330
+ assert Product(x*y*z, (x, a, b), (y, c, d), (z, m, n)).reorder(\
331
+ (0, 1), (1, 2), (0, 2)) == \
332
+ Product(x*y*z, (x, a, b), (z, m, n), (y, c, d))
333
+ assert Product(x*y*z, (x, a, b), (y, c, d), (z, m, n)).reorder(\
334
+ (x, y), (y, z), (x, z)) == \
335
+ Product(x*y*z, (x, a, b), (z, m, n), (y, c, d))
336
+ assert Product(x*y, (x, a, b), (y, c, d)).reorder((x, 1)) == \
337
+ Product(x*y, (y, c, d), (x, a, b))
338
+ assert Product(x*y, (x, a, b), (y, c, d)).reorder((y, x)) == \
339
+ Product(x*y, (y, c, d), (x, a, b))
340
+
341
+
342
+ def test_Product_is_convergent():
343
+ assert Product(1/n**2, (n, 1, oo)).is_convergent() is S.false
344
+ assert Product(exp(1/n**2), (n, 1, oo)).is_convergent() is S.true
345
+ assert Product(1/n, (n, 1, oo)).is_convergent() is S.false
346
+ assert Product(1 + 1/n, (n, 1, oo)).is_convergent() is S.false
347
+ assert Product(1 + 1/n**2, (n, 1, oo)).is_convergent() is S.true
348
+
349
+
350
+ def test_reverse_order():
351
+ x, y, a, b, c, d= symbols('x, y, a, b, c, d', integer = True)
352
+
353
+ assert Product(x, (x, 0, 3)).reverse_order(0) == Product(1/x, (x, 4, -1))
354
+ assert Product(x*y, (x, 1, 5), (y, 0, 6)).reverse_order(0, 1) == \
355
+ Product(x*y, (x, 6, 0), (y, 7, -1))
356
+ assert Product(x, (x, 1, 2)).reverse_order(0) == Product(1/x, (x, 3, 0))
357
+ assert Product(x, (x, 1, 3)).reverse_order(0) == Product(1/x, (x, 4, 0))
358
+ assert Product(x, (x, 1, a)).reverse_order(0) == Product(1/x, (x, a + 1, 0))
359
+ assert Product(x, (x, a, 5)).reverse_order(0) == Product(1/x, (x, 6, a - 1))
360
+ assert Product(x, (x, a + 1, a + 5)).reverse_order(0) == \
361
+ Product(1/x, (x, a + 6, a))
362
+ assert Product(x, (x, a + 1, a + 2)).reverse_order(0) == \
363
+ Product(1/x, (x, a + 3, a))
364
+ assert Product(x, (x, a + 1, a + 1)).reverse_order(0) == \
365
+ Product(1/x, (x, a + 2, a))
366
+ assert Product(x, (x, a, b)).reverse_order(0) == Product(1/x, (x, b + 1, a - 1))
367
+ assert Product(x, (x, a, b)).reverse_order(x) == Product(1/x, (x, b + 1, a - 1))
368
+ assert Product(x*y, (x, a, b), (y, 2, 5)).reverse_order(x, 1) == \
369
+ Product(x*y, (x, b + 1, a - 1), (y, 6, 1))
370
+ assert Product(x*y, (x, a, b), (y, 2, 5)).reverse_order(y, x) == \
371
+ Product(x*y, (x, b + 1, a - 1), (y, 6, 1))
372
+
373
+
374
+ def test_issue_9983():
375
+ n = Symbol('n', integer=True, positive=True)
376
+ p = Product(1 + 1/n**Rational(2, 3), (n, 1, oo))
377
+ assert p.is_convergent() is S.false
378
+ assert product(1 + 1/n**Rational(2, 3), (n, 1, oo)) == p.doit()
379
+
380
+
381
+ def test_issue_13546():
382
+ n = Symbol('n')
383
+ k = Symbol('k')
384
+ p = Product(n + 1 / 2**k, (k, 0, n-1)).doit()
385
+ assert p.subs(n, 2).doit() == Rational(15, 2)
386
+
387
+
388
+ def test_issue_14036():
389
+ a, n = symbols('a n')
390
+ assert product(1 - a**2 / (n*pi)**2, [n, 1, oo]) != 0
391
+
392
+
393
+ def test_rewrite_Sum():
394
+ assert Product(1 - S.Half**2/k**2, (k, 1, oo)).rewrite(Sum) == \
395
+ exp(Sum(log(1 - 1/(4*k**2)), (k, 1, oo)))
396
+
397
+
398
+ def test_KroneckerDelta_Product():
399
+ y = Symbol('y')
400
+ assert Product(x*KroneckerDelta(x, y), (x, 0, 1)).doit() == 0
401
+
402
+
403
+ def test_issue_20848():
404
+ _i = Dummy('i')
405
+ t, y, z = symbols('t y z')
406
+ assert diff(Product(x, (y, 1, z)), x).as_dummy() == Sum(Product(x, (y, 1, _i - 1))*Product(x, (y, _i + 1, z)), (_i, 1, z)).as_dummy()
407
+ assert diff(Product(x, (y, 1, z)), x).doit() == x**(z - 1)*z
408
+ assert diff(Product(x, (y, x, z)), x) == Derivative(Product(x, (y, x, z)), x)
409
+ assert diff(Product(t, (x, 1, z)), x) == S(0)
410
+ assert Product(sin(n*x), (n, -1, 1)).diff(x).doit() == S(0)
env-llmeval/lib/python3.10/site-packages/sympy/concrete/tests/test_sums_products.py ADDED
@@ -0,0 +1,1646 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from math import prod
2
+
3
+ from sympy.concrete.expr_with_intlimits import ReorderError
4
+ from sympy.concrete.products import (Product, product)
5
+ from sympy.concrete.summations import (Sum, summation, telescopic,
6
+ eval_sum_residue, _dummy_with_inherited_properties_concrete)
7
+ from sympy.core.function import (Derivative, Function)
8
+ from sympy.core import (Catalan, EulerGamma)
9
+ from sympy.core.facts import InconsistentAssumptions
10
+ from sympy.core.mod import Mod
11
+ from sympy.core.numbers import (E, I, Rational, nan, oo, pi)
12
+ from sympy.core.relational import Eq
13
+ from sympy.core.numbers import Float
14
+ from sympy.core.singleton import S
15
+ from sympy.core.symbol import (Dummy, Symbol, symbols)
16
+ from sympy.core.sympify import sympify
17
+ from sympy.functions.combinatorial.factorials import (rf, binomial, factorial)
18
+ from sympy.functions.combinatorial.numbers import harmonic
19
+ from sympy.functions.elementary.complexes import Abs
20
+ from sympy.functions.elementary.exponential import (exp, log)
21
+ from sympy.functions.elementary.hyperbolic import (sinh, tanh)
22
+ from sympy.functions.elementary.integers import floor
23
+ from sympy.functions.elementary.miscellaneous import sqrt
24
+ from sympy.functions.elementary.piecewise import Piecewise
25
+ from sympy.functions.elementary.trigonometric import (cos, sin)
26
+ from sympy.functions.special.gamma_functions import (gamma, lowergamma)
27
+ from sympy.functions.special.tensor_functions import KroneckerDelta
28
+ from sympy.functions.special.zeta_functions import zeta
29
+ from sympy.integrals.integrals import Integral
30
+ from sympy.logic.boolalg import And, Or
31
+ from sympy.matrices.expressions.matexpr import MatrixSymbol
32
+ from sympy.matrices.expressions.special import Identity
33
+ from sympy.matrices import (Matrix, SparseMatrix,
34
+ ImmutableDenseMatrix, ImmutableSparseMatrix, diag)
35
+ from sympy.sets.fancysets import Range
36
+ from sympy.sets.sets import Interval
37
+ from sympy.simplify.combsimp import combsimp
38
+ from sympy.simplify.simplify import simplify
39
+ from sympy.tensor.indexed import (Idx, Indexed, IndexedBase)
40
+ from sympy.testing.pytest import XFAIL, raises, slow
41
+ from sympy.abc import a, b, c, d, k, m, x, y, z
42
+
43
+ n = Symbol('n', integer=True)
44
+ f, g = symbols('f g', cls=Function)
45
+
46
+ def test_karr_convention():
47
+ # Test the Karr summation convention that we want to hold.
48
+ # See his paper "Summation in Finite Terms" for a detailed
49
+ # reasoning why we really want exactly this definition.
50
+ # The convention is described on page 309 and essentially
51
+ # in section 1.4, definition 3:
52
+ #
53
+ # \sum_{m <= i < n} f(i) 'has the obvious meaning' for m < n
54
+ # \sum_{m <= i < n} f(i) = 0 for m = n
55
+ # \sum_{m <= i < n} f(i) = - \sum_{n <= i < m} f(i) for m > n
56
+ #
57
+ # It is important to note that he defines all sums with
58
+ # the upper limit being *exclusive*.
59
+ # In contrast, SymPy and the usual mathematical notation has:
60
+ #
61
+ # sum_{i = a}^b f(i) = f(a) + f(a+1) + ... + f(b-1) + f(b)
62
+ #
63
+ # with the upper limit *inclusive*. So translating between
64
+ # the two we find that:
65
+ #
66
+ # \sum_{m <= i < n} f(i) = \sum_{i = m}^{n-1} f(i)
67
+ #
68
+ # where we intentionally used two different ways to typeset the
69
+ # sum and its limits.
70
+
71
+ i = Symbol("i", integer=True)
72
+ k = Symbol("k", integer=True)
73
+ j = Symbol("j", integer=True)
74
+
75
+ # A simple example with a concrete summand and symbolic limits.
76
+
77
+ # The normal sum: m = k and n = k + j and therefore m < n:
78
+ m = k
79
+ n = k + j
80
+
81
+ a = m
82
+ b = n - 1
83
+ S1 = Sum(i**2, (i, a, b)).doit()
84
+
85
+ # The reversed sum: m = k + j and n = k and therefore m > n:
86
+ m = k + j
87
+ n = k
88
+
89
+ a = m
90
+ b = n - 1
91
+ S2 = Sum(i**2, (i, a, b)).doit()
92
+
93
+ assert simplify(S1 + S2) == 0
94
+
95
+ # Test the empty sum: m = k and n = k and therefore m = n:
96
+ m = k
97
+ n = k
98
+
99
+ a = m
100
+ b = n - 1
101
+ Sz = Sum(i**2, (i, a, b)).doit()
102
+
103
+ assert Sz == 0
104
+
105
+ # Another example this time with an unspecified summand and
106
+ # numeric limits. (We can not do both tests in the same example.)
107
+
108
+ # The normal sum with m < n:
109
+ m = 2
110
+ n = 11
111
+
112
+ a = m
113
+ b = n - 1
114
+ S1 = Sum(f(i), (i, a, b)).doit()
115
+
116
+ # The reversed sum with m > n:
117
+ m = 11
118
+ n = 2
119
+
120
+ a = m
121
+ b = n - 1
122
+ S2 = Sum(f(i), (i, a, b)).doit()
123
+
124
+ assert simplify(S1 + S2) == 0
125
+
126
+ # Test the empty sum with m = n:
127
+ m = 5
128
+ n = 5
129
+
130
+ a = m
131
+ b = n - 1
132
+ Sz = Sum(f(i), (i, a, b)).doit()
133
+
134
+ assert Sz == 0
135
+
136
+ e = Piecewise((exp(-i), Mod(i, 2) > 0), (0, True))
137
+ s = Sum(e, (i, 0, 11))
138
+ assert s.n(3) == s.doit().n(3)
139
+
140
+
141
+ def test_karr_proposition_2a():
142
+ # Test Karr, page 309, proposition 2, part a
143
+ i = Symbol("i", integer=True)
144
+ u = Symbol("u", integer=True)
145
+ v = Symbol("v", integer=True)
146
+
147
+ def test_the_sum(m, n):
148
+ # g
149
+ g = i**3 + 2*i**2 - 3*i
150
+ # f = Delta g
151
+ f = simplify(g.subs(i, i+1) - g)
152
+ # The sum
153
+ a = m
154
+ b = n - 1
155
+ S = Sum(f, (i, a, b)).doit()
156
+ # Test if Sum_{m <= i < n} f(i) = g(n) - g(m)
157
+ assert simplify(S - (g.subs(i, n) - g.subs(i, m))) == 0
158
+
159
+ # m < n
160
+ test_the_sum(u, u+v)
161
+ # m = n
162
+ test_the_sum(u, u )
163
+ # m > n
164
+ test_the_sum(u+v, u )
165
+
166
+
167
+ def test_karr_proposition_2b():
168
+ # Test Karr, page 309, proposition 2, part b
169
+ i = Symbol("i", integer=True)
170
+ u = Symbol("u", integer=True)
171
+ v = Symbol("v", integer=True)
172
+ w = Symbol("w", integer=True)
173
+
174
+ def test_the_sum(l, n, m):
175
+ # Summand
176
+ s = i**3
177
+ # First sum
178
+ a = l
179
+ b = n - 1
180
+ S1 = Sum(s, (i, a, b)).doit()
181
+ # Second sum
182
+ a = l
183
+ b = m - 1
184
+ S2 = Sum(s, (i, a, b)).doit()
185
+ # Third sum
186
+ a = m
187
+ b = n - 1
188
+ S3 = Sum(s, (i, a, b)).doit()
189
+ # Test if S1 = S2 + S3 as required
190
+ assert S1 - (S2 + S3) == 0
191
+
192
+ # l < m < n
193
+ test_the_sum(u, u+v, u+v+w)
194
+ # l < m = n
195
+ test_the_sum(u, u+v, u+v )
196
+ # l < m > n
197
+ test_the_sum(u, u+v+w, v )
198
+ # l = m < n
199
+ test_the_sum(u, u, u+v )
200
+ # l = m = n
201
+ test_the_sum(u, u, u )
202
+ # l = m > n
203
+ test_the_sum(u+v, u+v, u )
204
+ # l > m < n
205
+ test_the_sum(u+v, u, u+w )
206
+ # l > m = n
207
+ test_the_sum(u+v, u, u )
208
+ # l > m > n
209
+ test_the_sum(u+v+w, u+v, u )
210
+
211
+
212
+ def test_arithmetic_sums():
213
+ assert summation(1, (n, a, b)) == b - a + 1
214
+ assert Sum(S.NaN, (n, a, b)) is S.NaN
215
+ assert Sum(x, (n, a, a)).doit() == x
216
+ assert Sum(x, (x, a, a)).doit() == a
217
+ assert Sum(x, (n, 1, a)).doit() == a*x
218
+ assert Sum(x, (x, Range(1, 11))).doit() == 55
219
+ assert Sum(x, (x, Range(1, 11, 2))).doit() == 25
220
+ assert Sum(x, (x, Range(1, 10, 2))) == Sum(x, (x, Range(9, 0, -2)))
221
+ lo, hi = 1, 2
222
+ s1 = Sum(n, (n, lo, hi))
223
+ s2 = Sum(n, (n, hi, lo))
224
+ assert s1 != s2
225
+ assert s1.doit() == 3 and s2.doit() == 0
226
+ lo, hi = x, x + 1
227
+ s1 = Sum(n, (n, lo, hi))
228
+ s2 = Sum(n, (n, hi, lo))
229
+ assert s1 != s2
230
+ assert s1.doit() == 2*x + 1 and s2.doit() == 0
231
+ assert Sum(Integral(x, (x, 1, y)) + x, (x, 1, 2)).doit() == \
232
+ y**2 + 2
233
+ assert summation(1, (n, 1, 10)) == 10
234
+ assert summation(2*n, (n, 0, 10**10)) == 100000000010000000000
235
+ assert summation(4*n*m, (n, a, 1), (m, 1, d)).expand() == \
236
+ 2*d + 2*d**2 + a*d + a*d**2 - d*a**2 - a**2*d**2
237
+ assert summation(cos(n), (n, -2, 1)) == cos(-2) + cos(-1) + cos(0) + cos(1)
238
+ assert summation(cos(n), (n, x, x + 2)) == cos(x) + cos(x + 1) + cos(x + 2)
239
+ assert isinstance(summation(cos(n), (n, x, x + S.Half)), Sum)
240
+ assert summation(k, (k, 0, oo)) is oo
241
+ assert summation(k, (k, Range(1, 11))) == 55
242
+
243
+
244
+ def test_polynomial_sums():
245
+ assert summation(n**2, (n, 3, 8)) == 199
246
+ assert summation(n, (n, a, b)) == \
247
+ ((a + b)*(b - a + 1)/2).expand()
248
+ assert summation(n**2, (n, 1, b)) == \
249
+ ((2*b**3 + 3*b**2 + b)/6).expand()
250
+ assert summation(n**3, (n, 1, b)) == \
251
+ ((b**4 + 2*b**3 + b**2)/4).expand()
252
+ assert summation(n**6, (n, 1, b)) == \
253
+ ((6*b**7 + 21*b**6 + 21*b**5 - 7*b**3 + b)/42).expand()
254
+
255
+
256
+ def test_geometric_sums():
257
+ assert summation(pi**n, (n, 0, b)) == (1 - pi**(b + 1)) / (1 - pi)
258
+ assert summation(2 * 3**n, (n, 0, b)) == 3**(b + 1) - 1
259
+ assert summation(S.Half**n, (n, 1, oo)) == 1
260
+ assert summation(2**n, (n, 0, b)) == 2**(b + 1) - 1
261
+ assert summation(2**n, (n, 1, oo)) is oo
262
+ assert summation(2**(-n), (n, 1, oo)) == 1
263
+ assert summation(3**(-n), (n, 4, oo)) == Rational(1, 54)
264
+ assert summation(2**(-4*n + 3), (n, 1, oo)) == Rational(8, 15)
265
+ assert summation(2**(n + 1), (n, 1, b)).expand() == 4*(2**b - 1)
266
+
267
+ # issue 6664:
268
+ assert summation(x**n, (n, 0, oo)) == \
269
+ Piecewise((1/(-x + 1), Abs(x) < 1), (Sum(x**n, (n, 0, oo)), True))
270
+
271
+ assert summation(-2**n, (n, 0, oo)) is -oo
272
+ assert summation(I**n, (n, 0, oo)) == Sum(I**n, (n, 0, oo))
273
+
274
+ # issue 6802:
275
+ assert summation((-1)**(2*x + 2), (x, 0, n)) == n + 1
276
+ assert summation((-2)**(2*x + 2), (x, 0, n)) == 4*4**(n + 1)/S(3) - Rational(4, 3)
277
+ assert summation((-1)**x, (x, 0, n)) == -(-1)**(n + 1)/S(2) + S.Half
278
+ assert summation(y**x, (x, a, b)) == \
279
+ Piecewise((-a + b + 1, Eq(y, 1)), ((y**a - y**(b + 1))/(-y + 1), True))
280
+ assert summation((-2)**(y*x + 2), (x, 0, n)) == \
281
+ 4*Piecewise((n + 1, Eq((-2)**y, 1)),
282
+ ((-(-2)**(y*(n + 1)) + 1)/(-(-2)**y + 1), True))
283
+
284
+ # issue 8251:
285
+ assert summation((1/(n + 1)**2)*n**2, (n, 0, oo)) is oo
286
+
287
+ #issue 9908:
288
+ assert Sum(1/(n**3 - 1), (n, -oo, -2)).doit() == summation(1/(n**3 - 1), (n, -oo, -2))
289
+
290
+ #issue 11642:
291
+ result = Sum(0.5**n, (n, 1, oo)).doit()
292
+ assert result == 1.0
293
+ assert result.is_Float
294
+
295
+ result = Sum(0.25**n, (n, 1, oo)).doit()
296
+ assert result == 1/3.
297
+ assert result.is_Float
298
+
299
+ result = Sum(0.99999**n, (n, 1, oo)).doit()
300
+ assert result == 99999.0
301
+ assert result.is_Float
302
+
303
+ result = Sum(S.Half**n, (n, 1, oo)).doit()
304
+ assert result == 1
305
+ assert not result.is_Float
306
+
307
+ result = Sum(Rational(3, 5)**n, (n, 1, oo)).doit()
308
+ assert result == Rational(3, 2)
309
+ assert not result.is_Float
310
+
311
+ assert Sum(1.0**n, (n, 1, oo)).doit() is oo
312
+ assert Sum(2.43**n, (n, 1, oo)).doit() is oo
313
+
314
+ # Issue 13979
315
+ i, k, q = symbols('i k q', integer=True)
316
+ result = summation(
317
+ exp(-2*I*pi*k*i/n) * exp(2*I*pi*q*i/n) / n, (i, 0, n - 1)
318
+ )
319
+ assert result.simplify() == Piecewise(
320
+ (1, Eq(exp(-2*I*pi*(k - q)/n), 1)), (0, True)
321
+ )
322
+
323
+ #Issue 23491
324
+ assert Sum(1/(n**2 + 1), (n, 1, oo)).doit() == S(-1)/2 + pi/(2*tanh(pi))
325
+
326
+ def test_harmonic_sums():
327
+ assert summation(1/k, (k, 0, n)) == Sum(1/k, (k, 0, n))
328
+ assert summation(1/k, (k, 1, n)) == harmonic(n)
329
+ assert summation(n/k, (k, 1, n)) == n*harmonic(n)
330
+ assert summation(1/k, (k, 5, n)) == harmonic(n) - harmonic(4)
331
+
332
+
333
+ def test_composite_sums():
334
+ f = S.Half*(7 - 6*n + Rational(1, 7)*n**3)
335
+ s = summation(f, (n, a, b))
336
+ assert not isinstance(s, Sum)
337
+ A = 0
338
+ for i in range(-3, 5):
339
+ A += f.subs(n, i)
340
+ B = s.subs(a, -3).subs(b, 4)
341
+ assert A == B
342
+
343
+
344
+ def test_hypergeometric_sums():
345
+ assert summation(
346
+ binomial(2*k, k)/4**k, (k, 0, n)) == (1 + 2*n)*binomial(2*n, n)/4**n
347
+ assert summation(binomial(2*k, k)/5**k, (k, -oo, oo)) == sqrt(5)
348
+
349
+
350
+ def test_other_sums():
351
+ f = m**2 + m*exp(m)
352
+ g = 3*exp(Rational(3, 2))/2 + exp(S.Half)/2 - exp(Rational(-1, 2))/2 - 3*exp(Rational(-3, 2))/2 + 5
353
+
354
+ assert summation(f, (m, Rational(-3, 2), Rational(3, 2))) == g
355
+ assert summation(f, (m, -1.5, 1.5)).evalf().epsilon_eq(g.evalf(), 1e-10)
356
+
357
+ fac = factorial
358
+
359
+
360
+ def NS(e, n=15, **options):
361
+ return str(sympify(e).evalf(n, **options))
362
+
363
+
364
+ def test_evalf_fast_series():
365
+ # Euler transformed series for sqrt(1+x)
366
+ assert NS(Sum(
367
+ fac(2*n + 1)/fac(n)**2/2**(3*n + 1), (n, 0, oo)), 100) == NS(sqrt(2), 100)
368
+
369
+ # Some series for exp(1)
370
+ estr = NS(E, 100)
371
+ assert NS(Sum(1/fac(n), (n, 0, oo)), 100) == estr
372
+ assert NS(1/Sum((1 - 2*n)/fac(2*n), (n, 0, oo)), 100) == estr
373
+ assert NS(Sum((2*n + 1)/fac(2*n), (n, 0, oo)), 100) == estr
374
+ assert NS(Sum((4*n + 3)/2**(2*n + 1)/fac(2*n + 1), (n, 0, oo))**2, 100) == estr
375
+
376
+ pistr = NS(pi, 100)
377
+ # Ramanujan series for pi
378
+ assert NS(9801/sqrt(8)/Sum(fac(
379
+ 4*n)*(1103 + 26390*n)/fac(n)**4/396**(4*n), (n, 0, oo)), 100) == pistr
380
+ assert NS(1/Sum(
381
+ binomial(2*n, n)**3 * (42*n + 5)/2**(12*n + 4), (n, 0, oo)), 100) == pistr
382
+ # Machin's formula for pi
383
+ assert NS(16*Sum((-1)**n/(2*n + 1)/5**(2*n + 1), (n, 0, oo)) -
384
+ 4*Sum((-1)**n/(2*n + 1)/239**(2*n + 1), (n, 0, oo)), 100) == pistr
385
+
386
+ # Apery's constant
387
+ astr = NS(zeta(3), 100)
388
+ P = 126392*n**5 + 412708*n**4 + 531578*n**3 + 336367*n**2 + 104000* \
389
+ n + 12463
390
+ assert NS(Sum((-1)**n * P / 24 * (fac(2*n + 1)*fac(2*n)*fac(
391
+ n))**3 / fac(3*n + 2) / fac(4*n + 3)**3, (n, 0, oo)), 100) == astr
392
+ assert NS(Sum((-1)**n * (205*n**2 + 250*n + 77)/64 * fac(n)**10 /
393
+ fac(2*n + 1)**5, (n, 0, oo)), 100) == astr
394
+
395
+
396
+ def test_evalf_fast_series_issue_4021():
397
+ # Catalan's constant
398
+ assert NS(Sum((-1)**(n - 1)*2**(8*n)*(40*n**2 - 24*n + 3)*fac(2*n)**3*
399
+ fac(n)**2/n**3/(2*n - 1)/fac(4*n)**2, (n, 1, oo))/64, 100) == \
400
+ NS(Catalan, 100)
401
+ astr = NS(zeta(3), 100)
402
+ assert NS(5*Sum(
403
+ (-1)**(n - 1)*fac(n)**2 / n**3 / fac(2*n), (n, 1, oo))/2, 100) == astr
404
+ assert NS(Sum((-1)**(n - 1)*(56*n**2 - 32*n + 5) / (2*n - 1)**2 * fac(n - 1)
405
+ **3 / fac(3*n), (n, 1, oo))/4, 100) == astr
406
+
407
+
408
+ def test_evalf_slow_series():
409
+ assert NS(Sum((-1)**n / n, (n, 1, oo)), 15) == NS(-log(2), 15)
410
+ assert NS(Sum((-1)**n / n, (n, 1, oo)), 50) == NS(-log(2), 50)
411
+ assert NS(Sum(1/n**2, (n, 1, oo)), 15) == NS(pi**2/6, 15)
412
+ assert NS(Sum(1/n**2, (n, 1, oo)), 100) == NS(pi**2/6, 100)
413
+ assert NS(Sum(1/n**2, (n, 1, oo)), 500) == NS(pi**2/6, 500)
414
+ assert NS(Sum((-1)**n / (2*n + 1)**3, (n, 0, oo)), 15) == NS(pi**3/32, 15)
415
+ assert NS(Sum((-1)**n / (2*n + 1)**3, (n, 0, oo)), 50) == NS(pi**3/32, 50)
416
+
417
+
418
+ def test_evalf_oo_to_oo():
419
+ # There used to be an error in certain cases
420
+ # Does not evaluate, but at least do not throw an error
421
+ # Evaluates symbolically to 0, which is not correct
422
+ assert Sum(1/(n**2+1), (n, -oo, oo)).evalf() == Sum(1/(n**2+1), (n, -oo, oo))
423
+ # This evaluates if from 1 to oo and symbolically
424
+ assert Sum(1/(factorial(abs(n))), (n, -oo, -1)).evalf() == Sum(1/(factorial(abs(n))), (n, -oo, -1))
425
+
426
+
427
+ def test_euler_maclaurin():
428
+ # Exact polynomial sums with E-M
429
+ def check_exact(f, a, b, m, n):
430
+ A = Sum(f, (k, a, b))
431
+ s, e = A.euler_maclaurin(m, n)
432
+ assert (e == 0) and (s.expand() == A.doit())
433
+ check_exact(k**4, a, b, 0, 2)
434
+ check_exact(k**4 + 2*k, a, b, 1, 2)
435
+ check_exact(k**4 + k**2, a, b, 1, 5)
436
+ check_exact(k**5, 2, 6, 1, 2)
437
+ check_exact(k**5, 2, 6, 1, 3)
438
+ assert Sum(x-1, (x, 0, 2)).euler_maclaurin(m=30, n=30, eps=2**-15) == (0, 0)
439
+ # Not exact
440
+ assert Sum(k**6, (k, a, b)).euler_maclaurin(0, 2)[1] != 0
441
+ # Numerical test
442
+ for mi, ni in [(2, 4), (2, 20), (10, 20), (18, 20)]:
443
+ A = Sum(1/k**3, (k, 1, oo))
444
+ s, e = A.euler_maclaurin(mi, ni)
445
+ assert abs((s - zeta(3)).evalf()) < e.evalf()
446
+
447
+ raises(ValueError, lambda: Sum(1, (x, 0, 1), (k, 0, 1)).euler_maclaurin())
448
+
449
+
450
+ @slow
451
+ def test_evalf_euler_maclaurin():
452
+ assert NS(Sum(1/k**k, (k, 1, oo)), 15) == '1.29128599706266'
453
+ assert NS(Sum(1/k**k, (k, 1, oo)),
454
+ 50) == '1.2912859970626635404072825905956005414986193682745'
455
+ assert NS(Sum(1/k - log(1 + 1/k), (k, 1, oo)), 15) == NS(EulerGamma, 15)
456
+ assert NS(Sum(1/k - log(1 + 1/k), (k, 1, oo)), 50) == NS(EulerGamma, 50)
457
+ assert NS(Sum(log(k)/k**2, (k, 1, oo)), 15) == '0.937548254315844'
458
+ assert NS(Sum(log(k)/k**2, (k, 1, oo)),
459
+ 50) == '0.93754825431584375370257409456786497789786028861483'
460
+ assert NS(Sum(1/k, (k, 1000000, 2000000)), 15) == '0.693147930560008'
461
+ assert NS(Sum(1/k, (k, 1000000, 2000000)),
462
+ 50) == '0.69314793056000780941723211364567656807940638436025'
463
+
464
+
465
+ def test_evalf_symbolic():
466
+ # issue 6328
467
+ expr = Sum(f(x), (x, 1, 3)) + Sum(g(x), (x, 1, 3))
468
+ assert expr.evalf() == expr
469
+
470
+
471
+ def test_evalf_issue_3273():
472
+ assert Sum(0, (k, 1, oo)).evalf() == 0
473
+
474
+
475
+ def test_simple_products():
476
+ assert Product(S.NaN, (x, 1, 3)) is S.NaN
477
+ assert product(S.NaN, (x, 1, 3)) is S.NaN
478
+ assert Product(x, (n, a, a)).doit() == x
479
+ assert Product(x, (x, a, a)).doit() == a
480
+ assert Product(x, (y, 1, a)).doit() == x**a
481
+
482
+ lo, hi = 1, 2
483
+ s1 = Product(n, (n, lo, hi))
484
+ s2 = Product(n, (n, hi, lo))
485
+ assert s1 != s2
486
+ # This IS correct according to Karr product convention
487
+ assert s1.doit() == 2
488
+ assert s2.doit() == 1
489
+
490
+ lo, hi = x, x + 1
491
+ s1 = Product(n, (n, lo, hi))
492
+ s2 = Product(n, (n, hi, lo))
493
+ s3 = 1 / Product(n, (n, hi + 1, lo - 1))
494
+ assert s1 != s2
495
+ # This IS correct according to Karr product convention
496
+ assert s1.doit() == x*(x + 1)
497
+ assert s2.doit() == 1
498
+ assert s3.doit() == x*(x + 1)
499
+
500
+ assert Product(Integral(2*x, (x, 1, y)) + 2*x, (x, 1, 2)).doit() == \
501
+ (y**2 + 1)*(y**2 + 3)
502
+ assert product(2, (n, a, b)) == 2**(b - a + 1)
503
+ assert product(n, (n, 1, b)) == factorial(b)
504
+ assert product(n**3, (n, 1, b)) == factorial(b)**3
505
+ assert product(3**(2 + n), (n, a, b)) \
506
+ == 3**(2*(1 - a + b) + b/2 + (b**2)/2 + a/2 - (a**2)/2)
507
+ assert product(cos(n), (n, 3, 5)) == cos(3)*cos(4)*cos(5)
508
+ assert product(cos(n), (n, x, x + 2)) == cos(x)*cos(x + 1)*cos(x + 2)
509
+ assert isinstance(product(cos(n), (n, x, x + S.Half)), Product)
510
+ # If Product managed to evaluate this one, it most likely got it wrong!
511
+ assert isinstance(Product(n**n, (n, 1, b)), Product)
512
+
513
+
514
+ def test_rational_products():
515
+ assert combsimp(product(1 + 1/n, (n, a, b))) == (1 + b)/a
516
+ assert combsimp(product(n + 1, (n, a, b))) == gamma(2 + b)/gamma(1 + a)
517
+ assert combsimp(product((n + 1)/(n - 1), (n, a, b))) == b*(1 + b)/(a*(a - 1))
518
+ assert combsimp(product(n/(n + 1)/(n + 2), (n, a, b))) == \
519
+ a*gamma(a + 2)/(b + 1)/gamma(b + 3)
520
+ assert combsimp(product(n*(n + 1)/(n - 1)/(n - 2), (n, a, b))) == \
521
+ b**2*(b - 1)*(1 + b)/(a - 1)**2/(a*(a - 2))
522
+
523
+
524
+ def test_wallis_product():
525
+ # Wallis product, given in two different forms to ensure that Product
526
+ # can factor simple rational expressions
527
+ A = Product(4*n**2 / (4*n**2 - 1), (n, 1, b))
528
+ B = Product((2*n)*(2*n)/(2*n - 1)/(2*n + 1), (n, 1, b))
529
+ R = pi*gamma(b + 1)**2/(2*gamma(b + S.Half)*gamma(b + Rational(3, 2)))
530
+ assert simplify(A.doit()) == R
531
+ assert simplify(B.doit()) == R
532
+ # This one should eventually also be doable (Euler's product formula for sin)
533
+ # assert Product(1+x/n**2, (n, 1, b)) == ...
534
+
535
+
536
+ def test_telescopic_sums():
537
+ #checks also input 2 of comment 1 issue 4127
538
+ assert Sum(1/k - 1/(k + 1), (k, 1, n)).doit() == 1 - 1/(1 + n)
539
+ assert Sum(
540
+ f(k) - f(k + 2), (k, m, n)).doit() == -f(1 + n) - f(2 + n) + f(m) + f(1 + m)
541
+ assert Sum(cos(k) - cos(k + 3), (k, 1, n)).doit() == -cos(1 + n) - \
542
+ cos(2 + n) - cos(3 + n) + cos(1) + cos(2) + cos(3)
543
+
544
+ # dummy variable shouldn't matter
545
+ assert telescopic(1/m, -m/(1 + m), (m, n - 1, n)) == \
546
+ telescopic(1/k, -k/(1 + k), (k, n - 1, n))
547
+
548
+ assert Sum(1/x/(x - 1), (x, a, b)).doit() == 1/(a - 1) - 1/b
549
+ eq = 1/((5*n + 2)*(5*(n + 1) + 2))
550
+ assert Sum(eq, (n, 0, oo)).doit() == S(1)/10
551
+ nz = symbols('nz', nonzero=True)
552
+ v = Sum(eq.subs(5, nz), (n, 0, oo)).doit()
553
+ assert v.subs(nz, 5).simplify() == S(1)/10
554
+ # check that apart is being used in non-symbolic case
555
+ s = Sum(eq, (n, 0, k)).doit()
556
+ v = Sum(eq, (n, 0, 10**100)).doit()
557
+ assert v == s.subs(k, 10**100)
558
+
559
+
560
+ def test_sum_reconstruct():
561
+ s = Sum(n**2, (n, -1, 1))
562
+ assert s == Sum(*s.args)
563
+ raises(ValueError, lambda: Sum(x, x))
564
+ raises(ValueError, lambda: Sum(x, (x, 1)))
565
+
566
+
567
+ def test_limit_subs():
568
+ for F in (Sum, Product, Integral):
569
+ assert F(a*exp(a), (a, -2, 2)) == F(a*exp(a), (a, -b, b)).subs(b, 2)
570
+ assert F(a, (a, F(b, (b, 1, 2)), 4)).subs(F(b, (b, 1, 2)), c) == \
571
+ F(a, (a, c, 4))
572
+ assert F(x, (x, 1, x + y)).subs(x, 1) == F(x, (x, 1, y + 1))
573
+
574
+
575
+ def test_function_subs():
576
+ S = Sum(x*f(y),(x,0,oo),(y,0,oo))
577
+ assert S.subs(f(y),y) == Sum(x*y,(x,0,oo),(y,0,oo))
578
+ assert S.subs(f(x),x) == S
579
+ raises(ValueError, lambda: S.subs(f(y),x+y) )
580
+ S = Sum(x*log(y),(x,0,oo),(y,0,oo))
581
+ assert S.subs(log(y),y) == S
582
+ S = Sum(x*f(y),(x,0,oo),(y,0,oo))
583
+ assert S.subs(f(y),y) == Sum(x*y,(x,0,oo),(y,0,oo))
584
+
585
+
586
+ def test_equality():
587
+ # if this fails remove special handling below
588
+ raises(ValueError, lambda: Sum(x, x))
589
+ r = symbols('x', real=True)
590
+ for F in (Sum, Product, Integral):
591
+ try:
592
+ assert F(x, x) != F(y, y)
593
+ assert F(x, (x, 1, 2)) != F(x, x)
594
+ assert F(x, (x, x)) != F(x, x) # or else they print the same
595
+ assert F(1, x) != F(1, y)
596
+ except ValueError:
597
+ pass
598
+ assert F(a, (x, 1, 2)) != F(a, (x, 1, 3)) # diff limit
599
+ assert F(a, (x, 1, x)) != F(a, (y, 1, y))
600
+ assert F(a, (x, 1, 2)) != F(b, (x, 1, 2)) # diff expression
601
+ assert F(x, (x, 1, 2)) != F(r, (r, 1, 2)) # diff assumptions
602
+ assert F(1, (x, 1, x)) != F(1, (y, 1, x)) # only dummy is diff
603
+ assert F(1, (x, 1, x)).dummy_eq(F(1, (y, 1, x)))
604
+
605
+ # issue 5265
606
+ assert Sum(x, (x, 1, x)).subs(x, a) == Sum(x, (x, 1, a))
607
+
608
+
609
+ def test_Sum_doit():
610
+ assert Sum(n*Integral(a**2), (n, 0, 2)).doit() == a**3
611
+ assert Sum(n*Integral(a**2), (n, 0, 2)).doit(deep=False) == \
612
+ 3*Integral(a**2)
613
+ assert summation(n*Integral(a**2), (n, 0, 2)) == 3*Integral(a**2)
614
+
615
+ # test nested sum evaluation
616
+ s = Sum( Sum( Sum(2,(z,1,n+1)), (y,x+1,n)), (x,1,n))
617
+ assert 0 == (s.doit() - n*(n+1)*(n-1)).factor()
618
+
619
+ # Integer assumes finite
620
+ assert Sum(KroneckerDelta(x, y), (x, -oo, oo)).doit() == Piecewise((1, And(-oo < y, y < oo)), (0, True))
621
+ assert Sum(KroneckerDelta(m, n), (m, -oo, oo)).doit() == 1
622
+ assert Sum(m*KroneckerDelta(x, y), (x, -oo, oo)).doit() == Piecewise((m, And(-oo < y, y < oo)), (0, True))
623
+ assert Sum(x*KroneckerDelta(m, n), (m, -oo, oo)).doit() == x
624
+ assert Sum(Sum(KroneckerDelta(m, n), (m, 1, 3)), (n, 1, 3)).doit() == 3
625
+ assert Sum(Sum(KroneckerDelta(k, m), (m, 1, 3)), (n, 1, 3)).doit() == \
626
+ 3 * Piecewise((1, And(1 <= k, k <= 3)), (0, True))
627
+ assert Sum(f(n) * Sum(KroneckerDelta(m, n), (m, 0, oo)), (n, 1, 3)).doit() == \
628
+ f(1) + f(2) + f(3)
629
+ assert Sum(f(n) * Sum(KroneckerDelta(m, n), (m, 0, oo)), (n, 1, oo)).doit() == \
630
+ Sum(f(n), (n, 1, oo))
631
+
632
+ # issue 2597
633
+ nmax = symbols('N', integer=True, positive=True)
634
+ pw = Piecewise((1, And(1 <= n, n <= nmax)), (0, True))
635
+ assert Sum(pw, (n, 1, nmax)).doit() == Sum(Piecewise((1, nmax >= n),
636
+ (0, True)), (n, 1, nmax))
637
+
638
+ q, s = symbols('q, s')
639
+ assert summation(1/n**(2*s), (n, 1, oo)) == Piecewise((zeta(2*s), 2*s > 1),
640
+ (Sum(n**(-2*s), (n, 1, oo)), True))
641
+ assert summation(1/(n+1)**s, (n, 0, oo)) == Piecewise((zeta(s), s > 1),
642
+ (Sum((n + 1)**(-s), (n, 0, oo)), True))
643
+ assert summation(1/(n+q)**s, (n, 0, oo)) == Piecewise(
644
+ (zeta(s, q), And(q > 0, s > 1)),
645
+ (Sum((n + q)**(-s), (n, 0, oo)), True))
646
+ assert summation(1/(n+q)**s, (n, q, oo)) == Piecewise(
647
+ (zeta(s, 2*q), And(2*q > 0, s > 1)),
648
+ (Sum((n + q)**(-s), (n, q, oo)), True))
649
+ assert summation(1/n**2, (n, 1, oo)) == zeta(2)
650
+ assert summation(1/n**s, (n, 0, oo)) == Sum(n**(-s), (n, 0, oo))
651
+
652
+
653
+ def test_Product_doit():
654
+ assert Product(n*Integral(a**2), (n, 1, 3)).doit() == 2 * a**9 / 9
655
+ assert Product(n*Integral(a**2), (n, 1, 3)).doit(deep=False) == \
656
+ 6*Integral(a**2)**3
657
+ assert product(n*Integral(a**2), (n, 1, 3)) == 6*Integral(a**2)**3
658
+
659
+
660
+ def test_Sum_interface():
661
+ assert isinstance(Sum(0, (n, 0, 2)), Sum)
662
+ assert Sum(nan, (n, 0, 2)) is nan
663
+ assert Sum(nan, (n, 0, oo)) is nan
664
+ assert Sum(0, (n, 0, 2)).doit() == 0
665
+ assert isinstance(Sum(0, (n, 0, oo)), Sum)
666
+ assert Sum(0, (n, 0, oo)).doit() == 0
667
+ raises(ValueError, lambda: Sum(1))
668
+ raises(ValueError, lambda: summation(1))
669
+
670
+
671
+ def test_diff():
672
+ assert Sum(x, (x, 1, 2)).diff(x) == 0
673
+ assert Sum(x*y, (x, 1, 2)).diff(x) == 0
674
+ assert Sum(x*y, (y, 1, 2)).diff(x) == Sum(y, (y, 1, 2))
675
+ e = Sum(x*y, (x, 1, a))
676
+ assert e.diff(a) == Derivative(e, a)
677
+ assert Sum(x*y, (x, 1, 3), (a, 2, 5)).diff(y).doit() == \
678
+ Sum(x*y, (x, 1, 3), (a, 2, 5)).doit().diff(y) == 24
679
+ assert Sum(x, (x, 1, 2)).diff(y) == 0
680
+
681
+
682
+ def test_hypersum():
683
+ assert simplify(summation(x**n/fac(n), (n, 1, oo))) == -1 + exp(x)
684
+ assert summation((-1)**n * x**(2*n) / fac(2*n), (n, 0, oo)) == cos(x)
685
+ assert simplify(summation((-1)**n*x**(2*n + 1) /
686
+ factorial(2*n + 1), (n, 3, oo))) == -x + sin(x) + x**3/6 - x**5/120
687
+
688
+ assert summation(1/(n + 2)**3, (n, 1, oo)) == Rational(-9, 8) + zeta(3)
689
+ assert summation(1/n**4, (n, 1, oo)) == pi**4/90
690
+
691
+ s = summation(x**n*n, (n, -oo, 0))
692
+ assert s.is_Piecewise
693
+ assert s.args[0].args[0] == -1/(x*(1 - 1/x)**2)
694
+ assert s.args[0].args[1] == (abs(1/x) < 1)
695
+
696
+ m = Symbol('n', integer=True, positive=True)
697
+ assert summation(binomial(m, k), (k, 0, m)) == 2**m
698
+
699
+
700
+ def test_issue_4170():
701
+ assert summation(1/factorial(k), (k, 0, oo)) == E
702
+
703
+
704
+ def test_is_commutative():
705
+ from sympy.physics.secondquant import NO, F, Fd
706
+ m = Symbol('m', commutative=False)
707
+ for f in (Sum, Product, Integral):
708
+ assert f(z, (z, 1, 1)).is_commutative is True
709
+ assert f(z*y, (z, 1, 6)).is_commutative is True
710
+ assert f(m*x, (x, 1, 2)).is_commutative is False
711
+
712
+ assert f(NO(Fd(x)*F(y))*z, (z, 1, 2)).is_commutative is False
713
+
714
+
715
+ def test_is_zero():
716
+ for func in [Sum, Product]:
717
+ assert func(0, (x, 1, 1)).is_zero is True
718
+ assert func(x, (x, 1, 1)).is_zero is None
719
+
720
+ assert Sum(0, (x, 1, 0)).is_zero is True
721
+ assert Product(0, (x, 1, 0)).is_zero is False
722
+
723
+
724
+ def test_is_number():
725
+ # is number should not rely on evaluation or assumptions,
726
+ # it should be equivalent to `not foo.free_symbols`
727
+ assert Sum(1, (x, 1, 1)).is_number is True
728
+ assert Sum(1, (x, 1, x)).is_number is False
729
+ assert Sum(0, (x, y, z)).is_number is False
730
+ assert Sum(x, (y, 1, 2)).is_number is False
731
+ assert Sum(x, (y, 1, 1)).is_number is False
732
+ assert Sum(x, (x, 1, 2)).is_number is True
733
+ assert Sum(x*y, (x, 1, 2), (y, 1, 3)).is_number is True
734
+
735
+ assert Product(2, (x, 1, 1)).is_number is True
736
+ assert Product(2, (x, 1, y)).is_number is False
737
+ assert Product(0, (x, y, z)).is_number is False
738
+ assert Product(1, (x, y, z)).is_number is False
739
+ assert Product(x, (y, 1, x)).is_number is False
740
+ assert Product(x, (y, 1, 2)).is_number is False
741
+ assert Product(x, (y, 1, 1)).is_number is False
742
+ assert Product(x, (x, 1, 2)).is_number is True
743
+
744
+
745
+ def test_free_symbols():
746
+ for func in [Sum, Product]:
747
+ assert func(1, (x, 1, 2)).free_symbols == set()
748
+ assert func(0, (x, 1, y)).free_symbols == {y}
749
+ assert func(2, (x, 1, y)).free_symbols == {y}
750
+ assert func(x, (x, 1, 2)).free_symbols == set()
751
+ assert func(x, (x, 1, y)).free_symbols == {y}
752
+ assert func(x, (y, 1, y)).free_symbols == {x, y}
753
+ assert func(x, (y, 1, 2)).free_symbols == {x}
754
+ assert func(x, (y, 1, 1)).free_symbols == {x}
755
+ assert func(x, (y, 1, z)).free_symbols == {x, z}
756
+ assert func(x, (x, 1, y), (y, 1, 2)).free_symbols == set()
757
+ assert func(x, (x, 1, y), (y, 1, z)).free_symbols == {z}
758
+ assert func(x, (x, 1, y), (y, 1, y)).free_symbols == {y}
759
+ assert func(x, (y, 1, y), (y, 1, z)).free_symbols == {x, z}
760
+ assert Sum(1, (x, 1, y)).free_symbols == {y}
761
+ # free_symbols answers whether the object *as written* has free symbols,
762
+ # not whether the evaluated expression has free symbols
763
+ assert Product(1, (x, 1, y)).free_symbols == {y}
764
+ # don't count free symbols that are not independent of integration
765
+ # variable(s)
766
+ assert func(f(x), (f(x), 1, 2)).free_symbols == set()
767
+ assert func(f(x), (f(x), 1, x)).free_symbols == {x}
768
+ assert func(f(x), (f(x), 1, y)).free_symbols == {y}
769
+ assert func(f(x), (z, 1, y)).free_symbols == {x, y}
770
+
771
+
772
+ def test_conjugate_transpose():
773
+ A, B = symbols("A B", commutative=False)
774
+ p = Sum(A*B**n, (n, 1, 3))
775
+ assert p.adjoint().doit() == p.doit().adjoint()
776
+ assert p.conjugate().doit() == p.doit().conjugate()
777
+ assert p.transpose().doit() == p.doit().transpose()
778
+
779
+ p = Sum(B**n*A, (n, 1, 3))
780
+ assert p.adjoint().doit() == p.doit().adjoint()
781
+ assert p.conjugate().doit() == p.doit().conjugate()
782
+ assert p.transpose().doit() == p.doit().transpose()
783
+
784
+
785
+ def test_noncommutativity_honoured():
786
+ A, B = symbols("A B", commutative=False)
787
+ M = symbols('M', integer=True, positive=True)
788
+ p = Sum(A*B**n, (n, 1, M))
789
+ assert p.doit() == A*Piecewise((M, Eq(B, 1)),
790
+ ((B - B**(M + 1))*(1 - B)**(-1), True))
791
+
792
+ p = Sum(B**n*A, (n, 1, M))
793
+ assert p.doit() == Piecewise((M, Eq(B, 1)),
794
+ ((B - B**(M + 1))*(1 - B)**(-1), True))*A
795
+
796
+ p = Sum(B**n*A*B**n, (n, 1, M))
797
+ assert p.doit() == p
798
+
799
+
800
+ def test_issue_4171():
801
+ assert summation(factorial(2*k + 1)/factorial(2*k), (k, 0, oo)) is oo
802
+ assert summation(2*k + 1, (k, 0, oo)) is oo
803
+
804
+
805
+ def test_issue_6273():
806
+ assert Sum(x, (x, 1, n)).n(2, subs={n: 1}) == Float(1, 2)
807
+
808
+
809
+ def test_issue_6274():
810
+ assert Sum(x, (x, 1, 0)).doit() == 0
811
+ assert NS(Sum(x, (x, 1, 0))) == '0'
812
+ assert Sum(n, (n, 10, 5)).doit() == -30
813
+ assert NS(Sum(n, (n, 10, 5))) == '-30.0000000000000'
814
+
815
+
816
+ def test_simplify_sum():
817
+ y, t, v = symbols('y, t, v')
818
+
819
+ _simplify = lambda e: simplify(e, doit=False)
820
+ assert _simplify(Sum(x*y, (x, n, m), (y, a, k)) + \
821
+ Sum(y, (x, n, m), (y, a, k))) == Sum(y * (x + 1), (x, n, m), (y, a, k))
822
+ assert _simplify(Sum(x, (x, n, m)) + Sum(x, (x, m + 1, a))) == \
823
+ Sum(x, (x, n, a))
824
+ assert _simplify(Sum(x, (x, k + 1, a)) + Sum(x, (x, n, k))) == \
825
+ Sum(x, (x, n, a))
826
+ assert _simplify(Sum(x, (x, k + 1, a)) + Sum(x + 1, (x, n, k))) == \
827
+ Sum(x, (x, n, a)) + Sum(1, (x, n, k))
828
+ assert _simplify(Sum(x, (x, 0, 3)) * 3 + 3 * Sum(x, (x, 4, 6)) + \
829
+ 4 * Sum(z, (z, 0, 1))) == 4*Sum(z, (z, 0, 1)) + 3*Sum(x, (x, 0, 6))
830
+ assert _simplify(3*Sum(x**2, (x, a, b)) + Sum(x, (x, a, b))) == \
831
+ Sum(x*(3*x + 1), (x, a, b))
832
+ assert _simplify(Sum(x**3, (x, n, k)) * 3 + 3 * Sum(x, (x, n, k)) + \
833
+ 4 * y * Sum(z, (z, n, k))) + 1 == \
834
+ 4*y*Sum(z, (z, n, k)) + 3*Sum(x**3 + x, (x, n, k)) + 1
835
+ assert _simplify(Sum(x, (x, a, b)) + 1 + Sum(x, (x, b + 1, c))) == \
836
+ 1 + Sum(x, (x, a, c))
837
+ assert _simplify(Sum(x, (t, a, b)) + Sum(y, (t, a, b)) + \
838
+ Sum(x, (t, b+1, c))) == x * Sum(1, (t, a, c)) + y * Sum(1, (t, a, b))
839
+ assert _simplify(Sum(x, (t, a, b)) + Sum(x, (t, b+1, c)) + \
840
+ Sum(y, (t, a, b))) == x * Sum(1, (t, a, c)) + y * Sum(1, (t, a, b))
841
+ assert _simplify(Sum(x, (t, a, b)) + 2 * Sum(x, (t, b+1, c))) == \
842
+ _simplify(Sum(x, (t, a, b)) + Sum(x, (t, b+1, c)) + Sum(x, (t, b+1, c)))
843
+ assert _simplify(Sum(x, (x, a, b))*Sum(x**2, (x, a, b))) == \
844
+ Sum(x, (x, a, b)) * Sum(x**2, (x, a, b))
845
+ assert _simplify(Sum(x, (t, a, b)) + Sum(y, (t, a, b)) + Sum(z, (t, a, b))) \
846
+ == (x + y + z) * Sum(1, (t, a, b)) # issue 8596
847
+ assert _simplify(Sum(x, (t, a, b)) + Sum(y, (t, a, b)) + Sum(z, (t, a, b)) + \
848
+ Sum(v, (t, a, b))) == (x + y + z + v) * Sum(1, (t, a, b)) # issue 8596
849
+ assert _simplify(Sum(x * y, (x, a, b)) / (3 * y)) == \
850
+ (Sum(x, (x, a, b)) / 3)
851
+ assert _simplify(Sum(f(x) * y * z, (x, a, b)) / (y * z)) \
852
+ == Sum(f(x), (x, a, b))
853
+ assert _simplify(Sum(c * x, (x, a, b)) - c * Sum(x, (x, a, b))) == 0
854
+ assert _simplify(c * (Sum(x, (x, a, b)) + y)) == c * (y + Sum(x, (x, a, b)))
855
+ assert _simplify(c * (Sum(x, (x, a, b)) + y * Sum(x, (x, a, b)))) == \
856
+ c * (y + 1) * Sum(x, (x, a, b))
857
+ assert _simplify(Sum(Sum(c * x, (x, a, b)), (y, a, b))) == \
858
+ c * Sum(x, (x, a, b), (y, a, b))
859
+ assert _simplify(Sum((3 + y) * Sum(c * x, (x, a, b)), (y, a, b))) == \
860
+ c * Sum((3 + y), (y, a, b)) * Sum(x, (x, a, b))
861
+ assert _simplify(Sum((3 + t) * Sum(c * t, (x, a, b)), (y, a, b))) == \
862
+ c*t*(t + 3)*Sum(1, (x, a, b))*Sum(1, (y, a, b))
863
+ assert _simplify(Sum(Sum(d * t, (x, a, b - 1)) + \
864
+ Sum(d * t, (x, b, c)), (t, a, b))) == \
865
+ d * Sum(1, (x, a, c)) * Sum(t, (t, a, b))
866
+ assert _simplify(Sum(sin(t)**2 + cos(t)**2 + 1, (t, a, b))) == \
867
+ 2 * Sum(1, (t, a, b))
868
+
869
+
870
+ def test_change_index():
871
+ b, v, w = symbols('b, v, w', integer = True)
872
+
873
+ assert Sum(x, (x, a, b)).change_index(x, x + 1, y) == \
874
+ Sum(y - 1, (y, a + 1, b + 1))
875
+ assert Sum(x**2, (x, a, b)).change_index( x, x - 1) == \
876
+ Sum((x+1)**2, (x, a - 1, b - 1))
877
+ assert Sum(x**2, (x, a, b)).change_index( x, -x, y) == \
878
+ Sum((-y)**2, (y, -b, -a))
879
+ assert Sum(x, (x, a, b)).change_index( x, -x - 1) == \
880
+ Sum(-x - 1, (x, -b - 1, -a - 1))
881
+ assert Sum(x*y, (x, a, b), (y, c, d)).change_index( x, x - 1, z) == \
882
+ Sum((z + 1)*y, (z, a - 1, b - 1), (y, c, d))
883
+ assert Sum(x, (x, a, b)).change_index( x, x + v) == \
884
+ Sum(-v + x, (x, a + v, b + v))
885
+ assert Sum(x, (x, a, b)).change_index( x, -x - v) == \
886
+ Sum(-v - x, (x, -b - v, -a - v))
887
+ assert Sum(x, (x, a, b)).change_index(x, w*x, v) == \
888
+ Sum(v/w, (v, b*w, a*w))
889
+ raises(ValueError, lambda: Sum(x, (x, a, b)).change_index(x, 2*x))
890
+
891
+
892
+ def test_reorder():
893
+ b, y, c, d, z = symbols('b, y, c, d, z', integer = True)
894
+
895
+ assert Sum(x*y, (x, a, b), (y, c, d)).reorder((0, 1)) == \
896
+ Sum(x*y, (y, c, d), (x, a, b))
897
+ assert Sum(x, (x, a, b), (x, c, d)).reorder((0, 1)) == \
898
+ Sum(x, (x, c, d), (x, a, b))
899
+ assert Sum(x*y + z, (x, a, b), (z, m, n), (y, c, d)).reorder(\
900
+ (2, 0), (0, 1)) == Sum(x*y + z, (z, m, n), (y, c, d), (x, a, b))
901
+ assert Sum(x*y*z, (x, a, b), (y, c, d), (z, m, n)).reorder(\
902
+ (0, 1), (1, 2), (0, 2)) == Sum(x*y*z, (x, a, b), (z, m, n), (y, c, d))
903
+ assert Sum(x*y*z, (x, a, b), (y, c, d), (z, m, n)).reorder(\
904
+ (x, y), (y, z), (x, z)) == Sum(x*y*z, (x, a, b), (z, m, n), (y, c, d))
905
+ assert Sum(x*y, (x, a, b), (y, c, d)).reorder((x, 1)) == \
906
+ Sum(x*y, (y, c, d), (x, a, b))
907
+ assert Sum(x*y, (x, a, b), (y, c, d)).reorder((y, x)) == \
908
+ Sum(x*y, (y, c, d), (x, a, b))
909
+
910
+
911
+ def test_reverse_order():
912
+ assert Sum(x, (x, 0, 3)).reverse_order(0) == Sum(-x, (x, 4, -1))
913
+ assert Sum(x*y, (x, 1, 5), (y, 0, 6)).reverse_order(0, 1) == \
914
+ Sum(x*y, (x, 6, 0), (y, 7, -1))
915
+ assert Sum(x, (x, 1, 2)).reverse_order(0) == Sum(-x, (x, 3, 0))
916
+ assert Sum(x, (x, 1, 3)).reverse_order(0) == Sum(-x, (x, 4, 0))
917
+ assert Sum(x, (x, 1, a)).reverse_order(0) == Sum(-x, (x, a + 1, 0))
918
+ assert Sum(x, (x, a, 5)).reverse_order(0) == Sum(-x, (x, 6, a - 1))
919
+ assert Sum(x, (x, a + 1, a + 5)).reverse_order(0) == \
920
+ Sum(-x, (x, a + 6, a))
921
+ assert Sum(x, (x, a + 1, a + 2)).reverse_order(0) == \
922
+ Sum(-x, (x, a + 3, a))
923
+ assert Sum(x, (x, a + 1, a + 1)).reverse_order(0) == \
924
+ Sum(-x, (x, a + 2, a))
925
+ assert Sum(x, (x, a, b)).reverse_order(0) == Sum(-x, (x, b + 1, a - 1))
926
+ assert Sum(x, (x, a, b)).reverse_order(x) == Sum(-x, (x, b + 1, a - 1))
927
+ assert Sum(x*y, (x, a, b), (y, 2, 5)).reverse_order(x, 1) == \
928
+ Sum(x*y, (x, b + 1, a - 1), (y, 6, 1))
929
+ assert Sum(x*y, (x, a, b), (y, 2, 5)).reverse_order(y, x) == \
930
+ Sum(x*y, (x, b + 1, a - 1), (y, 6, 1))
931
+
932
+
933
+ def test_issue_7097():
934
+ assert sum(x**n/n for n in range(1, 401)) == summation(x**n/n, (n, 1, 400))
935
+
936
+
937
+ def test_factor_expand_subs():
938
+ # test factoring
939
+ assert Sum(4 * x, (x, 1, y)).factor() == 4 * Sum(x, (x, 1, y))
940
+ assert Sum(x * a, (x, 1, y)).factor() == a * Sum(x, (x, 1, y))
941
+ assert Sum(4 * x * a, (x, 1, y)).factor() == 4 * a * Sum(x, (x, 1, y))
942
+ assert Sum(4 * x * y, (x, 1, y)).factor() == 4 * y * Sum(x, (x, 1, y))
943
+
944
+ # test expand
945
+ _x = Symbol('x', zero=False)
946
+ assert Sum(x+1,(x,1,y)).expand() == Sum(x,(x,1,y)) + Sum(1,(x,1,y))
947
+ assert Sum(x+a*x**2,(x,1,y)).expand() == Sum(x,(x,1,y)) + Sum(a*x**2,(x,1,y))
948
+ assert Sum(_x**(n + 1)*(n + 1), (n, -1, oo)).expand() \
949
+ == Sum(n*_x*_x**n + _x*_x**n, (n, -1, oo))
950
+ assert Sum(x**(n + 1)*(n + 1), (n, -1, oo)).expand(power_exp=False) \
951
+ == Sum(n*x**(n + 1) + x**(n + 1), (n, -1, oo))
952
+ assert Sum(x**(n + 1)*(n + 1), (n, -1, oo)).expand(force=True) \
953
+ == Sum(x*x**n, (n, -1, oo)) + Sum(n*x*x**n, (n, -1, oo))
954
+ assert Sum(a*n+a*n**2,(n,0,4)).expand() \
955
+ == Sum(a*n,(n,0,4)) + Sum(a*n**2,(n,0,4))
956
+ assert Sum(_x**a*_x**n,(x,0,3)) \
957
+ == Sum(_x**(a+n),(x,0,3)).expand(power_exp=True)
958
+ _a, _n = symbols('a n', positive=True)
959
+ assert Sum(x**(_a+_n),(x,0,3)).expand(power_exp=True) \
960
+ == Sum(x**_a*x**_n, (x, 0, 3))
961
+ assert Sum(x**(_a-_n),(x,0,3)).expand(power_exp=True) \
962
+ == Sum(x**(_a-_n),(x,0,3)).expand(power_exp=False)
963
+
964
+ # test subs
965
+ assert Sum(1/(1+a*x**2),(x,0,3)).subs([(a,3)]) == Sum(1/(1+3*x**2),(x,0,3))
966
+ assert Sum(x*y,(x,0,y),(y,0,x)).subs([(x,3)]) == Sum(x*y,(x,0,y),(y,0,3))
967
+ assert Sum(x,(x,1,10)).subs([(x,y-2)]) == Sum(x,(x,1,10))
968
+ assert Sum(1/x,(x,1,10)).subs([(x,(3+n)**3)]) == Sum(1/x,(x,1,10))
969
+ assert Sum(1/x,(x,1,10)).subs([(x,3*x-2)]) == Sum(1/x,(x,1,10))
970
+
971
+
972
+ def test_distribution_over_equality():
973
+ assert Product(Eq(x*2, f(x)), (x, 1, 3)).doit() == Eq(48, f(1)*f(2)*f(3))
974
+ assert Sum(Eq(f(x), x**2), (x, 0, y)) == \
975
+ Eq(Sum(f(x), (x, 0, y)), Sum(x**2, (x, 0, y)))
976
+
977
+
978
+ def test_issue_2787():
979
+ n, k = symbols('n k', positive=True, integer=True)
980
+ p = symbols('p', positive=True)
981
+ binomial_dist = binomial(n, k)*p**k*(1 - p)**(n - k)
982
+ s = Sum(binomial_dist*k, (k, 0, n))
983
+ res = s.doit().simplify()
984
+ ans = Piecewise(
985
+ (n*p, x),
986
+ (Sum(k*p**k*binomial(n, k)*(1 - p)**(n - k), (k, 0, n)),
987
+ True)).subs(x, (Eq(n, 1) | (n > 1)) & (p/Abs(p - 1) <= 1))
988
+ ans2 = Piecewise(
989
+ (n*p, x),
990
+ (factorial(n)*Sum(p**k*(1 - p)**(-k + n)/
991
+ (factorial(-k + n)*factorial(k - 1)), (k, 0, n)),
992
+ True)).subs(x, (Eq(n, 1) | (n > 1)) & (p/Abs(p - 1) <= 1))
993
+ assert res in [ans, ans2] # XXX system dependent
994
+ # Issue #17165: make sure that another simplify does not complicate
995
+ # the result by much. Why didn't first simplify replace
996
+ # Eq(n, 1) | (n > 1) with True?
997
+ assert res.simplify().count_ops() <= res.count_ops() + 2
998
+
999
+
1000
+ def test_issue_4668():
1001
+ assert summation(1/n, (n, 2, oo)) is oo
1002
+
1003
+
1004
+ def test_matrix_sum():
1005
+ A = Matrix([[0, 1], [n, 0]])
1006
+
1007
+ result = Sum(A, (n, 0, 3)).doit()
1008
+ assert result == Matrix([[0, 4], [6, 0]])
1009
+ assert result.__class__ == ImmutableDenseMatrix
1010
+
1011
+ A = SparseMatrix([[0, 1], [n, 0]])
1012
+
1013
+ result = Sum(A, (n, 0, 3)).doit()
1014
+ assert result.__class__ == ImmutableSparseMatrix
1015
+
1016
+
1017
+ def test_failing_matrix_sum():
1018
+ n = Symbol('n')
1019
+ # TODO Implement matrix geometric series summation.
1020
+ A = Matrix([[0, 1, 0], [-1, 0, 0], [0, 0, 0]])
1021
+ assert Sum(A ** n, (n, 1, 4)).doit() == \
1022
+ Matrix([[0, 0, 0], [0, 0, 0], [0, 0, 0]])
1023
+ # issue sympy/sympy#16989
1024
+ assert summation(A**n, (n, 1, 1)) == A
1025
+
1026
+
1027
+ def test_indexed_idx_sum():
1028
+ i = symbols('i', cls=Idx)
1029
+ r = Indexed('r', i)
1030
+ assert Sum(r, (i, 0, 3)).doit() == sum([r.xreplace({i: j}) for j in range(4)])
1031
+ assert Product(r, (i, 0, 3)).doit() == prod([r.xreplace({i: j}) for j in range(4)])
1032
+
1033
+ j = symbols('j', integer=True)
1034
+ assert Sum(r, (i, j, j+2)).doit() == sum([r.xreplace({i: j+k}) for k in range(3)])
1035
+ assert Product(r, (i, j, j+2)).doit() == prod([r.xreplace({i: j+k}) for k in range(3)])
1036
+
1037
+ k = Idx('k', range=(1, 3))
1038
+ A = IndexedBase('A')
1039
+ assert Sum(A[k], k).doit() == sum([A[Idx(j, (1, 3))] for j in range(1, 4)])
1040
+ assert Product(A[k], k).doit() == prod([A[Idx(j, (1, 3))] for j in range(1, 4)])
1041
+
1042
+ raises(ValueError, lambda: Sum(A[k], (k, 1, 4)))
1043
+ raises(ValueError, lambda: Sum(A[k], (k, 0, 3)))
1044
+ raises(ValueError, lambda: Sum(A[k], (k, 2, oo)))
1045
+
1046
+ raises(ValueError, lambda: Product(A[k], (k, 1, 4)))
1047
+ raises(ValueError, lambda: Product(A[k], (k, 0, 3)))
1048
+ raises(ValueError, lambda: Product(A[k], (k, 2, oo)))
1049
+
1050
+
1051
+ @slow
1052
+ def test_is_convergent():
1053
+ # divergence tests --
1054
+ assert Sum(n/(2*n + 1), (n, 1, oo)).is_convergent() is S.false
1055
+ assert Sum(factorial(n)/5**n, (n, 1, oo)).is_convergent() is S.false
1056
+ assert Sum(3**(-2*n - 1)*n**n, (n, 1, oo)).is_convergent() is S.false
1057
+ assert Sum((-1)**n*n, (n, 3, oo)).is_convergent() is S.false
1058
+ assert Sum((-1)**n, (n, 1, oo)).is_convergent() is S.false
1059
+ assert Sum(log(1/n), (n, 2, oo)).is_convergent() is S.false
1060
+
1061
+ # Raabe's test --
1062
+ assert Sum(Product((3*m),(m,1,n))/Product((3*m+4),(m,1,n)),(n,1,oo)).is_convergent() is S.true
1063
+
1064
+ # root test --
1065
+ assert Sum((-12)**n/n, (n, 1, oo)).is_convergent() is S.false
1066
+
1067
+ # integral test --
1068
+
1069
+ # p-series test --
1070
+ assert Sum(1/(n**2 + 1), (n, 1, oo)).is_convergent() is S.true
1071
+ assert Sum(1/n**Rational(6, 5), (n, 1, oo)).is_convergent() is S.true
1072
+ assert Sum(2/(n*sqrt(n - 1)), (n, 2, oo)).is_convergent() is S.true
1073
+ assert Sum(1/(sqrt(n)*sqrt(n)), (n, 2, oo)).is_convergent() is S.false
1074
+ assert Sum(factorial(n) / factorial(n+2), (n, 1, oo)).is_convergent() is S.true
1075
+ assert Sum(rf(5,n)/rf(7,n),(n,1,oo)).is_convergent() is S.true
1076
+ assert Sum((rf(1, n)*rf(2, n))/(rf(3, n)*factorial(n)),(n,1,oo)).is_convergent() is S.false
1077
+
1078
+ # comparison test --
1079
+ assert Sum(1/(n + log(n)), (n, 1, oo)).is_convergent() is S.false
1080
+ assert Sum(1/(n**2*log(n)), (n, 2, oo)).is_convergent() is S.true
1081
+ assert Sum(1/(n*log(n)), (n, 2, oo)).is_convergent() is S.false
1082
+ assert Sum(2/(n*log(n)*log(log(n))**2), (n, 5, oo)).is_convergent() is S.true
1083
+ assert Sum(2/(n*log(n)**2), (n, 2, oo)).is_convergent() is S.true
1084
+ assert Sum((n - 1)/(n**2*log(n)**3), (n, 2, oo)).is_convergent() is S.true
1085
+ assert Sum(1/(n*log(n)*log(log(n))), (n, 5, oo)).is_convergent() is S.false
1086
+ assert Sum((n - 1)/(n*log(n)**3), (n, 3, oo)).is_convergent() is S.false
1087
+ assert Sum(2/(n**2*log(n)), (n, 2, oo)).is_convergent() is S.true
1088
+ assert Sum(1/(n*sqrt(log(n))*log(log(n))), (n, 100, oo)).is_convergent() is S.false
1089
+ assert Sum(log(log(n))/(n*log(n)**2), (n, 100, oo)).is_convergent() is S.true
1090
+ assert Sum(log(n)/n**2, (n, 5, oo)).is_convergent() is S.true
1091
+
1092
+ # alternating series tests --
1093
+ assert Sum((-1)**(n - 1)/(n**2 - 1), (n, 3, oo)).is_convergent() is S.true
1094
+
1095
+ # with -negativeInfinite Limits
1096
+ assert Sum(1/(n**2 + 1), (n, -oo, 1)).is_convergent() is S.true
1097
+ assert Sum(1/(n - 1), (n, -oo, -1)).is_convergent() is S.false
1098
+ assert Sum(1/(n**2 - 1), (n, -oo, -5)).is_convergent() is S.true
1099
+ assert Sum(1/(n**2 - 1), (n, -oo, 2)).is_convergent() is S.true
1100
+ assert Sum(1/(n**2 - 1), (n, -oo, oo)).is_convergent() is S.true
1101
+
1102
+ # piecewise functions
1103
+ f = Piecewise((n**(-2), n <= 1), (n**2, n > 1))
1104
+ assert Sum(f, (n, 1, oo)).is_convergent() is S.false
1105
+ assert Sum(f, (n, -oo, oo)).is_convergent() is S.false
1106
+ assert Sum(f, (n, 1, 100)).is_convergent() is S.true
1107
+ #assert Sum(f, (n, -oo, 1)).is_convergent() is S.true
1108
+
1109
+ # integral test
1110
+
1111
+ assert Sum(log(n)/n**3, (n, 1, oo)).is_convergent() is S.true
1112
+ assert Sum(-log(n)/n**3, (n, 1, oo)).is_convergent() is S.true
1113
+ # the following function has maxima located at (x, y) =
1114
+ # (1.2, 0.43), (3.0, -0.25) and (6.8, 0.050)
1115
+ eq = (x - 2)*(x**2 - 6*x + 4)*exp(-x)
1116
+ assert Sum(eq, (x, 1, oo)).is_convergent() is S.true
1117
+ assert Sum(eq, (x, 1, 2)).is_convergent() is S.true
1118
+ assert Sum(1/(x**3), (x, 1, oo)).is_convergent() is S.true
1119
+ assert Sum(1/(x**S.Half), (x, 1, oo)).is_convergent() is S.false
1120
+
1121
+ # issue 19545
1122
+ assert Sum(1/n - 3/(3*n +2), (n, 1, oo)).is_convergent() is S.true
1123
+
1124
+ # issue 19836
1125
+ assert Sum(4/(n + 2) - 5/(n + 1) + 1/n,(n, 7, oo)).is_convergent() is S.true
1126
+
1127
+
1128
+ def test_is_absolutely_convergent():
1129
+ assert Sum((-1)**n, (n, 1, oo)).is_absolutely_convergent() is S.false
1130
+ assert Sum((-1)**n/n**2, (n, 1, oo)).is_absolutely_convergent() is S.true
1131
+
1132
+
1133
+ @XFAIL
1134
+ def test_convergent_failing():
1135
+ # dirichlet tests
1136
+ assert Sum(sin(n)/n, (n, 1, oo)).is_convergent() is S.true
1137
+ assert Sum(sin(2*n)/n, (n, 1, oo)).is_convergent() is S.true
1138
+
1139
+
1140
+ def test_issue_6966():
1141
+ i, k, m = symbols('i k m', integer=True)
1142
+ z_i, q_i = symbols('z_i q_i')
1143
+ a_k = Sum(-q_i*z_i/k,(i,1,m))
1144
+ b_k = a_k.diff(z_i)
1145
+ assert isinstance(b_k, Sum)
1146
+ assert b_k == Sum(-q_i/k,(i,1,m))
1147
+
1148
+
1149
+ def test_issue_10156():
1150
+ cx = Sum(2*y**2*x, (x, 1,3))
1151
+ e = 2*y*Sum(2*cx*x**2, (x, 1, 9))
1152
+ assert e.factor() == \
1153
+ 8*y**3*Sum(x, (x, 1, 3))*Sum(x**2, (x, 1, 9))
1154
+
1155
+
1156
+ def test_issue_10973():
1157
+ assert Sum((-n + (n**3 + 1)**(S(1)/3))/log(n), (n, 1, oo)).is_convergent() is S.true
1158
+
1159
+
1160
+ def test_issue_14129():
1161
+ x = Symbol('x', zero=False)
1162
+ assert Sum( k*x**k, (k, 0, n-1)).doit() == \
1163
+ Piecewise((n**2/2 - n/2, Eq(x, 1)), ((n*x*x**n -
1164
+ n*x**n - x*x**n + x)/(x - 1)**2, True))
1165
+ assert Sum( x**k, (k, 0, n-1)).doit() == \
1166
+ Piecewise((n, Eq(x, 1)), ((-x**n + 1)/(-x + 1), True))
1167
+ assert Sum( k*(x/y+x)**k, (k, 0, n-1)).doit() == \
1168
+ Piecewise((n*(n - 1)/2, Eq(x, y/(y + 1))),
1169
+ (x*(y + 1)*(n*x*y*(x + x/y)**(n - 1) +
1170
+ n*x*(x + x/y)**(n - 1) - n*y*(x + x/y)**(n - 1) -
1171
+ x*y*(x + x/y)**(n - 1) - x*(x + x/y)**(n - 1) + y)/
1172
+ (x*y + x - y)**2, True))
1173
+
1174
+
1175
+ def test_issue_14112():
1176
+ assert Sum((-1)**n/sqrt(n), (n, 1, oo)).is_absolutely_convergent() is S.false
1177
+ assert Sum((-1)**(2*n)/n, (n, 1, oo)).is_convergent() is S.false
1178
+ assert Sum((-2)**n + (-3)**n, (n, 1, oo)).is_convergent() is S.false
1179
+
1180
+
1181
+ def test_issue_14219():
1182
+ A = diag(0, 2, -3)
1183
+ res = diag(1, 15, -20)
1184
+ assert Sum(A**n, (n, 0, 3)).doit() == res
1185
+
1186
+
1187
+ def test_sin_times_absolutely_convergent():
1188
+ assert Sum(sin(n) / n**3, (n, 1, oo)).is_convergent() is S.true
1189
+ assert Sum(sin(n) * log(n) / n**3, (n, 1, oo)).is_convergent() is S.true
1190
+
1191
+
1192
+ def test_issue_14111():
1193
+ assert Sum(1/log(log(n)), (n, 22, oo)).is_convergent() is S.false
1194
+
1195
+
1196
+ def test_issue_14484():
1197
+ assert Sum(sin(n)/log(log(n)), (n, 22, oo)).is_convergent() is S.false
1198
+
1199
+
1200
+ def test_issue_14640():
1201
+ i, n = symbols("i n", integer=True)
1202
+ a, b, c = symbols("a b c", zero=False)
1203
+
1204
+ assert Sum(a**-i/(a - b), (i, 0, n)).doit() == Sum(
1205
+ 1/(a*a**i - a**i*b), (i, 0, n)).doit() == Piecewise(
1206
+ (n + 1, Eq(1/a, 1)),
1207
+ ((-a**(-n - 1) + 1)/(1 - 1/a), True))/(a - b)
1208
+
1209
+ assert Sum((b*a**i - c*a**i)**-2, (i, 0, n)).doit() == Piecewise(
1210
+ (n + 1, Eq(a**(-2), 1)),
1211
+ ((-a**(-2*n - 2) + 1)/(1 - 1/a**2), True))/(b - c)**2
1212
+
1213
+ s = Sum(i*(a**(n - i) - b**(n - i))/(a - b), (i, 0, n)).doit()
1214
+ assert not s.has(Sum)
1215
+ assert s.subs({a: 2, b: 3, n: 5}) == 122
1216
+
1217
+
1218
+ def test_issue_15943():
1219
+ s = Sum(binomial(n, k)*factorial(n - k), (k, 0, n)).doit().rewrite(gamma)
1220
+ assert s == -E*(n + 1)*gamma(n + 1)*lowergamma(n + 1, 1)/gamma(n + 2
1221
+ ) + E*gamma(n + 1)
1222
+ assert s.simplify() == E*(factorial(n) - lowergamma(n + 1, 1))
1223
+
1224
+
1225
+ def test_Sum_dummy_eq():
1226
+ assert not Sum(x, (x, a, b)).dummy_eq(1)
1227
+ assert not Sum(x, (x, a, b)).dummy_eq(Sum(x, (x, a, b), (a, 1, 2)))
1228
+ assert not Sum(x, (x, a, b)).dummy_eq(Sum(x, (x, a, c)))
1229
+ assert Sum(x, (x, a, b)).dummy_eq(Sum(x, (x, a, b)))
1230
+ d = Dummy()
1231
+ assert Sum(x, (x, a, d)).dummy_eq(Sum(x, (x, a, c)), c)
1232
+ assert not Sum(x, (x, a, d)).dummy_eq(Sum(x, (x, a, c)))
1233
+ assert Sum(x, (x, a, c)).dummy_eq(Sum(y, (y, a, c)))
1234
+ assert Sum(x, (x, a, d)).dummy_eq(Sum(y, (y, a, c)), c)
1235
+ assert not Sum(x, (x, a, d)).dummy_eq(Sum(y, (y, a, c)))
1236
+
1237
+
1238
+ def test_issue_15852():
1239
+ assert summation(x**y*y, (y, -oo, oo)).doit() == Sum(x**y*y, (y, -oo, oo))
1240
+
1241
+
1242
+ def test_exceptions():
1243
+ S = Sum(x, (x, a, b))
1244
+ raises(ValueError, lambda: S.change_index(x, x**2, y))
1245
+ S = Sum(x, (x, a, b), (x, 1, 4))
1246
+ raises(ValueError, lambda: S.index(x))
1247
+ S = Sum(x, (x, a, b), (y, 1, 4))
1248
+ raises(ValueError, lambda: S.reorder([x]))
1249
+ S = Sum(x, (x, y, b), (y, 1, 4))
1250
+ raises(ReorderError, lambda: S.reorder_limit(0, 1))
1251
+ S = Sum(x*y, (x, a, b), (y, 1, 4))
1252
+ raises(NotImplementedError, lambda: S.is_convergent())
1253
+
1254
+
1255
+ def test_sumproducts_assumptions():
1256
+ M = Symbol('M', integer=True, positive=True)
1257
+
1258
+ m = Symbol('m', integer=True)
1259
+ for func in [Sum, Product]:
1260
+ assert func(m, (m, -M, M)).is_positive is None
1261
+ assert func(m, (m, -M, M)).is_nonpositive is None
1262
+ assert func(m, (m, -M, M)).is_negative is None
1263
+ assert func(m, (m, -M, M)).is_nonnegative is None
1264
+ assert func(m, (m, -M, M)).is_finite is True
1265
+
1266
+ m = Symbol('m', integer=True, nonnegative=True)
1267
+ for func in [Sum, Product]:
1268
+ assert func(m, (m, 0, M)).is_positive is None
1269
+ assert func(m, (m, 0, M)).is_nonpositive is None
1270
+ assert func(m, (m, 0, M)).is_negative is False
1271
+ assert func(m, (m, 0, M)).is_nonnegative is True
1272
+ assert func(m, (m, 0, M)).is_finite is True
1273
+
1274
+ m = Symbol('m', integer=True, positive=True)
1275
+ for func in [Sum, Product]:
1276
+ assert func(m, (m, 1, M)).is_positive is True
1277
+ assert func(m, (m, 1, M)).is_nonpositive is False
1278
+ assert func(m, (m, 1, M)).is_negative is False
1279
+ assert func(m, (m, 1, M)).is_nonnegative is True
1280
+ assert func(m, (m, 1, M)).is_finite is True
1281
+
1282
+ m = Symbol('m', integer=True, negative=True)
1283
+ assert Sum(m, (m, -M, -1)).is_positive is False
1284
+ assert Sum(m, (m, -M, -1)).is_nonpositive is True
1285
+ assert Sum(m, (m, -M, -1)).is_negative is True
1286
+ assert Sum(m, (m, -M, -1)).is_nonnegative is False
1287
+ assert Sum(m, (m, -M, -1)).is_finite is True
1288
+ assert Product(m, (m, -M, -1)).is_positive is None
1289
+ assert Product(m, (m, -M, -1)).is_nonpositive is None
1290
+ assert Product(m, (m, -M, -1)).is_negative is None
1291
+ assert Product(m, (m, -M, -1)).is_nonnegative is None
1292
+ assert Product(m, (m, -M, -1)).is_finite is True
1293
+
1294
+ m = Symbol('m', integer=True, nonpositive=True)
1295
+ assert Sum(m, (m, -M, 0)).is_positive is False
1296
+ assert Sum(m, (m, -M, 0)).is_nonpositive is True
1297
+ assert Sum(m, (m, -M, 0)).is_negative is None
1298
+ assert Sum(m, (m, -M, 0)).is_nonnegative is None
1299
+ assert Sum(m, (m, -M, 0)).is_finite is True
1300
+ assert Product(m, (m, -M, 0)).is_positive is None
1301
+ assert Product(m, (m, -M, 0)).is_nonpositive is None
1302
+ assert Product(m, (m, -M, 0)).is_negative is None
1303
+ assert Product(m, (m, -M, 0)).is_nonnegative is None
1304
+ assert Product(m, (m, -M, 0)).is_finite is True
1305
+
1306
+ m = Symbol('m', integer=True)
1307
+ assert Sum(2, (m, 0, oo)).is_positive is None
1308
+ assert Sum(2, (m, 0, oo)).is_nonpositive is None
1309
+ assert Sum(2, (m, 0, oo)).is_negative is None
1310
+ assert Sum(2, (m, 0, oo)).is_nonnegative is None
1311
+ assert Sum(2, (m, 0, oo)).is_finite is None
1312
+
1313
+ assert Product(2, (m, 0, oo)).is_positive is None
1314
+ assert Product(2, (m, 0, oo)).is_nonpositive is None
1315
+ assert Product(2, (m, 0, oo)).is_negative is False
1316
+ assert Product(2, (m, 0, oo)).is_nonnegative is None
1317
+ assert Product(2, (m, 0, oo)).is_finite is None
1318
+
1319
+ assert Product(0, (x, M, M-1)).is_positive is True
1320
+ assert Product(0, (x, M, M-1)).is_finite is True
1321
+
1322
+
1323
+ def test_expand_with_assumptions():
1324
+ M = Symbol('M', integer=True, positive=True)
1325
+ x = Symbol('x', positive=True)
1326
+ m = Symbol('m', nonnegative=True)
1327
+ assert log(Product(x**m, (m, 0, M))).expand() == Sum(m*log(x), (m, 0, M))
1328
+ assert log(Product(exp(x**m), (m, 0, M))).expand() == Sum(x**m, (m, 0, M))
1329
+ assert log(Product(x**m, (m, 0, M))).rewrite(Sum).expand() == Sum(m*log(x), (m, 0, M))
1330
+ assert log(Product(exp(x**m), (m, 0, M))).rewrite(Sum).expand() == Sum(x**m, (m, 0, M))
1331
+
1332
+ n = Symbol('n', nonnegative=True)
1333
+ i, j = symbols('i,j', positive=True, integer=True)
1334
+ x, y = symbols('x,y', positive=True)
1335
+ assert log(Product(x**i*y**j, (i, 1, n), (j, 1, m))).expand() \
1336
+ == Sum(i*log(x) + j*log(y), (i, 1, n), (j, 1, m))
1337
+
1338
+ m = Symbol('m', nonnegative=True, integer=True)
1339
+ s = Sum(x**m, (m, 0, M))
1340
+ s_as_product = s.rewrite(Product)
1341
+ assert s_as_product.has(Product)
1342
+ assert s_as_product == log(Product(exp(x**m), (m, 0, M)))
1343
+ assert s_as_product.expand() == s
1344
+ s5 = s.subs(M, 5)
1345
+ s5_as_product = s5.rewrite(Product)
1346
+ assert s5_as_product.has(Product)
1347
+ assert s5_as_product.doit().expand() == s5.doit()
1348
+
1349
+
1350
+ def test_has_finite_limits():
1351
+ x = Symbol('x')
1352
+ assert Sum(1, (x, 1, 9)).has_finite_limits is True
1353
+ assert Sum(1, (x, 1, oo)).has_finite_limits is False
1354
+ M = Symbol('M')
1355
+ assert Sum(1, (x, 1, M)).has_finite_limits is None
1356
+ M = Symbol('M', positive=True)
1357
+ assert Sum(1, (x, 1, M)).has_finite_limits is True
1358
+ x = Symbol('x', positive=True)
1359
+ M = Symbol('M')
1360
+ assert Sum(1, (x, 1, M)).has_finite_limits is True
1361
+
1362
+ assert Sum(1, (x, 1, M), (y, -oo, oo)).has_finite_limits is False
1363
+
1364
+ def test_has_reversed_limits():
1365
+ assert Sum(1, (x, 1, 1)).has_reversed_limits is False
1366
+ assert Sum(1, (x, 1, 9)).has_reversed_limits is False
1367
+ assert Sum(1, (x, 1, -9)).has_reversed_limits is True
1368
+ assert Sum(1, (x, 1, 0)).has_reversed_limits is True
1369
+ assert Sum(1, (x, 1, oo)).has_reversed_limits is False
1370
+ M = Symbol('M')
1371
+ assert Sum(1, (x, 1, M)).has_reversed_limits is None
1372
+ M = Symbol('M', positive=True, integer=True)
1373
+ assert Sum(1, (x, 1, M)).has_reversed_limits is False
1374
+ assert Sum(1, (x, 1, M), (y, -oo, oo)).has_reversed_limits is False
1375
+ M = Symbol('M', negative=True)
1376
+ assert Sum(1, (x, 1, M)).has_reversed_limits is True
1377
+
1378
+ assert Sum(1, (x, 1, M), (y, -oo, oo)).has_reversed_limits is True
1379
+ assert Sum(1, (x, oo, oo)).has_reversed_limits is None
1380
+
1381
+
1382
+ def test_has_empty_sequence():
1383
+ assert Sum(1, (x, 1, 1)).has_empty_sequence is False
1384
+ assert Sum(1, (x, 1, 9)).has_empty_sequence is False
1385
+ assert Sum(1, (x, 1, -9)).has_empty_sequence is False
1386
+ assert Sum(1, (x, 1, 0)).has_empty_sequence is True
1387
+ assert Sum(1, (x, y, y - 1)).has_empty_sequence is True
1388
+ assert Sum(1, (x, 3, 2), (y, -oo, oo)).has_empty_sequence is True
1389
+ assert Sum(1, (y, -oo, oo), (x, 3, 2)).has_empty_sequence is True
1390
+ assert Sum(1, (x, oo, oo)).has_empty_sequence is False
1391
+
1392
+
1393
+ def test_empty_sequence():
1394
+ assert Product(x*y, (x, -oo, oo), (y, 1, 0)).doit() == 1
1395
+ assert Product(x*y, (y, 1, 0), (x, -oo, oo)).doit() == 1
1396
+ assert Sum(x, (x, -oo, oo), (y, 1, 0)).doit() == 0
1397
+ assert Sum(x, (y, 1, 0), (x, -oo, oo)).doit() == 0
1398
+
1399
+
1400
+ def test_issue_8016():
1401
+ k = Symbol('k', integer=True)
1402
+ n, m = symbols('n, m', integer=True, positive=True)
1403
+ s = Sum(binomial(m, k)*binomial(m, n - k)*(-1)**k, (k, 0, n))
1404
+ assert s.doit().simplify() == \
1405
+ cos(pi*n/2)*gamma(m + 1)/gamma(n/2 + 1)/gamma(m - n/2 + 1)
1406
+
1407
+
1408
+ def test_issue_14313():
1409
+ assert Sum(S.Half**floor(n/2), (n, 1, oo)).is_convergent()
1410
+
1411
+
1412
+ def test_issue_14563():
1413
+ # The assertion was failing due to no assumptions methods in Sums and Product
1414
+ assert 1 % Sum(1, (x, 0, 1)) == 1
1415
+
1416
+
1417
+ def test_issue_16735():
1418
+ assert Sum(5**n/gamma(n+1), (n, 1, oo)).is_convergent() is S.true
1419
+
1420
+
1421
+ def test_issue_14871():
1422
+ assert Sum((Rational(1, 10))**n*rf(0, n)/factorial(n), (n, 0, oo)).rewrite(factorial).doit() == 1
1423
+
1424
+
1425
+ def test_issue_17165():
1426
+ n = symbols("n", integer=True)
1427
+ x = symbols('x')
1428
+ s = (x*Sum(x**n, (n, -1, oo)))
1429
+ ssimp = s.doit().simplify()
1430
+
1431
+ assert ssimp == Piecewise((-1/(x - 1), (x > -1) & (x < 1)),
1432
+ (x*Sum(x**n, (n, -1, oo)), True)), ssimp
1433
+ assert ssimp.simplify() == ssimp
1434
+
1435
+
1436
+ def test_issue_19379():
1437
+ assert Sum(factorial(n)/factorial(n + 2), (n, 1, oo)).is_convergent() is S.true
1438
+
1439
+
1440
+ def test_issue_20777():
1441
+ assert Sum(exp(x*sin(n/m)), (n, 1, m)).doit() == Sum(exp(x*sin(n/m)), (n, 1, m))
1442
+
1443
+
1444
+ def test__dummy_with_inherited_properties_concrete():
1445
+ x = Symbol('x')
1446
+
1447
+ from sympy.core.containers import Tuple
1448
+ d = _dummy_with_inherited_properties_concrete(Tuple(x, 0, 5))
1449
+ assert d.is_real
1450
+ assert d.is_integer
1451
+ assert d.is_nonnegative
1452
+ assert d.is_extended_nonnegative
1453
+
1454
+ d = _dummy_with_inherited_properties_concrete(Tuple(x, 1, 9))
1455
+ assert d.is_real
1456
+ assert d.is_integer
1457
+ assert d.is_positive
1458
+ assert d.is_odd is None
1459
+
1460
+ d = _dummy_with_inherited_properties_concrete(Tuple(x, -5, 5))
1461
+ assert d.is_real
1462
+ assert d.is_integer
1463
+ assert d.is_positive is None
1464
+ assert d.is_extended_nonnegative is None
1465
+ assert d.is_odd is None
1466
+
1467
+ d = _dummy_with_inherited_properties_concrete(Tuple(x, -1.5, 1.5))
1468
+ assert d.is_real
1469
+ assert d.is_integer is None
1470
+ assert d.is_positive is None
1471
+ assert d.is_extended_nonnegative is None
1472
+
1473
+ N = Symbol('N', integer=True, positive=True)
1474
+ d = _dummy_with_inherited_properties_concrete(Tuple(x, 2, N))
1475
+ assert d.is_real
1476
+ assert d.is_positive
1477
+ assert d.is_integer
1478
+
1479
+ # Return None if no assumptions are added
1480
+ N = Symbol('N', integer=True, positive=True)
1481
+ d = _dummy_with_inherited_properties_concrete(Tuple(N, 2, 4))
1482
+ assert d is None
1483
+
1484
+ x = Symbol('x', negative=True)
1485
+ raises(InconsistentAssumptions,
1486
+ lambda: _dummy_with_inherited_properties_concrete(Tuple(x, 1, 5)))
1487
+
1488
+
1489
+ def test_matrixsymbol_summation_numerical_limits():
1490
+ A = MatrixSymbol('A', 3, 3)
1491
+ n = Symbol('n', integer=True)
1492
+
1493
+ assert Sum(A**n, (n, 0, 2)).doit() == Identity(3) + A + A**2
1494
+ assert Sum(A, (n, 0, 2)).doit() == 3*A
1495
+ assert Sum(n*A, (n, 0, 2)).doit() == 3*A
1496
+
1497
+ B = Matrix([[0, n, 0], [-1, 0, 0], [0, 0, 2]])
1498
+ ans = Matrix([[0, 6, 0], [-4, 0, 0], [0, 0, 8]]) + 4*A
1499
+ assert Sum(A+B, (n, 0, 3)).doit() == ans
1500
+ ans = A*Matrix([[0, 6, 0], [-4, 0, 0], [0, 0, 8]])
1501
+ assert Sum(A*B, (n, 0, 3)).doit() == ans
1502
+
1503
+ ans = (A**2*Matrix([[-2, 0, 0], [0,-2, 0], [0, 0, 4]]) +
1504
+ A**3*Matrix([[0, -9, 0], [3, 0, 0], [0, 0, 8]]) +
1505
+ A*Matrix([[0, 1, 0], [-1, 0, 0], [0, 0, 2]]))
1506
+ assert Sum(A**n*B**n, (n, 1, 3)).doit() == ans
1507
+
1508
+
1509
+ def test_issue_21651():
1510
+ i = Symbol('i')
1511
+ a = Sum(floor(2*2**(-i)), (i, S.One, 2))
1512
+ assert a.doit() == S.One
1513
+
1514
+
1515
+ @XFAIL
1516
+ def test_matrixsymbol_summation_symbolic_limits():
1517
+ N = Symbol('N', integer=True, positive=True)
1518
+
1519
+ A = MatrixSymbol('A', 3, 3)
1520
+ n = Symbol('n', integer=True)
1521
+ assert Sum(A, (n, 0, N)).doit() == (N+1)*A
1522
+ assert Sum(n*A, (n, 0, N)).doit() == (N**2/2+N/2)*A
1523
+
1524
+
1525
+ def test_summation_by_residues():
1526
+ x = Symbol('x')
1527
+
1528
+ # Examples from Nakhle H. Asmar, Loukas Grafakos,
1529
+ # Complex Analysis with Applications
1530
+ assert eval_sum_residue(1 / (x**2 + 1), (x, -oo, oo)) == pi/tanh(pi)
1531
+ assert eval_sum_residue(1 / x**6, (x, S(1), oo)) == pi**6/945
1532
+ assert eval_sum_residue(1 / (x**2 + 9), (x, -oo, oo)) == pi/(3*tanh(3*pi))
1533
+ assert eval_sum_residue(1 / (x**2 + 1)**2, (x, -oo, oo)).cancel() == \
1534
+ (-pi**2*tanh(pi)**2 + pi*tanh(pi) + pi**2)/(2*tanh(pi)**2)
1535
+ assert eval_sum_residue(x**2 / (x**2 + 1)**2, (x, -oo, oo)).cancel() == \
1536
+ (-pi**2 + pi*tanh(pi) + pi**2*tanh(pi)**2)/(2*tanh(pi)**2)
1537
+ assert eval_sum_residue(1 / (4*x**2 - 1), (x, -oo, oo)) == 0
1538
+ assert eval_sum_residue(x**2 / (x**2 - S(1)/4)**2, (x, -oo, oo)) == pi**2/2
1539
+ assert eval_sum_residue(1 / (4*x**2 - 1)**2, (x, -oo, oo)) == pi**2/8
1540
+ assert eval_sum_residue(1 / ((x - S(1)/2)**2 + 1), (x, -oo, oo)) == pi*tanh(pi)
1541
+ assert eval_sum_residue(1 / x**2, (x, S(1), oo)) == pi**2/6
1542
+ assert eval_sum_residue(1 / x**4, (x, S(1), oo)) == pi**4/90
1543
+ assert eval_sum_residue(1 / x**2 / (x**2 + 4), (x, S(1), oo)) == \
1544
+ -pi*(-pi/12 - 1/(16*pi) + 1/(8*tanh(2*pi)))/2
1545
+
1546
+ # Some examples made from 1 / (x**2 + 1)
1547
+ assert eval_sum_residue(1 / (x**2 + 1), (x, S(0), oo)) == \
1548
+ S(1)/2 + pi/(2*tanh(pi))
1549
+ assert eval_sum_residue(1 / (x**2 + 1), (x, S(1), oo)) == \
1550
+ -S(1)/2 + pi/(2*tanh(pi))
1551
+ assert eval_sum_residue(1 / (x**2 + 1), (x, S(-1), oo)) == \
1552
+ 1 + pi/(2*tanh(pi))
1553
+ assert eval_sum_residue((-1)**x / (x**2 + 1), (x, -oo, oo)) == \
1554
+ pi/sinh(pi)
1555
+ assert eval_sum_residue((-1)**x / (x**2 + 1), (x, S(0), oo)) == \
1556
+ pi/(2*sinh(pi)) + S(1)/2
1557
+ assert eval_sum_residue((-1)**x / (x**2 + 1), (x, S(1), oo)) == \
1558
+ -S(1)/2 + pi/(2*sinh(pi))
1559
+ assert eval_sum_residue((-1)**x / (x**2 + 1), (x, S(-1), oo)) == \
1560
+ pi/(2*sinh(pi))
1561
+
1562
+ # Some examples made from shifting of 1 / (x**2 + 1)
1563
+ assert eval_sum_residue(1 / (x**2 + 2*x + 2), (x, S(-1), oo)) == S(1)/2 + pi/(2*tanh(pi))
1564
+ assert eval_sum_residue(1 / (x**2 + 4*x + 5), (x, S(-2), oo)) == S(1)/2 + pi/(2*tanh(pi))
1565
+ assert eval_sum_residue(1 / (x**2 - 2*x + 2), (x, S(1), oo)) == S(1)/2 + pi/(2*tanh(pi))
1566
+ assert eval_sum_residue(1 / (x**2 - 4*x + 5), (x, S(2), oo)) == S(1)/2 + pi/(2*tanh(pi))
1567
+ assert eval_sum_residue((-1)**x * -1 / (x**2 + 2*x + 2), (x, S(-1), oo)) == S(1)/2 + pi/(2*sinh(pi))
1568
+ assert eval_sum_residue((-1)**x * -1 / (x**2 -2*x + 2), (x, S(1), oo)) == S(1)/2 + pi/(2*sinh(pi))
1569
+
1570
+ # Some examples made from 1 / x**2
1571
+ assert eval_sum_residue(1 / x**2, (x, S(2), oo)) == -1 + pi**2/6
1572
+ assert eval_sum_residue(1 / x**2, (x, S(3), oo)) == -S(5)/4 + pi**2/6
1573
+ assert eval_sum_residue((-1)**x / x**2, (x, S(1), oo)) == -pi**2/12
1574
+ assert eval_sum_residue((-1)**x / x**2, (x, S(2), oo)) == 1 - pi**2/12
1575
+
1576
+
1577
+ @slow
1578
+ def test_summation_by_residues_failing():
1579
+ x = Symbol('x')
1580
+
1581
+ # Failing because of the bug in residue computation
1582
+ assert eval_sum_residue(x**2 / (x**4 + 1), (x, S(1), oo))
1583
+ assert eval_sum_residue(1 / ((x - 1)*(x - 2) + 1), (x, -oo, oo)) != 0
1584
+
1585
+
1586
+ def test_process_limits():
1587
+ from sympy.concrete.expr_with_limits import _process_limits
1588
+
1589
+ # these should be (x, Range(3)) not Range(3)
1590
+ raises(ValueError, lambda: _process_limits(
1591
+ Range(3), discrete=True))
1592
+ raises(ValueError, lambda: _process_limits(
1593
+ Range(3), discrete=False))
1594
+ # these should be (x, union) not union
1595
+ # (but then we would get a TypeError because we don't
1596
+ # handle non-contiguous sets: see below use of `union`)
1597
+ union = Or(x < 1, x > 3).as_set()
1598
+ raises(ValueError, lambda: _process_limits(
1599
+ union, discrete=True))
1600
+ raises(ValueError, lambda: _process_limits(
1601
+ union, discrete=False))
1602
+
1603
+ # error not triggered if not needed
1604
+ assert _process_limits((x, 1, 2)) == ([(x, 1, 2)], 1)
1605
+
1606
+ # this equivalence is used to detect Reals in _process_limits
1607
+ assert isinstance(S.Reals, Interval)
1608
+
1609
+ C = Integral # continuous limits
1610
+ assert C(x, x >= 5) == C(x, (x, 5, oo))
1611
+ assert C(x, x < 3) == C(x, (x, -oo, 3))
1612
+ ans = C(x, (x, 0, 3))
1613
+ assert C(x, And(x >= 0, x < 3)) == ans
1614
+ assert C(x, (x, Interval.Ropen(0, 3))) == ans
1615
+ raises(TypeError, lambda: C(x, (x, Range(3))))
1616
+
1617
+ # discrete limits
1618
+ for D in (Sum, Product):
1619
+ r, ans = Range(3, 10, 2), D(2*x + 3, (x, 0, 3))
1620
+ assert D(x, (x, r)) == ans
1621
+ assert D(x, (x, r.reversed)) == ans
1622
+ r, ans = Range(3, oo, 2), D(2*x + 3, (x, 0, oo))
1623
+ assert D(x, (x, r)) == ans
1624
+ assert D(x, (x, r.reversed)) == ans
1625
+ r, ans = Range(-oo, 5, 2), D(3 - 2*x, (x, 0, oo))
1626
+ assert D(x, (x, r)) == ans
1627
+ assert D(x, (x, r.reversed)) == ans
1628
+ raises(TypeError, lambda: D(x, x > 0))
1629
+ raises(ValueError, lambda: D(x, Interval(1, 3)))
1630
+ raises(NotImplementedError, lambda: D(x, (x, union)))
1631
+
1632
+
1633
+ def test_pr_22677():
1634
+ b = Symbol('b', integer=True, positive=True)
1635
+ assert Sum(1/x**2,(x, 0, b)).doit() == Sum(x**(-2), (x, 0, b))
1636
+ assert Sum(1/(x - b)**2,(x, 0, b-1)).doit() == Sum(
1637
+ (-b + x)**(-2), (x, 0, b - 1))
1638
+
1639
+
1640
+ def test_issue_23952():
1641
+ p, q = symbols("p q", real=True, nonnegative=True)
1642
+ k1, k2 = symbols("k1 k2", integer=True, nonnegative=True)
1643
+ n = Symbol("n", integer=True, positive=True)
1644
+ expr = Sum(abs(k1 - k2)*p**k1 *(1 - q)**(n - k2),
1645
+ (k1, 0, n), (k2, 0, n))
1646
+ assert expr.subs(p,0).subs(q,1).subs(n, 3).doit() == 3
env-llmeval/lib/python3.10/site-packages/sympy/printing/aesaracode.py ADDED
@@ -0,0 +1,539 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ from typing import Any
3
+
4
+ from sympy.external import import_module
5
+ from sympy.printing.printer import Printer
6
+ from sympy.utilities.iterables import is_sequence
7
+ import sympy
8
+ from functools import partial
9
+
10
+
11
+ aesara = import_module('aesara')
12
+
13
+ if aesara:
14
+ aes = aesara.scalar
15
+ aet = aesara.tensor
16
+ from aesara.tensor import nlinalg
17
+ from aesara.tensor.elemwise import Elemwise
18
+ from aesara.tensor.elemwise import DimShuffle
19
+
20
+ # `true_divide` replaced `true_div` in Aesara 2.8.11 (released 2023) to
21
+ # match NumPy
22
+ # XXX: Remove this when not needed to support older versions.
23
+ true_divide = getattr(aet, 'true_divide', None)
24
+ if true_divide is None:
25
+ true_divide = aet.true_div
26
+
27
+ mapping = {
28
+ sympy.Add: aet.add,
29
+ sympy.Mul: aet.mul,
30
+ sympy.Abs: aet.abs,
31
+ sympy.sign: aet.sgn,
32
+ sympy.ceiling: aet.ceil,
33
+ sympy.floor: aet.floor,
34
+ sympy.log: aet.log,
35
+ sympy.exp: aet.exp,
36
+ sympy.sqrt: aet.sqrt,
37
+ sympy.cos: aet.cos,
38
+ sympy.acos: aet.arccos,
39
+ sympy.sin: aet.sin,
40
+ sympy.asin: aet.arcsin,
41
+ sympy.tan: aet.tan,
42
+ sympy.atan: aet.arctan,
43
+ sympy.atan2: aet.arctan2,
44
+ sympy.cosh: aet.cosh,
45
+ sympy.acosh: aet.arccosh,
46
+ sympy.sinh: aet.sinh,
47
+ sympy.asinh: aet.arcsinh,
48
+ sympy.tanh: aet.tanh,
49
+ sympy.atanh: aet.arctanh,
50
+ sympy.re: aet.real,
51
+ sympy.im: aet.imag,
52
+ sympy.arg: aet.angle,
53
+ sympy.erf: aet.erf,
54
+ sympy.gamma: aet.gamma,
55
+ sympy.loggamma: aet.gammaln,
56
+ sympy.Pow: aet.pow,
57
+ sympy.Eq: aet.eq,
58
+ sympy.StrictGreaterThan: aet.gt,
59
+ sympy.StrictLessThan: aet.lt,
60
+ sympy.LessThan: aet.le,
61
+ sympy.GreaterThan: aet.ge,
62
+ sympy.And: aet.bitwise_and, # bitwise
63
+ sympy.Or: aet.bitwise_or, # bitwise
64
+ sympy.Not: aet.invert, # bitwise
65
+ sympy.Xor: aet.bitwise_xor, # bitwise
66
+ sympy.Max: aet.maximum, # Sympy accept >2 inputs, Aesara only 2
67
+ sympy.Min: aet.minimum, # Sympy accept >2 inputs, Aesara only 2
68
+ sympy.conjugate: aet.conj,
69
+ sympy.core.numbers.ImaginaryUnit: lambda:aet.complex(0,1),
70
+ # Matrices
71
+ sympy.MatAdd: Elemwise(aes.add),
72
+ sympy.HadamardProduct: Elemwise(aes.mul),
73
+ sympy.Trace: nlinalg.trace,
74
+ sympy.Determinant : nlinalg.det,
75
+ sympy.Inverse: nlinalg.matrix_inverse,
76
+ sympy.Transpose: DimShuffle((False, False), [1, 0]),
77
+ }
78
+
79
+
80
+ class AesaraPrinter(Printer):
81
+ """ Code printer which creates Aesara symbolic expression graphs.
82
+
83
+ Parameters
84
+ ==========
85
+
86
+ cache : dict
87
+ Cache dictionary to use. If None (default) will use
88
+ the global cache. To create a printer which does not depend on or alter
89
+ global state pass an empty dictionary. Note: the dictionary is not
90
+ copied on initialization of the printer and will be updated in-place,
91
+ so using the same dict object when creating multiple printers or making
92
+ multiple calls to :func:`.aesara_code` or :func:`.aesara_function` means
93
+ the cache is shared between all these applications.
94
+
95
+ Attributes
96
+ ==========
97
+
98
+ cache : dict
99
+ A cache of Aesara variables which have been created for SymPy
100
+ symbol-like objects (e.g. :class:`sympy.core.symbol.Symbol` or
101
+ :class:`sympy.matrices.expressions.MatrixSymbol`). This is used to
102
+ ensure that all references to a given symbol in an expression (or
103
+ multiple expressions) are printed as the same Aesara variable, which is
104
+ created only once. Symbols are differentiated only by name and type. The
105
+ format of the cache's contents should be considered opaque to the user.
106
+ """
107
+ printmethod = "_aesara"
108
+
109
+ def __init__(self, *args, **kwargs):
110
+ self.cache = kwargs.pop('cache', {})
111
+ super().__init__(*args, **kwargs)
112
+
113
+ def _get_key(self, s, name=None, dtype=None, broadcastable=None):
114
+ """ Get the cache key for a SymPy object.
115
+
116
+ Parameters
117
+ ==========
118
+
119
+ s : sympy.core.basic.Basic
120
+ SymPy object to get key for.
121
+
122
+ name : str
123
+ Name of object, if it does not have a ``name`` attribute.
124
+ """
125
+
126
+ if name is None:
127
+ name = s.name
128
+
129
+ return (name, type(s), s.args, dtype, broadcastable)
130
+
131
+ def _get_or_create(self, s, name=None, dtype=None, broadcastable=None):
132
+ """
133
+ Get the Aesara variable for a SymPy symbol from the cache, or create it
134
+ if it does not exist.
135
+ """
136
+
137
+ # Defaults
138
+ if name is None:
139
+ name = s.name
140
+ if dtype is None:
141
+ dtype = 'floatX'
142
+ if broadcastable is None:
143
+ broadcastable = ()
144
+
145
+ key = self._get_key(s, name, dtype=dtype, broadcastable=broadcastable)
146
+
147
+ if key in self.cache:
148
+ return self.cache[key]
149
+
150
+ value = aet.tensor(name=name, dtype=dtype, broadcastable=broadcastable)
151
+ self.cache[key] = value
152
+ return value
153
+
154
+ def _print_Symbol(self, s, **kwargs):
155
+ dtype = kwargs.get('dtypes', {}).get(s)
156
+ bc = kwargs.get('broadcastables', {}).get(s)
157
+ return self._get_or_create(s, dtype=dtype, broadcastable=bc)
158
+
159
+ def _print_AppliedUndef(self, s, **kwargs):
160
+ name = str(type(s)) + '_' + str(s.args[0])
161
+ dtype = kwargs.get('dtypes', {}).get(s)
162
+ bc = kwargs.get('broadcastables', {}).get(s)
163
+ return self._get_or_create(s, name=name, dtype=dtype, broadcastable=bc)
164
+
165
+ def _print_Basic(self, expr, **kwargs):
166
+ op = mapping[type(expr)]
167
+ children = [self._print(arg, **kwargs) for arg in expr.args]
168
+ return op(*children)
169
+
170
+ def _print_Number(self, n, **kwargs):
171
+ # Integers already taken care of below, interpret as float
172
+ return float(n.evalf())
173
+
174
+ def _print_MatrixSymbol(self, X, **kwargs):
175
+ dtype = kwargs.get('dtypes', {}).get(X)
176
+ return self._get_or_create(X, dtype=dtype, broadcastable=(None, None))
177
+
178
+ def _print_DenseMatrix(self, X, **kwargs):
179
+ if not hasattr(aet, 'stacklists'):
180
+ raise NotImplementedError(
181
+ "Matrix translation not yet supported in this version of Aesara")
182
+
183
+ return aet.stacklists([
184
+ [self._print(arg, **kwargs) for arg in L]
185
+ for L in X.tolist()
186
+ ])
187
+
188
+ _print_ImmutableMatrix = _print_ImmutableDenseMatrix = _print_DenseMatrix
189
+
190
+ def _print_MatMul(self, expr, **kwargs):
191
+ children = [self._print(arg, **kwargs) for arg in expr.args]
192
+ result = children[0]
193
+ for child in children[1:]:
194
+ result = aet.dot(result, child)
195
+ return result
196
+
197
+ def _print_MatPow(self, expr, **kwargs):
198
+ children = [self._print(arg, **kwargs) for arg in expr.args]
199
+ result = 1
200
+ if isinstance(children[1], int) and children[1] > 0:
201
+ for i in range(children[1]):
202
+ result = aet.dot(result, children[0])
203
+ else:
204
+ raise NotImplementedError('''Only non-negative integer
205
+ powers of matrices can be handled by Aesara at the moment''')
206
+ return result
207
+
208
+ def _print_MatrixSlice(self, expr, **kwargs):
209
+ parent = self._print(expr.parent, **kwargs)
210
+ rowslice = self._print(slice(*expr.rowslice), **kwargs)
211
+ colslice = self._print(slice(*expr.colslice), **kwargs)
212
+ return parent[rowslice, colslice]
213
+
214
+ def _print_BlockMatrix(self, expr, **kwargs):
215
+ nrows, ncols = expr.blocks.shape
216
+ blocks = [[self._print(expr.blocks[r, c], **kwargs)
217
+ for c in range(ncols)]
218
+ for r in range(nrows)]
219
+ return aet.join(0, *[aet.join(1, *row) for row in blocks])
220
+
221
+
222
+ def _print_slice(self, expr, **kwargs):
223
+ return slice(*[self._print(i, **kwargs)
224
+ if isinstance(i, sympy.Basic) else i
225
+ for i in (expr.start, expr.stop, expr.step)])
226
+
227
+ def _print_Pi(self, expr, **kwargs):
228
+ return 3.141592653589793
229
+
230
+ def _print_Piecewise(self, expr, **kwargs):
231
+ import numpy as np
232
+ e, cond = expr.args[0].args # First condition and corresponding value
233
+
234
+ # Print conditional expression and value for first condition
235
+ p_cond = self._print(cond, **kwargs)
236
+ p_e = self._print(e, **kwargs)
237
+
238
+ # One condition only
239
+ if len(expr.args) == 1:
240
+ # Return value if condition else NaN
241
+ return aet.switch(p_cond, p_e, np.nan)
242
+
243
+ # Return value_1 if condition_1 else evaluate remaining conditions
244
+ p_remaining = self._print(sympy.Piecewise(*expr.args[1:]), **kwargs)
245
+ return aet.switch(p_cond, p_e, p_remaining)
246
+
247
+ def _print_Rational(self, expr, **kwargs):
248
+ return true_divide(self._print(expr.p, **kwargs),
249
+ self._print(expr.q, **kwargs))
250
+
251
+ def _print_Integer(self, expr, **kwargs):
252
+ return expr.p
253
+
254
+ def _print_factorial(self, expr, **kwargs):
255
+ return self._print(sympy.gamma(expr.args[0] + 1), **kwargs)
256
+
257
+ def _print_Derivative(self, deriv, **kwargs):
258
+ from aesara.gradient import Rop
259
+
260
+ rv = self._print(deriv.expr, **kwargs)
261
+ for var in deriv.variables:
262
+ var = self._print(var, **kwargs)
263
+ rv = Rop(rv, var, aet.ones_like(var))
264
+ return rv
265
+
266
+ def emptyPrinter(self, expr):
267
+ return expr
268
+
269
+ def doprint(self, expr, dtypes=None, broadcastables=None):
270
+ """ Convert a SymPy expression to a Aesara graph variable.
271
+
272
+ The ``dtypes`` and ``broadcastables`` arguments are used to specify the
273
+ data type, dimension, and broadcasting behavior of the Aesara variables
274
+ corresponding to the free symbols in ``expr``. Each is a mapping from
275
+ SymPy symbols to the value of the corresponding argument to
276
+ ``aesara.tensor.var.TensorVariable``.
277
+
278
+ See the corresponding `documentation page`__ for more information on
279
+ broadcasting in Aesara.
280
+
281
+ .. __: https://aesara.readthedocs.io/en/latest/tutorial/broadcasting.html
282
+
283
+ Parameters
284
+ ==========
285
+
286
+ expr : sympy.core.expr.Expr
287
+ SymPy expression to print.
288
+
289
+ dtypes : dict
290
+ Mapping from SymPy symbols to Aesara datatypes to use when creating
291
+ new Aesara variables for those symbols. Corresponds to the ``dtype``
292
+ argument to ``aesara.tensor.var.TensorVariable``. Defaults to ``'floatX'``
293
+ for symbols not included in the mapping.
294
+
295
+ broadcastables : dict
296
+ Mapping from SymPy symbols to the value of the ``broadcastable``
297
+ argument to ``aesara.tensor.var.TensorVariable`` to use when creating Aesara
298
+ variables for those symbols. Defaults to the empty tuple for symbols
299
+ not included in the mapping (resulting in a scalar).
300
+
301
+ Returns
302
+ =======
303
+
304
+ aesara.graph.basic.Variable
305
+ A variable corresponding to the expression's value in a Aesara
306
+ symbolic expression graph.
307
+
308
+ """
309
+ if dtypes is None:
310
+ dtypes = {}
311
+ if broadcastables is None:
312
+ broadcastables = {}
313
+
314
+ return self._print(expr, dtypes=dtypes, broadcastables=broadcastables)
315
+
316
+
317
+ global_cache: dict[Any, Any] = {}
318
+
319
+
320
+ def aesara_code(expr, cache=None, **kwargs):
321
+ """
322
+ Convert a SymPy expression into a Aesara graph variable.
323
+
324
+ Parameters
325
+ ==========
326
+
327
+ expr : sympy.core.expr.Expr
328
+ SymPy expression object to convert.
329
+
330
+ cache : dict
331
+ Cached Aesara variables (see :class:`AesaraPrinter.cache
332
+ <AesaraPrinter>`). Defaults to the module-level global cache.
333
+
334
+ dtypes : dict
335
+ Passed to :meth:`.AesaraPrinter.doprint`.
336
+
337
+ broadcastables : dict
338
+ Passed to :meth:`.AesaraPrinter.doprint`.
339
+
340
+ Returns
341
+ =======
342
+
343
+ aesara.graph.basic.Variable
344
+ A variable corresponding to the expression's value in a Aesara symbolic
345
+ expression graph.
346
+
347
+ """
348
+ if not aesara:
349
+ raise ImportError("aesara is required for aesara_code")
350
+
351
+ if cache is None:
352
+ cache = global_cache
353
+
354
+ return AesaraPrinter(cache=cache, settings={}).doprint(expr, **kwargs)
355
+
356
+
357
+ def dim_handling(inputs, dim=None, dims=None, broadcastables=None):
358
+ r"""
359
+ Get value of ``broadcastables`` argument to :func:`.aesara_code` from
360
+ keyword arguments to :func:`.aesara_function`.
361
+
362
+ Included for backwards compatibility.
363
+
364
+ Parameters
365
+ ==========
366
+
367
+ inputs
368
+ Sequence of input symbols.
369
+
370
+ dim : int
371
+ Common number of dimensions for all inputs. Overrides other arguments
372
+ if given.
373
+
374
+ dims : dict
375
+ Mapping from input symbols to number of dimensions. Overrides
376
+ ``broadcastables`` argument if given.
377
+
378
+ broadcastables : dict
379
+ Explicit value of ``broadcastables`` argument to
380
+ :meth:`.AesaraPrinter.doprint`. If not None function will return this value unchanged.
381
+
382
+ Returns
383
+ =======
384
+ dict
385
+ Dictionary mapping elements of ``inputs`` to their "broadcastable"
386
+ values (tuple of ``bool``\ s).
387
+ """
388
+ if dim is not None:
389
+ return {s: (False,) * dim for s in inputs}
390
+
391
+ if dims is not None:
392
+ maxdim = max(dims.values())
393
+ return {
394
+ s: (False,) * d + (True,) * (maxdim - d)
395
+ for s, d in dims.items()
396
+ }
397
+
398
+ if broadcastables is not None:
399
+ return broadcastables
400
+
401
+ return {}
402
+
403
+
404
+ def aesara_function(inputs, outputs, scalar=False, *,
405
+ dim=None, dims=None, broadcastables=None, **kwargs):
406
+ """
407
+ Create a Aesara function from SymPy expressions.
408
+
409
+ The inputs and outputs are converted to Aesara variables using
410
+ :func:`.aesara_code` and then passed to ``aesara.function``.
411
+
412
+ Parameters
413
+ ==========
414
+
415
+ inputs
416
+ Sequence of symbols which constitute the inputs of the function.
417
+
418
+ outputs
419
+ Sequence of expressions which constitute the outputs(s) of the
420
+ function. The free symbols of each expression must be a subset of
421
+ ``inputs``.
422
+
423
+ scalar : bool
424
+ Convert 0-dimensional arrays in output to scalars. This will return a
425
+ Python wrapper function around the Aesara function object.
426
+
427
+ cache : dict
428
+ Cached Aesara variables (see :class:`AesaraPrinter.cache
429
+ <AesaraPrinter>`). Defaults to the module-level global cache.
430
+
431
+ dtypes : dict
432
+ Passed to :meth:`.AesaraPrinter.doprint`.
433
+
434
+ broadcastables : dict
435
+ Passed to :meth:`.AesaraPrinter.doprint`.
436
+
437
+ dims : dict
438
+ Alternative to ``broadcastables`` argument. Mapping from elements of
439
+ ``inputs`` to integers indicating the dimension of their associated
440
+ arrays/tensors. Overrides ``broadcastables`` argument if given.
441
+
442
+ dim : int
443
+ Another alternative to the ``broadcastables`` argument. Common number of
444
+ dimensions to use for all arrays/tensors.
445
+ ``aesara_function([x, y], [...], dim=2)`` is equivalent to using
446
+ ``broadcastables={x: (False, False), y: (False, False)}``.
447
+
448
+ Returns
449
+ =======
450
+ callable
451
+ A callable object which takes values of ``inputs`` as positional
452
+ arguments and returns an output array for each of the expressions
453
+ in ``outputs``. If ``outputs`` is a single expression the function will
454
+ return a Numpy array, if it is a list of multiple expressions the
455
+ function will return a list of arrays. See description of the ``squeeze``
456
+ argument above for the behavior when a single output is passed in a list.
457
+ The returned object will either be an instance of
458
+ ``aesara.compile.function.types.Function`` or a Python wrapper
459
+ function around one. In both cases, the returned value will have a
460
+ ``aesara_function`` attribute which points to the return value of
461
+ ``aesara.function``.
462
+
463
+ Examples
464
+ ========
465
+
466
+ >>> from sympy.abc import x, y, z
467
+ >>> from sympy.printing.aesaracode import aesara_function
468
+
469
+ A simple function with one input and one output:
470
+
471
+ >>> f1 = aesara_function([x], [x**2 - 1], scalar=True)
472
+ >>> f1(3)
473
+ 8.0
474
+
475
+ A function with multiple inputs and one output:
476
+
477
+ >>> f2 = aesara_function([x, y, z], [(x**z + y**z)**(1/z)], scalar=True)
478
+ >>> f2(3, 4, 2)
479
+ 5.0
480
+
481
+ A function with multiple inputs and multiple outputs:
482
+
483
+ >>> f3 = aesara_function([x, y], [x**2 + y**2, x**2 - y**2], scalar=True)
484
+ >>> f3(2, 3)
485
+ [13.0, -5.0]
486
+
487
+ See also
488
+ ========
489
+
490
+ dim_handling
491
+
492
+ """
493
+ if not aesara:
494
+ raise ImportError("Aesara is required for aesara_function")
495
+
496
+ # Pop off non-aesara keyword args
497
+ cache = kwargs.pop('cache', {})
498
+ dtypes = kwargs.pop('dtypes', {})
499
+
500
+ broadcastables = dim_handling(
501
+ inputs, dim=dim, dims=dims, broadcastables=broadcastables,
502
+ )
503
+
504
+ # Print inputs/outputs
505
+ code = partial(aesara_code, cache=cache, dtypes=dtypes,
506
+ broadcastables=broadcastables)
507
+ tinputs = list(map(code, inputs))
508
+ toutputs = list(map(code, outputs))
509
+
510
+ #fix constant expressions as variables
511
+ toutputs = [output if isinstance(output, aesara.graph.basic.Variable) else aet.as_tensor_variable(output) for output in toutputs]
512
+
513
+ if len(toutputs) == 1:
514
+ toutputs = toutputs[0]
515
+
516
+ # Compile aesara func
517
+ func = aesara.function(tinputs, toutputs, **kwargs)
518
+
519
+ is_0d = [len(o.variable.broadcastable) == 0 for o in func.outputs]
520
+
521
+ # No wrapper required
522
+ if not scalar or not any(is_0d):
523
+ func.aesara_function = func
524
+ return func
525
+
526
+ # Create wrapper to convert 0-dimensional outputs to scalars
527
+ def wrapper(*args):
528
+ out = func(*args)
529
+ # out can be array(1.0) or [array(1.0), array(2.0)]
530
+
531
+ if is_sequence(out):
532
+ return [o[()] if is_0d[i] else o for i, o in enumerate(out)]
533
+ else:
534
+ return out[()]
535
+
536
+ wrapper.__wrapped__ = func
537
+ wrapper.__doc__ = func.__doc__
538
+ wrapper.aesara_function = func
539
+ return wrapper
env-llmeval/lib/python3.10/site-packages/sympy/printing/c.py ADDED
@@ -0,0 +1,747 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ C code printer
3
+
4
+ The C89CodePrinter & C99CodePrinter converts single SymPy expressions into
5
+ single C expressions, using the functions defined in math.h where possible.
6
+
7
+ A complete code generator, which uses ccode extensively, can be found in
8
+ sympy.utilities.codegen. The codegen module can be used to generate complete
9
+ source code files that are compilable without further modifications.
10
+
11
+
12
+ """
13
+
14
+ from __future__ import annotations
15
+ from typing import Any
16
+
17
+ from functools import wraps
18
+ from itertools import chain
19
+
20
+ from sympy.core import S
21
+ from sympy.core.numbers import equal_valued
22
+ from sympy.codegen.ast import (
23
+ Assignment, Pointer, Variable, Declaration, Type,
24
+ real, complex_, integer, bool_, float32, float64, float80,
25
+ complex64, complex128, intc, value_const, pointer_const,
26
+ int8, int16, int32, int64, uint8, uint16, uint32, uint64, untyped,
27
+ none
28
+ )
29
+ from sympy.printing.codeprinter import CodePrinter, requires
30
+ from sympy.printing.precedence import precedence, PRECEDENCE
31
+ from sympy.sets.fancysets import Range
32
+
33
+ # These are defined in the other file so we can avoid importing sympy.codegen
34
+ # from the top-level 'import sympy'. Export them here as well.
35
+ from sympy.printing.codeprinter import ccode, print_ccode # noqa:F401
36
+
37
+ # dictionary mapping SymPy function to (argument_conditions, C_function).
38
+ # Used in C89CodePrinter._print_Function(self)
39
+ known_functions_C89 = {
40
+ "Abs": [(lambda x: not x.is_integer, "fabs"), (lambda x: x.is_integer, "abs")],
41
+ "sin": "sin",
42
+ "cos": "cos",
43
+ "tan": "tan",
44
+ "asin": "asin",
45
+ "acos": "acos",
46
+ "atan": "atan",
47
+ "atan2": "atan2",
48
+ "exp": "exp",
49
+ "log": "log",
50
+ "sinh": "sinh",
51
+ "cosh": "cosh",
52
+ "tanh": "tanh",
53
+ "floor": "floor",
54
+ "ceiling": "ceil",
55
+ "sqrt": "sqrt", # To enable automatic rewrites
56
+ }
57
+
58
+ known_functions_C99 = dict(known_functions_C89, **{
59
+ 'exp2': 'exp2',
60
+ 'expm1': 'expm1',
61
+ 'log10': 'log10',
62
+ 'log2': 'log2',
63
+ 'log1p': 'log1p',
64
+ 'Cbrt': 'cbrt',
65
+ 'hypot': 'hypot',
66
+ 'fma': 'fma',
67
+ 'loggamma': 'lgamma',
68
+ 'erfc': 'erfc',
69
+ 'Max': 'fmax',
70
+ 'Min': 'fmin',
71
+ "asinh": "asinh",
72
+ "acosh": "acosh",
73
+ "atanh": "atanh",
74
+ "erf": "erf",
75
+ "gamma": "tgamma",
76
+ })
77
+
78
+ # These are the core reserved words in the C language. Taken from:
79
+ # https://en.cppreference.com/w/c/keyword
80
+
81
+ reserved_words = [
82
+ 'auto', 'break', 'case', 'char', 'const', 'continue', 'default', 'do',
83
+ 'double', 'else', 'enum', 'extern', 'float', 'for', 'goto', 'if', 'int',
84
+ 'long', 'register', 'return', 'short', 'signed', 'sizeof', 'static',
85
+ 'struct', 'entry', # never standardized, we'll leave it here anyway
86
+ 'switch', 'typedef', 'union', 'unsigned', 'void', 'volatile', 'while'
87
+ ]
88
+
89
+ reserved_words_c99 = ['inline', 'restrict']
90
+
91
+ def get_math_macros():
92
+ """ Returns a dictionary with math-related macros from math.h/cmath
93
+
94
+ Note that these macros are not strictly required by the C/C++-standard.
95
+ For MSVC they are enabled by defining "_USE_MATH_DEFINES" (preferably
96
+ via a compilation flag).
97
+
98
+ Returns
99
+ =======
100
+
101
+ Dictionary mapping SymPy expressions to strings (macro names)
102
+
103
+ """
104
+ from sympy.codegen.cfunctions import log2, Sqrt
105
+ from sympy.functions.elementary.exponential import log
106
+ from sympy.functions.elementary.miscellaneous import sqrt
107
+
108
+ return {
109
+ S.Exp1: 'M_E',
110
+ log2(S.Exp1): 'M_LOG2E',
111
+ 1/log(2): 'M_LOG2E',
112
+ log(2): 'M_LN2',
113
+ log(10): 'M_LN10',
114
+ S.Pi: 'M_PI',
115
+ S.Pi/2: 'M_PI_2',
116
+ S.Pi/4: 'M_PI_4',
117
+ 1/S.Pi: 'M_1_PI',
118
+ 2/S.Pi: 'M_2_PI',
119
+ 2/sqrt(S.Pi): 'M_2_SQRTPI',
120
+ 2/Sqrt(S.Pi): 'M_2_SQRTPI',
121
+ sqrt(2): 'M_SQRT2',
122
+ Sqrt(2): 'M_SQRT2',
123
+ 1/sqrt(2): 'M_SQRT1_2',
124
+ 1/Sqrt(2): 'M_SQRT1_2'
125
+ }
126
+
127
+
128
+ def _as_macro_if_defined(meth):
129
+ """ Decorator for printer methods
130
+
131
+ When a Printer's method is decorated using this decorator the expressions printed
132
+ will first be looked for in the attribute ``math_macros``, and if present it will
133
+ print the macro name in ``math_macros`` followed by a type suffix for the type
134
+ ``real``. e.g. printing ``sympy.pi`` would print ``M_PIl`` if real is mapped to float80.
135
+
136
+ """
137
+ @wraps(meth)
138
+ def _meth_wrapper(self, expr, **kwargs):
139
+ if expr in self.math_macros:
140
+ return '%s%s' % (self.math_macros[expr], self._get_math_macro_suffix(real))
141
+ else:
142
+ return meth(self, expr, **kwargs)
143
+
144
+ return _meth_wrapper
145
+
146
+
147
+ class C89CodePrinter(CodePrinter):
148
+ """A printer to convert Python expressions to strings of C code"""
149
+ printmethod = "_ccode"
150
+ language = "C"
151
+ standard = "C89"
152
+ reserved_words = set(reserved_words)
153
+
154
+ _default_settings: dict[str, Any] = {
155
+ 'order': None,
156
+ 'full_prec': 'auto',
157
+ 'precision': 17,
158
+ 'user_functions': {},
159
+ 'human': True,
160
+ 'allow_unknown_functions': False,
161
+ 'contract': True,
162
+ 'dereference': set(),
163
+ 'error_on_reserved': False,
164
+ 'reserved_word_suffix': '_',
165
+ }
166
+
167
+ type_aliases = {
168
+ real: float64,
169
+ complex_: complex128,
170
+ integer: intc
171
+ }
172
+
173
+ type_mappings: dict[Type, Any] = {
174
+ real: 'double',
175
+ intc: 'int',
176
+ float32: 'float',
177
+ float64: 'double',
178
+ integer: 'int',
179
+ bool_: 'bool',
180
+ int8: 'int8_t',
181
+ int16: 'int16_t',
182
+ int32: 'int32_t',
183
+ int64: 'int64_t',
184
+ uint8: 'int8_t',
185
+ uint16: 'int16_t',
186
+ uint32: 'int32_t',
187
+ uint64: 'int64_t',
188
+ }
189
+
190
+ type_headers = {
191
+ bool_: {'stdbool.h'},
192
+ int8: {'stdint.h'},
193
+ int16: {'stdint.h'},
194
+ int32: {'stdint.h'},
195
+ int64: {'stdint.h'},
196
+ uint8: {'stdint.h'},
197
+ uint16: {'stdint.h'},
198
+ uint32: {'stdint.h'},
199
+ uint64: {'stdint.h'},
200
+ }
201
+
202
+ # Macros needed to be defined when using a Type
203
+ type_macros: dict[Type, tuple[str, ...]] = {}
204
+
205
+ type_func_suffixes = {
206
+ float32: 'f',
207
+ float64: '',
208
+ float80: 'l'
209
+ }
210
+
211
+ type_literal_suffixes = {
212
+ float32: 'F',
213
+ float64: '',
214
+ float80: 'L'
215
+ }
216
+
217
+ type_math_macro_suffixes = {
218
+ float80: 'l'
219
+ }
220
+
221
+ math_macros = None
222
+
223
+ _ns = '' # namespace, C++ uses 'std::'
224
+ # known_functions-dict to copy
225
+ _kf: dict[str, Any] = known_functions_C89
226
+
227
+ def __init__(self, settings=None):
228
+ settings = settings or {}
229
+ if self.math_macros is None:
230
+ self.math_macros = settings.pop('math_macros', get_math_macros())
231
+ self.type_aliases = dict(chain(self.type_aliases.items(),
232
+ settings.pop('type_aliases', {}).items()))
233
+ self.type_mappings = dict(chain(self.type_mappings.items(),
234
+ settings.pop('type_mappings', {}).items()))
235
+ self.type_headers = dict(chain(self.type_headers.items(),
236
+ settings.pop('type_headers', {}).items()))
237
+ self.type_macros = dict(chain(self.type_macros.items(),
238
+ settings.pop('type_macros', {}).items()))
239
+ self.type_func_suffixes = dict(chain(self.type_func_suffixes.items(),
240
+ settings.pop('type_func_suffixes', {}).items()))
241
+ self.type_literal_suffixes = dict(chain(self.type_literal_suffixes.items(),
242
+ settings.pop('type_literal_suffixes', {}).items()))
243
+ self.type_math_macro_suffixes = dict(chain(self.type_math_macro_suffixes.items(),
244
+ settings.pop('type_math_macro_suffixes', {}).items()))
245
+ super().__init__(settings)
246
+ self.known_functions = dict(self._kf, **settings.get('user_functions', {}))
247
+ self._dereference = set(settings.get('dereference', []))
248
+ self.headers = set()
249
+ self.libraries = set()
250
+ self.macros = set()
251
+
252
+ def _rate_index_position(self, p):
253
+ return p*5
254
+
255
+ def _get_statement(self, codestring):
256
+ """ Get code string as a statement - i.e. ending with a semicolon. """
257
+ return codestring if codestring.endswith(';') else codestring + ';'
258
+
259
+ def _get_comment(self, text):
260
+ return "/* {} */".format(text)
261
+
262
+ def _declare_number_const(self, name, value):
263
+ type_ = self.type_aliases[real]
264
+ var = Variable(name, type=type_, value=value.evalf(type_.decimal_dig), attrs={value_const})
265
+ decl = Declaration(var)
266
+ return self._get_statement(self._print(decl))
267
+
268
+ def _format_code(self, lines):
269
+ return self.indent_code(lines)
270
+
271
+ def _traverse_matrix_indices(self, mat):
272
+ rows, cols = mat.shape
273
+ return ((i, j) for i in range(rows) for j in range(cols))
274
+
275
+ @_as_macro_if_defined
276
+ def _print_Mul(self, expr, **kwargs):
277
+ return super()._print_Mul(expr, **kwargs)
278
+
279
+ @_as_macro_if_defined
280
+ def _print_Pow(self, expr):
281
+ if "Pow" in self.known_functions:
282
+ return self._print_Function(expr)
283
+ PREC = precedence(expr)
284
+ suffix = self._get_func_suffix(real)
285
+ if equal_valued(expr.exp, -1):
286
+ literal_suffix = self._get_literal_suffix(real)
287
+ return '1.0%s/%s' % (literal_suffix, self.parenthesize(expr.base, PREC))
288
+ elif equal_valued(expr.exp, 0.5):
289
+ return '%ssqrt%s(%s)' % (self._ns, suffix, self._print(expr.base))
290
+ elif expr.exp == S.One/3 and self.standard != 'C89':
291
+ return '%scbrt%s(%s)' % (self._ns, suffix, self._print(expr.base))
292
+ else:
293
+ return '%spow%s(%s, %s)' % (self._ns, suffix, self._print(expr.base),
294
+ self._print(expr.exp))
295
+
296
+ def _print_Mod(self, expr):
297
+ num, den = expr.args
298
+ if num.is_integer and den.is_integer:
299
+ PREC = precedence(expr)
300
+ snum, sden = [self.parenthesize(arg, PREC) for arg in expr.args]
301
+ # % is remainder (same sign as numerator), not modulo (same sign as
302
+ # denominator), in C. Hence, % only works as modulo if both numbers
303
+ # have the same sign
304
+ if (num.is_nonnegative and den.is_nonnegative or
305
+ num.is_nonpositive and den.is_nonpositive):
306
+ return f"{snum} % {sden}"
307
+ return f"(({snum} % {sden}) + {sden}) % {sden}"
308
+ # Not guaranteed integer
309
+ return self._print_math_func(expr, known='fmod')
310
+
311
+ def _print_Rational(self, expr):
312
+ p, q = int(expr.p), int(expr.q)
313
+ suffix = self._get_literal_suffix(real)
314
+ return '%d.0%s/%d.0%s' % (p, suffix, q, suffix)
315
+
316
+ def _print_Indexed(self, expr):
317
+ # calculate index for 1d array
318
+ offset = getattr(expr.base, 'offset', S.Zero)
319
+ strides = getattr(expr.base, 'strides', None)
320
+ indices = expr.indices
321
+
322
+ if strides is None or isinstance(strides, str):
323
+ dims = expr.shape
324
+ shift = S.One
325
+ temp = ()
326
+ if strides == 'C' or strides is None:
327
+ traversal = reversed(range(expr.rank))
328
+ indices = indices[::-1]
329
+ elif strides == 'F':
330
+ traversal = range(expr.rank)
331
+
332
+ for i in traversal:
333
+ temp += (shift,)
334
+ shift *= dims[i]
335
+ strides = temp
336
+ flat_index = sum([x[0]*x[1] for x in zip(indices, strides)]) + offset
337
+ return "%s[%s]" % (self._print(expr.base.label),
338
+ self._print(flat_index))
339
+
340
+ def _print_Idx(self, expr):
341
+ return self._print(expr.label)
342
+
343
+ @_as_macro_if_defined
344
+ def _print_NumberSymbol(self, expr):
345
+ return super()._print_NumberSymbol(expr)
346
+
347
+ def _print_Infinity(self, expr):
348
+ return 'HUGE_VAL'
349
+
350
+ def _print_NegativeInfinity(self, expr):
351
+ return '-HUGE_VAL'
352
+
353
+ def _print_Piecewise(self, expr):
354
+ if expr.args[-1].cond != True:
355
+ # We need the last conditional to be a True, otherwise the resulting
356
+ # function may not return a result.
357
+ raise ValueError("All Piecewise expressions must contain an "
358
+ "(expr, True) statement to be used as a default "
359
+ "condition. Without one, the generated "
360
+ "expression may not evaluate to anything under "
361
+ "some condition.")
362
+ lines = []
363
+ if expr.has(Assignment):
364
+ for i, (e, c) in enumerate(expr.args):
365
+ if i == 0:
366
+ lines.append("if (%s) {" % self._print(c))
367
+ elif i == len(expr.args) - 1 and c == True:
368
+ lines.append("else {")
369
+ else:
370
+ lines.append("else if (%s) {" % self._print(c))
371
+ code0 = self._print(e)
372
+ lines.append(code0)
373
+ lines.append("}")
374
+ return "\n".join(lines)
375
+ else:
376
+ # The piecewise was used in an expression, need to do inline
377
+ # operators. This has the downside that inline operators will
378
+ # not work for statements that span multiple lines (Matrix or
379
+ # Indexed expressions).
380
+ ecpairs = ["((%s) ? (\n%s\n)\n" % (self._print(c),
381
+ self._print(e))
382
+ for e, c in expr.args[:-1]]
383
+ last_line = ": (\n%s\n)" % self._print(expr.args[-1].expr)
384
+ return ": ".join(ecpairs) + last_line + " ".join([")"*len(ecpairs)])
385
+
386
+ def _print_ITE(self, expr):
387
+ from sympy.functions import Piecewise
388
+ return self._print(expr.rewrite(Piecewise, deep=False))
389
+
390
+ def _print_MatrixElement(self, expr):
391
+ return "{}[{}]".format(self.parenthesize(expr.parent, PRECEDENCE["Atom"],
392
+ strict=True), expr.j + expr.i*expr.parent.shape[1])
393
+
394
+ def _print_Symbol(self, expr):
395
+ name = super()._print_Symbol(expr)
396
+ if expr in self._settings['dereference']:
397
+ return '(*{})'.format(name)
398
+ else:
399
+ return name
400
+
401
+ def _print_Relational(self, expr):
402
+ lhs_code = self._print(expr.lhs)
403
+ rhs_code = self._print(expr.rhs)
404
+ op = expr.rel_op
405
+ return "{} {} {}".format(lhs_code, op, rhs_code)
406
+
407
+ def _print_For(self, expr):
408
+ target = self._print(expr.target)
409
+ if isinstance(expr.iterable, Range):
410
+ start, stop, step = expr.iterable.args
411
+ else:
412
+ raise NotImplementedError("Only iterable currently supported is Range")
413
+ body = self._print(expr.body)
414
+ return ('for ({target} = {start}; {target} < {stop}; {target} += '
415
+ '{step}) {{\n{body}\n}}').format(target=target, start=start,
416
+ stop=stop, step=step, body=body)
417
+
418
+ def _print_sign(self, func):
419
+ return '((({0}) > 0) - (({0}) < 0))'.format(self._print(func.args[0]))
420
+
421
+ def _print_Max(self, expr):
422
+ if "Max" in self.known_functions:
423
+ return self._print_Function(expr)
424
+ def inner_print_max(args): # The more natural abstraction of creating
425
+ if len(args) == 1: # and printing smaller Max objects is slow
426
+ return self._print(args[0]) # when there are many arguments.
427
+ half = len(args) // 2
428
+ return "((%(a)s > %(b)s) ? %(a)s : %(b)s)" % {
429
+ 'a': inner_print_max(args[:half]),
430
+ 'b': inner_print_max(args[half:])
431
+ }
432
+ return inner_print_max(expr.args)
433
+
434
+ def _print_Min(self, expr):
435
+ if "Min" in self.known_functions:
436
+ return self._print_Function(expr)
437
+ def inner_print_min(args): # The more natural abstraction of creating
438
+ if len(args) == 1: # and printing smaller Min objects is slow
439
+ return self._print(args[0]) # when there are many arguments.
440
+ half = len(args) // 2
441
+ return "((%(a)s < %(b)s) ? %(a)s : %(b)s)" % {
442
+ 'a': inner_print_min(args[:half]),
443
+ 'b': inner_print_min(args[half:])
444
+ }
445
+ return inner_print_min(expr.args)
446
+
447
+ def indent_code(self, code):
448
+ """Accepts a string of code or a list of code lines"""
449
+
450
+ if isinstance(code, str):
451
+ code_lines = self.indent_code(code.splitlines(True))
452
+ return ''.join(code_lines)
453
+
454
+ tab = " "
455
+ inc_token = ('{', '(', '{\n', '(\n')
456
+ dec_token = ('}', ')')
457
+
458
+ code = [line.lstrip(' \t') for line in code]
459
+
460
+ increase = [int(any(map(line.endswith, inc_token))) for line in code]
461
+ decrease = [int(any(map(line.startswith, dec_token))) for line in code]
462
+
463
+ pretty = []
464
+ level = 0
465
+ for n, line in enumerate(code):
466
+ if line in ('', '\n'):
467
+ pretty.append(line)
468
+ continue
469
+ level -= decrease[n]
470
+ pretty.append("%s%s" % (tab*level, line))
471
+ level += increase[n]
472
+ return pretty
473
+
474
+ def _get_func_suffix(self, type_):
475
+ return self.type_func_suffixes[self.type_aliases.get(type_, type_)]
476
+
477
+ def _get_literal_suffix(self, type_):
478
+ return self.type_literal_suffixes[self.type_aliases.get(type_, type_)]
479
+
480
+ def _get_math_macro_suffix(self, type_):
481
+ alias = self.type_aliases.get(type_, type_)
482
+ dflt = self.type_math_macro_suffixes.get(alias, '')
483
+ return self.type_math_macro_suffixes.get(type_, dflt)
484
+
485
+ def _print_Tuple(self, expr):
486
+ return '{'+', '.join(self._print(e) for e in expr)+'}'
487
+
488
+ _print_List = _print_Tuple
489
+
490
+ def _print_Type(self, type_):
491
+ self.headers.update(self.type_headers.get(type_, set()))
492
+ self.macros.update(self.type_macros.get(type_, set()))
493
+ return self._print(self.type_mappings.get(type_, type_.name))
494
+
495
+ def _print_Declaration(self, decl):
496
+ from sympy.codegen.cnodes import restrict
497
+ var = decl.variable
498
+ val = var.value
499
+ if var.type == untyped:
500
+ raise ValueError("C does not support untyped variables")
501
+
502
+ if isinstance(var, Pointer):
503
+ result = '{vc}{t} *{pc} {r}{s}'.format(
504
+ vc='const ' if value_const in var.attrs else '',
505
+ t=self._print(var.type),
506
+ pc=' const' if pointer_const in var.attrs else '',
507
+ r='restrict ' if restrict in var.attrs else '',
508
+ s=self._print(var.symbol)
509
+ )
510
+ elif isinstance(var, Variable):
511
+ result = '{vc}{t} {s}'.format(
512
+ vc='const ' if value_const in var.attrs else '',
513
+ t=self._print(var.type),
514
+ s=self._print(var.symbol)
515
+ )
516
+ else:
517
+ raise NotImplementedError("Unknown type of var: %s" % type(var))
518
+ if val != None: # Must be "!= None", cannot be "is not None"
519
+ result += ' = %s' % self._print(val)
520
+ return result
521
+
522
+ def _print_Float(self, flt):
523
+ type_ = self.type_aliases.get(real, real)
524
+ self.macros.update(self.type_macros.get(type_, set()))
525
+ suffix = self._get_literal_suffix(type_)
526
+ num = str(flt.evalf(type_.decimal_dig))
527
+ if 'e' not in num and '.' not in num:
528
+ num += '.0'
529
+ num_parts = num.split('e')
530
+ num_parts[0] = num_parts[0].rstrip('0')
531
+ if num_parts[0].endswith('.'):
532
+ num_parts[0] += '0'
533
+ return 'e'.join(num_parts) + suffix
534
+
535
+ @requires(headers={'stdbool.h'})
536
+ def _print_BooleanTrue(self, expr):
537
+ return 'true'
538
+
539
+ @requires(headers={'stdbool.h'})
540
+ def _print_BooleanFalse(self, expr):
541
+ return 'false'
542
+
543
+ def _print_Element(self, elem):
544
+ if elem.strides == None: # Must be "== None", cannot be "is None"
545
+ if elem.offset != None: # Must be "!= None", cannot be "is not None"
546
+ raise ValueError("Expected strides when offset is given")
547
+ idxs = ']['.join((self._print(arg) for arg in elem.indices))
548
+ else:
549
+ global_idx = sum([i*s for i, s in zip(elem.indices, elem.strides)])
550
+ if elem.offset != None: # Must be "!= None", cannot be "is not None"
551
+ global_idx += elem.offset
552
+ idxs = self._print(global_idx)
553
+
554
+ return "{symb}[{idxs}]".format(
555
+ symb=self._print(elem.symbol),
556
+ idxs=idxs
557
+ )
558
+
559
+ def _print_CodeBlock(self, expr):
560
+ """ Elements of code blocks printed as statements. """
561
+ return '\n'.join([self._get_statement(self._print(i)) for i in expr.args])
562
+
563
+ def _print_While(self, expr):
564
+ return 'while ({condition}) {{\n{body}\n}}'.format(**expr.kwargs(
565
+ apply=lambda arg: self._print(arg)))
566
+
567
+ def _print_Scope(self, expr):
568
+ return '{\n%s\n}' % self._print_CodeBlock(expr.body)
569
+
570
+ @requires(headers={'stdio.h'})
571
+ def _print_Print(self, expr):
572
+ return 'printf({fmt}, {pargs})'.format(
573
+ fmt=self._print(expr.format_string),
574
+ pargs=', '.join((self._print(arg) for arg in expr.print_args))
575
+ )
576
+
577
+ def _print_FunctionPrototype(self, expr):
578
+ pars = ', '.join((self._print(Declaration(arg)) for arg in expr.parameters))
579
+ return "%s %s(%s)" % (
580
+ tuple((self._print(arg) for arg in (expr.return_type, expr.name))) + (pars,)
581
+ )
582
+
583
+ def _print_FunctionDefinition(self, expr):
584
+ return "%s%s" % (self._print_FunctionPrototype(expr),
585
+ self._print_Scope(expr))
586
+
587
+ def _print_Return(self, expr):
588
+ arg, = expr.args
589
+ return 'return %s' % self._print(arg)
590
+
591
+ def _print_CommaOperator(self, expr):
592
+ return '(%s)' % ', '.join((self._print(arg) for arg in expr.args))
593
+
594
+ def _print_Label(self, expr):
595
+ if expr.body == none:
596
+ return '%s:' % str(expr.name)
597
+ if len(expr.body.args) == 1:
598
+ return '%s:\n%s' % (str(expr.name), self._print_CodeBlock(expr.body))
599
+ return '%s:\n{\n%s\n}' % (str(expr.name), self._print_CodeBlock(expr.body))
600
+
601
+ def _print_goto(self, expr):
602
+ return 'goto %s' % expr.label.name
603
+
604
+ def _print_PreIncrement(self, expr):
605
+ arg, = expr.args
606
+ return '++(%s)' % self._print(arg)
607
+
608
+ def _print_PostIncrement(self, expr):
609
+ arg, = expr.args
610
+ return '(%s)++' % self._print(arg)
611
+
612
+ def _print_PreDecrement(self, expr):
613
+ arg, = expr.args
614
+ return '--(%s)' % self._print(arg)
615
+
616
+ def _print_PostDecrement(self, expr):
617
+ arg, = expr.args
618
+ return '(%s)--' % self._print(arg)
619
+
620
+ def _print_struct(self, expr):
621
+ return "%(keyword)s %(name)s {\n%(lines)s}" % {
622
+ "keyword": expr.__class__.__name__, "name": expr.name, "lines": ';\n'.join(
623
+ [self._print(decl) for decl in expr.declarations] + [''])
624
+ }
625
+
626
+ def _print_BreakToken(self, _):
627
+ return 'break'
628
+
629
+ def _print_ContinueToken(self, _):
630
+ return 'continue'
631
+
632
+ _print_union = _print_struct
633
+
634
+ class C99CodePrinter(C89CodePrinter):
635
+ standard = 'C99'
636
+ reserved_words = set(reserved_words + reserved_words_c99)
637
+ type_mappings=dict(chain(C89CodePrinter.type_mappings.items(), {
638
+ complex64: 'float complex',
639
+ complex128: 'double complex',
640
+ }.items()))
641
+ type_headers = dict(chain(C89CodePrinter.type_headers.items(), {
642
+ complex64: {'complex.h'},
643
+ complex128: {'complex.h'}
644
+ }.items()))
645
+
646
+ # known_functions-dict to copy
647
+ _kf: dict[str, Any] = known_functions_C99
648
+
649
+ # functions with versions with 'f' and 'l' suffixes:
650
+ _prec_funcs = ('fabs fmod remainder remquo fma fmax fmin fdim nan exp exp2'
651
+ ' expm1 log log10 log2 log1p pow sqrt cbrt hypot sin cos tan'
652
+ ' asin acos atan atan2 sinh cosh tanh asinh acosh atanh erf'
653
+ ' erfc tgamma lgamma ceil floor trunc round nearbyint rint'
654
+ ' frexp ldexp modf scalbn ilogb logb nextafter copysign').split()
655
+
656
+ def _print_Infinity(self, expr):
657
+ return 'INFINITY'
658
+
659
+ def _print_NegativeInfinity(self, expr):
660
+ return '-INFINITY'
661
+
662
+ def _print_NaN(self, expr):
663
+ return 'NAN'
664
+
665
+ # tgamma was already covered by 'known_functions' dict
666
+
667
+ @requires(headers={'math.h'}, libraries={'m'})
668
+ @_as_macro_if_defined
669
+ def _print_math_func(self, expr, nest=False, known=None):
670
+ if known is None:
671
+ known = self.known_functions[expr.__class__.__name__]
672
+ if not isinstance(known, str):
673
+ for cb, name in known:
674
+ if cb(*expr.args):
675
+ known = name
676
+ break
677
+ else:
678
+ raise ValueError("No matching printer")
679
+ try:
680
+ return known(self, *expr.args)
681
+ except TypeError:
682
+ suffix = self._get_func_suffix(real) if self._ns + known in self._prec_funcs else ''
683
+
684
+ if nest:
685
+ args = self._print(expr.args[0])
686
+ if len(expr.args) > 1:
687
+ paren_pile = ''
688
+ for curr_arg in expr.args[1:-1]:
689
+ paren_pile += ')'
690
+ args += ', {ns}{name}{suffix}({next}'.format(
691
+ ns=self._ns,
692
+ name=known,
693
+ suffix=suffix,
694
+ next = self._print(curr_arg)
695
+ )
696
+ args += ', %s%s' % (
697
+ self._print(expr.func(expr.args[-1])),
698
+ paren_pile
699
+ )
700
+ else:
701
+ args = ', '.join((self._print(arg) for arg in expr.args))
702
+ return '{ns}{name}{suffix}({args})'.format(
703
+ ns=self._ns,
704
+ name=known,
705
+ suffix=suffix,
706
+ args=args
707
+ )
708
+
709
+ def _print_Max(self, expr):
710
+ return self._print_math_func(expr, nest=True)
711
+
712
+ def _print_Min(self, expr):
713
+ return self._print_math_func(expr, nest=True)
714
+
715
+ def _get_loop_opening_ending(self, indices):
716
+ open_lines = []
717
+ close_lines = []
718
+ loopstart = "for (int %(var)s=%(start)s; %(var)s<%(end)s; %(var)s++){" # C99
719
+ for i in indices:
720
+ # C arrays start at 0 and end at dimension-1
721
+ open_lines.append(loopstart % {
722
+ 'var': self._print(i.label),
723
+ 'start': self._print(i.lower),
724
+ 'end': self._print(i.upper + 1)})
725
+ close_lines.append("}")
726
+ return open_lines, close_lines
727
+
728
+
729
+ for k in ('Abs Sqrt exp exp2 expm1 log log10 log2 log1p Cbrt hypot fma'
730
+ ' loggamma sin cos tan asin acos atan atan2 sinh cosh tanh asinh acosh '
731
+ 'atanh erf erfc loggamma gamma ceiling floor').split():
732
+ setattr(C99CodePrinter, '_print_%s' % k, C99CodePrinter._print_math_func)
733
+
734
+
735
+ class C11CodePrinter(C99CodePrinter):
736
+
737
+ @requires(headers={'stdalign.h'})
738
+ def _print_alignof(self, expr):
739
+ arg, = expr.args
740
+ return 'alignof(%s)' % self._print(arg)
741
+
742
+
743
+ c_code_printers = {
744
+ 'c89': C89CodePrinter,
745
+ 'c99': C99CodePrinter,
746
+ 'c11': C11CodePrinter
747
+ }
env-llmeval/lib/python3.10/site-packages/sympy/printing/conventions.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ A few practical conventions common to all printers.
3
+ """
4
+
5
+ import re
6
+
7
+ from collections.abc import Iterable
8
+ from sympy.core.function import Derivative
9
+
10
+ _name_with_digits_p = re.compile(r'^([^\W\d_]+)(\d+)$', re.U)
11
+
12
+
13
+ def split_super_sub(text):
14
+ """Split a symbol name into a name, superscripts and subscripts
15
+
16
+ The first part of the symbol name is considered to be its actual
17
+ 'name', followed by super- and subscripts. Each superscript is
18
+ preceded with a "^" character or by "__". Each subscript is preceded
19
+ by a "_" character. The three return values are the actual name, a
20
+ list with superscripts and a list with subscripts.
21
+
22
+ Examples
23
+ ========
24
+
25
+ >>> from sympy.printing.conventions import split_super_sub
26
+ >>> split_super_sub('a_x^1')
27
+ ('a', ['1'], ['x'])
28
+ >>> split_super_sub('var_sub1__sup_sub2')
29
+ ('var', ['sup'], ['sub1', 'sub2'])
30
+
31
+ """
32
+ if not text:
33
+ return text, [], []
34
+
35
+ pos = 0
36
+ name = None
37
+ supers = []
38
+ subs = []
39
+ while pos < len(text):
40
+ start = pos + 1
41
+ if text[pos:pos + 2] == "__":
42
+ start += 1
43
+ pos_hat = text.find("^", start)
44
+ if pos_hat < 0:
45
+ pos_hat = len(text)
46
+ pos_usc = text.find("_", start)
47
+ if pos_usc < 0:
48
+ pos_usc = len(text)
49
+ pos_next = min(pos_hat, pos_usc)
50
+ part = text[pos:pos_next]
51
+ pos = pos_next
52
+ if name is None:
53
+ name = part
54
+ elif part.startswith("^"):
55
+ supers.append(part[1:])
56
+ elif part.startswith("__"):
57
+ supers.append(part[2:])
58
+ elif part.startswith("_"):
59
+ subs.append(part[1:])
60
+ else:
61
+ raise RuntimeError("This should never happen.")
62
+
63
+ # Make a little exception when a name ends with digits, i.e. treat them
64
+ # as a subscript too.
65
+ m = _name_with_digits_p.match(name)
66
+ if m:
67
+ name, sub = m.groups()
68
+ subs.insert(0, sub)
69
+
70
+ return name, supers, subs
71
+
72
+
73
+ def requires_partial(expr):
74
+ """Return whether a partial derivative symbol is required for printing
75
+
76
+ This requires checking how many free variables there are,
77
+ filtering out the ones that are integers. Some expressions do not have
78
+ free variables. In that case, check its variable list explicitly to
79
+ get the context of the expression.
80
+ """
81
+
82
+ if isinstance(expr, Derivative):
83
+ return requires_partial(expr.expr)
84
+
85
+ if not isinstance(expr.free_symbols, Iterable):
86
+ return len(set(expr.variables)) > 1
87
+
88
+ return sum(not s.is_integer for s in expr.free_symbols) > 1
env-llmeval/lib/python3.10/site-packages/sympy/printing/dot.py ADDED
@@ -0,0 +1,294 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.basic import Basic
2
+ from sympy.core.expr import Expr
3
+ from sympy.core.symbol import Symbol
4
+ from sympy.core.numbers import Integer, Rational, Float
5
+ from sympy.printing.repr import srepr
6
+
7
+ __all__ = ['dotprint']
8
+
9
+ default_styles = (
10
+ (Basic, {'color': 'blue', 'shape': 'ellipse'}),
11
+ (Expr, {'color': 'black'})
12
+ )
13
+
14
+ slotClasses = (Symbol, Integer, Rational, Float)
15
+ def purestr(x, with_args=False):
16
+ """A string that follows ```obj = type(obj)(*obj.args)``` exactly.
17
+
18
+ Parameters
19
+ ==========
20
+
21
+ with_args : boolean, optional
22
+ If ``True``, there will be a second argument for the return
23
+ value, which is a tuple containing ``purestr`` applied to each
24
+ of the subnodes.
25
+
26
+ If ``False``, there will not be a second argument for the
27
+ return.
28
+
29
+ Default is ``False``
30
+
31
+ Examples
32
+ ========
33
+
34
+ >>> from sympy import Float, Symbol, MatrixSymbol
35
+ >>> from sympy import Integer # noqa: F401
36
+ >>> from sympy.core.symbol import Str # noqa: F401
37
+ >>> from sympy.printing.dot import purestr
38
+
39
+ Applying ``purestr`` for basic symbolic object:
40
+ >>> code = purestr(Symbol('x'))
41
+ >>> code
42
+ "Symbol('x')"
43
+ >>> eval(code) == Symbol('x')
44
+ True
45
+
46
+ For basic numeric object:
47
+ >>> purestr(Float(2))
48
+ "Float('2.0', precision=53)"
49
+
50
+ For matrix symbol:
51
+ >>> code = purestr(MatrixSymbol('x', 2, 2))
52
+ >>> code
53
+ "MatrixSymbol(Str('x'), Integer(2), Integer(2))"
54
+ >>> eval(code) == MatrixSymbol('x', 2, 2)
55
+ True
56
+
57
+ With ``with_args=True``:
58
+ >>> purestr(Float(2), with_args=True)
59
+ ("Float('2.0', precision=53)", ())
60
+ >>> purestr(MatrixSymbol('x', 2, 2), with_args=True)
61
+ ("MatrixSymbol(Str('x'), Integer(2), Integer(2))",
62
+ ("Str('x')", 'Integer(2)', 'Integer(2)'))
63
+ """
64
+ sargs = ()
65
+ if not isinstance(x, Basic):
66
+ rv = str(x)
67
+ elif not x.args:
68
+ rv = srepr(x)
69
+ else:
70
+ args = x.args
71
+ sargs = tuple(map(purestr, args))
72
+ rv = "%s(%s)"%(type(x).__name__, ', '.join(sargs))
73
+ if with_args:
74
+ rv = rv, sargs
75
+ return rv
76
+
77
+
78
+ def styleof(expr, styles=default_styles):
79
+ """ Merge style dictionaries in order
80
+
81
+ Examples
82
+ ========
83
+
84
+ >>> from sympy import Symbol, Basic, Expr, S
85
+ >>> from sympy.printing.dot import styleof
86
+ >>> styles = [(Basic, {'color': 'blue', 'shape': 'ellipse'}),
87
+ ... (Expr, {'color': 'black'})]
88
+
89
+ >>> styleof(Basic(S(1)), styles)
90
+ {'color': 'blue', 'shape': 'ellipse'}
91
+
92
+ >>> x = Symbol('x')
93
+ >>> styleof(x + 1, styles) # this is an Expr
94
+ {'color': 'black', 'shape': 'ellipse'}
95
+ """
96
+ style = {}
97
+ for typ, sty in styles:
98
+ if isinstance(expr, typ):
99
+ style.update(sty)
100
+ return style
101
+
102
+
103
+ def attrprint(d, delimiter=', '):
104
+ """ Print a dictionary of attributes
105
+
106
+ Examples
107
+ ========
108
+
109
+ >>> from sympy.printing.dot import attrprint
110
+ >>> print(attrprint({'color': 'blue', 'shape': 'ellipse'}))
111
+ "color"="blue", "shape"="ellipse"
112
+ """
113
+ return delimiter.join('"%s"="%s"'%item for item in sorted(d.items()))
114
+
115
+
116
+ def dotnode(expr, styles=default_styles, labelfunc=str, pos=(), repeat=True):
117
+ """ String defining a node
118
+
119
+ Examples
120
+ ========
121
+
122
+ >>> from sympy.printing.dot import dotnode
123
+ >>> from sympy.abc import x
124
+ >>> print(dotnode(x))
125
+ "Symbol('x')_()" ["color"="black", "label"="x", "shape"="ellipse"];
126
+ """
127
+ style = styleof(expr, styles)
128
+
129
+ if isinstance(expr, Basic) and not expr.is_Atom:
130
+ label = str(expr.__class__.__name__)
131
+ else:
132
+ label = labelfunc(expr)
133
+ style['label'] = label
134
+ expr_str = purestr(expr)
135
+ if repeat:
136
+ expr_str += '_%s' % str(pos)
137
+ return '"%s" [%s];' % (expr_str, attrprint(style))
138
+
139
+
140
+ def dotedges(expr, atom=lambda x: not isinstance(x, Basic), pos=(), repeat=True):
141
+ """ List of strings for all expr->expr.arg pairs
142
+
143
+ See the docstring of dotprint for explanations of the options.
144
+
145
+ Examples
146
+ ========
147
+
148
+ >>> from sympy.printing.dot import dotedges
149
+ >>> from sympy.abc import x
150
+ >>> for e in dotedges(x+2):
151
+ ... print(e)
152
+ "Add(Integer(2), Symbol('x'))_()" -> "Integer(2)_(0,)";
153
+ "Add(Integer(2), Symbol('x'))_()" -> "Symbol('x')_(1,)";
154
+ """
155
+ if atom(expr):
156
+ return []
157
+ else:
158
+ expr_str, arg_strs = purestr(expr, with_args=True)
159
+ if repeat:
160
+ expr_str += '_%s' % str(pos)
161
+ arg_strs = ['%s_%s' % (a, str(pos + (i,)))
162
+ for i, a in enumerate(arg_strs)]
163
+ return ['"%s" -> "%s";' % (expr_str, a) for a in arg_strs]
164
+
165
+ template = \
166
+ """digraph{
167
+
168
+ # Graph style
169
+ %(graphstyle)s
170
+
171
+ #########
172
+ # Nodes #
173
+ #########
174
+
175
+ %(nodes)s
176
+
177
+ #########
178
+ # Edges #
179
+ #########
180
+
181
+ %(edges)s
182
+ }"""
183
+
184
+ _graphstyle = {'rankdir': 'TD', 'ordering': 'out'}
185
+
186
+ def dotprint(expr,
187
+ styles=default_styles, atom=lambda x: not isinstance(x, Basic),
188
+ maxdepth=None, repeat=True, labelfunc=str, **kwargs):
189
+ """DOT description of a SymPy expression tree
190
+
191
+ Parameters
192
+ ==========
193
+
194
+ styles : list of lists composed of (Class, mapping), optional
195
+ Styles for different classes.
196
+
197
+ The default is
198
+
199
+ .. code-block:: python
200
+
201
+ (
202
+ (Basic, {'color': 'blue', 'shape': 'ellipse'}),
203
+ (Expr, {'color': 'black'})
204
+ )
205
+
206
+ atom : function, optional
207
+ Function used to determine if an arg is an atom.
208
+
209
+ A good choice is ``lambda x: not x.args``.
210
+
211
+ The default is ``lambda x: not isinstance(x, Basic)``.
212
+
213
+ maxdepth : integer, optional
214
+ The maximum depth.
215
+
216
+ The default is ``None``, meaning no limit.
217
+
218
+ repeat : boolean, optional
219
+ Whether to use different nodes for common subexpressions.
220
+
221
+ The default is ``True``.
222
+
223
+ For example, for ``x + x*y`` with ``repeat=True``, it will have
224
+ two nodes for ``x``; with ``repeat=False``, it will have one
225
+ node.
226
+
227
+ .. warning::
228
+ Even if a node appears twice in the same object like ``x`` in
229
+ ``Pow(x, x)``, it will still only appear once.
230
+ Hence, with ``repeat=False``, the number of arrows out of an
231
+ object might not equal the number of args it has.
232
+
233
+ labelfunc : function, optional
234
+ A function to create a label for a given leaf node.
235
+
236
+ The default is ``str``.
237
+
238
+ Another good option is ``srepr``.
239
+
240
+ For example with ``str``, the leaf nodes of ``x + 1`` are labeled,
241
+ ``x`` and ``1``. With ``srepr``, they are labeled ``Symbol('x')``
242
+ and ``Integer(1)``.
243
+
244
+ **kwargs : optional
245
+ Additional keyword arguments are included as styles for the graph.
246
+
247
+ Examples
248
+ ========
249
+
250
+ >>> from sympy import dotprint
251
+ >>> from sympy.abc import x
252
+ >>> print(dotprint(x+2)) # doctest: +NORMALIZE_WHITESPACE
253
+ digraph{
254
+ <BLANKLINE>
255
+ # Graph style
256
+ "ordering"="out"
257
+ "rankdir"="TD"
258
+ <BLANKLINE>
259
+ #########
260
+ # Nodes #
261
+ #########
262
+ <BLANKLINE>
263
+ "Add(Integer(2), Symbol('x'))_()" ["color"="black", "label"="Add", "shape"="ellipse"];
264
+ "Integer(2)_(0,)" ["color"="black", "label"="2", "shape"="ellipse"];
265
+ "Symbol('x')_(1,)" ["color"="black", "label"="x", "shape"="ellipse"];
266
+ <BLANKLINE>
267
+ #########
268
+ # Edges #
269
+ #########
270
+ <BLANKLINE>
271
+ "Add(Integer(2), Symbol('x'))_()" -> "Integer(2)_(0,)";
272
+ "Add(Integer(2), Symbol('x'))_()" -> "Symbol('x')_(1,)";
273
+ }
274
+
275
+ """
276
+ # repeat works by adding a signature tuple to the end of each node for its
277
+ # position in the graph. For example, for expr = Add(x, Pow(x, 2)), the x in the
278
+ # Pow will have the tuple (1, 0), meaning it is expr.args[1].args[0].
279
+ graphstyle = _graphstyle.copy()
280
+ graphstyle.update(kwargs)
281
+
282
+ nodes = []
283
+ edges = []
284
+ def traverse(e, depth, pos=()):
285
+ nodes.append(dotnode(e, styles, labelfunc=labelfunc, pos=pos, repeat=repeat))
286
+ if maxdepth and depth >= maxdepth:
287
+ return
288
+ edges.extend(dotedges(e, atom=atom, pos=pos, repeat=repeat))
289
+ [traverse(arg, depth+1, pos + (i,)) for i, arg in enumerate(e.args) if not atom(arg)]
290
+ traverse(expr, 0)
291
+
292
+ return template%{'graphstyle': attrprint(graphstyle, delimiter='\n'),
293
+ 'nodes': '\n'.join(nodes),
294
+ 'edges': '\n'.join(edges)}
env-llmeval/lib/python3.10/site-packages/sympy/printing/precedence.py ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """A module providing information about the necessity of brackets"""
2
+
3
+
4
+ # Default precedence values for some basic types
5
+ PRECEDENCE = {
6
+ "Lambda": 1,
7
+ "Xor": 10,
8
+ "Or": 20,
9
+ "And": 30,
10
+ "Relational": 35,
11
+ "Add": 40,
12
+ "Mul": 50,
13
+ "Pow": 60,
14
+ "Func": 70,
15
+ "Not": 100,
16
+ "Atom": 1000,
17
+ "BitwiseOr": 36,
18
+ "BitwiseXor": 37,
19
+ "BitwiseAnd": 38
20
+ }
21
+
22
+ # A dictionary assigning precedence values to certain classes. These values are
23
+ # treated like they were inherited, so not every single class has to be named
24
+ # here.
25
+ # Do not use this with printers other than StrPrinter
26
+ PRECEDENCE_VALUES = {
27
+ "Equivalent": PRECEDENCE["Xor"],
28
+ "Xor": PRECEDENCE["Xor"],
29
+ "Implies": PRECEDENCE["Xor"],
30
+ "Or": PRECEDENCE["Or"],
31
+ "And": PRECEDENCE["And"],
32
+ "Add": PRECEDENCE["Add"],
33
+ "Pow": PRECEDENCE["Pow"],
34
+ "Relational": PRECEDENCE["Relational"],
35
+ "Sub": PRECEDENCE["Add"],
36
+ "Not": PRECEDENCE["Not"],
37
+ "Function" : PRECEDENCE["Func"],
38
+ "NegativeInfinity": PRECEDENCE["Add"],
39
+ "MatAdd": PRECEDENCE["Add"],
40
+ "MatPow": PRECEDENCE["Pow"],
41
+ "MatrixSolve": PRECEDENCE["Mul"],
42
+ "Mod": PRECEDENCE["Mul"],
43
+ "TensAdd": PRECEDENCE["Add"],
44
+ # As soon as `TensMul` is a subclass of `Mul`, remove this:
45
+ "TensMul": PRECEDENCE["Mul"],
46
+ "HadamardProduct": PRECEDENCE["Mul"],
47
+ "HadamardPower": PRECEDENCE["Pow"],
48
+ "KroneckerProduct": PRECEDENCE["Mul"],
49
+ "Equality": PRECEDENCE["Mul"],
50
+ "Unequality": PRECEDENCE["Mul"],
51
+ }
52
+
53
+ # Sometimes it's not enough to assign a fixed precedence value to a
54
+ # class. Then a function can be inserted in this dictionary that takes
55
+ # an instance of this class as argument and returns the appropriate
56
+ # precedence value.
57
+
58
+ # Precedence functions
59
+
60
+
61
+ def precedence_Mul(item):
62
+ if item.could_extract_minus_sign():
63
+ return PRECEDENCE["Add"]
64
+ return PRECEDENCE["Mul"]
65
+
66
+
67
+ def precedence_Rational(item):
68
+ if item.p < 0:
69
+ return PRECEDENCE["Add"]
70
+ return PRECEDENCE["Mul"]
71
+
72
+
73
+ def precedence_Integer(item):
74
+ if item.p < 0:
75
+ return PRECEDENCE["Add"]
76
+ return PRECEDENCE["Atom"]
77
+
78
+
79
+ def precedence_Float(item):
80
+ if item < 0:
81
+ return PRECEDENCE["Add"]
82
+ return PRECEDENCE["Atom"]
83
+
84
+
85
+ def precedence_PolyElement(item):
86
+ if item.is_generator:
87
+ return PRECEDENCE["Atom"]
88
+ elif item.is_ground:
89
+ return precedence(item.coeff(1))
90
+ elif item.is_term:
91
+ return PRECEDENCE["Mul"]
92
+ else:
93
+ return PRECEDENCE["Add"]
94
+
95
+
96
+ def precedence_FracElement(item):
97
+ if item.denom == 1:
98
+ return precedence_PolyElement(item.numer)
99
+ else:
100
+ return PRECEDENCE["Mul"]
101
+
102
+
103
+ def precedence_UnevaluatedExpr(item):
104
+ return precedence(item.args[0]) - 0.5
105
+
106
+
107
+ PRECEDENCE_FUNCTIONS = {
108
+ "Integer": precedence_Integer,
109
+ "Mul": precedence_Mul,
110
+ "Rational": precedence_Rational,
111
+ "Float": precedence_Float,
112
+ "PolyElement": precedence_PolyElement,
113
+ "FracElement": precedence_FracElement,
114
+ "UnevaluatedExpr": precedence_UnevaluatedExpr,
115
+ }
116
+
117
+
118
+ def precedence(item):
119
+ """Returns the precedence of a given object.
120
+
121
+ This is the precedence for StrPrinter.
122
+ """
123
+ if hasattr(item, "precedence"):
124
+ return item.precedence
125
+ try:
126
+ mro = item.__class__.__mro__
127
+ except AttributeError:
128
+ return PRECEDENCE["Atom"]
129
+ for i in mro:
130
+ n = i.__name__
131
+ if n in PRECEDENCE_FUNCTIONS:
132
+ return PRECEDENCE_FUNCTIONS[n](item)
133
+ elif n in PRECEDENCE_VALUES:
134
+ return PRECEDENCE_VALUES[n]
135
+ return PRECEDENCE["Atom"]
136
+
137
+
138
+ PRECEDENCE_TRADITIONAL = PRECEDENCE.copy()
139
+ PRECEDENCE_TRADITIONAL['Integral'] = PRECEDENCE["Mul"]
140
+ PRECEDENCE_TRADITIONAL['Sum'] = PRECEDENCE["Mul"]
141
+ PRECEDENCE_TRADITIONAL['Product'] = PRECEDENCE["Mul"]
142
+ PRECEDENCE_TRADITIONAL['Limit'] = PRECEDENCE["Mul"]
143
+ PRECEDENCE_TRADITIONAL['Derivative'] = PRECEDENCE["Mul"]
144
+ PRECEDENCE_TRADITIONAL['TensorProduct'] = PRECEDENCE["Mul"]
145
+ PRECEDENCE_TRADITIONAL['Transpose'] = PRECEDENCE["Pow"]
146
+ PRECEDENCE_TRADITIONAL['Adjoint'] = PRECEDENCE["Pow"]
147
+ PRECEDENCE_TRADITIONAL['Dot'] = PRECEDENCE["Mul"] - 1
148
+ PRECEDENCE_TRADITIONAL['Cross'] = PRECEDENCE["Mul"] - 1
149
+ PRECEDENCE_TRADITIONAL['Gradient'] = PRECEDENCE["Mul"] - 1
150
+ PRECEDENCE_TRADITIONAL['Divergence'] = PRECEDENCE["Mul"] - 1
151
+ PRECEDENCE_TRADITIONAL['Curl'] = PRECEDENCE["Mul"] - 1
152
+ PRECEDENCE_TRADITIONAL['Laplacian'] = PRECEDENCE["Mul"] - 1
153
+ PRECEDENCE_TRADITIONAL['Union'] = PRECEDENCE['Xor']
154
+ PRECEDENCE_TRADITIONAL['Intersection'] = PRECEDENCE['Xor']
155
+ PRECEDENCE_TRADITIONAL['Complement'] = PRECEDENCE['Xor']
156
+ PRECEDENCE_TRADITIONAL['SymmetricDifference'] = PRECEDENCE['Xor']
157
+ PRECEDENCE_TRADITIONAL['ProductSet'] = PRECEDENCE['Xor']
158
+
159
+
160
+ def precedence_traditional(item):
161
+ """Returns the precedence of a given object according to the
162
+ traditional rules of mathematics.
163
+
164
+ This is the precedence for the LaTeX and pretty printer.
165
+ """
166
+ # Integral, Sum, Product, Limit have the precedence of Mul in LaTeX,
167
+ # the precedence of Atom for other printers:
168
+ from sympy.core.expr import UnevaluatedExpr
169
+
170
+ if isinstance(item, UnevaluatedExpr):
171
+ return precedence_traditional(item.args[0])
172
+
173
+ n = item.__class__.__name__
174
+ if n in PRECEDENCE_TRADITIONAL:
175
+ return PRECEDENCE_TRADITIONAL[n]
176
+
177
+ return precedence(item)
env-llmeval/lib/python3.10/site-packages/sympy/printing/rcode.py ADDED
@@ -0,0 +1,410 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ R code printer
3
+
4
+ The RCodePrinter converts single SymPy expressions into single R expressions,
5
+ using the functions defined in math.h where possible.
6
+
7
+
8
+
9
+ """
10
+
11
+ from __future__ import annotations
12
+ from typing import Any
13
+
14
+ from sympy.core.numbers import equal_valued
15
+ from sympy.printing.codeprinter import CodePrinter
16
+ from sympy.printing.precedence import precedence, PRECEDENCE
17
+ from sympy.sets.fancysets import Range
18
+
19
+ # dictionary mapping SymPy function to (argument_conditions, C_function).
20
+ # Used in RCodePrinter._print_Function(self)
21
+ known_functions = {
22
+ #"Abs": [(lambda x: not x.is_integer, "fabs")],
23
+ "Abs": "abs",
24
+ "sin": "sin",
25
+ "cos": "cos",
26
+ "tan": "tan",
27
+ "asin": "asin",
28
+ "acos": "acos",
29
+ "atan": "atan",
30
+ "atan2": "atan2",
31
+ "exp": "exp",
32
+ "log": "log",
33
+ "erf": "erf",
34
+ "sinh": "sinh",
35
+ "cosh": "cosh",
36
+ "tanh": "tanh",
37
+ "asinh": "asinh",
38
+ "acosh": "acosh",
39
+ "atanh": "atanh",
40
+ "floor": "floor",
41
+ "ceiling": "ceiling",
42
+ "sign": "sign",
43
+ "Max": "max",
44
+ "Min": "min",
45
+ "factorial": "factorial",
46
+ "gamma": "gamma",
47
+ "digamma": "digamma",
48
+ "trigamma": "trigamma",
49
+ "beta": "beta",
50
+ "sqrt": "sqrt", # To enable automatic rewrite
51
+ }
52
+
53
+ # These are the core reserved words in the R language. Taken from:
54
+ # https://cran.r-project.org/doc/manuals/r-release/R-lang.html#Reserved-words
55
+
56
+ reserved_words = ['if',
57
+ 'else',
58
+ 'repeat',
59
+ 'while',
60
+ 'function',
61
+ 'for',
62
+ 'in',
63
+ 'next',
64
+ 'break',
65
+ 'TRUE',
66
+ 'FALSE',
67
+ 'NULL',
68
+ 'Inf',
69
+ 'NaN',
70
+ 'NA',
71
+ 'NA_integer_',
72
+ 'NA_real_',
73
+ 'NA_complex_',
74
+ 'NA_character_',
75
+ 'volatile']
76
+
77
+
78
+ class RCodePrinter(CodePrinter):
79
+ """A printer to convert SymPy expressions to strings of R code"""
80
+ printmethod = "_rcode"
81
+ language = "R"
82
+
83
+ _default_settings: dict[str, Any] = {
84
+ 'order': None,
85
+ 'full_prec': 'auto',
86
+ 'precision': 15,
87
+ 'user_functions': {},
88
+ 'human': True,
89
+ 'contract': True,
90
+ 'dereference': set(),
91
+ 'error_on_reserved': False,
92
+ 'reserved_word_suffix': '_',
93
+ }
94
+ _operators = {
95
+ 'and': '&',
96
+ 'or': '|',
97
+ 'not': '!',
98
+ }
99
+
100
+ _relationals: dict[str, str] = {}
101
+
102
+ def __init__(self, settings={}):
103
+ CodePrinter.__init__(self, settings)
104
+ self.known_functions = dict(known_functions)
105
+ userfuncs = settings.get('user_functions', {})
106
+ self.known_functions.update(userfuncs)
107
+ self._dereference = set(settings.get('dereference', []))
108
+ self.reserved_words = set(reserved_words)
109
+
110
+ def _rate_index_position(self, p):
111
+ return p*5
112
+
113
+ def _get_statement(self, codestring):
114
+ return "%s;" % codestring
115
+
116
+ def _get_comment(self, text):
117
+ return "// {}".format(text)
118
+
119
+ def _declare_number_const(self, name, value):
120
+ return "{} = {};".format(name, value)
121
+
122
+ def _format_code(self, lines):
123
+ return self.indent_code(lines)
124
+
125
+ def _traverse_matrix_indices(self, mat):
126
+ rows, cols = mat.shape
127
+ return ((i, j) for i in range(rows) for j in range(cols))
128
+
129
+ def _get_loop_opening_ending(self, indices):
130
+ """Returns a tuple (open_lines, close_lines) containing lists of codelines
131
+ """
132
+ open_lines = []
133
+ close_lines = []
134
+ loopstart = "for (%(var)s in %(start)s:%(end)s){"
135
+ for i in indices:
136
+ # R arrays start at 1 and end at dimension
137
+ open_lines.append(loopstart % {
138
+ 'var': self._print(i.label),
139
+ 'start': self._print(i.lower+1),
140
+ 'end': self._print(i.upper + 1)})
141
+ close_lines.append("}")
142
+ return open_lines, close_lines
143
+
144
+ def _print_Pow(self, expr):
145
+ if "Pow" in self.known_functions:
146
+ return self._print_Function(expr)
147
+ PREC = precedence(expr)
148
+ if equal_valued(expr.exp, -1):
149
+ return '1.0/%s' % (self.parenthesize(expr.base, PREC))
150
+ elif equal_valued(expr.exp, 0.5):
151
+ return 'sqrt(%s)' % self._print(expr.base)
152
+ else:
153
+ return '%s^%s' % (self.parenthesize(expr.base, PREC),
154
+ self.parenthesize(expr.exp, PREC))
155
+
156
+
157
+ def _print_Rational(self, expr):
158
+ p, q = int(expr.p), int(expr.q)
159
+ return '%d.0/%d.0' % (p, q)
160
+
161
+ def _print_Indexed(self, expr):
162
+ inds = [ self._print(i) for i in expr.indices ]
163
+ return "%s[%s]" % (self._print(expr.base.label), ", ".join(inds))
164
+
165
+ def _print_Idx(self, expr):
166
+ return self._print(expr.label)
167
+
168
+ def _print_Exp1(self, expr):
169
+ return "exp(1)"
170
+
171
+ def _print_Pi(self, expr):
172
+ return 'pi'
173
+
174
+ def _print_Infinity(self, expr):
175
+ return 'Inf'
176
+
177
+ def _print_NegativeInfinity(self, expr):
178
+ return '-Inf'
179
+
180
+ def _print_Assignment(self, expr):
181
+ from sympy.codegen.ast import Assignment
182
+
183
+ from sympy.matrices.expressions.matexpr import MatrixSymbol
184
+ from sympy.tensor.indexed import IndexedBase
185
+ lhs = expr.lhs
186
+ rhs = expr.rhs
187
+ # We special case assignments that take multiple lines
188
+ #if isinstance(expr.rhs, Piecewise):
189
+ # from sympy.functions.elementary.piecewise import Piecewise
190
+ # # Here we modify Piecewise so each expression is now
191
+ # # an Assignment, and then continue on the print.
192
+ # expressions = []
193
+ # conditions = []
194
+ # for (e, c) in rhs.args:
195
+ # expressions.append(Assignment(lhs, e))
196
+ # conditions.append(c)
197
+ # temp = Piecewise(*zip(expressions, conditions))
198
+ # return self._print(temp)
199
+ #elif isinstance(lhs, MatrixSymbol):
200
+ if isinstance(lhs, MatrixSymbol):
201
+ # Here we form an Assignment for each element in the array,
202
+ # printing each one.
203
+ lines = []
204
+ for (i, j) in self._traverse_matrix_indices(lhs):
205
+ temp = Assignment(lhs[i, j], rhs[i, j])
206
+ code0 = self._print(temp)
207
+ lines.append(code0)
208
+ return "\n".join(lines)
209
+ elif self._settings["contract"] and (lhs.has(IndexedBase) or
210
+ rhs.has(IndexedBase)):
211
+ # Here we check if there is looping to be done, and if so
212
+ # print the required loops.
213
+ return self._doprint_loops(rhs, lhs)
214
+ else:
215
+ lhs_code = self._print(lhs)
216
+ rhs_code = self._print(rhs)
217
+ return self._get_statement("%s = %s" % (lhs_code, rhs_code))
218
+
219
+ def _print_Piecewise(self, expr):
220
+ # This method is called only for inline if constructs
221
+ # Top level piecewise is handled in doprint()
222
+ if expr.args[-1].cond == True:
223
+ last_line = "%s" % self._print(expr.args[-1].expr)
224
+ else:
225
+ last_line = "ifelse(%s,%s,NA)" % (self._print(expr.args[-1].cond), self._print(expr.args[-1].expr))
226
+ code=last_line
227
+ for e, c in reversed(expr.args[:-1]):
228
+ code= "ifelse(%s,%s," % (self._print(c), self._print(e))+code+")"
229
+ return(code)
230
+
231
+ def _print_ITE(self, expr):
232
+ from sympy.functions import Piecewise
233
+ return self._print(expr.rewrite(Piecewise))
234
+
235
+ def _print_MatrixElement(self, expr):
236
+ return "{}[{}]".format(self.parenthesize(expr.parent, PRECEDENCE["Atom"],
237
+ strict=True), expr.j + expr.i*expr.parent.shape[1])
238
+
239
+ def _print_Symbol(self, expr):
240
+ name = super()._print_Symbol(expr)
241
+ if expr in self._dereference:
242
+ return '(*{})'.format(name)
243
+ else:
244
+ return name
245
+
246
+ def _print_Relational(self, expr):
247
+ lhs_code = self._print(expr.lhs)
248
+ rhs_code = self._print(expr.rhs)
249
+ op = expr.rel_op
250
+ return "{} {} {}".format(lhs_code, op, rhs_code)
251
+
252
+ def _print_AugmentedAssignment(self, expr):
253
+ lhs_code = self._print(expr.lhs)
254
+ op = expr.op
255
+ rhs_code = self._print(expr.rhs)
256
+ return "{} {} {};".format(lhs_code, op, rhs_code)
257
+
258
+ def _print_For(self, expr):
259
+ target = self._print(expr.target)
260
+ if isinstance(expr.iterable, Range):
261
+ start, stop, step = expr.iterable.args
262
+ else:
263
+ raise NotImplementedError("Only iterable currently supported is Range")
264
+ body = self._print(expr.body)
265
+ return 'for({target} in seq(from={start}, to={stop}, by={step}){{\n{body}\n}}'.format(target=target, start=start,
266
+ stop=stop-1, step=step, body=body)
267
+
268
+
269
+ def indent_code(self, code):
270
+ """Accepts a string of code or a list of code lines"""
271
+
272
+ if isinstance(code, str):
273
+ code_lines = self.indent_code(code.splitlines(True))
274
+ return ''.join(code_lines)
275
+
276
+ tab = " "
277
+ inc_token = ('{', '(', '{\n', '(\n')
278
+ dec_token = ('}', ')')
279
+
280
+ code = [ line.lstrip(' \t') for line in code ]
281
+
282
+ increase = [ int(any(map(line.endswith, inc_token))) for line in code ]
283
+ decrease = [ int(any(map(line.startswith, dec_token)))
284
+ for line in code ]
285
+
286
+ pretty = []
287
+ level = 0
288
+ for n, line in enumerate(code):
289
+ if line in ('', '\n'):
290
+ pretty.append(line)
291
+ continue
292
+ level -= decrease[n]
293
+ pretty.append("%s%s" % (tab*level, line))
294
+ level += increase[n]
295
+ return pretty
296
+
297
+
298
+ def rcode(expr, assign_to=None, **settings):
299
+ """Converts an expr to a string of r code
300
+
301
+ Parameters
302
+ ==========
303
+
304
+ expr : Expr
305
+ A SymPy expression to be converted.
306
+ assign_to : optional
307
+ When given, the argument is used as the name of the variable to which
308
+ the expression is assigned. Can be a string, ``Symbol``,
309
+ ``MatrixSymbol``, or ``Indexed`` type. This is helpful in case of
310
+ line-wrapping, or for expressions that generate multi-line statements.
311
+ precision : integer, optional
312
+ The precision for numbers such as pi [default=15].
313
+ user_functions : dict, optional
314
+ A dictionary where the keys are string representations of either
315
+ ``FunctionClass`` or ``UndefinedFunction`` instances and the values
316
+ are their desired R string representations. Alternatively, the
317
+ dictionary value can be a list of tuples i.e. [(argument_test,
318
+ rfunction_string)] or [(argument_test, rfunction_formater)]. See below
319
+ for examples.
320
+ human : bool, optional
321
+ If True, the result is a single string that may contain some constant
322
+ declarations for the number symbols. If False, the same information is
323
+ returned in a tuple of (symbols_to_declare, not_supported_functions,
324
+ code_text). [default=True].
325
+ contract: bool, optional
326
+ If True, ``Indexed`` instances are assumed to obey tensor contraction
327
+ rules and the corresponding nested loops over indices are generated.
328
+ Setting contract=False will not generate loops, instead the user is
329
+ responsible to provide values for the indices in the code.
330
+ [default=True].
331
+
332
+ Examples
333
+ ========
334
+
335
+ >>> from sympy import rcode, symbols, Rational, sin, ceiling, Abs, Function
336
+ >>> x, tau = symbols("x, tau")
337
+ >>> rcode((2*tau)**Rational(7, 2))
338
+ '8*sqrt(2)*tau^(7.0/2.0)'
339
+ >>> rcode(sin(x), assign_to="s")
340
+ 's = sin(x);'
341
+
342
+ Simple custom printing can be defined for certain types by passing a
343
+ dictionary of {"type" : "function"} to the ``user_functions`` kwarg.
344
+ Alternatively, the dictionary value can be a list of tuples i.e.
345
+ [(argument_test, cfunction_string)].
346
+
347
+ >>> custom_functions = {
348
+ ... "ceiling": "CEIL",
349
+ ... "Abs": [(lambda x: not x.is_integer, "fabs"),
350
+ ... (lambda x: x.is_integer, "ABS")],
351
+ ... "func": "f"
352
+ ... }
353
+ >>> func = Function('func')
354
+ >>> rcode(func(Abs(x) + ceiling(x)), user_functions=custom_functions)
355
+ 'f(fabs(x) + CEIL(x))'
356
+
357
+ or if the R-function takes a subset of the original arguments:
358
+
359
+ >>> rcode(2**x + 3**x, user_functions={'Pow': [
360
+ ... (lambda b, e: b == 2, lambda b, e: 'exp2(%s)' % e),
361
+ ... (lambda b, e: b != 2, 'pow')]})
362
+ 'exp2(x) + pow(3, x)'
363
+
364
+ ``Piecewise`` expressions are converted into conditionals. If an
365
+ ``assign_to`` variable is provided an if statement is created, otherwise
366
+ the ternary operator is used. Note that if the ``Piecewise`` lacks a
367
+ default term, represented by ``(expr, True)`` then an error will be thrown.
368
+ This is to prevent generating an expression that may not evaluate to
369
+ anything.
370
+
371
+ >>> from sympy import Piecewise
372
+ >>> expr = Piecewise((x + 1, x > 0), (x, True))
373
+ >>> print(rcode(expr, assign_to=tau))
374
+ tau = ifelse(x > 0,x + 1,x);
375
+
376
+ Support for loops is provided through ``Indexed`` types. With
377
+ ``contract=True`` these expressions will be turned into loops, whereas
378
+ ``contract=False`` will just print the assignment expression that should be
379
+ looped over:
380
+
381
+ >>> from sympy import Eq, IndexedBase, Idx
382
+ >>> len_y = 5
383
+ >>> y = IndexedBase('y', shape=(len_y,))
384
+ >>> t = IndexedBase('t', shape=(len_y,))
385
+ >>> Dy = IndexedBase('Dy', shape=(len_y-1,))
386
+ >>> i = Idx('i', len_y-1)
387
+ >>> e=Eq(Dy[i], (y[i+1]-y[i])/(t[i+1]-t[i]))
388
+ >>> rcode(e.rhs, assign_to=e.lhs, contract=False)
389
+ 'Dy[i] = (y[i + 1] - y[i])/(t[i + 1] - t[i]);'
390
+
391
+ Matrices are also supported, but a ``MatrixSymbol`` of the same dimensions
392
+ must be provided to ``assign_to``. Note that any expression that can be
393
+ generated normally can also exist inside a Matrix:
394
+
395
+ >>> from sympy import Matrix, MatrixSymbol
396
+ >>> mat = Matrix([x**2, Piecewise((x + 1, x > 0), (x, True)), sin(x)])
397
+ >>> A = MatrixSymbol('A', 3, 1)
398
+ >>> print(rcode(mat, A))
399
+ A[0] = x^2;
400
+ A[1] = ifelse(x > 0,x + 1,x);
401
+ A[2] = sin(x);
402
+
403
+ """
404
+
405
+ return RCodePrinter(settings).doprint(expr, assign_to)
406
+
407
+
408
+ def print_rcode(expr, **settings):
409
+ """Prints R representation of the given expression."""
410
+ print(rcode(expr, **settings))
env-llmeval/lib/python3.10/site-packages/sympy/printing/rust.py ADDED
@@ -0,0 +1,625 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Rust code printer
3
+
4
+ The `RustCodePrinter` converts SymPy expressions into Rust expressions.
5
+
6
+ A complete code generator, which uses `rust_code` extensively, can be found
7
+ in `sympy.utilities.codegen`. The `codegen` module can be used to generate
8
+ complete source code files.
9
+
10
+ """
11
+
12
+ # Possible Improvement
13
+ #
14
+ # * make sure we follow Rust Style Guidelines_
15
+ # * make use of pattern matching
16
+ # * better support for reference
17
+ # * generate generic code and use trait to make sure they have specific methods
18
+ # * use crates_ to get more math support
19
+ # - num_
20
+ # + BigInt_, BigUint_
21
+ # + Complex_
22
+ # + Rational64_, Rational32_, BigRational_
23
+ #
24
+ # .. _crates: https://crates.io/
25
+ # .. _Guidelines: https://github.com/rust-lang/rust/tree/master/src/doc/style
26
+ # .. _num: http://rust-num.github.io/num/num/
27
+ # .. _BigInt: http://rust-num.github.io/num/num/bigint/struct.BigInt.html
28
+ # .. _BigUint: http://rust-num.github.io/num/num/bigint/struct.BigUint.html
29
+ # .. _Complex: http://rust-num.github.io/num/num/complex/struct.Complex.html
30
+ # .. _Rational32: http://rust-num.github.io/num/num/rational/type.Rational32.html
31
+ # .. _Rational64: http://rust-num.github.io/num/num/rational/type.Rational64.html
32
+ # .. _BigRational: http://rust-num.github.io/num/num/rational/type.BigRational.html
33
+
34
+ from __future__ import annotations
35
+ from typing import Any
36
+
37
+ from sympy.core import S, Rational, Float, Lambda
38
+ from sympy.core.numbers import equal_valued
39
+ from sympy.printing.codeprinter import CodePrinter
40
+
41
+ # Rust's methods for integer and float can be found at here :
42
+ #
43
+ # * `Rust - Primitive Type f64 <https://doc.rust-lang.org/std/primitive.f64.html>`_
44
+ # * `Rust - Primitive Type i64 <https://doc.rust-lang.org/std/primitive.i64.html>`_
45
+ #
46
+ # Function Style :
47
+ #
48
+ # 1. args[0].func(args[1:]), method with arguments
49
+ # 2. args[0].func(), method without arguments
50
+ # 3. args[1].func(), method without arguments (e.g. (e, x) => x.exp())
51
+ # 4. func(args), function with arguments
52
+
53
+ # dictionary mapping SymPy function to (argument_conditions, Rust_function).
54
+ # Used in RustCodePrinter._print_Function(self)
55
+
56
+ # f64 method in Rust
57
+ known_functions = {
58
+ # "": "is_nan",
59
+ # "": "is_infinite",
60
+ # "": "is_finite",
61
+ # "": "is_normal",
62
+ # "": "classify",
63
+ "floor": "floor",
64
+ "ceiling": "ceil",
65
+ # "": "round",
66
+ # "": "trunc",
67
+ # "": "fract",
68
+ "Abs": "abs",
69
+ "sign": "signum",
70
+ # "": "is_sign_positive",
71
+ # "": "is_sign_negative",
72
+ # "": "mul_add",
73
+ "Pow": [(lambda base, exp: equal_valued(exp, -1), "recip", 2), # 1.0/x
74
+ (lambda base, exp: equal_valued(exp, 0.5), "sqrt", 2), # x ** 0.5
75
+ (lambda base, exp: equal_valued(exp, -0.5), "sqrt().recip", 2), # 1/(x ** 0.5)
76
+ (lambda base, exp: exp == Rational(1, 3), "cbrt", 2), # x ** (1/3)
77
+ (lambda base, exp: equal_valued(base, 2), "exp2", 3), # 2 ** x
78
+ (lambda base, exp: exp.is_integer, "powi", 1), # x ** y, for i32
79
+ (lambda base, exp: not exp.is_integer, "powf", 1)], # x ** y, for f64
80
+ "exp": [(lambda exp: True, "exp", 2)], # e ** x
81
+ "log": "ln",
82
+ # "": "log", # number.log(base)
83
+ # "": "log2",
84
+ # "": "log10",
85
+ # "": "to_degrees",
86
+ # "": "to_radians",
87
+ "Max": "max",
88
+ "Min": "min",
89
+ # "": "hypot", # (x**2 + y**2) ** 0.5
90
+ "sin": "sin",
91
+ "cos": "cos",
92
+ "tan": "tan",
93
+ "asin": "asin",
94
+ "acos": "acos",
95
+ "atan": "atan",
96
+ "atan2": "atan2",
97
+ # "": "sin_cos",
98
+ # "": "exp_m1", # e ** x - 1
99
+ # "": "ln_1p", # ln(1 + x)
100
+ "sinh": "sinh",
101
+ "cosh": "cosh",
102
+ "tanh": "tanh",
103
+ "asinh": "asinh",
104
+ "acosh": "acosh",
105
+ "atanh": "atanh",
106
+ "sqrt": "sqrt", # To enable automatic rewrites
107
+ }
108
+
109
+ # i64 method in Rust
110
+ # known_functions_i64 = {
111
+ # "": "min_value",
112
+ # "": "max_value",
113
+ # "": "from_str_radix",
114
+ # "": "count_ones",
115
+ # "": "count_zeros",
116
+ # "": "leading_zeros",
117
+ # "": "trainling_zeros",
118
+ # "": "rotate_left",
119
+ # "": "rotate_right",
120
+ # "": "swap_bytes",
121
+ # "": "from_be",
122
+ # "": "from_le",
123
+ # "": "to_be", # to big endian
124
+ # "": "to_le", # to little endian
125
+ # "": "checked_add",
126
+ # "": "checked_sub",
127
+ # "": "checked_mul",
128
+ # "": "checked_div",
129
+ # "": "checked_rem",
130
+ # "": "checked_neg",
131
+ # "": "checked_shl",
132
+ # "": "checked_shr",
133
+ # "": "checked_abs",
134
+ # "": "saturating_add",
135
+ # "": "saturating_sub",
136
+ # "": "saturating_mul",
137
+ # "": "wrapping_add",
138
+ # "": "wrapping_sub",
139
+ # "": "wrapping_mul",
140
+ # "": "wrapping_div",
141
+ # "": "wrapping_rem",
142
+ # "": "wrapping_neg",
143
+ # "": "wrapping_shl",
144
+ # "": "wrapping_shr",
145
+ # "": "wrapping_abs",
146
+ # "": "overflowing_add",
147
+ # "": "overflowing_sub",
148
+ # "": "overflowing_mul",
149
+ # "": "overflowing_div",
150
+ # "": "overflowing_rem",
151
+ # "": "overflowing_neg",
152
+ # "": "overflowing_shl",
153
+ # "": "overflowing_shr",
154
+ # "": "overflowing_abs",
155
+ # "Pow": "pow",
156
+ # "Abs": "abs",
157
+ # "sign": "signum",
158
+ # "": "is_positive",
159
+ # "": "is_negnative",
160
+ # }
161
+
162
+ # These are the core reserved words in the Rust language. Taken from:
163
+ # http://doc.rust-lang.org/grammar.html#keywords
164
+
165
+ reserved_words = ['abstract',
166
+ 'alignof',
167
+ 'as',
168
+ 'become',
169
+ 'box',
170
+ 'break',
171
+ 'const',
172
+ 'continue',
173
+ 'crate',
174
+ 'do',
175
+ 'else',
176
+ 'enum',
177
+ 'extern',
178
+ 'false',
179
+ 'final',
180
+ 'fn',
181
+ 'for',
182
+ 'if',
183
+ 'impl',
184
+ 'in',
185
+ 'let',
186
+ 'loop',
187
+ 'macro',
188
+ 'match',
189
+ 'mod',
190
+ 'move',
191
+ 'mut',
192
+ 'offsetof',
193
+ 'override',
194
+ 'priv',
195
+ 'proc',
196
+ 'pub',
197
+ 'pure',
198
+ 'ref',
199
+ 'return',
200
+ 'Self',
201
+ 'self',
202
+ 'sizeof',
203
+ 'static',
204
+ 'struct',
205
+ 'super',
206
+ 'trait',
207
+ 'true',
208
+ 'type',
209
+ 'typeof',
210
+ 'unsafe',
211
+ 'unsized',
212
+ 'use',
213
+ 'virtual',
214
+ 'where',
215
+ 'while',
216
+ 'yield']
217
+
218
+
219
+ class RustCodePrinter(CodePrinter):
220
+ """A printer to convert SymPy expressions to strings of Rust code"""
221
+ printmethod = "_rust_code"
222
+ language = "Rust"
223
+
224
+ _default_settings: dict[str, Any] = {
225
+ 'order': None,
226
+ 'full_prec': 'auto',
227
+ 'precision': 17,
228
+ 'user_functions': {},
229
+ 'human': True,
230
+ 'contract': True,
231
+ 'dereference': set(),
232
+ 'error_on_reserved': False,
233
+ 'reserved_word_suffix': '_',
234
+ 'inline': False,
235
+ }
236
+
237
+ def __init__(self, settings={}):
238
+ CodePrinter.__init__(self, settings)
239
+ self.known_functions = dict(known_functions)
240
+ userfuncs = settings.get('user_functions', {})
241
+ self.known_functions.update(userfuncs)
242
+ self._dereference = set(settings.get('dereference', []))
243
+ self.reserved_words = set(reserved_words)
244
+
245
+ def _rate_index_position(self, p):
246
+ return p*5
247
+
248
+ def _get_statement(self, codestring):
249
+ return "%s;" % codestring
250
+
251
+ def _get_comment(self, text):
252
+ return "// %s" % text
253
+
254
+ def _declare_number_const(self, name, value):
255
+ return "const %s: f64 = %s;" % (name, value)
256
+
257
+ def _format_code(self, lines):
258
+ return self.indent_code(lines)
259
+
260
+ def _traverse_matrix_indices(self, mat):
261
+ rows, cols = mat.shape
262
+ return ((i, j) for i in range(rows) for j in range(cols))
263
+
264
+ def _get_loop_opening_ending(self, indices):
265
+ open_lines = []
266
+ close_lines = []
267
+ loopstart = "for %(var)s in %(start)s..%(end)s {"
268
+ for i in indices:
269
+ # Rust arrays start at 0 and end at dimension-1
270
+ open_lines.append(loopstart % {
271
+ 'var': self._print(i),
272
+ 'start': self._print(i.lower),
273
+ 'end': self._print(i.upper + 1)})
274
+ close_lines.append("}")
275
+ return open_lines, close_lines
276
+
277
+ def _print_caller_var(self, expr):
278
+ if len(expr.args) > 1:
279
+ # for something like `sin(x + y + z)`,
280
+ # make sure we can get '(x + y + z).sin()'
281
+ # instead of 'x + y + z.sin()'
282
+ return '(' + self._print(expr) + ')'
283
+ elif expr.is_number:
284
+ return self._print(expr, _type=True)
285
+ else:
286
+ return self._print(expr)
287
+
288
+ def _print_Function(self, expr):
289
+ """
290
+ basic function for printing `Function`
291
+
292
+ Function Style :
293
+
294
+ 1. args[0].func(args[1:]), method with arguments
295
+ 2. args[0].func(), method without arguments
296
+ 3. args[1].func(), method without arguments (e.g. (e, x) => x.exp())
297
+ 4. func(args), function with arguments
298
+ """
299
+
300
+ if expr.func.__name__ in self.known_functions:
301
+ cond_func = self.known_functions[expr.func.__name__]
302
+ func = None
303
+ style = 1
304
+ if isinstance(cond_func, str):
305
+ func = cond_func
306
+ else:
307
+ for cond, func, style in cond_func:
308
+ if cond(*expr.args):
309
+ break
310
+ if func is not None:
311
+ if style == 1:
312
+ ret = "%(var)s.%(method)s(%(args)s)" % {
313
+ 'var': self._print_caller_var(expr.args[0]),
314
+ 'method': func,
315
+ 'args': self.stringify(expr.args[1:], ", ") if len(expr.args) > 1 else ''
316
+ }
317
+ elif style == 2:
318
+ ret = "%(var)s.%(method)s()" % {
319
+ 'var': self._print_caller_var(expr.args[0]),
320
+ 'method': func,
321
+ }
322
+ elif style == 3:
323
+ ret = "%(var)s.%(method)s()" % {
324
+ 'var': self._print_caller_var(expr.args[1]),
325
+ 'method': func,
326
+ }
327
+ else:
328
+ ret = "%(func)s(%(args)s)" % {
329
+ 'func': func,
330
+ 'args': self.stringify(expr.args, ", "),
331
+ }
332
+ return ret
333
+ elif hasattr(expr, '_imp_') and isinstance(expr._imp_, Lambda):
334
+ # inlined function
335
+ return self._print(expr._imp_(*expr.args))
336
+ elif expr.func.__name__ in self._rewriteable_functions:
337
+ # Simple rewrite to supported function possible
338
+ target_f, required_fs = self._rewriteable_functions[expr.func.__name__]
339
+ if self._can_print(target_f) and all(self._can_print(f) for f in required_fs):
340
+ return self._print(expr.rewrite(target_f))
341
+ else:
342
+ return self._print_not_supported(expr)
343
+
344
+ def _print_Pow(self, expr):
345
+ if expr.base.is_integer and not expr.exp.is_integer:
346
+ expr = type(expr)(Float(expr.base), expr.exp)
347
+ return self._print(expr)
348
+ return self._print_Function(expr)
349
+
350
+ def _print_Float(self, expr, _type=False):
351
+ ret = super()._print_Float(expr)
352
+ if _type:
353
+ return ret + '_f64'
354
+ else:
355
+ return ret
356
+
357
+ def _print_Integer(self, expr, _type=False):
358
+ ret = super()._print_Integer(expr)
359
+ if _type:
360
+ return ret + '_i32'
361
+ else:
362
+ return ret
363
+
364
+ def _print_Rational(self, expr):
365
+ p, q = int(expr.p), int(expr.q)
366
+ return '%d_f64/%d.0' % (p, q)
367
+
368
+ def _print_Relational(self, expr):
369
+ lhs_code = self._print(expr.lhs)
370
+ rhs_code = self._print(expr.rhs)
371
+ op = expr.rel_op
372
+ return "{} {} {}".format(lhs_code, op, rhs_code)
373
+
374
+ def _print_Indexed(self, expr):
375
+ # calculate index for 1d array
376
+ dims = expr.shape
377
+ elem = S.Zero
378
+ offset = S.One
379
+ for i in reversed(range(expr.rank)):
380
+ elem += expr.indices[i]*offset
381
+ offset *= dims[i]
382
+ return "%s[%s]" % (self._print(expr.base.label), self._print(elem))
383
+
384
+ def _print_Idx(self, expr):
385
+ return expr.label.name
386
+
387
+ def _print_Dummy(self, expr):
388
+ return expr.name
389
+
390
+ def _print_Exp1(self, expr, _type=False):
391
+ return "E"
392
+
393
+ def _print_Pi(self, expr, _type=False):
394
+ return 'PI'
395
+
396
+ def _print_Infinity(self, expr, _type=False):
397
+ return 'INFINITY'
398
+
399
+ def _print_NegativeInfinity(self, expr, _type=False):
400
+ return 'NEG_INFINITY'
401
+
402
+ def _print_BooleanTrue(self, expr, _type=False):
403
+ return "true"
404
+
405
+ def _print_BooleanFalse(self, expr, _type=False):
406
+ return "false"
407
+
408
+ def _print_bool(self, expr, _type=False):
409
+ return str(expr).lower()
410
+
411
+ def _print_NaN(self, expr, _type=False):
412
+ return "NAN"
413
+
414
+ def _print_Piecewise(self, expr):
415
+ if expr.args[-1].cond != True:
416
+ # We need the last conditional to be a True, otherwise the resulting
417
+ # function may not return a result.
418
+ raise ValueError("All Piecewise expressions must contain an "
419
+ "(expr, True) statement to be used as a default "
420
+ "condition. Without one, the generated "
421
+ "expression may not evaluate to anything under "
422
+ "some condition.")
423
+ lines = []
424
+
425
+ for i, (e, c) in enumerate(expr.args):
426
+ if i == 0:
427
+ lines.append("if (%s) {" % self._print(c))
428
+ elif i == len(expr.args) - 1 and c == True:
429
+ lines[-1] += " else {"
430
+ else:
431
+ lines[-1] += " else if (%s) {" % self._print(c)
432
+ code0 = self._print(e)
433
+ lines.append(code0)
434
+ lines.append("}")
435
+
436
+ if self._settings['inline']:
437
+ return " ".join(lines)
438
+ else:
439
+ return "\n".join(lines)
440
+
441
+ def _print_ITE(self, expr):
442
+ from sympy.functions import Piecewise
443
+ return self._print(expr.rewrite(Piecewise, deep=False))
444
+
445
+ def _print_MatrixBase(self, A):
446
+ if A.cols == 1:
447
+ return "[%s]" % ", ".join(self._print(a) for a in A)
448
+ else:
449
+ raise ValueError("Full Matrix Support in Rust need Crates (https://crates.io/keywords/matrix).")
450
+
451
+ def _print_SparseRepMatrix(self, mat):
452
+ # do not allow sparse matrices to be made dense
453
+ return self._print_not_supported(mat)
454
+
455
+ def _print_MatrixElement(self, expr):
456
+ return "%s[%s]" % (expr.parent,
457
+ expr.j + expr.i*expr.parent.shape[1])
458
+
459
+ def _print_Symbol(self, expr):
460
+
461
+ name = super()._print_Symbol(expr)
462
+
463
+ if expr in self._dereference:
464
+ return '(*%s)' % name
465
+ else:
466
+ return name
467
+
468
+ def _print_Assignment(self, expr):
469
+ from sympy.tensor.indexed import IndexedBase
470
+ lhs = expr.lhs
471
+ rhs = expr.rhs
472
+ if self._settings["contract"] and (lhs.has(IndexedBase) or
473
+ rhs.has(IndexedBase)):
474
+ # Here we check if there is looping to be done, and if so
475
+ # print the required loops.
476
+ return self._doprint_loops(rhs, lhs)
477
+ else:
478
+ lhs_code = self._print(lhs)
479
+ rhs_code = self._print(rhs)
480
+ return self._get_statement("%s = %s" % (lhs_code, rhs_code))
481
+
482
+ def indent_code(self, code):
483
+ """Accepts a string of code or a list of code lines"""
484
+
485
+ if isinstance(code, str):
486
+ code_lines = self.indent_code(code.splitlines(True))
487
+ return ''.join(code_lines)
488
+
489
+ tab = " "
490
+ inc_token = ('{', '(', '{\n', '(\n')
491
+ dec_token = ('}', ')')
492
+
493
+ code = [ line.lstrip(' \t') for line in code ]
494
+
495
+ increase = [ int(any(map(line.endswith, inc_token))) for line in code ]
496
+ decrease = [ int(any(map(line.startswith, dec_token)))
497
+ for line in code ]
498
+
499
+ pretty = []
500
+ level = 0
501
+ for n, line in enumerate(code):
502
+ if line in ('', '\n'):
503
+ pretty.append(line)
504
+ continue
505
+ level -= decrease[n]
506
+ pretty.append("%s%s" % (tab*level, line))
507
+ level += increase[n]
508
+ return pretty
509
+
510
+
511
+ def rust_code(expr, assign_to=None, **settings):
512
+ """Converts an expr to a string of Rust code
513
+
514
+ Parameters
515
+ ==========
516
+
517
+ expr : Expr
518
+ A SymPy expression to be converted.
519
+ assign_to : optional
520
+ When given, the argument is used as the name of the variable to which
521
+ the expression is assigned. Can be a string, ``Symbol``,
522
+ ``MatrixSymbol``, or ``Indexed`` type. This is helpful in case of
523
+ line-wrapping, or for expressions that generate multi-line statements.
524
+ precision : integer, optional
525
+ The precision for numbers such as pi [default=15].
526
+ user_functions : dict, optional
527
+ A dictionary where the keys are string representations of either
528
+ ``FunctionClass`` or ``UndefinedFunction`` instances and the values
529
+ are their desired C string representations. Alternatively, the
530
+ dictionary value can be a list of tuples i.e. [(argument_test,
531
+ cfunction_string)]. See below for examples.
532
+ dereference : iterable, optional
533
+ An iterable of symbols that should be dereferenced in the printed code
534
+ expression. These would be values passed by address to the function.
535
+ For example, if ``dereference=[a]``, the resulting code would print
536
+ ``(*a)`` instead of ``a``.
537
+ human : bool, optional
538
+ If True, the result is a single string that may contain some constant
539
+ declarations for the number symbols. If False, the same information is
540
+ returned in a tuple of (symbols_to_declare, not_supported_functions,
541
+ code_text). [default=True].
542
+ contract: bool, optional
543
+ If True, ``Indexed`` instances are assumed to obey tensor contraction
544
+ rules and the corresponding nested loops over indices are generated.
545
+ Setting contract=False will not generate loops, instead the user is
546
+ responsible to provide values for the indices in the code.
547
+ [default=True].
548
+
549
+ Examples
550
+ ========
551
+
552
+ >>> from sympy import rust_code, symbols, Rational, sin, ceiling, Abs, Function
553
+ >>> x, tau = symbols("x, tau")
554
+ >>> rust_code((2*tau)**Rational(7, 2))
555
+ '8*1.4142135623731*tau.powf(7_f64/2.0)'
556
+ >>> rust_code(sin(x), assign_to="s")
557
+ 's = x.sin();'
558
+
559
+ Simple custom printing can be defined for certain types by passing a
560
+ dictionary of {"type" : "function"} to the ``user_functions`` kwarg.
561
+ Alternatively, the dictionary value can be a list of tuples i.e.
562
+ [(argument_test, cfunction_string)].
563
+
564
+ >>> custom_functions = {
565
+ ... "ceiling": "CEIL",
566
+ ... "Abs": [(lambda x: not x.is_integer, "fabs", 4),
567
+ ... (lambda x: x.is_integer, "ABS", 4)],
568
+ ... "func": "f"
569
+ ... }
570
+ >>> func = Function('func')
571
+ >>> rust_code(func(Abs(x) + ceiling(x)), user_functions=custom_functions)
572
+ '(fabs(x) + x.CEIL()).f()'
573
+
574
+ ``Piecewise`` expressions are converted into conditionals. If an
575
+ ``assign_to`` variable is provided an if statement is created, otherwise
576
+ the ternary operator is used. Note that if the ``Piecewise`` lacks a
577
+ default term, represented by ``(expr, True)`` then an error will be thrown.
578
+ This is to prevent generating an expression that may not evaluate to
579
+ anything.
580
+
581
+ >>> from sympy import Piecewise
582
+ >>> expr = Piecewise((x + 1, x > 0), (x, True))
583
+ >>> print(rust_code(expr, tau))
584
+ tau = if (x > 0) {
585
+ x + 1
586
+ } else {
587
+ x
588
+ };
589
+
590
+ Support for loops is provided through ``Indexed`` types. With
591
+ ``contract=True`` these expressions will be turned into loops, whereas
592
+ ``contract=False`` will just print the assignment expression that should be
593
+ looped over:
594
+
595
+ >>> from sympy import Eq, IndexedBase, Idx
596
+ >>> len_y = 5
597
+ >>> y = IndexedBase('y', shape=(len_y,))
598
+ >>> t = IndexedBase('t', shape=(len_y,))
599
+ >>> Dy = IndexedBase('Dy', shape=(len_y-1,))
600
+ >>> i = Idx('i', len_y-1)
601
+ >>> e=Eq(Dy[i], (y[i+1]-y[i])/(t[i+1]-t[i]))
602
+ >>> rust_code(e.rhs, assign_to=e.lhs, contract=False)
603
+ 'Dy[i] = (y[i + 1] - y[i])/(t[i + 1] - t[i]);'
604
+
605
+ Matrices are also supported, but a ``MatrixSymbol`` of the same dimensions
606
+ must be provided to ``assign_to``. Note that any expression that can be
607
+ generated normally can also exist inside a Matrix:
608
+
609
+ >>> from sympy import Matrix, MatrixSymbol
610
+ >>> mat = Matrix([x**2, Piecewise((x + 1, x > 0), (x, True)), sin(x)])
611
+ >>> A = MatrixSymbol('A', 3, 1)
612
+ >>> print(rust_code(mat, A))
613
+ A = [x.powi(2), if (x > 0) {
614
+ x + 1
615
+ } else {
616
+ x
617
+ }, x.sin()];
618
+ """
619
+
620
+ return RustCodePrinter(settings).doprint(expr, assign_to)
621
+
622
+
623
+ def print_rust_code(expr, **settings):
624
+ """Prints Rust representation of the given expression."""
625
+ print(rust_code(expr, **settings))
env-llmeval/lib/python3.10/site-packages/sympy/printing/smtlib.py ADDED
@@ -0,0 +1,526 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import typing
2
+
3
+ import sympy
4
+ from sympy.core import Add, Mul
5
+ from sympy.core import Symbol, Expr, Float, Rational, Integer, Basic
6
+ from sympy.core.function import UndefinedFunction, Function
7
+ from sympy.core.relational import Relational, Unequality, Equality, LessThan, GreaterThan, StrictLessThan, StrictGreaterThan
8
+ from sympy.functions.elementary.complexes import Abs
9
+ from sympy.functions.elementary.exponential import exp, log, Pow
10
+ from sympy.functions.elementary.hyperbolic import sinh, cosh, tanh
11
+ from sympy.functions.elementary.miscellaneous import Min, Max
12
+ from sympy.functions.elementary.piecewise import Piecewise
13
+ from sympy.functions.elementary.trigonometric import sin, cos, tan, asin, acos, atan, atan2
14
+ from sympy.logic.boolalg import And, Or, Xor, Implies, Boolean
15
+ from sympy.logic.boolalg import BooleanTrue, BooleanFalse, BooleanFunction, Not, ITE
16
+ from sympy.printing.printer import Printer
17
+ from sympy.sets import Interval
18
+
19
+
20
+ class SMTLibPrinter(Printer):
21
+ printmethod = "_smtlib"
22
+
23
+ # based on dReal, an automated reasoning tool for solving problems that can be encoded as first-order logic formulas over the real numbers.
24
+ # dReal's special strength is in handling problems that involve a wide range of nonlinear real functions.
25
+ _default_settings: dict = {
26
+ 'precision': None,
27
+ 'known_types': {
28
+ bool: 'Bool',
29
+ int: 'Int',
30
+ float: 'Real'
31
+ },
32
+ 'known_constants': {
33
+ # pi: 'MY_VARIABLE_PI_DECLARED_ELSEWHERE',
34
+ },
35
+ 'known_functions': {
36
+ Add: '+',
37
+ Mul: '*',
38
+
39
+ Equality: '=',
40
+ LessThan: '<=',
41
+ GreaterThan: '>=',
42
+ StrictLessThan: '<',
43
+ StrictGreaterThan: '>',
44
+
45
+ exp: 'exp',
46
+ log: 'log',
47
+ Abs: 'abs',
48
+ sin: 'sin',
49
+ cos: 'cos',
50
+ tan: 'tan',
51
+ asin: 'arcsin',
52
+ acos: 'arccos',
53
+ atan: 'arctan',
54
+ atan2: 'arctan2',
55
+ sinh: 'sinh',
56
+ cosh: 'cosh',
57
+ tanh: 'tanh',
58
+ Min: 'min',
59
+ Max: 'max',
60
+ Pow: 'pow',
61
+
62
+ And: 'and',
63
+ Or: 'or',
64
+ Xor: 'xor',
65
+ Not: 'not',
66
+ ITE: 'ite',
67
+ Implies: '=>',
68
+ }
69
+ }
70
+
71
+ symbol_table: dict
72
+
73
+ def __init__(self, settings: typing.Optional[dict] = None,
74
+ symbol_table=None):
75
+ settings = settings or {}
76
+ self.symbol_table = symbol_table or {}
77
+ Printer.__init__(self, settings)
78
+ self._precision = self._settings['precision']
79
+ self._known_types = dict(self._settings['known_types'])
80
+ self._known_constants = dict(self._settings['known_constants'])
81
+ self._known_functions = dict(self._settings['known_functions'])
82
+
83
+ for _ in self._known_types.values(): assert self._is_legal_name(_)
84
+ for _ in self._known_constants.values(): assert self._is_legal_name(_)
85
+ # for _ in self._known_functions.values(): assert self._is_legal_name(_) # +, *, <, >, etc.
86
+
87
+ def _is_legal_name(self, s: str):
88
+ if not s: return False
89
+ if s[0].isnumeric(): return False
90
+ return all(_.isalnum() or _ == '_' for _ in s)
91
+
92
+ def _s_expr(self, op: str, args: typing.Union[list, tuple]) -> str:
93
+ args_str = ' '.join(
94
+ a if isinstance(a, str)
95
+ else self._print(a)
96
+ for a in args
97
+ )
98
+ return f'({op} {args_str})'
99
+
100
+ def _print_Function(self, e):
101
+ if e in self._known_functions:
102
+ op = self._known_functions[e]
103
+ elif type(e) in self._known_functions:
104
+ op = self._known_functions[type(e)]
105
+ elif type(type(e)) == UndefinedFunction:
106
+ op = e.name
107
+ else:
108
+ op = self._known_functions[e] # throw KeyError
109
+
110
+ return self._s_expr(op, e.args)
111
+
112
+ def _print_Relational(self, e: Relational):
113
+ return self._print_Function(e)
114
+
115
+ def _print_BooleanFunction(self, e: BooleanFunction):
116
+ return self._print_Function(e)
117
+
118
+ def _print_Expr(self, e: Expr):
119
+ return self._print_Function(e)
120
+
121
+ def _print_Unequality(self, e: Unequality):
122
+ if type(e) in self._known_functions:
123
+ return self._print_Relational(e) # default
124
+ else:
125
+ eq_op = self._known_functions[Equality]
126
+ not_op = self._known_functions[Not]
127
+ return self._s_expr(not_op, [self._s_expr(eq_op, e.args)])
128
+
129
+ def _print_Piecewise(self, e: Piecewise):
130
+ def _print_Piecewise_recursive(args: typing.Union[list, tuple]):
131
+ e, c = args[0]
132
+ if len(args) == 1:
133
+ assert (c is True) or isinstance(c, BooleanTrue)
134
+ return self._print(e)
135
+ else:
136
+ ite = self._known_functions[ITE]
137
+ return self._s_expr(ite, [
138
+ c, e, _print_Piecewise_recursive(args[1:])
139
+ ])
140
+
141
+ return _print_Piecewise_recursive(e.args)
142
+
143
+ def _print_Interval(self, e: Interval):
144
+ if e.start.is_infinite and e.end.is_infinite:
145
+ return ''
146
+ elif e.start.is_infinite != e.end.is_infinite:
147
+ raise ValueError(f'One-sided intervals (`{e}`) are not supported in SMT.')
148
+ else:
149
+ return f'[{e.start}, {e.end}]'
150
+
151
+ # todo: Sympy does not support quantifiers yet as of 2022, but quantifiers can be handy in SMT.
152
+ # For now, users can extend this class and build in their own quantifier support.
153
+ # See `test_quantifier_extensions()` in test_smtlib.py for an example of how this might look.
154
+
155
+ # def _print_ForAll(self, e: ForAll):
156
+ # return self._s('forall', [
157
+ # self._s('', [
158
+ # self._s(sym.name, [self._type_name(sym), Interval(start, end)])
159
+ # for sym, start, end in e.limits
160
+ # ]),
161
+ # e.function
162
+ # ])
163
+
164
+ def _print_BooleanTrue(self, x: BooleanTrue):
165
+ return 'true'
166
+
167
+ def _print_BooleanFalse(self, x: BooleanFalse):
168
+ return 'false'
169
+
170
+ def _print_Float(self, x: Float):
171
+ f = x.evalf(self._precision) if self._precision else x.evalf()
172
+ return str(f).rstrip('0')
173
+
174
+ def _print_float(self, x: float):
175
+ return str(x)
176
+
177
+ def _print_Rational(self, x: Rational):
178
+ return self._s_expr('/', [x.p, x.q])
179
+
180
+ def _print_Integer(self, x: Integer):
181
+ assert x.q == 1
182
+ return str(x.p)
183
+
184
+ def _print_int(self, x: int):
185
+ return str(x)
186
+
187
+ def _print_Symbol(self, x: Symbol):
188
+ assert self._is_legal_name(x.name)
189
+ return x.name
190
+
191
+ def _print_NumberSymbol(self, x):
192
+ name = self._known_constants.get(x)
193
+ return name if name else self._print_Float(x)
194
+
195
+ def _print_UndefinedFunction(self, x):
196
+ assert self._is_legal_name(x.name)
197
+ return x.name
198
+
199
+ def _print_Exp1(self, x):
200
+ return (
201
+ self._print_Function(exp(1, evaluate=False))
202
+ if exp in self._known_functions else
203
+ self._print_NumberSymbol(x)
204
+ )
205
+
206
+ def emptyPrinter(self, expr):
207
+ raise NotImplementedError(f'Cannot convert `{repr(expr)}` of type `{type(expr)}` to SMT.')
208
+
209
+
210
+ def smtlib_code(
211
+ expr,
212
+ auto_assert=True, auto_declare=True,
213
+ precision=None,
214
+ symbol_table=None,
215
+ known_types=None, known_constants=None, known_functions=None,
216
+ prefix_expressions=None, suffix_expressions=None,
217
+ log_warn=None
218
+ ):
219
+ r"""Converts ``expr`` to a string of smtlib code.
220
+
221
+ Parameters
222
+ ==========
223
+
224
+ expr : Expr | List[Expr]
225
+ A SymPy expression or system to be converted.
226
+ auto_assert : bool, optional
227
+ If false, do not modify expr and produce only the S-Expression equivalent of expr.
228
+ If true, assume expr is a system and assert each boolean element.
229
+ auto_declare : bool, optional
230
+ If false, do not produce declarations for the symbols used in expr.
231
+ If true, prepend all necessary declarations for variables used in expr based on symbol_table.
232
+ precision : integer, optional
233
+ The ``evalf(..)`` precision for numbers such as pi.
234
+ symbol_table : dict, optional
235
+ A dictionary where keys are ``Symbol`` or ``Function`` instances and values are their Python type i.e. ``bool``, ``int``, ``float``, or ``Callable[...]``.
236
+ If incomplete, an attempt will be made to infer types from ``expr``.
237
+ known_types: dict, optional
238
+ A dictionary where keys are ``bool``, ``int``, ``float`` etc. and values are their corresponding SMT type names.
239
+ If not given, a partial listing compatible with several solvers will be used.
240
+ known_functions : dict, optional
241
+ A dictionary where keys are ``Function``, ``Relational``, ``BooleanFunction``, or ``Expr`` instances and values are their SMT string representations.
242
+ If not given, a partial listing optimized for dReal solver (but compatible with others) will be used.
243
+ known_constants: dict, optional
244
+ A dictionary where keys are ``NumberSymbol`` instances and values are their SMT variable names.
245
+ When using this feature, extra caution must be taken to avoid naming collisions between user symbols and listed constants.
246
+ If not given, constants will be expanded inline i.e. ``3.14159`` instead of ``MY_SMT_VARIABLE_FOR_PI``.
247
+ prefix_expressions: list, optional
248
+ A list of lists of ``str`` and/or expressions to convert into SMTLib and prefix to the output.
249
+ suffix_expressions: list, optional
250
+ A list of lists of ``str`` and/or expressions to convert into SMTLib and postfix to the output.
251
+ log_warn: lambda function, optional
252
+ A function to record all warnings during potentially risky operations.
253
+ Soundness is a core value in SMT solving, so it is good to log all assumptions made.
254
+
255
+ Examples
256
+ ========
257
+ >>> from sympy import smtlib_code, symbols, sin, Eq
258
+ >>> x = symbols('x')
259
+ >>> smtlib_code(sin(x).series(x).removeO(), log_warn=print)
260
+ Could not infer type of `x`. Defaulting to float.
261
+ Non-Boolean expression `x**5/120 - x**3/6 + x` will not be asserted. Converting to SMTLib verbatim.
262
+ '(declare-const x Real)\n(+ x (* (/ -1 6) (pow x 3)) (* (/ 1 120) (pow x 5)))'
263
+
264
+ >>> from sympy import Rational
265
+ >>> x, y, tau = symbols("x, y, tau")
266
+ >>> smtlib_code((2*tau)**Rational(7, 2), log_warn=print)
267
+ Could not infer type of `tau`. Defaulting to float.
268
+ Non-Boolean expression `8*sqrt(2)*tau**(7/2)` will not be asserted. Converting to SMTLib verbatim.
269
+ '(declare-const tau Real)\n(* 8 (pow 2 (/ 1 2)) (pow tau (/ 7 2)))'
270
+
271
+ ``Piecewise`` expressions are implemented with ``ite`` expressions by default.
272
+ Note that if the ``Piecewise`` lacks a default term, represented by
273
+ ``(expr, True)`` then an error will be thrown. This is to prevent
274
+ generating an expression that may not evaluate to anything.
275
+
276
+ >>> from sympy import Piecewise
277
+ >>> pw = Piecewise((x + 1, x > 0), (x, True))
278
+ >>> smtlib_code(Eq(pw, 3), symbol_table={x: float}, log_warn=print)
279
+ '(declare-const x Real)\n(assert (= (ite (> x 0) (+ 1 x) x) 3))'
280
+
281
+ Custom printing can be defined for certain types by passing a dictionary of
282
+ PythonType : "SMT Name" to the ``known_types``, ``known_constants``, and ``known_functions`` kwargs.
283
+
284
+ >>> from typing import Callable
285
+ >>> from sympy import Function, Add
286
+ >>> f = Function('f')
287
+ >>> g = Function('g')
288
+ >>> smt_builtin_funcs = { # functions our SMT solver will understand
289
+ ... f: "existing_smtlib_fcn",
290
+ ... Add: "sum",
291
+ ... }
292
+ >>> user_def_funcs = { # functions defined by the user must have their types specified explicitly
293
+ ... g: Callable[[int], float],
294
+ ... }
295
+ >>> smtlib_code(f(x) + g(x), symbol_table=user_def_funcs, known_functions=smt_builtin_funcs, log_warn=print)
296
+ Non-Boolean expression `f(x) + g(x)` will not be asserted. Converting to SMTLib verbatim.
297
+ '(declare-const x Int)\n(declare-fun g (Int) Real)\n(sum (existing_smtlib_fcn x) (g x))'
298
+ """
299
+ log_warn = log_warn or (lambda _: None)
300
+
301
+ if not isinstance(expr, list): expr = [expr]
302
+ expr = [
303
+ sympy.sympify(_, strict=True, evaluate=False, convert_xor=False)
304
+ for _ in expr
305
+ ]
306
+
307
+ if not symbol_table: symbol_table = {}
308
+ symbol_table = _auto_infer_smtlib_types(
309
+ *expr, symbol_table=symbol_table
310
+ )
311
+ # See [FALLBACK RULES]
312
+ # Need SMTLibPrinter to populate known_functions and known_constants first.
313
+
314
+ settings = {}
315
+ if precision: settings['precision'] = precision
316
+ del precision
317
+
318
+ if known_types: settings['known_types'] = known_types
319
+ del known_types
320
+
321
+ if known_functions: settings['known_functions'] = known_functions
322
+ del known_functions
323
+
324
+ if known_constants: settings['known_constants'] = known_constants
325
+ del known_constants
326
+
327
+ if not prefix_expressions: prefix_expressions = []
328
+ if not suffix_expressions: suffix_expressions = []
329
+
330
+ p = SMTLibPrinter(settings, symbol_table)
331
+ del symbol_table
332
+
333
+ # [FALLBACK RULES]
334
+ for e in expr:
335
+ for sym in e.atoms(Symbol, Function):
336
+ if (
337
+ sym.is_Symbol and
338
+ sym not in p._known_constants and
339
+ sym not in p.symbol_table
340
+ ):
341
+ log_warn(f"Could not infer type of `{sym}`. Defaulting to float.")
342
+ p.symbol_table[sym] = float
343
+ if (
344
+ sym.is_Function and
345
+ type(sym) not in p._known_functions and
346
+ type(sym) not in p.symbol_table and
347
+ not sym.is_Piecewise
348
+ ): raise TypeError(
349
+ f"Unknown type of undefined function `{sym}`. "
350
+ f"Must be mapped to ``str`` in known_functions or mapped to ``Callable[..]`` in symbol_table."
351
+ )
352
+
353
+ declarations = []
354
+ if auto_declare:
355
+ constants = {sym.name: sym for e in expr for sym in e.free_symbols
356
+ if sym not in p._known_constants}
357
+ functions = {fnc.name: fnc for e in expr for fnc in e.atoms(Function)
358
+ if type(fnc) not in p._known_functions and not fnc.is_Piecewise}
359
+ declarations = \
360
+ [
361
+ _auto_declare_smtlib(sym, p, log_warn)
362
+ for sym in constants.values()
363
+ ] + [
364
+ _auto_declare_smtlib(fnc, p, log_warn)
365
+ for fnc in functions.values()
366
+ ]
367
+ declarations = [decl for decl in declarations if decl]
368
+
369
+ if auto_assert:
370
+ expr = [_auto_assert_smtlib(e, p, log_warn) for e in expr]
371
+
372
+ # return SMTLibPrinter().doprint(expr)
373
+ return '\n'.join([
374
+ # ';; PREFIX EXPRESSIONS',
375
+ *[
376
+ e if isinstance(e, str) else p.doprint(e)
377
+ for e in prefix_expressions
378
+ ],
379
+
380
+ # ';; DECLARATIONS',
381
+ *sorted(e for e in declarations),
382
+
383
+ # ';; EXPRESSIONS',
384
+ *[
385
+ e if isinstance(e, str) else p.doprint(e)
386
+ for e in expr
387
+ ],
388
+
389
+ # ';; SUFFIX EXPRESSIONS',
390
+ *[
391
+ e if isinstance(e, str) else p.doprint(e)
392
+ for e in suffix_expressions
393
+ ],
394
+ ])
395
+
396
+
397
+ def _auto_declare_smtlib(sym: typing.Union[Symbol, Function], p: SMTLibPrinter, log_warn: typing.Callable[[str], None]):
398
+ if sym.is_Symbol:
399
+ type_signature = p.symbol_table[sym]
400
+ assert isinstance(type_signature, type)
401
+ type_signature = p._known_types[type_signature]
402
+ return p._s_expr('declare-const', [sym, type_signature])
403
+
404
+ elif sym.is_Function:
405
+ type_signature = p.symbol_table[type(sym)]
406
+ assert callable(type_signature)
407
+ type_signature = [p._known_types[_] for _ in type_signature.__args__]
408
+ assert len(type_signature) > 0
409
+ params_signature = f"({' '.join(type_signature[:-1])})"
410
+ return_signature = type_signature[-1]
411
+ return p._s_expr('declare-fun', [type(sym), params_signature, return_signature])
412
+
413
+ else:
414
+ log_warn(f"Non-Symbol/Function `{sym}` will not be declared.")
415
+ return None
416
+
417
+
418
+ def _auto_assert_smtlib(e: Expr, p: SMTLibPrinter, log_warn: typing.Callable[[str], None]):
419
+ if isinstance(e, Boolean) or (
420
+ e in p.symbol_table and p.symbol_table[e] == bool
421
+ ) or (
422
+ e.is_Function and
423
+ type(e) in p.symbol_table and
424
+ p.symbol_table[type(e)].__args__[-1] == bool
425
+ ):
426
+ return p._s_expr('assert', [e])
427
+ else:
428
+ log_warn(f"Non-Boolean expression `{e}` will not be asserted. Converting to SMTLib verbatim.")
429
+ return e
430
+
431
+
432
+ def _auto_infer_smtlib_types(
433
+ *exprs: Basic,
434
+ symbol_table: typing.Optional[dict] = None
435
+ ) -> dict:
436
+ # [TYPE INFERENCE RULES]
437
+ # X is alone in an expr => X is bool
438
+ # X in BooleanFunction.args => X is bool
439
+ # X matches to a bool param of a symbol_table function => X is bool
440
+ # X matches to an int param of a symbol_table function => X is int
441
+ # X.is_integer => X is int
442
+ # X == Y, where X is T => Y is T
443
+
444
+ # [FALLBACK RULES]
445
+ # see _auto_declare_smtlib(..)
446
+ # X is not bool and X is not int and X is Symbol => X is float
447
+ # else (e.g. X is Function) => error. must be specified explicitly.
448
+
449
+ _symbols = dict(symbol_table) if symbol_table else {}
450
+
451
+ def safe_update(syms: set, inf):
452
+ for s in syms:
453
+ assert s.is_Symbol
454
+ if (old_type := _symbols.setdefault(s, inf)) != inf:
455
+ raise TypeError(f"Could not infer type of `{s}`. Apparently both `{old_type}` and `{inf}`?")
456
+
457
+ # EXPLICIT TYPES
458
+ safe_update({
459
+ e
460
+ for e in exprs
461
+ if e.is_Symbol
462
+ }, bool)
463
+
464
+ safe_update({
465
+ symbol
466
+ for e in exprs
467
+ for boolfunc in e.atoms(BooleanFunction)
468
+ for symbol in boolfunc.args
469
+ if symbol.is_Symbol
470
+ }, bool)
471
+
472
+ safe_update({
473
+ symbol
474
+ for e in exprs
475
+ for boolfunc in e.atoms(Function)
476
+ if type(boolfunc) in _symbols
477
+ for symbol, param in zip(boolfunc.args, _symbols[type(boolfunc)].__args__)
478
+ if symbol.is_Symbol and param == bool
479
+ }, bool)
480
+
481
+ safe_update({
482
+ symbol
483
+ for e in exprs
484
+ for intfunc in e.atoms(Function)
485
+ if type(intfunc) in _symbols
486
+ for symbol, param in zip(intfunc.args, _symbols[type(intfunc)].__args__)
487
+ if symbol.is_Symbol and param == int
488
+ }, int)
489
+
490
+ safe_update({
491
+ symbol
492
+ for e in exprs
493
+ for symbol in e.atoms(Symbol)
494
+ if symbol.is_integer
495
+ }, int)
496
+
497
+ safe_update({
498
+ symbol
499
+ for e in exprs
500
+ for symbol in e.atoms(Symbol)
501
+ if symbol.is_real and not symbol.is_integer
502
+ }, float)
503
+
504
+ # EQUALITY RELATION RULE
505
+ rels = [rel for expr in exprs for rel in expr.atoms(Equality)]
506
+ rels = [
507
+ (rel.lhs, rel.rhs) for rel in rels if rel.lhs.is_Symbol
508
+ ] + [
509
+ (rel.rhs, rel.lhs) for rel in rels if rel.rhs.is_Symbol
510
+ ]
511
+ for infer, reltd in rels:
512
+ inference = (
513
+ _symbols[infer] if infer in _symbols else
514
+ _symbols[reltd] if reltd in _symbols else
515
+
516
+ _symbols[type(reltd)].__args__[-1]
517
+ if reltd.is_Function and type(reltd) in _symbols else
518
+
519
+ bool if reltd.is_Boolean else
520
+ int if reltd.is_integer or reltd.is_Integer else
521
+ float if reltd.is_real else
522
+ None
523
+ )
524
+ if inference: safe_update({infer}, inference)
525
+
526
+ return _symbols
env-llmeval/lib/python3.10/site-packages/sympy/printing/tableform.py ADDED
@@ -0,0 +1,366 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.containers import Tuple
2
+ from sympy.core.singleton import S
3
+ from sympy.core.symbol import Symbol
4
+ from sympy.core.sympify import SympifyError
5
+
6
+ from types import FunctionType
7
+
8
+
9
+ class TableForm:
10
+ r"""
11
+ Create a nice table representation of data.
12
+
13
+ Examples
14
+ ========
15
+
16
+ >>> from sympy import TableForm
17
+ >>> t = TableForm([[5, 7], [4, 2], [10, 3]])
18
+ >>> print(t)
19
+ 5 7
20
+ 4 2
21
+ 10 3
22
+
23
+ You can use the SymPy's printing system to produce tables in any
24
+ format (ascii, latex, html, ...).
25
+
26
+ >>> print(t.as_latex())
27
+ \begin{tabular}{l l}
28
+ $5$ & $7$ \\
29
+ $4$ & $2$ \\
30
+ $10$ & $3$ \\
31
+ \end{tabular}
32
+
33
+ """
34
+
35
+ def __init__(self, data, **kwarg):
36
+ """
37
+ Creates a TableForm.
38
+
39
+ Parameters:
40
+
41
+ data ...
42
+ 2D data to be put into the table; data can be
43
+ given as a Matrix
44
+
45
+ headings ...
46
+ gives the labels for rows and columns:
47
+
48
+ Can be a single argument that applies to both
49
+ dimensions:
50
+
51
+ - None ... no labels
52
+ - "automatic" ... labels are 1, 2, 3, ...
53
+
54
+ Can be a list of labels for rows and columns:
55
+ The labels for each dimension can be given
56
+ as None, "automatic", or [l1, l2, ...] e.g.
57
+ ["automatic", None] will number the rows
58
+
59
+ [default: None]
60
+
61
+ alignments ...
62
+ alignment of the columns with:
63
+
64
+ - "left" or "<"
65
+ - "center" or "^"
66
+ - "right" or ">"
67
+
68
+ When given as a single value, the value is used for
69
+ all columns. The row headings (if given) will be
70
+ right justified unless an explicit alignment is
71
+ given for it and all other columns.
72
+
73
+ [default: "left"]
74
+
75
+ formats ...
76
+ a list of format strings or functions that accept
77
+ 3 arguments (entry, row number, col number) and
78
+ return a string for the table entry. (If a function
79
+ returns None then the _print method will be used.)
80
+
81
+ wipe_zeros ...
82
+ Do not show zeros in the table.
83
+
84
+ [default: True]
85
+
86
+ pad ...
87
+ the string to use to indicate a missing value (e.g.
88
+ elements that are None or those that are missing
89
+ from the end of a row (i.e. any row that is shorter
90
+ than the rest is assumed to have missing values).
91
+ When None, nothing will be shown for values that
92
+ are missing from the end of a row; values that are
93
+ None, however, will be shown.
94
+
95
+ [default: None]
96
+
97
+ Examples
98
+ ========
99
+
100
+ >>> from sympy import TableForm, Symbol
101
+ >>> TableForm([[5, 7], [4, 2], [10, 3]])
102
+ 5 7
103
+ 4 2
104
+ 10 3
105
+ >>> TableForm([list('.'*i) for i in range(1, 4)], headings='automatic')
106
+ | 1 2 3
107
+ ---------
108
+ 1 | .
109
+ 2 | . .
110
+ 3 | . . .
111
+ >>> TableForm([[Symbol('.'*(j if not i%2 else 1)) for i in range(3)]
112
+ ... for j in range(4)], alignments='rcl')
113
+ .
114
+ . . .
115
+ .. . ..
116
+ ... . ...
117
+ """
118
+ from sympy.matrices.dense import Matrix
119
+
120
+ # We only support 2D data. Check the consistency:
121
+ if isinstance(data, Matrix):
122
+ data = data.tolist()
123
+ _h = len(data)
124
+
125
+ # fill out any short lines
126
+ pad = kwarg.get('pad', None)
127
+ ok_None = False
128
+ if pad is None:
129
+ pad = " "
130
+ ok_None = True
131
+ pad = Symbol(pad)
132
+ _w = max(len(line) for line in data)
133
+ for i, line in enumerate(data):
134
+ if len(line) != _w:
135
+ line.extend([pad]*(_w - len(line)))
136
+ for j, lj in enumerate(line):
137
+ if lj is None:
138
+ if not ok_None:
139
+ lj = pad
140
+ else:
141
+ try:
142
+ lj = S(lj)
143
+ except SympifyError:
144
+ lj = Symbol(str(lj))
145
+ line[j] = lj
146
+ data[i] = line
147
+ _lines = Tuple(*[Tuple(*d) for d in data])
148
+
149
+ headings = kwarg.get("headings", [None, None])
150
+ if headings == "automatic":
151
+ _headings = [range(1, _h + 1), range(1, _w + 1)]
152
+ else:
153
+ h1, h2 = headings
154
+ if h1 == "automatic":
155
+ h1 = range(1, _h + 1)
156
+ if h2 == "automatic":
157
+ h2 = range(1, _w + 1)
158
+ _headings = [h1, h2]
159
+
160
+ allow = ('l', 'r', 'c')
161
+ alignments = kwarg.get("alignments", "l")
162
+
163
+ def _std_align(a):
164
+ a = a.strip().lower()
165
+ if len(a) > 1:
166
+ return {'left': 'l', 'right': 'r', 'center': 'c'}.get(a, a)
167
+ else:
168
+ return {'<': 'l', '>': 'r', '^': 'c'}.get(a, a)
169
+ std_align = _std_align(alignments)
170
+ if std_align in allow:
171
+ _alignments = [std_align]*_w
172
+ else:
173
+ _alignments = []
174
+ for a in alignments:
175
+ std_align = _std_align(a)
176
+ _alignments.append(std_align)
177
+ if std_align not in ('l', 'r', 'c'):
178
+ raise ValueError('alignment "%s" unrecognized' %
179
+ alignments)
180
+ if _headings[0] and len(_alignments) == _w + 1:
181
+ _head_align = _alignments[0]
182
+ _alignments = _alignments[1:]
183
+ else:
184
+ _head_align = 'r'
185
+ if len(_alignments) != _w:
186
+ raise ValueError(
187
+ 'wrong number of alignments: expected %s but got %s' %
188
+ (_w, len(_alignments)))
189
+
190
+ _column_formats = kwarg.get("formats", [None]*_w)
191
+
192
+ _wipe_zeros = kwarg.get("wipe_zeros", True)
193
+
194
+ self._w = _w
195
+ self._h = _h
196
+ self._lines = _lines
197
+ self._headings = _headings
198
+ self._head_align = _head_align
199
+ self._alignments = _alignments
200
+ self._column_formats = _column_formats
201
+ self._wipe_zeros = _wipe_zeros
202
+
203
+ def __repr__(self):
204
+ from .str import sstr
205
+ return sstr(self, order=None)
206
+
207
+ def __str__(self):
208
+ from .str import sstr
209
+ return sstr(self, order=None)
210
+
211
+ def as_matrix(self):
212
+ """Returns the data of the table in Matrix form.
213
+
214
+ Examples
215
+ ========
216
+
217
+ >>> from sympy import TableForm
218
+ >>> t = TableForm([[5, 7], [4, 2], [10, 3]], headings='automatic')
219
+ >>> t
220
+ | 1 2
221
+ --------
222
+ 1 | 5 7
223
+ 2 | 4 2
224
+ 3 | 10 3
225
+ >>> t.as_matrix()
226
+ Matrix([
227
+ [ 5, 7],
228
+ [ 4, 2],
229
+ [10, 3]])
230
+ """
231
+ from sympy.matrices.dense import Matrix
232
+ return Matrix(self._lines)
233
+
234
+ def as_str(self):
235
+ # XXX obsolete ?
236
+ return str(self)
237
+
238
+ def as_latex(self):
239
+ from .latex import latex
240
+ return latex(self)
241
+
242
+ def _sympystr(self, p):
243
+ """
244
+ Returns the string representation of 'self'.
245
+
246
+ Examples
247
+ ========
248
+
249
+ >>> from sympy import TableForm
250
+ >>> t = TableForm([[5, 7], [4, 2], [10, 3]])
251
+ >>> s = t.as_str()
252
+
253
+ """
254
+ column_widths = [0] * self._w
255
+ lines = []
256
+ for line in self._lines:
257
+ new_line = []
258
+ for i in range(self._w):
259
+ # Format the item somehow if needed:
260
+ s = str(line[i])
261
+ if self._wipe_zeros and (s == "0"):
262
+ s = " "
263
+ w = len(s)
264
+ if w > column_widths[i]:
265
+ column_widths[i] = w
266
+ new_line.append(s)
267
+ lines.append(new_line)
268
+
269
+ # Check heading:
270
+ if self._headings[0]:
271
+ self._headings[0] = [str(x) for x in self._headings[0]]
272
+ _head_width = max([len(x) for x in self._headings[0]])
273
+
274
+ if self._headings[1]:
275
+ new_line = []
276
+ for i in range(self._w):
277
+ # Format the item somehow if needed:
278
+ s = str(self._headings[1][i])
279
+ w = len(s)
280
+ if w > column_widths[i]:
281
+ column_widths[i] = w
282
+ new_line.append(s)
283
+ self._headings[1] = new_line
284
+
285
+ format_str = []
286
+
287
+ def _align(align, w):
288
+ return '%%%s%ss' % (
289
+ ("-" if align == "l" else ""),
290
+ str(w))
291
+ format_str = [_align(align, w) for align, w in
292
+ zip(self._alignments, column_widths)]
293
+ if self._headings[0]:
294
+ format_str.insert(0, _align(self._head_align, _head_width))
295
+ format_str.insert(1, '|')
296
+ format_str = ' '.join(format_str) + '\n'
297
+
298
+ s = []
299
+ if self._headings[1]:
300
+ d = self._headings[1]
301
+ if self._headings[0]:
302
+ d = [""] + d
303
+ first_line = format_str % tuple(d)
304
+ s.append(first_line)
305
+ s.append("-" * (len(first_line) - 1) + "\n")
306
+ for i, line in enumerate(lines):
307
+ d = [l if self._alignments[j] != 'c' else
308
+ l.center(column_widths[j]) for j, l in enumerate(line)]
309
+ if self._headings[0]:
310
+ l = self._headings[0][i]
311
+ l = (l if self._head_align != 'c' else
312
+ l.center(_head_width))
313
+ d = [l] + d
314
+ s.append(format_str % tuple(d))
315
+ return ''.join(s)[:-1] # don't include trailing newline
316
+
317
+ def _latex(self, printer):
318
+ """
319
+ Returns the string representation of 'self'.
320
+ """
321
+ # Check heading:
322
+ if self._headings[1]:
323
+ new_line = []
324
+ for i in range(self._w):
325
+ # Format the item somehow if needed:
326
+ new_line.append(str(self._headings[1][i]))
327
+ self._headings[1] = new_line
328
+
329
+ alignments = []
330
+ if self._headings[0]:
331
+ self._headings[0] = [str(x) for x in self._headings[0]]
332
+ alignments = [self._head_align]
333
+ alignments.extend(self._alignments)
334
+
335
+ s = r"\begin{tabular}{" + " ".join(alignments) + "}\n"
336
+
337
+ if self._headings[1]:
338
+ d = self._headings[1]
339
+ if self._headings[0]:
340
+ d = [""] + d
341
+ first_line = " & ".join(d) + r" \\" + "\n"
342
+ s += first_line
343
+ s += r"\hline" + "\n"
344
+ for i, line in enumerate(self._lines):
345
+ d = []
346
+ for j, x in enumerate(line):
347
+ if self._wipe_zeros and (x in (0, "0")):
348
+ d.append(" ")
349
+ continue
350
+ f = self._column_formats[j]
351
+ if f:
352
+ if isinstance(f, FunctionType):
353
+ v = f(x, i, j)
354
+ if v is None:
355
+ v = printer._print(x)
356
+ else:
357
+ v = f % x
358
+ d.append(v)
359
+ else:
360
+ v = printer._print(x)
361
+ d.append("$%s$" % v)
362
+ if self._headings[0]:
363
+ d = [self._headings[0][i]] + d
364
+ s += " & ".join(d) + r" \\" + "\n"
365
+ s += r"\end{tabular}"
366
+ return s
env-llmeval/lib/python3.10/site-packages/sympy/printing/tensorflow.py ADDED
@@ -0,0 +1,216 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.external.importtools import version_tuple
2
+ from collections.abc import Iterable
3
+
4
+ from sympy.core.mul import Mul
5
+ from sympy.core.singleton import S
6
+ from sympy.codegen.cfunctions import Sqrt
7
+ from sympy.external import import_module
8
+ from sympy.printing.precedence import PRECEDENCE
9
+ from sympy.printing.pycode import AbstractPythonCodePrinter, ArrayPrinter
10
+ import sympy
11
+
12
+ tensorflow = import_module('tensorflow')
13
+
14
+ class TensorflowPrinter(ArrayPrinter, AbstractPythonCodePrinter):
15
+ """
16
+ Tensorflow printer which handles vectorized piecewise functions,
17
+ logical operators, max/min, and relational operators.
18
+ """
19
+ printmethod = "_tensorflowcode"
20
+
21
+ mapping = {
22
+ sympy.Abs: "tensorflow.math.abs",
23
+ sympy.sign: "tensorflow.math.sign",
24
+
25
+ # XXX May raise error for ints.
26
+ sympy.ceiling: "tensorflow.math.ceil",
27
+ sympy.floor: "tensorflow.math.floor",
28
+ sympy.log: "tensorflow.math.log",
29
+ sympy.exp: "tensorflow.math.exp",
30
+ Sqrt: "tensorflow.math.sqrt",
31
+ sympy.cos: "tensorflow.math.cos",
32
+ sympy.acos: "tensorflow.math.acos",
33
+ sympy.sin: "tensorflow.math.sin",
34
+ sympy.asin: "tensorflow.math.asin",
35
+ sympy.tan: "tensorflow.math.tan",
36
+ sympy.atan: "tensorflow.math.atan",
37
+ sympy.atan2: "tensorflow.math.atan2",
38
+ # XXX Also may give NaN for complex results.
39
+ sympy.cosh: "tensorflow.math.cosh",
40
+ sympy.acosh: "tensorflow.math.acosh",
41
+ sympy.sinh: "tensorflow.math.sinh",
42
+ sympy.asinh: "tensorflow.math.asinh",
43
+ sympy.tanh: "tensorflow.math.tanh",
44
+ sympy.atanh: "tensorflow.math.atanh",
45
+
46
+ sympy.re: "tensorflow.math.real",
47
+ sympy.im: "tensorflow.math.imag",
48
+ sympy.arg: "tensorflow.math.angle",
49
+
50
+ # XXX May raise error for ints and complexes
51
+ sympy.erf: "tensorflow.math.erf",
52
+ sympy.loggamma: "tensorflow.math.lgamma",
53
+
54
+ sympy.Eq: "tensorflow.math.equal",
55
+ sympy.Ne: "tensorflow.math.not_equal",
56
+ sympy.StrictGreaterThan: "tensorflow.math.greater",
57
+ sympy.StrictLessThan: "tensorflow.math.less",
58
+ sympy.LessThan: "tensorflow.math.less_equal",
59
+ sympy.GreaterThan: "tensorflow.math.greater_equal",
60
+
61
+ sympy.And: "tensorflow.math.logical_and",
62
+ sympy.Or: "tensorflow.math.logical_or",
63
+ sympy.Not: "tensorflow.math.logical_not",
64
+ sympy.Max: "tensorflow.math.maximum",
65
+ sympy.Min: "tensorflow.math.minimum",
66
+
67
+ # Matrices
68
+ sympy.MatAdd: "tensorflow.math.add",
69
+ sympy.HadamardProduct: "tensorflow.math.multiply",
70
+ sympy.Trace: "tensorflow.linalg.trace",
71
+
72
+ # XXX May raise error for integer matrices.
73
+ sympy.Determinant : "tensorflow.linalg.det",
74
+ }
75
+
76
+ _default_settings = dict(
77
+ AbstractPythonCodePrinter._default_settings,
78
+ tensorflow_version=None
79
+ )
80
+
81
+ def __init__(self, settings=None):
82
+ super().__init__(settings)
83
+
84
+ version = self._settings['tensorflow_version']
85
+ if version is None and tensorflow:
86
+ version = tensorflow.__version__
87
+ self.tensorflow_version = version
88
+
89
+ def _print_Function(self, expr):
90
+ op = self.mapping.get(type(expr), None)
91
+ if op is None:
92
+ return super()._print_Basic(expr)
93
+ children = [self._print(arg) for arg in expr.args]
94
+ if len(children) == 1:
95
+ return "%s(%s)" % (
96
+ self._module_format(op),
97
+ children[0]
98
+ )
99
+ else:
100
+ return self._expand_fold_binary_op(op, children)
101
+
102
+ _print_Expr = _print_Function
103
+ _print_Application = _print_Function
104
+ _print_MatrixExpr = _print_Function
105
+ # TODO: a better class structure would avoid this mess:
106
+ _print_Relational = _print_Function
107
+ _print_Not = _print_Function
108
+ _print_And = _print_Function
109
+ _print_Or = _print_Function
110
+ _print_HadamardProduct = _print_Function
111
+ _print_Trace = _print_Function
112
+ _print_Determinant = _print_Function
113
+
114
+ def _print_Inverse(self, expr):
115
+ op = self._module_format('tensorflow.linalg.inv')
116
+ return "{}({})".format(op, self._print(expr.arg))
117
+
118
+ def _print_Transpose(self, expr):
119
+ version = self.tensorflow_version
120
+ if version and version_tuple(version) < version_tuple('1.14'):
121
+ op = self._module_format('tensorflow.matrix_transpose')
122
+ else:
123
+ op = self._module_format('tensorflow.linalg.matrix_transpose')
124
+ return "{}({})".format(op, self._print(expr.arg))
125
+
126
+ def _print_Derivative(self, expr):
127
+ variables = expr.variables
128
+ if any(isinstance(i, Iterable) for i in variables):
129
+ raise NotImplementedError("derivation by multiple variables is not supported")
130
+ def unfold(expr, args):
131
+ if not args:
132
+ return self._print(expr)
133
+ return "%s(%s, %s)[0]" % (
134
+ self._module_format("tensorflow.gradients"),
135
+ unfold(expr, args[:-1]),
136
+ self._print(args[-1]),
137
+ )
138
+ return unfold(expr.expr, variables)
139
+
140
+ def _print_Piecewise(self, expr):
141
+ version = self.tensorflow_version
142
+ if version and version_tuple(version) < version_tuple('1.0'):
143
+ tensorflow_piecewise = "tensorflow.select"
144
+ else:
145
+ tensorflow_piecewise = "tensorflow.where"
146
+
147
+ from sympy.functions.elementary.piecewise import Piecewise
148
+ e, cond = expr.args[0].args
149
+ if len(expr.args) == 1:
150
+ return '{}({}, {}, {})'.format(
151
+ self._module_format(tensorflow_piecewise),
152
+ self._print(cond),
153
+ self._print(e),
154
+ 0)
155
+
156
+ return '{}({}, {}, {})'.format(
157
+ self._module_format(tensorflow_piecewise),
158
+ self._print(cond),
159
+ self._print(e),
160
+ self._print(Piecewise(*expr.args[1:])))
161
+
162
+ def _print_Pow(self, expr):
163
+ # XXX May raise error for
164
+ # int**float or int**complex or float**complex
165
+ base, exp = expr.args
166
+ if expr.exp == S.Half:
167
+ return "{}({})".format(
168
+ self._module_format("tensorflow.math.sqrt"), self._print(base))
169
+ return "{}({}, {})".format(
170
+ self._module_format("tensorflow.math.pow"),
171
+ self._print(base), self._print(exp))
172
+
173
+ def _print_MatrixBase(self, expr):
174
+ tensorflow_f = "tensorflow.Variable" if expr.free_symbols else "tensorflow.constant"
175
+ data = "["+", ".join(["["+", ".join([self._print(j) for j in i])+"]" for i in expr.tolist()])+"]"
176
+ return "%s(%s)" % (
177
+ self._module_format(tensorflow_f),
178
+ data,
179
+ )
180
+
181
+ def _print_MatMul(self, expr):
182
+ from sympy.matrices.expressions import MatrixExpr
183
+ mat_args = [arg for arg in expr.args if isinstance(arg, MatrixExpr)]
184
+ args = [arg for arg in expr.args if arg not in mat_args]
185
+ if args:
186
+ return "%s*%s" % (
187
+ self.parenthesize(Mul.fromiter(args), PRECEDENCE["Mul"]),
188
+ self._expand_fold_binary_op(
189
+ "tensorflow.linalg.matmul", mat_args)
190
+ )
191
+ else:
192
+ return self._expand_fold_binary_op(
193
+ "tensorflow.linalg.matmul", mat_args)
194
+
195
+ def _print_MatPow(self, expr):
196
+ return self._expand_fold_binary_op(
197
+ "tensorflow.linalg.matmul", [expr.base]*expr.exp)
198
+
199
+ def _print_CodeBlock(self, expr):
200
+ # TODO: is this necessary?
201
+ ret = []
202
+ for subexpr in expr.args:
203
+ ret.append(self._print(subexpr))
204
+ return "\n".join(ret)
205
+
206
+ _module = "tensorflow"
207
+ _einsum = "linalg.einsum"
208
+ _add = "math.add"
209
+ _transpose = "transpose"
210
+ _ones = "ones"
211
+ _zeros = "zeros"
212
+
213
+
214
+ def tensorflow_code(expr, **settings):
215
+ printer = TensorflowPrinter(settings)
216
+ return printer.doprint(expr)
env-llmeval/lib/python3.10/site-packages/sympy/utilities/__pycache__/autowrap.cpython-310.pyc ADDED
Binary file (36.7 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/utilities/__pycache__/decorator.cpython-310.pyc ADDED
Binary file (11.6 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/utilities/__pycache__/lambdify.cpython-310.pyc ADDED
Binary file (48.3 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/utilities/__pycache__/magic.cpython-310.pyc ADDED
Binary file (551 Bytes). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/utilities/__pycache__/misc.cpython-310.pyc ADDED
Binary file (15.5 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/utilities/__pycache__/pytest.cpython-310.pyc ADDED
Binary file (607 Bytes). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/utilities/__pycache__/runtests.cpython-310.pyc ADDED
Binary file (619 Bytes). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/utilities/_compilation/__init__.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ This sub-module is private, i.e. external code should not depend on it.
2
+
3
+ These functions are used by tests run as part of continuous integration.
4
+ Once the implementation is mature (it should support the major
5
+ platforms: Windows, OS X & Linux) it may become official API which
6
+ may be relied upon by downstream libraries. Until then API may break
7
+ without prior notice.
8
+
9
+ TODO:
10
+ - (optionally) clean up after tempfile.mkdtemp()
11
+ - cross-platform testing
12
+ - caching of compiler choice and intermediate files
13
+
14
+ """
15
+
16
+ from .compilation import compile_link_import_strings, compile_run_strings
17
+ from .availability import has_fortran, has_c, has_cxx
18
+
19
+ __all__ = [
20
+ 'compile_link_import_strings', 'compile_run_strings',
21
+ 'has_fortran', 'has_c', 'has_cxx',
22
+ ]
env-llmeval/lib/python3.10/site-packages/sympy/utilities/_compilation/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (937 Bytes). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/utilities/_compilation/__pycache__/availability.cpython-310.pyc ADDED
Binary file (1.51 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/utilities/_compilation/__pycache__/compilation.cpython-310.pyc ADDED
Binary file (16.6 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/utilities/_compilation/__pycache__/runners.cpython-310.pyc ADDED
Binary file (7.42 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/utilities/_compilation/__pycache__/util.cpython-310.pyc ADDED
Binary file (7.5 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/utilities/_compilation/availability.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from .compilation import compile_run_strings
3
+ from .util import CompilerNotFoundError
4
+
5
+ def has_fortran():
6
+ if not hasattr(has_fortran, 'result'):
7
+ try:
8
+ (stdout, stderr), info = compile_run_strings(
9
+ [('main.f90', (
10
+ 'program foo\n'
11
+ 'print *, "hello world"\n'
12
+ 'end program'
13
+ ))], clean=True
14
+ )
15
+ except CompilerNotFoundError:
16
+ has_fortran.result = False
17
+ if os.environ.get('SYMPY_STRICT_COMPILER_CHECKS', '0') == '1':
18
+ raise
19
+ else:
20
+ if info['exit_status'] != os.EX_OK or 'hello world' not in stdout:
21
+ if os.environ.get('SYMPY_STRICT_COMPILER_CHECKS', '0') == '1':
22
+ raise ValueError("Failed to compile test program:\n%s\n%s\n" % (stdout, stderr))
23
+ has_fortran.result = False
24
+ else:
25
+ has_fortran.result = True
26
+ return has_fortran.result
27
+
28
+
29
+ def has_c():
30
+ if not hasattr(has_c, 'result'):
31
+ try:
32
+ (stdout, stderr), info = compile_run_strings(
33
+ [('main.c', (
34
+ '#include <stdio.h>\n'
35
+ 'int main(){\n'
36
+ 'printf("hello world\\n");\n'
37
+ 'return 0;\n'
38
+ '}'
39
+ ))], clean=True
40
+ )
41
+ except CompilerNotFoundError:
42
+ has_c.result = False
43
+ if os.environ.get('SYMPY_STRICT_COMPILER_CHECKS', '0') == '1':
44
+ raise
45
+ else:
46
+ if info['exit_status'] != os.EX_OK or 'hello world' not in stdout:
47
+ if os.environ.get('SYMPY_STRICT_COMPILER_CHECKS', '0') == '1':
48
+ raise ValueError("Failed to compile test program:\n%s\n%s\n" % (stdout, stderr))
49
+ has_c.result = False
50
+ else:
51
+ has_c.result = True
52
+ return has_c.result
53
+
54
+
55
+ def has_cxx():
56
+ if not hasattr(has_cxx, 'result'):
57
+ try:
58
+ (stdout, stderr), info = compile_run_strings(
59
+ [('main.cxx', (
60
+ '#include <iostream>\n'
61
+ 'int main(){\n'
62
+ 'std::cout << "hello world" << std::endl;\n'
63
+ '}'
64
+ ))], clean=True
65
+ )
66
+ except CompilerNotFoundError:
67
+ has_cxx.result = False
68
+ if os.environ.get('SYMPY_STRICT_COMPILER_CHECKS', '0') == '1':
69
+ raise
70
+ else:
71
+ if info['exit_status'] != os.EX_OK or 'hello world' not in stdout:
72
+ if os.environ.get('SYMPY_STRICT_COMPILER_CHECKS', '0') == '1':
73
+ raise ValueError("Failed to compile test program:\n%s\n%s\n" % (stdout, stderr))
74
+ has_cxx.result = False
75
+ else:
76
+ has_cxx.result = True
77
+ return has_cxx.result
env-llmeval/lib/python3.10/site-packages/sympy/utilities/_compilation/compilation.py ADDED
@@ -0,0 +1,648 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import glob
2
+ import os
3
+ import shutil
4
+ import subprocess
5
+ import sys
6
+ import tempfile
7
+ import warnings
8
+ from sysconfig import get_config_var, get_config_vars, get_path
9
+
10
+ from .runners import (
11
+ CCompilerRunner,
12
+ CppCompilerRunner,
13
+ FortranCompilerRunner
14
+ )
15
+ from .util import (
16
+ get_abspath, make_dirs, copy, Glob, ArbitraryDepthGlob,
17
+ glob_at_depth, import_module_from_file, pyx_is_cplus,
18
+ sha256_of_string, sha256_of_file, CompileError
19
+ )
20
+
21
+ if os.name == 'posix':
22
+ objext = '.o'
23
+ elif os.name == 'nt':
24
+ objext = '.obj'
25
+ else:
26
+ warnings.warn("Unknown os.name: {}".format(os.name))
27
+ objext = '.o'
28
+
29
+
30
+ def compile_sources(files, Runner=None, destdir=None, cwd=None, keep_dir_struct=False,
31
+ per_file_kwargs=None, **kwargs):
32
+ """ Compile source code files to object files.
33
+
34
+ Parameters
35
+ ==========
36
+
37
+ files : iterable of str
38
+ Paths to source files, if ``cwd`` is given, the paths are taken as relative.
39
+ Runner: CompilerRunner subclass (optional)
40
+ Could be e.g. ``FortranCompilerRunner``. Will be inferred from filename
41
+ extensions if missing.
42
+ destdir: str
43
+ Output directory, if cwd is given, the path is taken as relative.
44
+ cwd: str
45
+ Working directory. Specify to have compiler run in other directory.
46
+ also used as root of relative paths.
47
+ keep_dir_struct: bool
48
+ Reproduce directory structure in `destdir`. default: ``False``
49
+ per_file_kwargs: dict
50
+ Dict mapping instances in ``files`` to keyword arguments.
51
+ \\*\\*kwargs: dict
52
+ Default keyword arguments to pass to ``Runner``.
53
+
54
+ """
55
+ _per_file_kwargs = {}
56
+
57
+ if per_file_kwargs is not None:
58
+ for k, v in per_file_kwargs.items():
59
+ if isinstance(k, Glob):
60
+ for path in glob.glob(k.pathname):
61
+ _per_file_kwargs[path] = v
62
+ elif isinstance(k, ArbitraryDepthGlob):
63
+ for path in glob_at_depth(k.filename, cwd):
64
+ _per_file_kwargs[path] = v
65
+ else:
66
+ _per_file_kwargs[k] = v
67
+
68
+ # Set up destination directory
69
+ destdir = destdir or '.'
70
+ if not os.path.isdir(destdir):
71
+ if os.path.exists(destdir):
72
+ raise OSError("{} is not a directory".format(destdir))
73
+ else:
74
+ make_dirs(destdir)
75
+ if cwd is None:
76
+ cwd = '.'
77
+ for f in files:
78
+ copy(f, destdir, only_update=True, dest_is_dir=True)
79
+
80
+ # Compile files and return list of paths to the objects
81
+ dstpaths = []
82
+ for f in files:
83
+ if keep_dir_struct:
84
+ name, ext = os.path.splitext(f)
85
+ else:
86
+ name, ext = os.path.splitext(os.path.basename(f))
87
+ file_kwargs = kwargs.copy()
88
+ file_kwargs.update(_per_file_kwargs.get(f, {}))
89
+ dstpaths.append(src2obj(f, Runner, cwd=cwd, **file_kwargs))
90
+ return dstpaths
91
+
92
+
93
+ def get_mixed_fort_c_linker(vendor=None, cplus=False, cwd=None):
94
+ vendor = vendor or os.environ.get('SYMPY_COMPILER_VENDOR', 'gnu')
95
+
96
+ if vendor.lower() == 'intel':
97
+ if cplus:
98
+ return (FortranCompilerRunner,
99
+ {'flags': ['-nofor_main', '-cxxlib']}, vendor)
100
+ else:
101
+ return (FortranCompilerRunner,
102
+ {'flags': ['-nofor_main']}, vendor)
103
+ elif vendor.lower() == 'gnu' or 'llvm':
104
+ if cplus:
105
+ return (CppCompilerRunner,
106
+ {'lib_options': ['fortran']}, vendor)
107
+ else:
108
+ return (FortranCompilerRunner,
109
+ {}, vendor)
110
+ else:
111
+ raise ValueError("No vendor found.")
112
+
113
+
114
+ def link(obj_files, out_file=None, shared=False, Runner=None,
115
+ cwd=None, cplus=False, fort=False, **kwargs):
116
+ """ Link object files.
117
+
118
+ Parameters
119
+ ==========
120
+
121
+ obj_files: iterable of str
122
+ Paths to object files.
123
+ out_file: str (optional)
124
+ Path to executable/shared library, if ``None`` it will be
125
+ deduced from the last item in obj_files.
126
+ shared: bool
127
+ Generate a shared library?
128
+ Runner: CompilerRunner subclass (optional)
129
+ If not given the ``cplus`` and ``fort`` flags will be inspected
130
+ (fallback is the C compiler).
131
+ cwd: str
132
+ Path to the root of relative paths and working directory for compiler.
133
+ cplus: bool
134
+ C++ objects? default: ``False``.
135
+ fort: bool
136
+ Fortran objects? default: ``False``.
137
+ \\*\\*kwargs: dict
138
+ Keyword arguments passed to ``Runner``.
139
+
140
+ Returns
141
+ =======
142
+
143
+ The absolute path to the generated shared object / executable.
144
+
145
+ """
146
+ if out_file is None:
147
+ out_file, ext = os.path.splitext(os.path.basename(obj_files[-1]))
148
+ if shared:
149
+ out_file += get_config_var('EXT_SUFFIX')
150
+
151
+ if not Runner:
152
+ if fort:
153
+ Runner, extra_kwargs, vendor = \
154
+ get_mixed_fort_c_linker(
155
+ vendor=kwargs.get('vendor', None),
156
+ cplus=cplus,
157
+ cwd=cwd,
158
+ )
159
+ for k, v in extra_kwargs.items():
160
+ if k in kwargs:
161
+ kwargs[k].expand(v)
162
+ else:
163
+ kwargs[k] = v
164
+ else:
165
+ if cplus:
166
+ Runner = CppCompilerRunner
167
+ else:
168
+ Runner = CCompilerRunner
169
+
170
+ flags = kwargs.pop('flags', [])
171
+ if shared:
172
+ if '-shared' not in flags:
173
+ flags.append('-shared')
174
+ run_linker = kwargs.pop('run_linker', True)
175
+ if not run_linker:
176
+ raise ValueError("run_linker was set to False (nonsensical).")
177
+
178
+ out_file = get_abspath(out_file, cwd=cwd)
179
+ runner = Runner(obj_files, out_file, flags, cwd=cwd, **kwargs)
180
+ runner.run()
181
+ return out_file
182
+
183
+
184
+ def link_py_so(obj_files, so_file=None, cwd=None, libraries=None,
185
+ cplus=False, fort=False, **kwargs):
186
+ """ Link Python extension module (shared object) for importing
187
+
188
+ Parameters
189
+ ==========
190
+
191
+ obj_files: iterable of str
192
+ Paths to object files to be linked.
193
+ so_file: str
194
+ Name (path) of shared object file to create. If not specified it will
195
+ have the basname of the last object file in `obj_files` but with the
196
+ extension '.so' (Unix).
197
+ cwd: path string
198
+ Root of relative paths and working directory of linker.
199
+ libraries: iterable of strings
200
+ Libraries to link against, e.g. ['m'].
201
+ cplus: bool
202
+ Any C++ objects? default: ``False``.
203
+ fort: bool
204
+ Any Fortran objects? default: ``False``.
205
+ kwargs**: dict
206
+ Keyword arguments passed to ``link(...)``.
207
+
208
+ Returns
209
+ =======
210
+
211
+ Absolute path to the generate shared object.
212
+ """
213
+ libraries = libraries or []
214
+
215
+ include_dirs = kwargs.pop('include_dirs', [])
216
+ library_dirs = kwargs.pop('library_dirs', [])
217
+
218
+ # Add Python include and library directories
219
+ # PY_LDFLAGS does not available on all python implementations
220
+ # e.g. when with pypy, so it's LDFLAGS we need to use
221
+ if sys.platform == "win32":
222
+ warnings.warn("Windows not yet supported.")
223
+ elif sys.platform == 'darwin':
224
+ cfgDict = get_config_vars()
225
+ kwargs['linkline'] = kwargs.get('linkline', []) + [cfgDict['LDFLAGS']]
226
+ library_dirs += [cfgDict['LIBDIR']]
227
+
228
+ # In macOS, linker needs to compile frameworks
229
+ # e.g. "-framework CoreFoundation"
230
+ is_framework = False
231
+ for opt in cfgDict['LIBS'].split():
232
+ if is_framework:
233
+ kwargs['linkline'] = kwargs.get('linkline', []) + ['-framework', opt]
234
+ is_framework = False
235
+ elif opt.startswith('-l'):
236
+ libraries.append(opt[2:])
237
+ elif opt.startswith('-framework'):
238
+ is_framework = True
239
+ # The python library is not included in LIBS
240
+ libfile = cfgDict['LIBRARY']
241
+ libname = ".".join(libfile.split('.')[:-1])[3:]
242
+ libraries.append(libname)
243
+
244
+ elif sys.platform[:3] == 'aix':
245
+ # Don't use the default code below
246
+ pass
247
+ else:
248
+ if get_config_var('Py_ENABLE_SHARED'):
249
+ cfgDict = get_config_vars()
250
+ kwargs['linkline'] = kwargs.get('linkline', []) + [cfgDict['LDFLAGS']]
251
+ library_dirs += [cfgDict['LIBDIR']]
252
+ for opt in cfgDict['BLDLIBRARY'].split():
253
+ if opt.startswith('-l'):
254
+ libraries += [opt[2:]]
255
+ else:
256
+ pass
257
+
258
+ flags = kwargs.pop('flags', [])
259
+ needed_flags = ('-pthread',)
260
+ for flag in needed_flags:
261
+ if flag not in flags:
262
+ flags.append(flag)
263
+
264
+ return link(obj_files, shared=True, flags=flags, cwd=cwd,
265
+ cplus=cplus, fort=fort, include_dirs=include_dirs,
266
+ libraries=libraries, library_dirs=library_dirs, **kwargs)
267
+
268
+
269
+ def simple_cythonize(src, destdir=None, cwd=None, **cy_kwargs):
270
+ """ Generates a C file from a Cython source file.
271
+
272
+ Parameters
273
+ ==========
274
+
275
+ src: str
276
+ Path to Cython source.
277
+ destdir: str (optional)
278
+ Path to output directory (default: '.').
279
+ cwd: path string (optional)
280
+ Root of relative paths (default: '.').
281
+ **cy_kwargs:
282
+ Second argument passed to cy_compile. Generates a .cpp file if ``cplus=True`` in ``cy_kwargs``,
283
+ else a .c file.
284
+ """
285
+ from Cython.Compiler.Main import (
286
+ default_options, CompilationOptions
287
+ )
288
+ from Cython.Compiler.Main import compile as cy_compile
289
+
290
+ assert src.lower().endswith('.pyx') or src.lower().endswith('.py')
291
+ cwd = cwd or '.'
292
+ destdir = destdir or '.'
293
+
294
+ ext = '.cpp' if cy_kwargs.get('cplus', False) else '.c'
295
+ c_name = os.path.splitext(os.path.basename(src))[0] + ext
296
+
297
+ dstfile = os.path.join(destdir, c_name)
298
+
299
+ if cwd:
300
+ ori_dir = os.getcwd()
301
+ else:
302
+ ori_dir = '.'
303
+ os.chdir(cwd)
304
+ try:
305
+ cy_options = CompilationOptions(default_options)
306
+ cy_options.__dict__.update(cy_kwargs)
307
+ # Set language_level if not set by cy_kwargs
308
+ # as not setting it is deprecated
309
+ if 'language_level' not in cy_kwargs:
310
+ cy_options.__dict__['language_level'] = 3
311
+ cy_result = cy_compile([src], cy_options)
312
+ if cy_result.num_errors > 0:
313
+ raise ValueError("Cython compilation failed.")
314
+
315
+ # Move generated C file to destination
316
+ # In macOS, the generated C file is in the same directory as the source
317
+ # but the /var is a symlink to /private/var, so we need to use realpath
318
+ if os.path.realpath(os.path.dirname(src)) != os.path.realpath(destdir):
319
+ if os.path.exists(dstfile):
320
+ os.unlink(dstfile)
321
+ shutil.move(os.path.join(os.path.dirname(src), c_name), destdir)
322
+ finally:
323
+ os.chdir(ori_dir)
324
+ return dstfile
325
+
326
+
327
+ extension_mapping = {
328
+ '.c': (CCompilerRunner, None),
329
+ '.cpp': (CppCompilerRunner, None),
330
+ '.cxx': (CppCompilerRunner, None),
331
+ '.f': (FortranCompilerRunner, None),
332
+ '.for': (FortranCompilerRunner, None),
333
+ '.ftn': (FortranCompilerRunner, None),
334
+ '.f90': (FortranCompilerRunner, None), # ifort only knows about .f90
335
+ '.f95': (FortranCompilerRunner, 'f95'),
336
+ '.f03': (FortranCompilerRunner, 'f2003'),
337
+ '.f08': (FortranCompilerRunner, 'f2008'),
338
+ }
339
+
340
+
341
+ def src2obj(srcpath, Runner=None, objpath=None, cwd=None, inc_py=False, **kwargs):
342
+ """ Compiles a source code file to an object file.
343
+
344
+ Files ending with '.pyx' assumed to be cython files and
345
+ are dispatched to pyx2obj.
346
+
347
+ Parameters
348
+ ==========
349
+
350
+ srcpath: str
351
+ Path to source file.
352
+ Runner: CompilerRunner subclass (optional)
353
+ If ``None``: deduced from extension of srcpath.
354
+ objpath : str (optional)
355
+ Path to generated object. If ``None``: deduced from ``srcpath``.
356
+ cwd: str (optional)
357
+ Working directory and root of relative paths. If ``None``: current dir.
358
+ inc_py: bool
359
+ Add Python include path to kwarg "include_dirs". Default: False
360
+ \\*\\*kwargs: dict
361
+ keyword arguments passed to Runner or pyx2obj
362
+
363
+ """
364
+ name, ext = os.path.splitext(os.path.basename(srcpath))
365
+ if objpath is None:
366
+ if os.path.isabs(srcpath):
367
+ objpath = '.'
368
+ else:
369
+ objpath = os.path.dirname(srcpath)
370
+ objpath = objpath or '.' # avoid objpath == ''
371
+
372
+ if os.path.isdir(objpath):
373
+ objpath = os.path.join(objpath, name + objext)
374
+
375
+ include_dirs = kwargs.pop('include_dirs', [])
376
+ if inc_py:
377
+ py_inc_dir = get_path('include')
378
+ if py_inc_dir not in include_dirs:
379
+ include_dirs.append(py_inc_dir)
380
+
381
+ if ext.lower() == '.pyx':
382
+ return pyx2obj(srcpath, objpath=objpath, include_dirs=include_dirs, cwd=cwd,
383
+ **kwargs)
384
+
385
+ if Runner is None:
386
+ Runner, std = extension_mapping[ext.lower()]
387
+ if 'std' not in kwargs:
388
+ kwargs['std'] = std
389
+
390
+ flags = kwargs.pop('flags', [])
391
+ needed_flags = ('-fPIC',)
392
+ for flag in needed_flags:
393
+ if flag not in flags:
394
+ flags.append(flag)
395
+
396
+ # src2obj implies not running the linker...
397
+ run_linker = kwargs.pop('run_linker', False)
398
+ if run_linker:
399
+ raise CompileError("src2obj called with run_linker=True")
400
+
401
+ runner = Runner([srcpath], objpath, include_dirs=include_dirs,
402
+ run_linker=run_linker, cwd=cwd, flags=flags, **kwargs)
403
+ runner.run()
404
+ return objpath
405
+
406
+
407
+ def pyx2obj(pyxpath, objpath=None, destdir=None, cwd=None,
408
+ include_dirs=None, cy_kwargs=None, cplus=None, **kwargs):
409
+ """
410
+ Convenience function
411
+
412
+ If cwd is specified, pyxpath and dst are taken to be relative
413
+ If only_update is set to `True` the modification time is checked
414
+ and compilation is only run if the source is newer than the
415
+ destination
416
+
417
+ Parameters
418
+ ==========
419
+
420
+ pyxpath: str
421
+ Path to Cython source file.
422
+ objpath: str (optional)
423
+ Path to object file to generate.
424
+ destdir: str (optional)
425
+ Directory to put generated C file. When ``None``: directory of ``objpath``.
426
+ cwd: str (optional)
427
+ Working directory and root of relative paths.
428
+ include_dirs: iterable of path strings (optional)
429
+ Passed onto src2obj and via cy_kwargs['include_path']
430
+ to simple_cythonize.
431
+ cy_kwargs: dict (optional)
432
+ Keyword arguments passed onto `simple_cythonize`
433
+ cplus: bool (optional)
434
+ Indicate whether C++ is used. default: auto-detect using ``.util.pyx_is_cplus``.
435
+ compile_kwargs: dict
436
+ keyword arguments passed onto src2obj
437
+
438
+ Returns
439
+ =======
440
+
441
+ Absolute path of generated object file.
442
+
443
+ """
444
+ assert pyxpath.endswith('.pyx')
445
+ cwd = cwd or '.'
446
+ objpath = objpath or '.'
447
+ destdir = destdir or os.path.dirname(objpath)
448
+
449
+ abs_objpath = get_abspath(objpath, cwd=cwd)
450
+
451
+ if os.path.isdir(abs_objpath):
452
+ pyx_fname = os.path.basename(pyxpath)
453
+ name, ext = os.path.splitext(pyx_fname)
454
+ objpath = os.path.join(objpath, name + objext)
455
+
456
+ cy_kwargs = cy_kwargs or {}
457
+ cy_kwargs['output_dir'] = cwd
458
+ if cplus is None:
459
+ cplus = pyx_is_cplus(pyxpath)
460
+ cy_kwargs['cplus'] = cplus
461
+
462
+ interm_c_file = simple_cythonize(pyxpath, destdir=destdir, cwd=cwd, **cy_kwargs)
463
+
464
+ include_dirs = include_dirs or []
465
+ flags = kwargs.pop('flags', [])
466
+ needed_flags = ('-fwrapv', '-pthread', '-fPIC')
467
+ for flag in needed_flags:
468
+ if flag not in flags:
469
+ flags.append(flag)
470
+
471
+ options = kwargs.pop('options', [])
472
+
473
+ if kwargs.pop('strict_aliasing', False):
474
+ raise CompileError("Cython requires strict aliasing to be disabled.")
475
+
476
+ # Let's be explicit about standard
477
+ if cplus:
478
+ std = kwargs.pop('std', 'c++98')
479
+ else:
480
+ std = kwargs.pop('std', 'c99')
481
+
482
+ return src2obj(interm_c_file, objpath=objpath, cwd=cwd,
483
+ include_dirs=include_dirs, flags=flags, std=std,
484
+ options=options, inc_py=True, strict_aliasing=False,
485
+ **kwargs)
486
+
487
+
488
+ def _any_X(srcs, cls):
489
+ for src in srcs:
490
+ name, ext = os.path.splitext(src)
491
+ key = ext.lower()
492
+ if key in extension_mapping:
493
+ if extension_mapping[key][0] == cls:
494
+ return True
495
+ return False
496
+
497
+
498
+ def any_fortran_src(srcs):
499
+ return _any_X(srcs, FortranCompilerRunner)
500
+
501
+
502
+ def any_cplus_src(srcs):
503
+ return _any_X(srcs, CppCompilerRunner)
504
+
505
+
506
+ def compile_link_import_py_ext(sources, extname=None, build_dir='.', compile_kwargs=None,
507
+ link_kwargs=None):
508
+ """ Compiles sources to a shared object (Python extension) and imports it
509
+
510
+ Sources in ``sources`` which is imported. If shared object is newer than the sources, they
511
+ are not recompiled but instead it is imported.
512
+
513
+ Parameters
514
+ ==========
515
+
516
+ sources : string
517
+ List of paths to sources.
518
+ extname : string
519
+ Name of extension (default: ``None``).
520
+ If ``None``: taken from the last file in ``sources`` without extension.
521
+ build_dir: str
522
+ Path to directory in which objects files etc. are generated.
523
+ compile_kwargs: dict
524
+ keyword arguments passed to ``compile_sources``
525
+ link_kwargs: dict
526
+ keyword arguments passed to ``link_py_so``
527
+
528
+ Returns
529
+ =======
530
+
531
+ The imported module from of the Python extension.
532
+ """
533
+ if extname is None:
534
+ extname = os.path.splitext(os.path.basename(sources[-1]))[0]
535
+
536
+ compile_kwargs = compile_kwargs or {}
537
+ link_kwargs = link_kwargs or {}
538
+
539
+ try:
540
+ mod = import_module_from_file(os.path.join(build_dir, extname), sources)
541
+ except ImportError:
542
+ objs = compile_sources(list(map(get_abspath, sources)), destdir=build_dir,
543
+ cwd=build_dir, **compile_kwargs)
544
+ so = link_py_so(objs, cwd=build_dir, fort=any_fortran_src(sources),
545
+ cplus=any_cplus_src(sources), **link_kwargs)
546
+ mod = import_module_from_file(so)
547
+ return mod
548
+
549
+
550
+ def _write_sources_to_build_dir(sources, build_dir):
551
+ build_dir = build_dir or tempfile.mkdtemp()
552
+ if not os.path.isdir(build_dir):
553
+ raise OSError("Non-existent directory: ", build_dir)
554
+
555
+ source_files = []
556
+ for name, src in sources:
557
+ dest = os.path.join(build_dir, name)
558
+ differs = True
559
+ sha256_in_mem = sha256_of_string(src.encode('utf-8')).hexdigest()
560
+ if os.path.exists(dest):
561
+ if os.path.exists(dest + '.sha256'):
562
+ with open(dest + '.sha256') as fh:
563
+ sha256_on_disk = fh.read()
564
+ else:
565
+ sha256_on_disk = sha256_of_file(dest).hexdigest()
566
+
567
+ differs = sha256_on_disk != sha256_in_mem
568
+ if differs:
569
+ with open(dest, 'wt') as fh:
570
+ fh.write(src)
571
+ with open(dest + '.sha256', 'wt') as fh:
572
+ fh.write(sha256_in_mem)
573
+ source_files.append(dest)
574
+ return source_files, build_dir
575
+
576
+
577
+ def compile_link_import_strings(sources, build_dir=None, **kwargs):
578
+ """ Compiles, links and imports extension module from source.
579
+
580
+ Parameters
581
+ ==========
582
+
583
+ sources : iterable of name/source pair tuples
584
+ build_dir : string (default: None)
585
+ Path. ``None`` implies use a temporary directory.
586
+ **kwargs:
587
+ Keyword arguments passed onto `compile_link_import_py_ext`.
588
+
589
+ Returns
590
+ =======
591
+
592
+ mod : module
593
+ The compiled and imported extension module.
594
+ info : dict
595
+ Containing ``build_dir`` as 'build_dir'.
596
+
597
+ """
598
+ source_files, build_dir = _write_sources_to_build_dir(sources, build_dir)
599
+ mod = compile_link_import_py_ext(source_files, build_dir=build_dir, **kwargs)
600
+ info = {"build_dir": build_dir}
601
+ return mod, info
602
+
603
+
604
+ def compile_run_strings(sources, build_dir=None, clean=False, compile_kwargs=None, link_kwargs=None):
605
+ """ Compiles, links and runs a program built from sources.
606
+
607
+ Parameters
608
+ ==========
609
+
610
+ sources : iterable of name/source pair tuples
611
+ build_dir : string (default: None)
612
+ Path. ``None`` implies use a temporary directory.
613
+ clean : bool
614
+ Whether to remove build_dir after use. This will only have an
615
+ effect if ``build_dir`` is ``None`` (which creates a temporary directory).
616
+ Passing ``clean == True`` and ``build_dir != None`` raises a ``ValueError``.
617
+ This will also set ``build_dir`` in returned info dictionary to ``None``.
618
+ compile_kwargs: dict
619
+ Keyword arguments passed onto ``compile_sources``
620
+ link_kwargs: dict
621
+ Keyword arguments passed onto ``link``
622
+
623
+ Returns
624
+ =======
625
+
626
+ (stdout, stderr): pair of strings
627
+ info: dict
628
+ Containing exit status as 'exit_status' and ``build_dir`` as 'build_dir'
629
+
630
+ """
631
+ if clean and build_dir is not None:
632
+ raise ValueError("Automatic removal of build_dir is only available for temporary directory.")
633
+ try:
634
+ source_files, build_dir = _write_sources_to_build_dir(sources, build_dir)
635
+ objs = compile_sources(list(map(get_abspath, source_files)), destdir=build_dir,
636
+ cwd=build_dir, **(compile_kwargs or {}))
637
+ prog = link(objs, cwd=build_dir,
638
+ fort=any_fortran_src(source_files),
639
+ cplus=any_cplus_src(source_files), **(link_kwargs or {}))
640
+ p = subprocess.Popen([prog], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
641
+ exit_status = p.wait()
642
+ stdout, stderr = [txt.decode('utf-8') for txt in p.communicate()]
643
+ finally:
644
+ if clean and os.path.isdir(build_dir):
645
+ shutil.rmtree(build_dir)
646
+ build_dir = None
647
+ info = {"exit_status": exit_status, "build_dir": build_dir}
648
+ return (stdout, stderr), info
env-llmeval/lib/python3.10/site-packages/sympy/utilities/_compilation/tests/__init__.py ADDED
File without changes
env-llmeval/lib/python3.10/site-packages/sympy/utilities/_compilation/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (199 Bytes). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/utilities/_compilation/tests/__pycache__/test_compilation.cpython-310.pyc ADDED
Binary file (1.98 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/utilities/_compilation/tests/test_compilation.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import shutil
2
+ from sympy.external import import_module
3
+ from sympy.testing.pytest import skip
4
+
5
+ from sympy.utilities._compilation.compilation import compile_link_import_strings
6
+
7
+ numpy = import_module('numpy')
8
+ cython = import_module('cython')
9
+
10
+ _sources1 = [
11
+ ('sigmoid.c', r"""
12
+ #include <math.h>
13
+
14
+ void sigmoid(int n, const double * const restrict in,
15
+ double * const restrict out, double lim){
16
+ for (int i=0; i<n; ++i){
17
+ const double x = in[i];
18
+ out[i] = x*pow(pow(x/lim, 8)+1, -1./8.);
19
+ }
20
+ }
21
+ """),
22
+ ('_sigmoid.pyx', r"""
23
+ import numpy as np
24
+ cimport numpy as cnp
25
+
26
+ cdef extern void c_sigmoid "sigmoid" (int, const double * const,
27
+ double * const, double)
28
+
29
+ def sigmoid(double [:] inp, double lim=350.0):
30
+ cdef cnp.ndarray[cnp.float64_t, ndim=1] out = np.empty(
31
+ inp.size, dtype=np.float64)
32
+ c_sigmoid(inp.size, &inp[0], &out[0], lim)
33
+ return out
34
+ """)
35
+ ]
36
+
37
+
38
+ def npy(data, lim=350.0):
39
+ return data/((data/lim)**8+1)**(1/8.)
40
+
41
+
42
+ def test_compile_link_import_strings():
43
+ if not numpy:
44
+ skip("numpy not installed.")
45
+ if not cython:
46
+ skip("cython not installed.")
47
+
48
+ from sympy.utilities._compilation import has_c
49
+ if not has_c():
50
+ skip("No C compiler found.")
51
+
52
+ compile_kw = {"std": 'c99', "include_dirs": [numpy.get_include()]}
53
+ info = None
54
+ try:
55
+ mod, info = compile_link_import_strings(_sources1, compile_kwargs=compile_kw)
56
+ data = numpy.random.random(1024*1024*8) # 64 MB of RAM needed..
57
+ res_mod = mod.sigmoid(data)
58
+ res_npy = npy(data)
59
+ assert numpy.allclose(res_mod, res_npy)
60
+ finally:
61
+ if info and info['build_dir']:
62
+ shutil.rmtree(info['build_dir'])
env-llmeval/lib/python3.10/site-packages/sympy/utilities/_compilation/util.py ADDED
@@ -0,0 +1,287 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections import namedtuple
2
+ from hashlib import sha256
3
+ import os
4
+ import shutil
5
+ import sys
6
+ import fnmatch
7
+
8
+ from sympy.testing.pytest import XFAIL
9
+
10
+
11
+ def may_xfail(func):
12
+ if sys.platform.lower() == 'darwin' or os.name == 'nt':
13
+ # sympy.utilities._compilation needs more testing on Windows and macOS
14
+ # once those two platforms are reliably supported this xfail decorator
15
+ # may be removed.
16
+ return XFAIL(func)
17
+ else:
18
+ return func
19
+
20
+
21
+ class CompilerNotFoundError(FileNotFoundError):
22
+ pass
23
+
24
+
25
+ class CompileError (Exception):
26
+ """Failure to compile one or more C/C++ source files."""
27
+
28
+
29
+ def get_abspath(path, cwd='.'):
30
+ """ Returns the absolute path.
31
+
32
+ Parameters
33
+ ==========
34
+
35
+ path : str
36
+ (relative) path.
37
+ cwd : str
38
+ Path to root of relative path.
39
+ """
40
+ if os.path.isabs(path):
41
+ return path
42
+ else:
43
+ if not os.path.isabs(cwd):
44
+ cwd = os.path.abspath(cwd)
45
+ return os.path.abspath(
46
+ os.path.join(cwd, path)
47
+ )
48
+
49
+
50
+ def make_dirs(path):
51
+ """ Create directories (equivalent of ``mkdir -p``). """
52
+ if path[-1] == '/':
53
+ parent = os.path.dirname(path[:-1])
54
+ else:
55
+ parent = os.path.dirname(path)
56
+
57
+ if len(parent) > 0:
58
+ if not os.path.exists(parent):
59
+ make_dirs(parent)
60
+
61
+ if not os.path.exists(path):
62
+ os.mkdir(path, 0o777)
63
+ else:
64
+ assert os.path.isdir(path)
65
+
66
+
67
+ def copy(src, dst, only_update=False, copystat=True, cwd=None,
68
+ dest_is_dir=False, create_dest_dirs=False):
69
+ """ Variation of ``shutil.copy`` with extra options.
70
+
71
+ Parameters
72
+ ==========
73
+
74
+ src : str
75
+ Path to source file.
76
+ dst : str
77
+ Path to destination.
78
+ only_update : bool
79
+ Only copy if source is newer than destination
80
+ (returns None if it was newer), default: ``False``.
81
+ copystat : bool
82
+ See ``shutil.copystat``. default: ``True``.
83
+ cwd : str
84
+ Path to working directory (root of relative paths).
85
+ dest_is_dir : bool
86
+ Ensures that dst is treated as a directory. default: ``False``
87
+ create_dest_dirs : bool
88
+ Creates directories if needed.
89
+
90
+ Returns
91
+ =======
92
+
93
+ Path to the copied file.
94
+
95
+ """
96
+ if cwd: # Handle working directory
97
+ if not os.path.isabs(src):
98
+ src = os.path.join(cwd, src)
99
+ if not os.path.isabs(dst):
100
+ dst = os.path.join(cwd, dst)
101
+
102
+ if not os.path.exists(src): # Make sure source file extists
103
+ raise FileNotFoundError("Source: `{}` does not exist".format(src))
104
+
105
+ # We accept both (re)naming destination file _or_
106
+ # passing a (possible non-existent) destination directory
107
+ if dest_is_dir:
108
+ if not dst[-1] == '/':
109
+ dst = dst+'/'
110
+ else:
111
+ if os.path.exists(dst) and os.path.isdir(dst):
112
+ dest_is_dir = True
113
+
114
+ if dest_is_dir:
115
+ dest_dir = dst
116
+ dest_fname = os.path.basename(src)
117
+ dst = os.path.join(dest_dir, dest_fname)
118
+ else:
119
+ dest_dir = os.path.dirname(dst)
120
+
121
+ if not os.path.exists(dest_dir):
122
+ if create_dest_dirs:
123
+ make_dirs(dest_dir)
124
+ else:
125
+ raise FileNotFoundError("You must create directory first.")
126
+
127
+ if only_update:
128
+ # This function is not defined:
129
+ # XXX: This branch is clearly not tested!
130
+ if not missing_or_other_newer(dst, src): # noqa
131
+ return
132
+
133
+ if os.path.islink(dst):
134
+ dst = os.path.abspath(os.path.realpath(dst), cwd=cwd)
135
+
136
+ shutil.copy(src, dst)
137
+ if copystat:
138
+ shutil.copystat(src, dst)
139
+
140
+ return dst
141
+
142
+ Glob = namedtuple('Glob', 'pathname')
143
+ ArbitraryDepthGlob = namedtuple('ArbitraryDepthGlob', 'filename')
144
+
145
+ def glob_at_depth(filename_glob, cwd=None):
146
+ if cwd is not None:
147
+ cwd = '.'
148
+ globbed = []
149
+ for root, dirs, filenames in os.walk(cwd):
150
+ for fn in filenames:
151
+ # This is not tested:
152
+ if fnmatch.fnmatch(fn, filename_glob):
153
+ globbed.append(os.path.join(root, fn))
154
+ return globbed
155
+
156
+ def sha256_of_file(path, nblocks=128):
157
+ """ Computes the SHA256 hash of a file.
158
+
159
+ Parameters
160
+ ==========
161
+
162
+ path : string
163
+ Path to file to compute hash of.
164
+ nblocks : int
165
+ Number of blocks to read per iteration.
166
+
167
+ Returns
168
+ =======
169
+
170
+ hashlib sha256 hash object. Use ``.digest()`` or ``.hexdigest()``
171
+ on returned object to get binary or hex encoded string.
172
+ """
173
+ sh = sha256()
174
+ with open(path, 'rb') as f:
175
+ for chunk in iter(lambda: f.read(nblocks*sh.block_size), b''):
176
+ sh.update(chunk)
177
+ return sh
178
+
179
+
180
+ def sha256_of_string(string):
181
+ """ Computes the SHA256 hash of a string. """
182
+ sh = sha256()
183
+ sh.update(string)
184
+ return sh
185
+
186
+
187
+ def pyx_is_cplus(path):
188
+ """
189
+ Inspect a Cython source file (.pyx) and look for comment line like:
190
+
191
+ # distutils: language = c++
192
+
193
+ Returns True if such a file is present in the file, else False.
194
+ """
195
+ with open(path) as fh:
196
+ for line in fh:
197
+ if line.startswith('#') and '=' in line:
198
+ splitted = line.split('=')
199
+ if len(splitted) != 2:
200
+ continue
201
+ lhs, rhs = splitted
202
+ if lhs.strip().split()[-1].lower() == 'language' and \
203
+ rhs.strip().split()[0].lower() == 'c++':
204
+ return True
205
+ return False
206
+
207
+ def import_module_from_file(filename, only_if_newer_than=None):
208
+ """ Imports Python extension (from shared object file)
209
+
210
+ Provide a list of paths in `only_if_newer_than` to check
211
+ timestamps of dependencies. import_ raises an ImportError
212
+ if any is newer.
213
+
214
+ Word of warning: The OS may cache shared objects which makes
215
+ reimporting same path of an shared object file very problematic.
216
+
217
+ It will not detect the new time stamp, nor new checksum, but will
218
+ instead silently use old module. Use unique names for this reason.
219
+
220
+ Parameters
221
+ ==========
222
+
223
+ filename : str
224
+ Path to shared object.
225
+ only_if_newer_than : iterable of strings
226
+ Paths to dependencies of the shared object.
227
+
228
+ Raises
229
+ ======
230
+
231
+ ``ImportError`` if any of the files specified in ``only_if_newer_than`` are newer
232
+ than the file given by filename.
233
+ """
234
+ path, name = os.path.split(filename)
235
+ name, ext = os.path.splitext(name)
236
+ name = name.split('.')[0]
237
+ if sys.version_info[0] == 2:
238
+ from imp import find_module, load_module
239
+ fobj, filename, data = find_module(name, [path])
240
+ if only_if_newer_than:
241
+ for dep in only_if_newer_than:
242
+ if os.path.getmtime(filename) < os.path.getmtime(dep):
243
+ raise ImportError("{} is newer than {}".format(dep, filename))
244
+ mod = load_module(name, fobj, filename, data)
245
+ else:
246
+ import importlib.util
247
+ spec = importlib.util.spec_from_file_location(name, filename)
248
+ if spec is None:
249
+ raise ImportError("Failed to import: '%s'" % filename)
250
+ mod = importlib.util.module_from_spec(spec)
251
+ spec.loader.exec_module(mod)
252
+ return mod
253
+
254
+
255
+ def find_binary_of_command(candidates):
256
+ """ Finds binary first matching name among candidates.
257
+
258
+ Calls ``which`` from shutils for provided candidates and returns
259
+ first hit.
260
+
261
+ Parameters
262
+ ==========
263
+
264
+ candidates : iterable of str
265
+ Names of candidate commands
266
+
267
+ Raises
268
+ ======
269
+
270
+ CompilerNotFoundError if no candidates match.
271
+ """
272
+ from shutil import which
273
+ for c in candidates:
274
+ binary_path = which(c)
275
+ if c and binary_path:
276
+ return c, binary_path
277
+
278
+ raise CompilerNotFoundError('No binary located for candidates: {}'.format(candidates))
279
+
280
+
281
+ def unique_list(l):
282
+ """ Uniquify a list (skip duplicate items). """
283
+ result = []
284
+ for x in l:
285
+ if x not in result:
286
+ result.append(x)
287
+ return result
env-llmeval/lib/python3.10/site-packages/sympy/utilities/mathml/__init__.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Module with some functions for MathML, like transforming MathML
2
+ content in MathML presentation.
3
+
4
+ To use this module, you will need lxml.
5
+ """
6
+
7
+ from sympy.utilities.pkgdata import get_resource
8
+ from sympy.utilities.decorator import doctest_depends_on
9
+
10
+
11
+ __doctest_requires__ = {('apply_xsl', 'c2p'): ['lxml']}
12
+
13
+
14
+ def add_mathml_headers(s):
15
+ return """<math xmlns:mml="http://www.w3.org/1998/Math/MathML"
16
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
17
+ xsi:schemaLocation="http://www.w3.org/1998/Math/MathML
18
+ http://www.w3.org/Math/XMLSchema/mathml2/mathml2.xsd">""" + s + "</math>"
19
+
20
+
21
+ @doctest_depends_on(modules=('lxml',))
22
+ def apply_xsl(mml, xsl):
23
+ """Apply a xsl to a MathML string.
24
+
25
+ Parameters
26
+ ==========
27
+
28
+ mml
29
+ A string with MathML code.
30
+ xsl
31
+ A string representing a path to a xsl (xml stylesheet) file.
32
+ This file name is relative to the PYTHONPATH.
33
+
34
+ Examples
35
+ ========
36
+
37
+ >>> from sympy.utilities.mathml import apply_xsl
38
+ >>> xsl = 'mathml/data/simple_mmlctop.xsl'
39
+ >>> mml = '<apply> <plus/> <ci>a</ci> <ci>b</ci> </apply>'
40
+ >>> res = apply_xsl(mml,xsl)
41
+ >>> ''.join(res.splitlines())
42
+ '<?xml version="1.0"?><mrow xmlns="http://www.w3.org/1998/Math/MathML"> <mi>a</mi> <mo> + </mo> <mi>b</mi></mrow>'
43
+ """
44
+ from lxml import etree
45
+
46
+ parser = etree.XMLParser(resolve_entities=False)
47
+ ac = etree.XSLTAccessControl.DENY_ALL
48
+
49
+ s = etree.XML(get_resource(xsl).read(), parser=parser)
50
+ transform = etree.XSLT(s, access_control=ac)
51
+ doc = etree.XML(mml, parser=parser)
52
+ result = transform(doc)
53
+ s = str(result)
54
+ return s
55
+
56
+
57
+ @doctest_depends_on(modules=('lxml',))
58
+ def c2p(mml, simple=False):
59
+ """Transforms a document in MathML content (like the one that sympy produces)
60
+ in one document in MathML presentation, more suitable for printing, and more
61
+ widely accepted
62
+
63
+ Examples
64
+ ========
65
+
66
+ >>> from sympy.utilities.mathml import c2p
67
+ >>> mml = '<apply> <exp/> <cn>2</cn> </apply>'
68
+ >>> c2p(mml,simple=True) != c2p(mml,simple=False)
69
+ True
70
+
71
+ """
72
+
73
+ if not mml.startswith('<math'):
74
+ mml = add_mathml_headers(mml)
75
+
76
+ if simple:
77
+ return apply_xsl(mml, 'mathml/data/simple_mmlctop.xsl')
78
+
79
+ return apply_xsl(mml, 'mathml/data/mmlctop.xsl')
env-llmeval/lib/python3.10/site-packages/sympy/utilities/mathml/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (2.59 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/utilities/mathml/data/mmlctop.xsl ADDED
The diff for this file is too large to render. See raw diff
 
env-llmeval/lib/python3.10/site-packages/sympy/utilities/mathml/data/mmltex.xsl ADDED
The diff for this file is too large to render. See raw diff
 
env-llmeval/lib/python3.10/site-packages/sympy/utilities/mathml/data/simple_mmlctop.xsl ADDED
The diff for this file is too large to render. See raw diff
 
env-llmeval/lib/python3.10/site-packages/sympy/utilities/pytest.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ .. deprecated:: 1.6
3
+
4
+ sympy.utilities.pytest has been renamed to sympy.testing.pytest.
5
+ """
6
+ from sympy.utilities.exceptions import sympy_deprecation_warning
7
+
8
+ sympy_deprecation_warning("The sympy.utilities.pytest submodule is deprecated. Use sympy.testing.pytest instead.",
9
+ deprecated_since_version="1.6",
10
+ active_deprecations_target="deprecated-sympy-utilities-submodules")
11
+
12
+ from sympy.testing.pytest import * # noqa:F401
env-llmeval/lib/python3.10/site-packages/sympy/utilities/tests/__init__.py ADDED
File without changes
env-llmeval/lib/python3.10/site-packages/sympy/utilities/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (186 Bytes). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/utilities/tests/__pycache__/test_autowrap.cpython-310.pyc ADDED
Binary file (14.5 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/utilities/tests/__pycache__/test_codegen.cpython-310.pyc ADDED
Binary file (44.2 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/utilities/tests/__pycache__/test_codegen_julia.cpython-310.pyc ADDED
Binary file (15.4 kB). View file