applied-ai-018 commited on
Commit
96d72fd
·
verified ·
1 Parent(s): 5975f57

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. llmeval-env/lib/python3.10/site-packages/sympy/categories/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  2. llmeval-env/lib/python3.10/site-packages/sympy/categories/tests/__pycache__/test_baseclasses.cpython-310.pyc +0 -0
  3. llmeval-env/lib/python3.10/site-packages/sympy/categories/tests/__pycache__/test_drawing.cpython-310.pyc +0 -0
  4. llmeval-env/lib/python3.10/site-packages/sympy/categories/tests/test_drawing.py +919 -0
  5. llmeval-env/lib/python3.10/site-packages/sympy/plotting/__init__.py +22 -0
  6. llmeval-env/lib/python3.10/site-packages/sympy/plotting/__pycache__/experimental_lambdify.cpython-310.pyc +0 -0
  7. llmeval-env/lib/python3.10/site-packages/sympy/plotting/__pycache__/plot_implicit.cpython-310.pyc +0 -0
  8. llmeval-env/lib/python3.10/site-packages/sympy/plotting/experimental_lambdify.py +643 -0
  9. llmeval-env/lib/python3.10/site-packages/sympy/plotting/intervalmath/__init__.py +12 -0
  10. llmeval-env/lib/python3.10/site-packages/sympy/plotting/intervalmath/__pycache__/__init__.cpython-310.pyc +0 -0
  11. llmeval-env/lib/python3.10/site-packages/sympy/plotting/intervalmath/__pycache__/interval_membership.cpython-310.pyc +0 -0
  12. llmeval-env/lib/python3.10/site-packages/sympy/plotting/intervalmath/__pycache__/lib_interval.cpython-310.pyc +0 -0
  13. llmeval-env/lib/python3.10/site-packages/sympy/plotting/intervalmath/interval_membership.py +78 -0
  14. llmeval-env/lib/python3.10/site-packages/sympy/plotting/intervalmath/lib_interval.py +452 -0
  15. llmeval-env/lib/python3.10/site-packages/sympy/plotting/plot.py +2637 -0
  16. llmeval-env/lib/python3.10/site-packages/sympy/plotting/plot_implicit.py +432 -0
  17. llmeval-env/lib/python3.10/site-packages/sympy/plotting/pygletplot/__init__.py +138 -0
  18. llmeval-env/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/__init__.cpython-310.pyc +0 -0
  19. llmeval-env/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/color_scheme.cpython-310.pyc +0 -0
  20. llmeval-env/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/managed_window.cpython-310.pyc +0 -0
  21. llmeval-env/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/plot.cpython-310.pyc +0 -0
  22. llmeval-env/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/plot_axes.cpython-310.pyc +0 -0
  23. llmeval-env/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/plot_camera.cpython-310.pyc +0 -0
  24. llmeval-env/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/plot_controller.cpython-310.pyc +0 -0
  25. llmeval-env/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/plot_curve.cpython-310.pyc +0 -0
  26. llmeval-env/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/plot_interval.cpython-310.pyc +0 -0
  27. llmeval-env/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/plot_mode.cpython-310.pyc +0 -0
  28. llmeval-env/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/plot_mode_base.cpython-310.pyc +0 -0
  29. llmeval-env/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/plot_modes.cpython-310.pyc +0 -0
  30. llmeval-env/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/plot_object.cpython-310.pyc +0 -0
  31. llmeval-env/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/plot_rotation.cpython-310.pyc +0 -0
  32. llmeval-env/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/plot_surface.cpython-310.pyc +0 -0
  33. llmeval-env/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/plot_window.cpython-310.pyc +0 -0
  34. llmeval-env/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/util.cpython-310.pyc +0 -0
  35. llmeval-env/lib/python3.10/site-packages/sympy/plotting/pygletplot/color_scheme.py +336 -0
  36. llmeval-env/lib/python3.10/site-packages/sympy/plotting/pygletplot/managed_window.py +106 -0
  37. llmeval-env/lib/python3.10/site-packages/sympy/plotting/pygletplot/plot.py +464 -0
  38. llmeval-env/lib/python3.10/site-packages/sympy/plotting/pygletplot/plot_axes.py +251 -0
  39. llmeval-env/lib/python3.10/site-packages/sympy/plotting/pygletplot/plot_camera.py +128 -0
  40. llmeval-env/lib/python3.10/site-packages/sympy/plotting/pygletplot/plot_controller.py +218 -0
  41. llmeval-env/lib/python3.10/site-packages/sympy/plotting/pygletplot/plot_curve.py +82 -0
  42. llmeval-env/lib/python3.10/site-packages/sympy/plotting/pygletplot/plot_interval.py +181 -0
  43. llmeval-env/lib/python3.10/site-packages/sympy/plotting/pygletplot/plot_mode.py +400 -0
  44. llmeval-env/lib/python3.10/site-packages/sympy/plotting/pygletplot/plot_mode_base.py +378 -0
  45. llmeval-env/lib/python3.10/site-packages/sympy/plotting/pygletplot/plot_modes.py +209 -0
  46. llmeval-env/lib/python3.10/site-packages/sympy/plotting/pygletplot/plot_object.py +17 -0
  47. llmeval-env/lib/python3.10/site-packages/sympy/plotting/pygletplot/plot_rotation.py +68 -0
  48. llmeval-env/lib/python3.10/site-packages/sympy/plotting/pygletplot/plot_surface.py +102 -0
  49. llmeval-env/lib/python3.10/site-packages/sympy/plotting/pygletplot/plot_window.py +144 -0
  50. llmeval-env/lib/python3.10/site-packages/sympy/plotting/pygletplot/tests/__init__.py +0 -0
llmeval-env/lib/python3.10/site-packages/sympy/categories/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (195 Bytes). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/categories/tests/__pycache__/test_baseclasses.cpython-310.pyc ADDED
Binary file (5 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/categories/tests/__pycache__/test_drawing.cpython-310.pyc ADDED
Binary file (17.5 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/categories/tests/test_drawing.py ADDED
@@ -0,0 +1,919 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.categories.diagram_drawing import _GrowableGrid, ArrowStringDescription
2
+ from sympy.categories import (DiagramGrid, Object, NamedMorphism,
3
+ Diagram, XypicDiagramDrawer, xypic_draw_diagram)
4
+ from sympy.sets.sets import FiniteSet
5
+
6
+
7
+ def test_GrowableGrid():
8
+ grid = _GrowableGrid(1, 2)
9
+
10
+ # Check dimensions.
11
+ assert grid.width == 1
12
+ assert grid.height == 2
13
+
14
+ # Check initialization of elements.
15
+ assert grid[0, 0] is None
16
+ assert grid[1, 0] is None
17
+
18
+ # Check assignment to elements.
19
+ grid[0, 0] = 1
20
+ grid[1, 0] = "two"
21
+
22
+ assert grid[0, 0] == 1
23
+ assert grid[1, 0] == "two"
24
+
25
+ # Check appending a row.
26
+ grid.append_row()
27
+
28
+ assert grid.width == 1
29
+ assert grid.height == 3
30
+
31
+ assert grid[0, 0] == 1
32
+ assert grid[1, 0] == "two"
33
+ assert grid[2, 0] is None
34
+
35
+ # Check appending a column.
36
+ grid.append_column()
37
+ assert grid.width == 2
38
+ assert grid.height == 3
39
+
40
+ assert grid[0, 0] == 1
41
+ assert grid[1, 0] == "two"
42
+ assert grid[2, 0] is None
43
+
44
+ assert grid[0, 1] is None
45
+ assert grid[1, 1] is None
46
+ assert grid[2, 1] is None
47
+
48
+ grid = _GrowableGrid(1, 2)
49
+ grid[0, 0] = 1
50
+ grid[1, 0] = "two"
51
+
52
+ # Check prepending a row.
53
+ grid.prepend_row()
54
+ assert grid.width == 1
55
+ assert grid.height == 3
56
+
57
+ assert grid[0, 0] is None
58
+ assert grid[1, 0] == 1
59
+ assert grid[2, 0] == "two"
60
+
61
+ # Check prepending a column.
62
+ grid.prepend_column()
63
+ assert grid.width == 2
64
+ assert grid.height == 3
65
+
66
+ assert grid[0, 0] is None
67
+ assert grid[1, 0] is None
68
+ assert grid[2, 0] is None
69
+
70
+ assert grid[0, 1] is None
71
+ assert grid[1, 1] == 1
72
+ assert grid[2, 1] == "two"
73
+
74
+
75
+ def test_DiagramGrid():
76
+ # Set up some objects and morphisms.
77
+ A = Object("A")
78
+ B = Object("B")
79
+ C = Object("C")
80
+ D = Object("D")
81
+ E = Object("E")
82
+
83
+ f = NamedMorphism(A, B, "f")
84
+ g = NamedMorphism(B, C, "g")
85
+ h = NamedMorphism(D, A, "h")
86
+ k = NamedMorphism(D, B, "k")
87
+
88
+ # A one-morphism diagram.
89
+ d = Diagram([f])
90
+ grid = DiagramGrid(d)
91
+
92
+ assert grid.width == 2
93
+ assert grid.height == 1
94
+ assert grid[0, 0] == A
95
+ assert grid[0, 1] == B
96
+ assert grid.morphisms == {f: FiniteSet()}
97
+
98
+ # A triangle.
99
+ d = Diagram([f, g], {g * f: "unique"})
100
+ grid = DiagramGrid(d)
101
+
102
+ assert grid.width == 2
103
+ assert grid.height == 2
104
+ assert grid[0, 0] == A
105
+ assert grid[0, 1] == B
106
+ assert grid[1, 0] == C
107
+ assert grid[1, 1] is None
108
+ assert grid.morphisms == {f: FiniteSet(), g: FiniteSet(),
109
+ g * f: FiniteSet("unique")}
110
+
111
+ # A triangle with a "loop" morphism.
112
+ l_A = NamedMorphism(A, A, "l_A")
113
+ d = Diagram([f, g, l_A])
114
+ grid = DiagramGrid(d)
115
+
116
+ assert grid.width == 2
117
+ assert grid.height == 2
118
+ assert grid[0, 0] == A
119
+ assert grid[0, 1] == B
120
+ assert grid[1, 0] is None
121
+ assert grid[1, 1] == C
122
+ assert grid.morphisms == {f: FiniteSet(), g: FiniteSet(), l_A: FiniteSet()}
123
+
124
+ # A simple diagram.
125
+ d = Diagram([f, g, h, k])
126
+ grid = DiagramGrid(d)
127
+
128
+ assert grid.width == 3
129
+ assert grid.height == 2
130
+ assert grid[0, 0] == A
131
+ assert grid[0, 1] == B
132
+ assert grid[0, 2] == D
133
+ assert grid[1, 0] is None
134
+ assert grid[1, 1] == C
135
+ assert grid[1, 2] is None
136
+ assert grid.morphisms == {f: FiniteSet(), g: FiniteSet(), h: FiniteSet(),
137
+ k: FiniteSet()}
138
+
139
+ assert str(grid) == '[[Object("A"), Object("B"), Object("D")], ' \
140
+ '[None, Object("C"), None]]'
141
+
142
+ # A chain of morphisms.
143
+ f = NamedMorphism(A, B, "f")
144
+ g = NamedMorphism(B, C, "g")
145
+ h = NamedMorphism(C, D, "h")
146
+ k = NamedMorphism(D, E, "k")
147
+ d = Diagram([f, g, h, k])
148
+ grid = DiagramGrid(d)
149
+
150
+ assert grid.width == 3
151
+ assert grid.height == 3
152
+ assert grid[0, 0] == A
153
+ assert grid[0, 1] == B
154
+ assert grid[0, 2] is None
155
+ assert grid[1, 0] is None
156
+ assert grid[1, 1] == C
157
+ assert grid[1, 2] == D
158
+ assert grid[2, 0] is None
159
+ assert grid[2, 1] is None
160
+ assert grid[2, 2] == E
161
+ assert grid.morphisms == {f: FiniteSet(), g: FiniteSet(), h: FiniteSet(),
162
+ k: FiniteSet()}
163
+
164
+ # A square.
165
+ f = NamedMorphism(A, B, "f")
166
+ g = NamedMorphism(B, D, "g")
167
+ h = NamedMorphism(A, C, "h")
168
+ k = NamedMorphism(C, D, "k")
169
+ d = Diagram([f, g, h, k])
170
+ grid = DiagramGrid(d)
171
+
172
+ assert grid.width == 2
173
+ assert grid.height == 2
174
+ assert grid[0, 0] == A
175
+ assert grid[0, 1] == B
176
+ assert grid[1, 0] == C
177
+ assert grid[1, 1] == D
178
+ assert grid.morphisms == {f: FiniteSet(), g: FiniteSet(), h: FiniteSet(),
179
+ k: FiniteSet()}
180
+
181
+ # A strange diagram which resulted from a typo when creating a
182
+ # test for five lemma, but which allowed to stop one extra problem
183
+ # in the algorithm.
184
+ A = Object("A")
185
+ B = Object("B")
186
+ C = Object("C")
187
+ D = Object("D")
188
+ E = Object("E")
189
+ A_ = Object("A'")
190
+ B_ = Object("B'")
191
+ C_ = Object("C'")
192
+ D_ = Object("D'")
193
+ E_ = Object("E'")
194
+
195
+ f = NamedMorphism(A, B, "f")
196
+ g = NamedMorphism(B, C, "g")
197
+ h = NamedMorphism(C, D, "h")
198
+ i = NamedMorphism(D, E, "i")
199
+
200
+ # These 4 morphisms should be between primed objects.
201
+ j = NamedMorphism(A, B, "j")
202
+ k = NamedMorphism(B, C, "k")
203
+ l = NamedMorphism(C, D, "l")
204
+ m = NamedMorphism(D, E, "m")
205
+
206
+ o = NamedMorphism(A, A_, "o")
207
+ p = NamedMorphism(B, B_, "p")
208
+ q = NamedMorphism(C, C_, "q")
209
+ r = NamedMorphism(D, D_, "r")
210
+ s = NamedMorphism(E, E_, "s")
211
+
212
+ d = Diagram([f, g, h, i, j, k, l, m, o, p, q, r, s])
213
+ grid = DiagramGrid(d)
214
+
215
+ assert grid.width == 3
216
+ assert grid.height == 4
217
+ assert grid[0, 0] is None
218
+ assert grid[0, 1] == A
219
+ assert grid[0, 2] == A_
220
+ assert grid[1, 0] == C
221
+ assert grid[1, 1] == B
222
+ assert grid[1, 2] == B_
223
+ assert grid[2, 0] == C_
224
+ assert grid[2, 1] == D
225
+ assert grid[2, 2] == D_
226
+ assert grid[3, 0] is None
227
+ assert grid[3, 1] == E
228
+ assert grid[3, 2] == E_
229
+
230
+ morphisms = {}
231
+ for m in [f, g, h, i, j, k, l, m, o, p, q, r, s]:
232
+ morphisms[m] = FiniteSet()
233
+ assert grid.morphisms == morphisms
234
+
235
+ # A cube.
236
+ A1 = Object("A1")
237
+ A2 = Object("A2")
238
+ A3 = Object("A3")
239
+ A4 = Object("A4")
240
+ A5 = Object("A5")
241
+ A6 = Object("A6")
242
+ A7 = Object("A7")
243
+ A8 = Object("A8")
244
+
245
+ # The top face of the cube.
246
+ f1 = NamedMorphism(A1, A2, "f1")
247
+ f2 = NamedMorphism(A1, A3, "f2")
248
+ f3 = NamedMorphism(A2, A4, "f3")
249
+ f4 = NamedMorphism(A3, A4, "f3")
250
+
251
+ # The bottom face of the cube.
252
+ f5 = NamedMorphism(A5, A6, "f5")
253
+ f6 = NamedMorphism(A5, A7, "f6")
254
+ f7 = NamedMorphism(A6, A8, "f7")
255
+ f8 = NamedMorphism(A7, A8, "f8")
256
+
257
+ # The remaining morphisms.
258
+ f9 = NamedMorphism(A1, A5, "f9")
259
+ f10 = NamedMorphism(A2, A6, "f10")
260
+ f11 = NamedMorphism(A3, A7, "f11")
261
+ f12 = NamedMorphism(A4, A8, "f11")
262
+
263
+ d = Diagram([f1, f2, f3, f4, f5, f6, f7, f8, f9, f10, f11, f12])
264
+ grid = DiagramGrid(d)
265
+
266
+ assert grid.width == 4
267
+ assert grid.height == 3
268
+ assert grid[0, 0] is None
269
+ assert grid[0, 1] == A5
270
+ assert grid[0, 2] == A6
271
+ assert grid[0, 3] is None
272
+ assert grid[1, 0] is None
273
+ assert grid[1, 1] == A1
274
+ assert grid[1, 2] == A2
275
+ assert grid[1, 3] is None
276
+ assert grid[2, 0] == A7
277
+ assert grid[2, 1] == A3
278
+ assert grid[2, 2] == A4
279
+ assert grid[2, 3] == A8
280
+
281
+ morphisms = {}
282
+ for m in [f1, f2, f3, f4, f5, f6, f7, f8, f9, f10, f11, f12]:
283
+ morphisms[m] = FiniteSet()
284
+ assert grid.morphisms == morphisms
285
+
286
+ # A line diagram.
287
+ A = Object("A")
288
+ B = Object("B")
289
+ C = Object("C")
290
+ D = Object("D")
291
+ E = Object("E")
292
+
293
+ f = NamedMorphism(A, B, "f")
294
+ g = NamedMorphism(B, C, "g")
295
+ h = NamedMorphism(C, D, "h")
296
+ i = NamedMorphism(D, E, "i")
297
+ d = Diagram([f, g, h, i])
298
+ grid = DiagramGrid(d, layout="sequential")
299
+
300
+ assert grid.width == 5
301
+ assert grid.height == 1
302
+ assert grid[0, 0] == A
303
+ assert grid[0, 1] == B
304
+ assert grid[0, 2] == C
305
+ assert grid[0, 3] == D
306
+ assert grid[0, 4] == E
307
+ assert grid.morphisms == {f: FiniteSet(), g: FiniteSet(), h: FiniteSet(),
308
+ i: FiniteSet()}
309
+
310
+ # Test the transposed version.
311
+ grid = DiagramGrid(d, layout="sequential", transpose=True)
312
+
313
+ assert grid.width == 1
314
+ assert grid.height == 5
315
+ assert grid[0, 0] == A
316
+ assert grid[1, 0] == B
317
+ assert grid[2, 0] == C
318
+ assert grid[3, 0] == D
319
+ assert grid[4, 0] == E
320
+ assert grid.morphisms == {f: FiniteSet(), g: FiniteSet(), h: FiniteSet(),
321
+ i: FiniteSet()}
322
+
323
+ # A pullback.
324
+ m1 = NamedMorphism(A, B, "m1")
325
+ m2 = NamedMorphism(A, C, "m2")
326
+ s1 = NamedMorphism(B, D, "s1")
327
+ s2 = NamedMorphism(C, D, "s2")
328
+ f1 = NamedMorphism(E, B, "f1")
329
+ f2 = NamedMorphism(E, C, "f2")
330
+ g = NamedMorphism(E, A, "g")
331
+
332
+ d = Diagram([m1, m2, s1, s2, f1, f2], {g: "unique"})
333
+ grid = DiagramGrid(d)
334
+
335
+ assert grid.width == 3
336
+ assert grid.height == 2
337
+ assert grid[0, 0] == A
338
+ assert grid[0, 1] == B
339
+ assert grid[0, 2] == E
340
+ assert grid[1, 0] == C
341
+ assert grid[1, 1] == D
342
+ assert grid[1, 2] is None
343
+
344
+ morphisms = {g: FiniteSet("unique")}
345
+ for m in [m1, m2, s1, s2, f1, f2]:
346
+ morphisms[m] = FiniteSet()
347
+ assert grid.morphisms == morphisms
348
+
349
+ # Test the pullback with sequential layout, just for stress
350
+ # testing.
351
+ grid = DiagramGrid(d, layout="sequential")
352
+
353
+ assert grid.width == 5
354
+ assert grid.height == 1
355
+ assert grid[0, 0] == D
356
+ assert grid[0, 1] == B
357
+ assert grid[0, 2] == A
358
+ assert grid[0, 3] == C
359
+ assert grid[0, 4] == E
360
+ assert grid.morphisms == morphisms
361
+
362
+ # Test a pullback with object grouping.
363
+ grid = DiagramGrid(d, groups=FiniteSet(E, FiniteSet(A, B, C, D)))
364
+
365
+ assert grid.width == 3
366
+ assert grid.height == 2
367
+ assert grid[0, 0] == E
368
+ assert grid[0, 1] == A
369
+ assert grid[0, 2] == B
370
+ assert grid[1, 0] is None
371
+ assert grid[1, 1] == C
372
+ assert grid[1, 2] == D
373
+ assert grid.morphisms == morphisms
374
+
375
+ # Five lemma, actually.
376
+ A = Object("A")
377
+ B = Object("B")
378
+ C = Object("C")
379
+ D = Object("D")
380
+ E = Object("E")
381
+ A_ = Object("A'")
382
+ B_ = Object("B'")
383
+ C_ = Object("C'")
384
+ D_ = Object("D'")
385
+ E_ = Object("E'")
386
+
387
+ f = NamedMorphism(A, B, "f")
388
+ g = NamedMorphism(B, C, "g")
389
+ h = NamedMorphism(C, D, "h")
390
+ i = NamedMorphism(D, E, "i")
391
+
392
+ j = NamedMorphism(A_, B_, "j")
393
+ k = NamedMorphism(B_, C_, "k")
394
+ l = NamedMorphism(C_, D_, "l")
395
+ m = NamedMorphism(D_, E_, "m")
396
+
397
+ o = NamedMorphism(A, A_, "o")
398
+ p = NamedMorphism(B, B_, "p")
399
+ q = NamedMorphism(C, C_, "q")
400
+ r = NamedMorphism(D, D_, "r")
401
+ s = NamedMorphism(E, E_, "s")
402
+
403
+ d = Diagram([f, g, h, i, j, k, l, m, o, p, q, r, s])
404
+ grid = DiagramGrid(d)
405
+
406
+ assert grid.width == 5
407
+ assert grid.height == 3
408
+ assert grid[0, 0] is None
409
+ assert grid[0, 1] == A
410
+ assert grid[0, 2] == A_
411
+ assert grid[0, 3] is None
412
+ assert grid[0, 4] is None
413
+ assert grid[1, 0] == C
414
+ assert grid[1, 1] == B
415
+ assert grid[1, 2] == B_
416
+ assert grid[1, 3] == C_
417
+ assert grid[1, 4] is None
418
+ assert grid[2, 0] == D
419
+ assert grid[2, 1] == E
420
+ assert grid[2, 2] is None
421
+ assert grid[2, 3] == D_
422
+ assert grid[2, 4] == E_
423
+
424
+ morphisms = {}
425
+ for m in [f, g, h, i, j, k, l, m, o, p, q, r, s]:
426
+ morphisms[m] = FiniteSet()
427
+ assert grid.morphisms == morphisms
428
+
429
+ # Test the five lemma with object grouping.
430
+ grid = DiagramGrid(d, FiniteSet(
431
+ FiniteSet(A, B, C, D, E), FiniteSet(A_, B_, C_, D_, E_)))
432
+
433
+ assert grid.width == 6
434
+ assert grid.height == 3
435
+ assert grid[0, 0] == A
436
+ assert grid[0, 1] == B
437
+ assert grid[0, 2] is None
438
+ assert grid[0, 3] == A_
439
+ assert grid[0, 4] == B_
440
+ assert grid[0, 5] is None
441
+ assert grid[1, 0] is None
442
+ assert grid[1, 1] == C
443
+ assert grid[1, 2] == D
444
+ assert grid[1, 3] is None
445
+ assert grid[1, 4] == C_
446
+ assert grid[1, 5] == D_
447
+ assert grid[2, 0] is None
448
+ assert grid[2, 1] is None
449
+ assert grid[2, 2] == E
450
+ assert grid[2, 3] is None
451
+ assert grid[2, 4] is None
452
+ assert grid[2, 5] == E_
453
+ assert grid.morphisms == morphisms
454
+
455
+ # Test the five lemma with object grouping, but mixing containers
456
+ # to represent groups.
457
+ grid = DiagramGrid(d, [(A, B, C, D, E), {A_, B_, C_, D_, E_}])
458
+
459
+ assert grid.width == 6
460
+ assert grid.height == 3
461
+ assert grid[0, 0] == A
462
+ assert grid[0, 1] == B
463
+ assert grid[0, 2] is None
464
+ assert grid[0, 3] == A_
465
+ assert grid[0, 4] == B_
466
+ assert grid[0, 5] is None
467
+ assert grid[1, 0] is None
468
+ assert grid[1, 1] == C
469
+ assert grid[1, 2] == D
470
+ assert grid[1, 3] is None
471
+ assert grid[1, 4] == C_
472
+ assert grid[1, 5] == D_
473
+ assert grid[2, 0] is None
474
+ assert grid[2, 1] is None
475
+ assert grid[2, 2] == E
476
+ assert grid[2, 3] is None
477
+ assert grid[2, 4] is None
478
+ assert grid[2, 5] == E_
479
+ assert grid.morphisms == morphisms
480
+
481
+ # Test the five lemma with object grouping and hints.
482
+ grid = DiagramGrid(d, {
483
+ FiniteSet(A, B, C, D, E): {"layout": "sequential",
484
+ "transpose": True},
485
+ FiniteSet(A_, B_, C_, D_, E_): {"layout": "sequential",
486
+ "transpose": True}},
487
+ transpose=True)
488
+
489
+ assert grid.width == 5
490
+ assert grid.height == 2
491
+ assert grid[0, 0] == A
492
+ assert grid[0, 1] == B
493
+ assert grid[0, 2] == C
494
+ assert grid[0, 3] == D
495
+ assert grid[0, 4] == E
496
+ assert grid[1, 0] == A_
497
+ assert grid[1, 1] == B_
498
+ assert grid[1, 2] == C_
499
+ assert grid[1, 3] == D_
500
+ assert grid[1, 4] == E_
501
+ assert grid.morphisms == morphisms
502
+
503
+ # A two-triangle disconnected diagram.
504
+ f = NamedMorphism(A, B, "f")
505
+ g = NamedMorphism(B, C, "g")
506
+ f_ = NamedMorphism(A_, B_, "f")
507
+ g_ = NamedMorphism(B_, C_, "g")
508
+ d = Diagram([f, g, f_, g_], {g * f: "unique", g_ * f_: "unique"})
509
+ grid = DiagramGrid(d)
510
+
511
+ assert grid.width == 4
512
+ assert grid.height == 2
513
+ assert grid[0, 0] == A
514
+ assert grid[0, 1] == B
515
+ assert grid[0, 2] == A_
516
+ assert grid[0, 3] == B_
517
+ assert grid[1, 0] == C
518
+ assert grid[1, 1] is None
519
+ assert grid[1, 2] == C_
520
+ assert grid[1, 3] is None
521
+ assert grid.morphisms == {f: FiniteSet(), g: FiniteSet(), f_: FiniteSet(),
522
+ g_: FiniteSet(), g * f: FiniteSet("unique"),
523
+ g_ * f_: FiniteSet("unique")}
524
+
525
+ # A two-morphism disconnected diagram.
526
+ f = NamedMorphism(A, B, "f")
527
+ g = NamedMorphism(C, D, "g")
528
+ d = Diagram([f, g])
529
+ grid = DiagramGrid(d)
530
+
531
+ assert grid.width == 4
532
+ assert grid.height == 1
533
+ assert grid[0, 0] == A
534
+ assert grid[0, 1] == B
535
+ assert grid[0, 2] == C
536
+ assert grid[0, 3] == D
537
+ assert grid.morphisms == {f: FiniteSet(), g: FiniteSet()}
538
+
539
+ # Test a one-object diagram.
540
+ f = NamedMorphism(A, A, "f")
541
+ d = Diagram([f])
542
+ grid = DiagramGrid(d)
543
+
544
+ assert grid.width == 1
545
+ assert grid.height == 1
546
+ assert grid[0, 0] == A
547
+
548
+ # Test a two-object disconnected diagram.
549
+ g = NamedMorphism(B, B, "g")
550
+ d = Diagram([f, g])
551
+ grid = DiagramGrid(d)
552
+
553
+ assert grid.width == 2
554
+ assert grid.height == 1
555
+ assert grid[0, 0] == A
556
+ assert grid[0, 1] == B
557
+
558
+
559
+ def test_DiagramGrid_pseudopod():
560
+ # Test a diagram in which even growing a pseudopod does not
561
+ # eventually help.
562
+ A = Object("A")
563
+ B = Object("B")
564
+ C = Object("C")
565
+ D = Object("D")
566
+ E = Object("E")
567
+ F = Object("F")
568
+ A_ = Object("A'")
569
+ B_ = Object("B'")
570
+ C_ = Object("C'")
571
+ D_ = Object("D'")
572
+ E_ = Object("E'")
573
+
574
+ f1 = NamedMorphism(A, B, "f1")
575
+ f2 = NamedMorphism(A, C, "f2")
576
+ f3 = NamedMorphism(A, D, "f3")
577
+ f4 = NamedMorphism(A, E, "f4")
578
+ f5 = NamedMorphism(A, A_, "f5")
579
+ f6 = NamedMorphism(A, B_, "f6")
580
+ f7 = NamedMorphism(A, C_, "f7")
581
+ f8 = NamedMorphism(A, D_, "f8")
582
+ f9 = NamedMorphism(A, E_, "f9")
583
+ f10 = NamedMorphism(A, F, "f10")
584
+ d = Diagram([f1, f2, f3, f4, f5, f6, f7, f8, f9, f10])
585
+ grid = DiagramGrid(d)
586
+
587
+ assert grid.width == 5
588
+ assert grid.height == 3
589
+ assert grid[0, 0] == E
590
+ assert grid[0, 1] == C
591
+ assert grid[0, 2] == C_
592
+ assert grid[0, 3] == E_
593
+ assert grid[0, 4] == F
594
+ assert grid[1, 0] == D
595
+ assert grid[1, 1] == A
596
+ assert grid[1, 2] == A_
597
+ assert grid[1, 3] is None
598
+ assert grid[1, 4] is None
599
+ assert grid[2, 0] == D_
600
+ assert grid[2, 1] == B
601
+ assert grid[2, 2] == B_
602
+ assert grid[2, 3] is None
603
+ assert grid[2, 4] is None
604
+
605
+ morphisms = {}
606
+ for f in [f1, f2, f3, f4, f5, f6, f7, f8, f9, f10]:
607
+ morphisms[f] = FiniteSet()
608
+ assert grid.morphisms == morphisms
609
+
610
+
611
+ def test_ArrowStringDescription():
612
+ astr = ArrowStringDescription("cm", "", None, "", "", "d", "r", "_", "f")
613
+ assert str(astr) == "\\ar[dr]_{f}"
614
+
615
+ astr = ArrowStringDescription("cm", "", 12, "", "", "d", "r", "_", "f")
616
+ assert str(astr) == "\\ar[dr]_{f}"
617
+
618
+ astr = ArrowStringDescription("cm", "^", 12, "", "", "d", "r", "_", "f")
619
+ assert str(astr) == "\\ar@/^12cm/[dr]_{f}"
620
+
621
+ astr = ArrowStringDescription("cm", "", 12, "r", "", "d", "r", "_", "f")
622
+ assert str(astr) == "\\ar[dr]_{f}"
623
+
624
+ astr = ArrowStringDescription("cm", "", 12, "r", "u", "d", "r", "_", "f")
625
+ assert str(astr) == "\\ar@(r,u)[dr]_{f}"
626
+
627
+ astr = ArrowStringDescription("cm", "", 12, "r", "u", "d", "r", "_", "f")
628
+ assert str(astr) == "\\ar@(r,u)[dr]_{f}"
629
+
630
+ astr = ArrowStringDescription("cm", "", 12, "r", "u", "d", "r", "_", "f")
631
+ astr.arrow_style = "{-->}"
632
+ assert str(astr) == "\\ar@(r,u)@{-->}[dr]_{f}"
633
+
634
+ astr = ArrowStringDescription("cm", "_", 12, "", "", "d", "r", "_", "f")
635
+ astr.arrow_style = "{-->}"
636
+ assert str(astr) == "\\ar@/_12cm/@{-->}[dr]_{f}"
637
+
638
+
639
+ def test_XypicDiagramDrawer_line():
640
+ # A linear diagram.
641
+ A = Object("A")
642
+ B = Object("B")
643
+ C = Object("C")
644
+ D = Object("D")
645
+ E = Object("E")
646
+
647
+ f = NamedMorphism(A, B, "f")
648
+ g = NamedMorphism(B, C, "g")
649
+ h = NamedMorphism(C, D, "h")
650
+ i = NamedMorphism(D, E, "i")
651
+ d = Diagram([f, g, h, i])
652
+ grid = DiagramGrid(d, layout="sequential")
653
+ drawer = XypicDiagramDrawer()
654
+ assert drawer.draw(d, grid) == "\\xymatrix{\n" \
655
+ "A \\ar[r]^{f} & B \\ar[r]^{g} & C \\ar[r]^{h} & D \\ar[r]^{i} & E \n" \
656
+ "}\n"
657
+
658
+ # The same diagram, transposed.
659
+ grid = DiagramGrid(d, layout="sequential", transpose=True)
660
+ drawer = XypicDiagramDrawer()
661
+ assert drawer.draw(d, grid) == "\\xymatrix{\n" \
662
+ "A \\ar[d]^{f} \\\\\n" \
663
+ "B \\ar[d]^{g} \\\\\n" \
664
+ "C \\ar[d]^{h} \\\\\n" \
665
+ "D \\ar[d]^{i} \\\\\n" \
666
+ "E \n" \
667
+ "}\n"
668
+
669
+
670
+ def test_XypicDiagramDrawer_triangle():
671
+ # A triangle diagram.
672
+ A = Object("A")
673
+ B = Object("B")
674
+ C = Object("C")
675
+ f = NamedMorphism(A, B, "f")
676
+ g = NamedMorphism(B, C, "g")
677
+
678
+ d = Diagram([f, g], {g * f: "unique"})
679
+ grid = DiagramGrid(d)
680
+ drawer = XypicDiagramDrawer()
681
+ assert drawer.draw(d, grid) == "\\xymatrix{\n" \
682
+ "A \\ar[d]_{g\\circ f} \\ar[r]^{f} & B \\ar[ld]^{g} \\\\\n" \
683
+ "C & \n" \
684
+ "}\n"
685
+
686
+ # The same diagram, transposed.
687
+ grid = DiagramGrid(d, transpose=True)
688
+ drawer = XypicDiagramDrawer()
689
+ assert drawer.draw(d, grid) == "\\xymatrix{\n" \
690
+ "A \\ar[r]^{g\\circ f} \\ar[d]_{f} & C \\\\\n" \
691
+ "B \\ar[ru]_{g} & \n" \
692
+ "}\n"
693
+
694
+ # The same diagram, with a masked morphism.
695
+ assert drawer.draw(d, grid, masked=[g]) == "\\xymatrix{\n" \
696
+ "A \\ar[r]^{g\\circ f} \\ar[d]_{f} & C \\\\\n" \
697
+ "B & \n" \
698
+ "}\n"
699
+
700
+ # The same diagram with a formatter for "unique".
701
+ def formatter(astr):
702
+ astr.label = "\\exists !" + astr.label
703
+ astr.arrow_style = "{-->}"
704
+
705
+ drawer.arrow_formatters["unique"] = formatter
706
+ assert drawer.draw(d, grid) == "\\xymatrix{\n" \
707
+ "A \\ar@{-->}[r]^{\\exists !g\\circ f} \\ar[d]_{f} & C \\\\\n" \
708
+ "B \\ar[ru]_{g} & \n" \
709
+ "}\n"
710
+
711
+ # The same diagram with a default formatter.
712
+ def default_formatter(astr):
713
+ astr.label_displacement = "(0.45)"
714
+
715
+ drawer.default_arrow_formatter = default_formatter
716
+ assert drawer.draw(d, grid) == "\\xymatrix{\n" \
717
+ "A \\ar@{-->}[r]^(0.45){\\exists !g\\circ f} \\ar[d]_(0.45){f} & C \\\\\n" \
718
+ "B \\ar[ru]_(0.45){g} & \n" \
719
+ "}\n"
720
+
721
+ # A triangle diagram with a lot of morphisms between the same
722
+ # objects.
723
+ f1 = NamedMorphism(B, A, "f1")
724
+ f2 = NamedMorphism(A, B, "f2")
725
+ g1 = NamedMorphism(C, B, "g1")
726
+ g2 = NamedMorphism(B, C, "g2")
727
+ d = Diagram([f, f1, f2, g, g1, g2], {f1 * g1: "unique", g2 * f2: "unique"})
728
+
729
+ grid = DiagramGrid(d, transpose=True)
730
+ drawer = XypicDiagramDrawer()
731
+ assert drawer.draw(d, grid, masked=[f1*g1*g2*f2, g2*f2*f1*g1]) == \
732
+ "\\xymatrix{\n" \
733
+ "A \\ar[r]^{g_{2}\\circ f_{2}} \\ar[d]_{f} \\ar@/^3mm/[d]^{f_{2}} " \
734
+ "& C \\ar@/^3mm/[l]^{f_{1}\\circ g_{1}} \\ar@/^3mm/[ld]^{g_{1}} \\\\\n" \
735
+ "B \\ar@/^3mm/[u]^{f_{1}} \\ar[ru]_{g} \\ar@/^3mm/[ru]^{g_{2}} & \n" \
736
+ "}\n"
737
+
738
+
739
+ def test_XypicDiagramDrawer_cube():
740
+ # A cube diagram.
741
+ A1 = Object("A1")
742
+ A2 = Object("A2")
743
+ A3 = Object("A3")
744
+ A4 = Object("A4")
745
+ A5 = Object("A5")
746
+ A6 = Object("A6")
747
+ A7 = Object("A7")
748
+ A8 = Object("A8")
749
+
750
+ # The top face of the cube.
751
+ f1 = NamedMorphism(A1, A2, "f1")
752
+ f2 = NamedMorphism(A1, A3, "f2")
753
+ f3 = NamedMorphism(A2, A4, "f3")
754
+ f4 = NamedMorphism(A3, A4, "f3")
755
+
756
+ # The bottom face of the cube.
757
+ f5 = NamedMorphism(A5, A6, "f5")
758
+ f6 = NamedMorphism(A5, A7, "f6")
759
+ f7 = NamedMorphism(A6, A8, "f7")
760
+ f8 = NamedMorphism(A7, A8, "f8")
761
+
762
+ # The remaining morphisms.
763
+ f9 = NamedMorphism(A1, A5, "f9")
764
+ f10 = NamedMorphism(A2, A6, "f10")
765
+ f11 = NamedMorphism(A3, A7, "f11")
766
+ f12 = NamedMorphism(A4, A8, "f11")
767
+
768
+ d = Diagram([f1, f2, f3, f4, f5, f6, f7, f8, f9, f10, f11, f12])
769
+ grid = DiagramGrid(d)
770
+ drawer = XypicDiagramDrawer()
771
+ assert drawer.draw(d, grid) == "\\xymatrix{\n" \
772
+ "& A_{5} \\ar[r]^{f_{5}} \\ar[ldd]_{f_{6}} & A_{6} \\ar[rdd]^{f_{7}} " \
773
+ "& \\\\\n" \
774
+ "& A_{1} \\ar[r]^{f_{1}} \\ar[d]^{f_{2}} \\ar[u]^{f_{9}} & A_{2} " \
775
+ "\\ar[d]^{f_{3}} \\ar[u]_{f_{10}} & \\\\\n" \
776
+ "A_{7} \\ar@/_3mm/[rrr]_{f_{8}} & A_{3} \\ar[r]^{f_{3}} \\ar[l]_{f_{11}} " \
777
+ "& A_{4} \\ar[r]^{f_{11}} & A_{8} \n" \
778
+ "}\n"
779
+
780
+ # The same diagram, transposed.
781
+ grid = DiagramGrid(d, transpose=True)
782
+ drawer = XypicDiagramDrawer()
783
+ assert drawer.draw(d, grid) == "\\xymatrix{\n" \
784
+ "& & A_{7} \\ar@/^3mm/[ddd]^{f_{8}} \\\\\n" \
785
+ "A_{5} \\ar[d]_{f_{5}} \\ar[rru]^{f_{6}} & A_{1} \\ar[d]^{f_{1}} " \
786
+ "\\ar[r]^{f_{2}} \\ar[l]^{f_{9}} & A_{3} \\ar[d]_{f_{3}} " \
787
+ "\\ar[u]^{f_{11}} \\\\\n" \
788
+ "A_{6} \\ar[rrd]_{f_{7}} & A_{2} \\ar[r]^{f_{3}} \\ar[l]^{f_{10}} " \
789
+ "& A_{4} \\ar[d]_{f_{11}} \\\\\n" \
790
+ "& & A_{8} \n" \
791
+ "}\n"
792
+
793
+
794
+ def test_XypicDiagramDrawer_curved_and_loops():
795
+ # A simple diagram, with a curved arrow.
796
+ A = Object("A")
797
+ B = Object("B")
798
+ C = Object("C")
799
+ D = Object("D")
800
+
801
+ f = NamedMorphism(A, B, "f")
802
+ g = NamedMorphism(B, C, "g")
803
+ h = NamedMorphism(D, A, "h")
804
+ k = NamedMorphism(D, B, "k")
805
+ d = Diagram([f, g, h, k])
806
+ grid = DiagramGrid(d)
807
+ drawer = XypicDiagramDrawer()
808
+ assert drawer.draw(d, grid) == "\\xymatrix{\n" \
809
+ "A \\ar[r]_{f} & B \\ar[d]^{g} & D \\ar[l]^{k} \\ar@/_3mm/[ll]_{h} \\\\\n" \
810
+ "& C & \n" \
811
+ "}\n"
812
+
813
+ # The same diagram, transposed.
814
+ grid = DiagramGrid(d, transpose=True)
815
+ drawer = XypicDiagramDrawer()
816
+ assert drawer.draw(d, grid) == "\\xymatrix{\n" \
817
+ "A \\ar[d]^{f} & \\\\\n" \
818
+ "B \\ar[r]^{g} & C \\\\\n" \
819
+ "D \\ar[u]_{k} \\ar@/^3mm/[uu]^{h} & \n" \
820
+ "}\n"
821
+
822
+ # The same diagram, larger and rotated.
823
+ assert drawer.draw(d, grid, diagram_format="@+1cm@dr") == \
824
+ "\\xymatrix@+1cm@dr{\n" \
825
+ "A \\ar[d]^{f} & \\\\\n" \
826
+ "B \\ar[r]^{g} & C \\\\\n" \
827
+ "D \\ar[u]_{k} \\ar@/^3mm/[uu]^{h} & \n" \
828
+ "}\n"
829
+
830
+ # A simple diagram with three curved arrows.
831
+ h1 = NamedMorphism(D, A, "h1")
832
+ h2 = NamedMorphism(A, D, "h2")
833
+ k = NamedMorphism(D, B, "k")
834
+ d = Diagram([f, g, h, k, h1, h2])
835
+ grid = DiagramGrid(d)
836
+ drawer = XypicDiagramDrawer()
837
+ assert drawer.draw(d, grid) == "\\xymatrix{\n" \
838
+ "A \\ar[r]_{f} \\ar@/^3mm/[rr]^{h_{2}} & B \\ar[d]^{g} & D \\ar[l]^{k} " \
839
+ "\\ar@/_7mm/[ll]_{h} \\ar@/_11mm/[ll]_{h_{1}} \\\\\n" \
840
+ "& C & \n" \
841
+ "}\n"
842
+
843
+ # The same diagram, transposed.
844
+ grid = DiagramGrid(d, transpose=True)
845
+ drawer = XypicDiagramDrawer()
846
+ assert drawer.draw(d, grid) == "\\xymatrix{\n" \
847
+ "A \\ar[d]^{f} \\ar@/_3mm/[dd]_{h_{2}} & \\\\\n" \
848
+ "B \\ar[r]^{g} & C \\\\\n" \
849
+ "D \\ar[u]_{k} \\ar@/^7mm/[uu]^{h} \\ar@/^11mm/[uu]^{h_{1}} & \n" \
850
+ "}\n"
851
+
852
+ # The same diagram, with "loop" morphisms.
853
+ l_A = NamedMorphism(A, A, "l_A")
854
+ l_D = NamedMorphism(D, D, "l_D")
855
+ l_C = NamedMorphism(C, C, "l_C")
856
+ d = Diagram([f, g, h, k, h1, h2, l_A, l_D, l_C])
857
+ grid = DiagramGrid(d)
858
+ drawer = XypicDiagramDrawer()
859
+ assert drawer.draw(d, grid) == "\\xymatrix{\n" \
860
+ "A \\ar[r]_{f} \\ar@/^3mm/[rr]^{h_{2}} \\ar@(u,l)[]^{l_{A}} " \
861
+ "& B \\ar[d]^{g} & D \\ar[l]^{k} \\ar@/_7mm/[ll]_{h} " \
862
+ "\\ar@/_11mm/[ll]_{h_{1}} \\ar@(r,u)[]^{l_{D}} \\\\\n" \
863
+ "& C \\ar@(l,d)[]^{l_{C}} & \n" \
864
+ "}\n"
865
+
866
+ # The same diagram with "loop" morphisms, transposed.
867
+ grid = DiagramGrid(d, transpose=True)
868
+ drawer = XypicDiagramDrawer()
869
+ assert drawer.draw(d, grid) == "\\xymatrix{\n" \
870
+ "A \\ar[d]^{f} \\ar@/_3mm/[dd]_{h_{2}} \\ar@(r,u)[]^{l_{A}} & \\\\\n" \
871
+ "B \\ar[r]^{g} & C \\ar@(r,u)[]^{l_{C}} \\\\\n" \
872
+ "D \\ar[u]_{k} \\ar@/^7mm/[uu]^{h} \\ar@/^11mm/[uu]^{h_{1}} " \
873
+ "\\ar@(l,d)[]^{l_{D}} & \n" \
874
+ "}\n"
875
+
876
+ # The same diagram with two "loop" morphisms per object.
877
+ l_A_ = NamedMorphism(A, A, "n_A")
878
+ l_D_ = NamedMorphism(D, D, "n_D")
879
+ l_C_ = NamedMorphism(C, C, "n_C")
880
+ d = Diagram([f, g, h, k, h1, h2, l_A, l_D, l_C, l_A_, l_D_, l_C_])
881
+ grid = DiagramGrid(d)
882
+ drawer = XypicDiagramDrawer()
883
+ assert drawer.draw(d, grid) == "\\xymatrix{\n" \
884
+ "A \\ar[r]_{f} \\ar@/^3mm/[rr]^{h_{2}} \\ar@(u,l)[]^{l_{A}} " \
885
+ "\\ar@/^3mm/@(l,d)[]^{n_{A}} & B \\ar[d]^{g} & D \\ar[l]^{k} " \
886
+ "\\ar@/_7mm/[ll]_{h} \\ar@/_11mm/[ll]_{h_{1}} \\ar@(r,u)[]^{l_{D}} " \
887
+ "\\ar@/^3mm/@(d,r)[]^{n_{D}} \\\\\n" \
888
+ "& C \\ar@(l,d)[]^{l_{C}} \\ar@/^3mm/@(d,r)[]^{n_{C}} & \n" \
889
+ "}\n"
890
+
891
+ # The same diagram with two "loop" morphisms per object, transposed.
892
+ grid = DiagramGrid(d, transpose=True)
893
+ drawer = XypicDiagramDrawer()
894
+ assert drawer.draw(d, grid) == "\\xymatrix{\n" \
895
+ "A \\ar[d]^{f} \\ar@/_3mm/[dd]_{h_{2}} \\ar@(r,u)[]^{l_{A}} " \
896
+ "\\ar@/^3mm/@(u,l)[]^{n_{A}} & \\\\\n" \
897
+ "B \\ar[r]^{g} & C \\ar@(r,u)[]^{l_{C}} \\ar@/^3mm/@(d,r)[]^{n_{C}} \\\\\n" \
898
+ "D \\ar[u]_{k} \\ar@/^7mm/[uu]^{h} \\ar@/^11mm/[uu]^{h_{1}} " \
899
+ "\\ar@(l,d)[]^{l_{D}} \\ar@/^3mm/@(d,r)[]^{n_{D}} & \n" \
900
+ "}\n"
901
+
902
+
903
+ def test_xypic_draw_diagram():
904
+ # A linear diagram.
905
+ A = Object("A")
906
+ B = Object("B")
907
+ C = Object("C")
908
+ D = Object("D")
909
+ E = Object("E")
910
+
911
+ f = NamedMorphism(A, B, "f")
912
+ g = NamedMorphism(B, C, "g")
913
+ h = NamedMorphism(C, D, "h")
914
+ i = NamedMorphism(D, E, "i")
915
+ d = Diagram([f, g, h, i])
916
+
917
+ grid = DiagramGrid(d, layout="sequential")
918
+ drawer = XypicDiagramDrawer()
919
+ assert drawer.draw(d, grid) == xypic_draw_diagram(d, layout="sequential")
llmeval-env/lib/python3.10/site-packages/sympy/plotting/__init__.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .plot import plot_backends
2
+ from .plot_implicit import plot_implicit
3
+ from .textplot import textplot
4
+ from .pygletplot import PygletPlot
5
+ from .plot import PlotGrid
6
+ from .plot import (plot, plot_parametric, plot3d, plot3d_parametric_surface,
7
+ plot3d_parametric_line, plot_contour)
8
+
9
+ __all__ = [
10
+ 'plot_backends',
11
+
12
+ 'plot_implicit',
13
+
14
+ 'textplot',
15
+
16
+ 'PygletPlot',
17
+
18
+ 'PlotGrid',
19
+
20
+ 'plot', 'plot_parametric', 'plot3d', 'plot3d_parametric_surface',
21
+ 'plot3d_parametric_line', 'plot_contour'
22
+ ]
llmeval-env/lib/python3.10/site-packages/sympy/plotting/__pycache__/experimental_lambdify.cpython-310.pyc ADDED
Binary file (14.3 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/plotting/__pycache__/plot_implicit.cpython-310.pyc ADDED
Binary file (12.9 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/plotting/experimental_lambdify.py ADDED
@@ -0,0 +1,643 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ rewrite of lambdify - This stuff is not stable at all.
2
+
3
+ It is for internal use in the new plotting module.
4
+ It may (will! see the Q'n'A in the source) be rewritten.
5
+
6
+ It's completely self contained. Especially it does not use lambdarepr.
7
+
8
+ It does not aim to replace the current lambdify. Most importantly it will never
9
+ ever support anything else than SymPy expressions (no Matrices, dictionaries
10
+ and so on).
11
+ """
12
+
13
+
14
+ import re
15
+ from sympy.core.numbers import (I, NumberSymbol, oo, zoo)
16
+ from sympy.core.symbol import Symbol
17
+ from sympy.utilities.iterables import numbered_symbols
18
+
19
+ # We parse the expression string into a tree that identifies functions. Then
20
+ # we translate the names of the functions and we translate also some strings
21
+ # that are not names of functions (all this according to translation
22
+ # dictionaries).
23
+ # If the translation goes to another module (like numpy) the
24
+ # module is imported and 'func' is translated to 'module.func'.
25
+ # If a function can not be translated, the inner nodes of that part of the
26
+ # tree are not translated. So if we have Integral(sqrt(x)), sqrt is not
27
+ # translated to np.sqrt and the Integral does not crash.
28
+ # A namespace for all this is generated by crawling the (func, args) tree of
29
+ # the expression. The creation of this namespace involves many ugly
30
+ # workarounds.
31
+ # The namespace consists of all the names needed for the SymPy expression and
32
+ # all the name of modules used for translation. Those modules are imported only
33
+ # as a name (import numpy as np) in order to keep the namespace small and
34
+ # manageable.
35
+
36
+ # Please, if there is a bug, do not try to fix it here! Rewrite this by using
37
+ # the method proposed in the last Q'n'A below. That way the new function will
38
+ # work just as well, be just as simple, but it wont need any new workarounds.
39
+ # If you insist on fixing it here, look at the workarounds in the function
40
+ # sympy_expression_namespace and in lambdify.
41
+
42
+ # Q: Why are you not using Python abstract syntax tree?
43
+ # A: Because it is more complicated and not much more powerful in this case.
44
+
45
+ # Q: What if I have Symbol('sin') or g=Function('f')?
46
+ # A: You will break the algorithm. We should use srepr to defend against this?
47
+ # The problem with Symbol('sin') is that it will be printed as 'sin'. The
48
+ # parser will distinguish it from the function 'sin' because functions are
49
+ # detected thanks to the opening parenthesis, but the lambda expression won't
50
+ # understand the difference if we have also the sin function.
51
+ # The solution (complicated) is to use srepr and maybe ast.
52
+ # The problem with the g=Function('f') is that it will be printed as 'f' but in
53
+ # the global namespace we have only 'g'. But as the same printer is used in the
54
+ # constructor of the namespace there will be no problem.
55
+
56
+ # Q: What if some of the printers are not printing as expected?
57
+ # A: The algorithm wont work. You must use srepr for those cases. But even
58
+ # srepr may not print well. All problems with printers should be considered
59
+ # bugs.
60
+
61
+ # Q: What about _imp_ functions?
62
+ # A: Those are taken care for by evalf. A special case treatment will work
63
+ # faster but it's not worth the code complexity.
64
+
65
+ # Q: Will ast fix all possible problems?
66
+ # A: No. You will always have to use some printer. Even srepr may not work in
67
+ # some cases. But if the printer does not work, that should be considered a
68
+ # bug.
69
+
70
+ # Q: Is there same way to fix all possible problems?
71
+ # A: Probably by constructing our strings ourself by traversing the (func,
72
+ # args) tree and creating the namespace at the same time. That actually sounds
73
+ # good.
74
+
75
+ from sympy.external import import_module
76
+ import warnings
77
+
78
+ #TODO debugging output
79
+
80
+
81
+ class vectorized_lambdify:
82
+ """ Return a sufficiently smart, vectorized and lambdified function.
83
+
84
+ Returns only reals.
85
+
86
+ Explanation
87
+ ===========
88
+
89
+ This function uses experimental_lambdify to created a lambdified
90
+ expression ready to be used with numpy. Many of the functions in SymPy
91
+ are not implemented in numpy so in some cases we resort to Python cmath or
92
+ even to evalf.
93
+
94
+ The following translations are tried:
95
+ only numpy complex
96
+ - on errors raised by SymPy trying to work with ndarray:
97
+ only Python cmath and then vectorize complex128
98
+
99
+ When using Python cmath there is no need for evalf or float/complex
100
+ because Python cmath calls those.
101
+
102
+ This function never tries to mix numpy directly with evalf because numpy
103
+ does not understand SymPy Float. If this is needed one can use the
104
+ float_wrap_evalf/complex_wrap_evalf options of experimental_lambdify or
105
+ better one can be explicit about the dtypes that numpy works with.
106
+ Check numpy bug http://projects.scipy.org/numpy/ticket/1013 to know what
107
+ types of errors to expect.
108
+ """
109
+ def __init__(self, args, expr):
110
+ self.args = args
111
+ self.expr = expr
112
+ self.np = import_module('numpy')
113
+
114
+ self.lambda_func_1 = experimental_lambdify(
115
+ args, expr, use_np=True)
116
+ self.vector_func_1 = self.lambda_func_1
117
+
118
+ self.lambda_func_2 = experimental_lambdify(
119
+ args, expr, use_python_cmath=True)
120
+ self.vector_func_2 = self.np.vectorize(
121
+ self.lambda_func_2, otypes=[complex])
122
+
123
+ self.vector_func = self.vector_func_1
124
+ self.failure = False
125
+
126
+ def __call__(self, *args):
127
+ np = self.np
128
+
129
+ try:
130
+ temp_args = (np.array(a, dtype=complex) for a in args)
131
+ results = self.vector_func(*temp_args)
132
+ results = np.ma.masked_where(
133
+ np.abs(results.imag) > 1e-7 * np.abs(results),
134
+ results.real, copy=False)
135
+ return results
136
+ except ValueError:
137
+ if self.failure:
138
+ raise
139
+
140
+ self.failure = True
141
+ self.vector_func = self.vector_func_2
142
+ warnings.warn(
143
+ 'The evaluation of the expression is problematic. '
144
+ 'We are trying a failback method that may still work. '
145
+ 'Please report this as a bug.')
146
+ return self.__call__(*args)
147
+
148
+
149
+ class lambdify:
150
+ """Returns the lambdified function.
151
+
152
+ Explanation
153
+ ===========
154
+
155
+ This function uses experimental_lambdify to create a lambdified
156
+ expression. It uses cmath to lambdify the expression. If the function
157
+ is not implemented in Python cmath, Python cmath calls evalf on those
158
+ functions.
159
+ """
160
+
161
+ def __init__(self, args, expr):
162
+ self.args = args
163
+ self.expr = expr
164
+ self.lambda_func_1 = experimental_lambdify(
165
+ args, expr, use_python_cmath=True, use_evalf=True)
166
+ self.lambda_func_2 = experimental_lambdify(
167
+ args, expr, use_python_math=True, use_evalf=True)
168
+ self.lambda_func_3 = experimental_lambdify(
169
+ args, expr, use_evalf=True, complex_wrap_evalf=True)
170
+ self.lambda_func = self.lambda_func_1
171
+ self.failure = False
172
+
173
+ def __call__(self, args):
174
+ try:
175
+ #The result can be sympy.Float. Hence wrap it with complex type.
176
+ result = complex(self.lambda_func(args))
177
+ if abs(result.imag) > 1e-7 * abs(result):
178
+ return None
179
+ return result.real
180
+ except (ZeroDivisionError, OverflowError):
181
+ return None
182
+ except TypeError as e:
183
+ if self.failure:
184
+ raise e
185
+
186
+ if self.lambda_func == self.lambda_func_1:
187
+ self.lambda_func = self.lambda_func_2
188
+ return self.__call__(args)
189
+
190
+ self.failure = True
191
+ self.lambda_func = self.lambda_func_3
192
+ warnings.warn(
193
+ 'The evaluation of the expression is problematic. '
194
+ 'We are trying a failback method that may still work. '
195
+ 'Please report this as a bug.', stacklevel=2)
196
+ return self.__call__(args)
197
+
198
+
199
+ def experimental_lambdify(*args, **kwargs):
200
+ l = Lambdifier(*args, **kwargs)
201
+ return l
202
+
203
+
204
+ class Lambdifier:
205
+ def __init__(self, args, expr, print_lambda=False, use_evalf=False,
206
+ float_wrap_evalf=False, complex_wrap_evalf=False,
207
+ use_np=False, use_python_math=False, use_python_cmath=False,
208
+ use_interval=False):
209
+
210
+ self.print_lambda = print_lambda
211
+ self.use_evalf = use_evalf
212
+ self.float_wrap_evalf = float_wrap_evalf
213
+ self.complex_wrap_evalf = complex_wrap_evalf
214
+ self.use_np = use_np
215
+ self.use_python_math = use_python_math
216
+ self.use_python_cmath = use_python_cmath
217
+ self.use_interval = use_interval
218
+
219
+ # Constructing the argument string
220
+ # - check
221
+ if not all(isinstance(a, Symbol) for a in args):
222
+ raise ValueError('The arguments must be Symbols.')
223
+ # - use numbered symbols
224
+ syms = numbered_symbols(exclude=expr.free_symbols)
225
+ newargs = [next(syms) for _ in args]
226
+ expr = expr.xreplace(dict(zip(args, newargs)))
227
+ argstr = ', '.join([str(a) for a in newargs])
228
+ del syms, newargs, args
229
+
230
+ # Constructing the translation dictionaries and making the translation
231
+ self.dict_str = self.get_dict_str()
232
+ self.dict_fun = self.get_dict_fun()
233
+ exprstr = str(expr)
234
+ newexpr = self.tree2str_translate(self.str2tree(exprstr))
235
+
236
+ # Constructing the namespaces
237
+ namespace = {}
238
+ namespace.update(self.sympy_atoms_namespace(expr))
239
+ namespace.update(self.sympy_expression_namespace(expr))
240
+ # XXX Workaround
241
+ # Ugly workaround because Pow(a,Half) prints as sqrt(a)
242
+ # and sympy_expression_namespace can not catch it.
243
+ from sympy.functions.elementary.miscellaneous import sqrt
244
+ namespace.update({'sqrt': sqrt})
245
+ namespace.update({'Eq': lambda x, y: x == y})
246
+ namespace.update({'Ne': lambda x, y: x != y})
247
+ # End workaround.
248
+ if use_python_math:
249
+ namespace.update({'math': __import__('math')})
250
+ if use_python_cmath:
251
+ namespace.update({'cmath': __import__('cmath')})
252
+ if use_np:
253
+ try:
254
+ namespace.update({'np': __import__('numpy')})
255
+ except ImportError:
256
+ raise ImportError(
257
+ 'experimental_lambdify failed to import numpy.')
258
+ if use_interval:
259
+ namespace.update({'imath': __import__(
260
+ 'sympy.plotting.intervalmath', fromlist=['intervalmath'])})
261
+ namespace.update({'math': __import__('math')})
262
+
263
+ # Construct the lambda
264
+ if self.print_lambda:
265
+ print(newexpr)
266
+ eval_str = 'lambda %s : ( %s )' % (argstr, newexpr)
267
+ self.eval_str = eval_str
268
+ exec("MYNEWLAMBDA = %s" % eval_str, namespace)
269
+ self.lambda_func = namespace['MYNEWLAMBDA']
270
+
271
+ def __call__(self, *args, **kwargs):
272
+ return self.lambda_func(*args, **kwargs)
273
+
274
+
275
+ ##############################################################################
276
+ # Dicts for translating from SymPy to other modules
277
+ ##############################################################################
278
+ ###
279
+ # builtins
280
+ ###
281
+ # Functions with different names in builtins
282
+ builtin_functions_different = {
283
+ 'Min': 'min',
284
+ 'Max': 'max',
285
+ 'Abs': 'abs',
286
+ }
287
+
288
+ # Strings that should be translated
289
+ builtin_not_functions = {
290
+ 'I': '1j',
291
+ # 'oo': '1e400',
292
+ }
293
+
294
+ ###
295
+ # numpy
296
+ ###
297
+
298
+ # Functions that are the same in numpy
299
+ numpy_functions_same = [
300
+ 'sin', 'cos', 'tan', 'sinh', 'cosh', 'tanh', 'exp', 'log',
301
+ 'sqrt', 'floor', 'conjugate',
302
+ ]
303
+
304
+ # Functions with different names in numpy
305
+ numpy_functions_different = {
306
+ "acos": "arccos",
307
+ "acosh": "arccosh",
308
+ "arg": "angle",
309
+ "asin": "arcsin",
310
+ "asinh": "arcsinh",
311
+ "atan": "arctan",
312
+ "atan2": "arctan2",
313
+ "atanh": "arctanh",
314
+ "ceiling": "ceil",
315
+ "im": "imag",
316
+ "ln": "log",
317
+ "Max": "amax",
318
+ "Min": "amin",
319
+ "re": "real",
320
+ "Abs": "abs",
321
+ }
322
+
323
+ # Strings that should be translated
324
+ numpy_not_functions = {
325
+ 'pi': 'np.pi',
326
+ 'oo': 'np.inf',
327
+ 'E': 'np.e',
328
+ }
329
+
330
+ ###
331
+ # Python math
332
+ ###
333
+
334
+ # Functions that are the same in math
335
+ math_functions_same = [
336
+ 'sin', 'cos', 'tan', 'asin', 'acos', 'atan', 'atan2',
337
+ 'sinh', 'cosh', 'tanh', 'asinh', 'acosh', 'atanh',
338
+ 'exp', 'log', 'erf', 'sqrt', 'floor', 'factorial', 'gamma',
339
+ ]
340
+
341
+ # Functions with different names in math
342
+ math_functions_different = {
343
+ 'ceiling': 'ceil',
344
+ 'ln': 'log',
345
+ 'loggamma': 'lgamma'
346
+ }
347
+
348
+ # Strings that should be translated
349
+ math_not_functions = {
350
+ 'pi': 'math.pi',
351
+ 'E': 'math.e',
352
+ }
353
+
354
+ ###
355
+ # Python cmath
356
+ ###
357
+
358
+ # Functions that are the same in cmath
359
+ cmath_functions_same = [
360
+ 'sin', 'cos', 'tan', 'asin', 'acos', 'atan',
361
+ 'sinh', 'cosh', 'tanh', 'asinh', 'acosh', 'atanh',
362
+ 'exp', 'log', 'sqrt',
363
+ ]
364
+
365
+ # Functions with different names in cmath
366
+ cmath_functions_different = {
367
+ 'ln': 'log',
368
+ 'arg': 'phase',
369
+ }
370
+
371
+ # Strings that should be translated
372
+ cmath_not_functions = {
373
+ 'pi': 'cmath.pi',
374
+ 'E': 'cmath.e',
375
+ }
376
+
377
+ ###
378
+ # intervalmath
379
+ ###
380
+
381
+ interval_not_functions = {
382
+ 'pi': 'math.pi',
383
+ 'E': 'math.e'
384
+ }
385
+
386
+ interval_functions_same = [
387
+ 'sin', 'cos', 'exp', 'tan', 'atan', 'log',
388
+ 'sqrt', 'cosh', 'sinh', 'tanh', 'floor',
389
+ 'acos', 'asin', 'acosh', 'asinh', 'atanh',
390
+ 'Abs', 'And', 'Or'
391
+ ]
392
+
393
+ interval_functions_different = {
394
+ 'Min': 'imin',
395
+ 'Max': 'imax',
396
+ 'ceiling': 'ceil',
397
+
398
+ }
399
+
400
+ ###
401
+ # mpmath, etc
402
+ ###
403
+ #TODO
404
+
405
+ ###
406
+ # Create the final ordered tuples of dictionaries
407
+ ###
408
+
409
+ # For strings
410
+ def get_dict_str(self):
411
+ dict_str = dict(self.builtin_not_functions)
412
+ if self.use_np:
413
+ dict_str.update(self.numpy_not_functions)
414
+ if self.use_python_math:
415
+ dict_str.update(self.math_not_functions)
416
+ if self.use_python_cmath:
417
+ dict_str.update(self.cmath_not_functions)
418
+ if self.use_interval:
419
+ dict_str.update(self.interval_not_functions)
420
+ return dict_str
421
+
422
+ # For functions
423
+ def get_dict_fun(self):
424
+ dict_fun = dict(self.builtin_functions_different)
425
+ if self.use_np:
426
+ for s in self.numpy_functions_same:
427
+ dict_fun[s] = 'np.' + s
428
+ for k, v in self.numpy_functions_different.items():
429
+ dict_fun[k] = 'np.' + v
430
+ if self.use_python_math:
431
+ for s in self.math_functions_same:
432
+ dict_fun[s] = 'math.' + s
433
+ for k, v in self.math_functions_different.items():
434
+ dict_fun[k] = 'math.' + v
435
+ if self.use_python_cmath:
436
+ for s in self.cmath_functions_same:
437
+ dict_fun[s] = 'cmath.' + s
438
+ for k, v in self.cmath_functions_different.items():
439
+ dict_fun[k] = 'cmath.' + v
440
+ if self.use_interval:
441
+ for s in self.interval_functions_same:
442
+ dict_fun[s] = 'imath.' + s
443
+ for k, v in self.interval_functions_different.items():
444
+ dict_fun[k] = 'imath.' + v
445
+ return dict_fun
446
+
447
+ ##############################################################################
448
+ # The translator functions, tree parsers, etc.
449
+ ##############################################################################
450
+
451
+ def str2tree(self, exprstr):
452
+ """Converts an expression string to a tree.
453
+
454
+ Explanation
455
+ ===========
456
+
457
+ Functions are represented by ('func_name(', tree_of_arguments).
458
+ Other expressions are (head_string, mid_tree, tail_str).
459
+ Expressions that do not contain functions are directly returned.
460
+
461
+ Examples
462
+ ========
463
+
464
+ >>> from sympy.abc import x, y, z
465
+ >>> from sympy import Integral, sin
466
+ >>> from sympy.plotting.experimental_lambdify import Lambdifier
467
+ >>> str2tree = Lambdifier([x], x).str2tree
468
+
469
+ >>> str2tree(str(Integral(x, (x, 1, y))))
470
+ ('', ('Integral(', 'x, (x, 1, y)'), ')')
471
+ >>> str2tree(str(x+y))
472
+ 'x + y'
473
+ >>> str2tree(str(x+y*sin(z)+1))
474
+ ('x + y*', ('sin(', 'z'), ') + 1')
475
+ >>> str2tree('sin(y*(y + 1.1) + (sin(y)))')
476
+ ('', ('sin(', ('y*(y + 1.1) + (', ('sin(', 'y'), '))')), ')')
477
+ """
478
+ #matches the first 'function_name('
479
+ first_par = re.search(r'(\w+\()', exprstr)
480
+ if first_par is None:
481
+ return exprstr
482
+ else:
483
+ start = first_par.start()
484
+ end = first_par.end()
485
+ head = exprstr[:start]
486
+ func = exprstr[start:end]
487
+ tail = exprstr[end:]
488
+ count = 0
489
+ for i, c in enumerate(tail):
490
+ if c == '(':
491
+ count += 1
492
+ elif c == ')':
493
+ count -= 1
494
+ if count == -1:
495
+ break
496
+ func_tail = self.str2tree(tail[:i])
497
+ tail = self.str2tree(tail[i:])
498
+ return (head, (func, func_tail), tail)
499
+
500
+ @classmethod
501
+ def tree2str(cls, tree):
502
+ """Converts a tree to string without translations.
503
+
504
+ Examples
505
+ ========
506
+
507
+ >>> from sympy.abc import x, y, z
508
+ >>> from sympy import sin
509
+ >>> from sympy.plotting.experimental_lambdify import Lambdifier
510
+ >>> str2tree = Lambdifier([x], x).str2tree
511
+ >>> tree2str = Lambdifier([x], x).tree2str
512
+
513
+ >>> tree2str(str2tree(str(x+y*sin(z)+1)))
514
+ 'x + y*sin(z) + 1'
515
+ """
516
+ if isinstance(tree, str):
517
+ return tree
518
+ else:
519
+ return ''.join(map(cls.tree2str, tree))
520
+
521
+ def tree2str_translate(self, tree):
522
+ """Converts a tree to string with translations.
523
+
524
+ Explanation
525
+ ===========
526
+
527
+ Function names are translated by translate_func.
528
+ Other strings are translated by translate_str.
529
+ """
530
+ if isinstance(tree, str):
531
+ return self.translate_str(tree)
532
+ elif isinstance(tree, tuple) and len(tree) == 2:
533
+ return self.translate_func(tree[0][:-1], tree[1])
534
+ else:
535
+ return ''.join([self.tree2str_translate(t) for t in tree])
536
+
537
+ def translate_str(self, estr):
538
+ """Translate substrings of estr using in order the dictionaries in
539
+ dict_tuple_str."""
540
+ for pattern, repl in self.dict_str.items():
541
+ estr = re.sub(pattern, repl, estr)
542
+ return estr
543
+
544
+ def translate_func(self, func_name, argtree):
545
+ """Translate function names and the tree of arguments.
546
+
547
+ Explanation
548
+ ===========
549
+
550
+ If the function name is not in the dictionaries of dict_tuple_fun then the
551
+ function is surrounded by a float((...).evalf()).
552
+
553
+ The use of float is necessary as np.<function>(sympy.Float(..)) raises an
554
+ error."""
555
+ if func_name in self.dict_fun:
556
+ new_name = self.dict_fun[func_name]
557
+ argstr = self.tree2str_translate(argtree)
558
+ return new_name + '(' + argstr
559
+ elif func_name in ['Eq', 'Ne']:
560
+ op = {'Eq': '==', 'Ne': '!='}
561
+ return "(lambda x, y: x {} y)({}".format(op[func_name], self.tree2str_translate(argtree))
562
+ else:
563
+ template = '(%s(%s)).evalf(' if self.use_evalf else '%s(%s'
564
+ if self.float_wrap_evalf:
565
+ template = 'float(%s)' % template
566
+ elif self.complex_wrap_evalf:
567
+ template = 'complex(%s)' % template
568
+
569
+ # Wrapping should only happen on the outermost expression, which
570
+ # is the only thing we know will be a number.
571
+ float_wrap_evalf = self.float_wrap_evalf
572
+ complex_wrap_evalf = self.complex_wrap_evalf
573
+ self.float_wrap_evalf = False
574
+ self.complex_wrap_evalf = False
575
+ ret = template % (func_name, self.tree2str_translate(argtree))
576
+ self.float_wrap_evalf = float_wrap_evalf
577
+ self.complex_wrap_evalf = complex_wrap_evalf
578
+ return ret
579
+
580
+ ##############################################################################
581
+ # The namespace constructors
582
+ ##############################################################################
583
+
584
+ @classmethod
585
+ def sympy_expression_namespace(cls, expr):
586
+ """Traverses the (func, args) tree of an expression and creates a SymPy
587
+ namespace. All other modules are imported only as a module name. That way
588
+ the namespace is not polluted and rests quite small. It probably causes much
589
+ more variable lookups and so it takes more time, but there are no tests on
590
+ that for the moment."""
591
+ if expr is None:
592
+ return {}
593
+ else:
594
+ funcname = str(expr.func)
595
+ # XXX Workaround
596
+ # Here we add an ugly workaround because str(func(x))
597
+ # is not always the same as str(func). Eg
598
+ # >>> str(Integral(x))
599
+ # "Integral(x)"
600
+ # >>> str(Integral)
601
+ # "<class 'sympy.integrals.integrals.Integral'>"
602
+ # >>> str(sqrt(x))
603
+ # "sqrt(x)"
604
+ # >>> str(sqrt)
605
+ # "<function sqrt at 0x3d92de8>"
606
+ # >>> str(sin(x))
607
+ # "sin(x)"
608
+ # >>> str(sin)
609
+ # "sin"
610
+ # Either one of those can be used but not all at the same time.
611
+ # The code considers the sin example as the right one.
612
+ regexlist = [
613
+ r'<class \'sympy[\w.]*?.([\w]*)\'>$',
614
+ # the example Integral
615
+ r'<function ([\w]*) at 0x[\w]*>$', # the example sqrt
616
+ ]
617
+ for r in regexlist:
618
+ m = re.match(r, funcname)
619
+ if m is not None:
620
+ funcname = m.groups()[0]
621
+ # End of the workaround
622
+ # XXX debug: print funcname
623
+ args_dict = {}
624
+ for a in expr.args:
625
+ if (isinstance(a, Symbol) or
626
+ isinstance(a, NumberSymbol) or
627
+ a in [I, zoo, oo]):
628
+ continue
629
+ else:
630
+ args_dict.update(cls.sympy_expression_namespace(a))
631
+ args_dict.update({funcname: expr.func})
632
+ return args_dict
633
+
634
+ @staticmethod
635
+ def sympy_atoms_namespace(expr):
636
+ """For no real reason this function is separated from
637
+ sympy_expression_namespace. It can be moved to it."""
638
+ atoms = expr.atoms(Symbol, NumberSymbol, I, zoo, oo)
639
+ d = {}
640
+ for a in atoms:
641
+ # XXX debug: print 'atom:' + str(a)
642
+ d[str(a)] = a
643
+ return d
llmeval-env/lib/python3.10/site-packages/sympy/plotting/intervalmath/__init__.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .interval_arithmetic import interval
2
+ from .lib_interval import (Abs, exp, log, log10, sin, cos, tan, sqrt,
3
+ imin, imax, sinh, cosh, tanh, acosh, asinh, atanh,
4
+ asin, acos, atan, ceil, floor, And, Or)
5
+
6
+ __all__ = [
7
+ 'interval',
8
+
9
+ 'Abs', 'exp', 'log', 'log10', 'sin', 'cos', 'tan', 'sqrt', 'imin', 'imax',
10
+ 'sinh', 'cosh', 'tanh', 'acosh', 'asinh', 'atanh', 'asin', 'acos', 'atan',
11
+ 'ceil', 'floor', 'And', 'Or',
12
+ ]
llmeval-env/lib/python3.10/site-packages/sympy/plotting/intervalmath/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (760 Bytes). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/plotting/intervalmath/__pycache__/interval_membership.cpython-310.pyc ADDED
Binary file (3.07 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/plotting/intervalmath/__pycache__/lib_interval.cpython-310.pyc ADDED
Binary file (9.61 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/plotting/intervalmath/interval_membership.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.logic import fuzzy_and, fuzzy_or, fuzzy_not, fuzzy_xor
2
+
3
+
4
+ class intervalMembership:
5
+ """Represents a boolean expression returned by the comparison of
6
+ the interval object.
7
+
8
+ Parameters
9
+ ==========
10
+
11
+ (a, b) : (bool, bool)
12
+ The first value determines the comparison as follows:
13
+ - True: If the comparison is True throughout the intervals.
14
+ - False: If the comparison is False throughout the intervals.
15
+ - None: If the comparison is True for some part of the intervals.
16
+
17
+ The second value is determined as follows:
18
+ - True: If both the intervals in comparison are valid.
19
+ - False: If at least one of the intervals is False, else
20
+ - None
21
+ """
22
+ def __init__(self, a, b):
23
+ self._wrapped = (a, b)
24
+
25
+ def __getitem__(self, i):
26
+ try:
27
+ return self._wrapped[i]
28
+ except IndexError:
29
+ raise IndexError(
30
+ "{} must be a valid indexing for the 2-tuple."
31
+ .format(i))
32
+
33
+ def __len__(self):
34
+ return 2
35
+
36
+ def __iter__(self):
37
+ return iter(self._wrapped)
38
+
39
+ def __str__(self):
40
+ return "intervalMembership({}, {})".format(*self)
41
+ __repr__ = __str__
42
+
43
+ def __and__(self, other):
44
+ if not isinstance(other, intervalMembership):
45
+ raise ValueError(
46
+ "The comparison is not supported for {}.".format(other))
47
+
48
+ a1, b1 = self
49
+ a2, b2 = other
50
+ return intervalMembership(fuzzy_and([a1, a2]), fuzzy_and([b1, b2]))
51
+
52
+ def __or__(self, other):
53
+ if not isinstance(other, intervalMembership):
54
+ raise ValueError(
55
+ "The comparison is not supported for {}.".format(other))
56
+
57
+ a1, b1 = self
58
+ a2, b2 = other
59
+ return intervalMembership(fuzzy_or([a1, a2]), fuzzy_and([b1, b2]))
60
+
61
+ def __invert__(self):
62
+ a, b = self
63
+ return intervalMembership(fuzzy_not(a), b)
64
+
65
+ def __xor__(self, other):
66
+ if not isinstance(other, intervalMembership):
67
+ raise ValueError(
68
+ "The comparison is not supported for {}.".format(other))
69
+
70
+ a1, b1 = self
71
+ a2, b2 = other
72
+ return intervalMembership(fuzzy_xor([a1, a2]), fuzzy_and([b1, b2]))
73
+
74
+ def __eq__(self, other):
75
+ return self._wrapped == other
76
+
77
+ def __ne__(self, other):
78
+ return self._wrapped != other
llmeval-env/lib/python3.10/site-packages/sympy/plotting/intervalmath/lib_interval.py ADDED
@@ -0,0 +1,452 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ The module contains implemented functions for interval arithmetic."""
2
+ from functools import reduce
3
+
4
+ from sympy.plotting.intervalmath import interval
5
+ from sympy.external import import_module
6
+
7
+
8
+ def Abs(x):
9
+ if isinstance(x, (int, float)):
10
+ return interval(abs(x))
11
+ elif isinstance(x, interval):
12
+ if x.start < 0 and x.end > 0:
13
+ return interval(0, max(abs(x.start), abs(x.end)), is_valid=x.is_valid)
14
+ else:
15
+ return interval(abs(x.start), abs(x.end))
16
+ else:
17
+ raise NotImplementedError
18
+
19
+ #Monotonic
20
+
21
+
22
+ def exp(x):
23
+ """evaluates the exponential of an interval"""
24
+ np = import_module('numpy')
25
+ if isinstance(x, (int, float)):
26
+ return interval(np.exp(x), np.exp(x))
27
+ elif isinstance(x, interval):
28
+ return interval(np.exp(x.start), np.exp(x.end), is_valid=x.is_valid)
29
+ else:
30
+ raise NotImplementedError
31
+
32
+
33
+ #Monotonic
34
+ def log(x):
35
+ """evaluates the natural logarithm of an interval"""
36
+ np = import_module('numpy')
37
+ if isinstance(x, (int, float)):
38
+ if x <= 0:
39
+ return interval(-np.inf, np.inf, is_valid=False)
40
+ else:
41
+ return interval(np.log(x))
42
+ elif isinstance(x, interval):
43
+ if not x.is_valid:
44
+ return interval(-np.inf, np.inf, is_valid=x.is_valid)
45
+ elif x.end <= 0:
46
+ return interval(-np.inf, np.inf, is_valid=False)
47
+ elif x.start <= 0:
48
+ return interval(-np.inf, np.inf, is_valid=None)
49
+
50
+ return interval(np.log(x.start), np.log(x.end))
51
+ else:
52
+ raise NotImplementedError
53
+
54
+
55
+ #Monotonic
56
+ def log10(x):
57
+ """evaluates the logarithm to the base 10 of an interval"""
58
+ np = import_module('numpy')
59
+ if isinstance(x, (int, float)):
60
+ if x <= 0:
61
+ return interval(-np.inf, np.inf, is_valid=False)
62
+ else:
63
+ return interval(np.log10(x))
64
+ elif isinstance(x, interval):
65
+ if not x.is_valid:
66
+ return interval(-np.inf, np.inf, is_valid=x.is_valid)
67
+ elif x.end <= 0:
68
+ return interval(-np.inf, np.inf, is_valid=False)
69
+ elif x.start <= 0:
70
+ return interval(-np.inf, np.inf, is_valid=None)
71
+ return interval(np.log10(x.start), np.log10(x.end))
72
+ else:
73
+ raise NotImplementedError
74
+
75
+
76
+ #Monotonic
77
+ def atan(x):
78
+ """evaluates the tan inverse of an interval"""
79
+ np = import_module('numpy')
80
+ if isinstance(x, (int, float)):
81
+ return interval(np.arctan(x))
82
+ elif isinstance(x, interval):
83
+ start = np.arctan(x.start)
84
+ end = np.arctan(x.end)
85
+ return interval(start, end, is_valid=x.is_valid)
86
+ else:
87
+ raise NotImplementedError
88
+
89
+
90
+ #periodic
91
+ def sin(x):
92
+ """evaluates the sine of an interval"""
93
+ np = import_module('numpy')
94
+ if isinstance(x, (int, float)):
95
+ return interval(np.sin(x))
96
+ elif isinstance(x, interval):
97
+ if not x.is_valid:
98
+ return interval(-1, 1, is_valid=x.is_valid)
99
+ na, __ = divmod(x.start, np.pi / 2.0)
100
+ nb, __ = divmod(x.end, np.pi / 2.0)
101
+ start = min(np.sin(x.start), np.sin(x.end))
102
+ end = max(np.sin(x.start), np.sin(x.end))
103
+ if nb - na > 4:
104
+ return interval(-1, 1, is_valid=x.is_valid)
105
+ elif na == nb:
106
+ return interval(start, end, is_valid=x.is_valid)
107
+ else:
108
+ if (na - 1) // 4 != (nb - 1) // 4:
109
+ #sin has max
110
+ end = 1
111
+ if (na - 3) // 4 != (nb - 3) // 4:
112
+ #sin has min
113
+ start = -1
114
+ return interval(start, end)
115
+ else:
116
+ raise NotImplementedError
117
+
118
+
119
+ #periodic
120
+ def cos(x):
121
+ """Evaluates the cos of an interval"""
122
+ np = import_module('numpy')
123
+ if isinstance(x, (int, float)):
124
+ return interval(np.sin(x))
125
+ elif isinstance(x, interval):
126
+ if not (np.isfinite(x.start) and np.isfinite(x.end)):
127
+ return interval(-1, 1, is_valid=x.is_valid)
128
+ na, __ = divmod(x.start, np.pi / 2.0)
129
+ nb, __ = divmod(x.end, np.pi / 2.0)
130
+ start = min(np.cos(x.start), np.cos(x.end))
131
+ end = max(np.cos(x.start), np.cos(x.end))
132
+ if nb - na > 4:
133
+ #differ more than 2*pi
134
+ return interval(-1, 1, is_valid=x.is_valid)
135
+ elif na == nb:
136
+ #in the same quadarant
137
+ return interval(start, end, is_valid=x.is_valid)
138
+ else:
139
+ if (na) // 4 != (nb) // 4:
140
+ #cos has max
141
+ end = 1
142
+ if (na - 2) // 4 != (nb - 2) // 4:
143
+ #cos has min
144
+ start = -1
145
+ return interval(start, end, is_valid=x.is_valid)
146
+ else:
147
+ raise NotImplementedError
148
+
149
+
150
+ def tan(x):
151
+ """Evaluates the tan of an interval"""
152
+ return sin(x) / cos(x)
153
+
154
+
155
+ #Monotonic
156
+ def sqrt(x):
157
+ """Evaluates the square root of an interval"""
158
+ np = import_module('numpy')
159
+ if isinstance(x, (int, float)):
160
+ if x > 0:
161
+ return interval(np.sqrt(x))
162
+ else:
163
+ return interval(-np.inf, np.inf, is_valid=False)
164
+ elif isinstance(x, interval):
165
+ #Outside the domain
166
+ if x.end < 0:
167
+ return interval(-np.inf, np.inf, is_valid=False)
168
+ #Partially outside the domain
169
+ elif x.start < 0:
170
+ return interval(-np.inf, np.inf, is_valid=None)
171
+ else:
172
+ return interval(np.sqrt(x.start), np.sqrt(x.end),
173
+ is_valid=x.is_valid)
174
+ else:
175
+ raise NotImplementedError
176
+
177
+
178
+ def imin(*args):
179
+ """Evaluates the minimum of a list of intervals"""
180
+ np = import_module('numpy')
181
+ if not all(isinstance(arg, (int, float, interval)) for arg in args):
182
+ return NotImplementedError
183
+ else:
184
+ new_args = [a for a in args if isinstance(a, (int, float))
185
+ or a.is_valid]
186
+ if len(new_args) == 0:
187
+ if all(a.is_valid is False for a in args):
188
+ return interval(-np.inf, np.inf, is_valid=False)
189
+ else:
190
+ return interval(-np.inf, np.inf, is_valid=None)
191
+ start_array = [a if isinstance(a, (int, float)) else a.start
192
+ for a in new_args]
193
+
194
+ end_array = [a if isinstance(a, (int, float)) else a.end
195
+ for a in new_args]
196
+ return interval(min(start_array), min(end_array))
197
+
198
+
199
+ def imax(*args):
200
+ """Evaluates the maximum of a list of intervals"""
201
+ np = import_module('numpy')
202
+ if not all(isinstance(arg, (int, float, interval)) for arg in args):
203
+ return NotImplementedError
204
+ else:
205
+ new_args = [a for a in args if isinstance(a, (int, float))
206
+ or a.is_valid]
207
+ if len(new_args) == 0:
208
+ if all(a.is_valid is False for a in args):
209
+ return interval(-np.inf, np.inf, is_valid=False)
210
+ else:
211
+ return interval(-np.inf, np.inf, is_valid=None)
212
+ start_array = [a if isinstance(a, (int, float)) else a.start
213
+ for a in new_args]
214
+
215
+ end_array = [a if isinstance(a, (int, float)) else a.end
216
+ for a in new_args]
217
+
218
+ return interval(max(start_array), max(end_array))
219
+
220
+
221
+ #Monotonic
222
+ def sinh(x):
223
+ """Evaluates the hyperbolic sine of an interval"""
224
+ np = import_module('numpy')
225
+ if isinstance(x, (int, float)):
226
+ return interval(np.sinh(x), np.sinh(x))
227
+ elif isinstance(x, interval):
228
+ return interval(np.sinh(x.start), np.sinh(x.end), is_valid=x.is_valid)
229
+ else:
230
+ raise NotImplementedError
231
+
232
+
233
+ def cosh(x):
234
+ """Evaluates the hyperbolic cos of an interval"""
235
+ np = import_module('numpy')
236
+ if isinstance(x, (int, float)):
237
+ return interval(np.cosh(x), np.cosh(x))
238
+ elif isinstance(x, interval):
239
+ #both signs
240
+ if x.start < 0 and x.end > 0:
241
+ end = max(np.cosh(x.start), np.cosh(x.end))
242
+ return interval(1, end, is_valid=x.is_valid)
243
+ else:
244
+ #Monotonic
245
+ start = np.cosh(x.start)
246
+ end = np.cosh(x.end)
247
+ return interval(start, end, is_valid=x.is_valid)
248
+ else:
249
+ raise NotImplementedError
250
+
251
+
252
+ #Monotonic
253
+ def tanh(x):
254
+ """Evaluates the hyperbolic tan of an interval"""
255
+ np = import_module('numpy')
256
+ if isinstance(x, (int, float)):
257
+ return interval(np.tanh(x), np.tanh(x))
258
+ elif isinstance(x, interval):
259
+ return interval(np.tanh(x.start), np.tanh(x.end), is_valid=x.is_valid)
260
+ else:
261
+ raise NotImplementedError
262
+
263
+
264
+ def asin(x):
265
+ """Evaluates the inverse sine of an interval"""
266
+ np = import_module('numpy')
267
+ if isinstance(x, (int, float)):
268
+ #Outside the domain
269
+ if abs(x) > 1:
270
+ return interval(-np.inf, np.inf, is_valid=False)
271
+ else:
272
+ return interval(np.arcsin(x), np.arcsin(x))
273
+ elif isinstance(x, interval):
274
+ #Outside the domain
275
+ if x.is_valid is False or x.start > 1 or x.end < -1:
276
+ return interval(-np.inf, np.inf, is_valid=False)
277
+ #Partially outside the domain
278
+ elif x.start < -1 or x.end > 1:
279
+ return interval(-np.inf, np.inf, is_valid=None)
280
+ else:
281
+ start = np.arcsin(x.start)
282
+ end = np.arcsin(x.end)
283
+ return interval(start, end, is_valid=x.is_valid)
284
+
285
+
286
+ def acos(x):
287
+ """Evaluates the inverse cos of an interval"""
288
+ np = import_module('numpy')
289
+ if isinstance(x, (int, float)):
290
+ if abs(x) > 1:
291
+ #Outside the domain
292
+ return interval(-np.inf, np.inf, is_valid=False)
293
+ else:
294
+ return interval(np.arccos(x), np.arccos(x))
295
+ elif isinstance(x, interval):
296
+ #Outside the domain
297
+ if x.is_valid is False or x.start > 1 or x.end < -1:
298
+ return interval(-np.inf, np.inf, is_valid=False)
299
+ #Partially outside the domain
300
+ elif x.start < -1 or x.end > 1:
301
+ return interval(-np.inf, np.inf, is_valid=None)
302
+ else:
303
+ start = np.arccos(x.start)
304
+ end = np.arccos(x.end)
305
+ return interval(start, end, is_valid=x.is_valid)
306
+
307
+
308
+ def ceil(x):
309
+ """Evaluates the ceiling of an interval"""
310
+ np = import_module('numpy')
311
+ if isinstance(x, (int, float)):
312
+ return interval(np.ceil(x))
313
+ elif isinstance(x, interval):
314
+ if x.is_valid is False:
315
+ return interval(-np.inf, np.inf, is_valid=False)
316
+ else:
317
+ start = np.ceil(x.start)
318
+ end = np.ceil(x.end)
319
+ #Continuous over the interval
320
+ if start == end:
321
+ return interval(start, end, is_valid=x.is_valid)
322
+ else:
323
+ #Not continuous over the interval
324
+ return interval(start, end, is_valid=None)
325
+ else:
326
+ return NotImplementedError
327
+
328
+
329
+ def floor(x):
330
+ """Evaluates the floor of an interval"""
331
+ np = import_module('numpy')
332
+ if isinstance(x, (int, float)):
333
+ return interval(np.floor(x))
334
+ elif isinstance(x, interval):
335
+ if x.is_valid is False:
336
+ return interval(-np.inf, np.inf, is_valid=False)
337
+ else:
338
+ start = np.floor(x.start)
339
+ end = np.floor(x.end)
340
+ #continuous over the argument
341
+ if start == end:
342
+ return interval(start, end, is_valid=x.is_valid)
343
+ else:
344
+ #not continuous over the interval
345
+ return interval(start, end, is_valid=None)
346
+ else:
347
+ return NotImplementedError
348
+
349
+
350
+ def acosh(x):
351
+ """Evaluates the inverse hyperbolic cosine of an interval"""
352
+ np = import_module('numpy')
353
+ if isinstance(x, (int, float)):
354
+ #Outside the domain
355
+ if x < 1:
356
+ return interval(-np.inf, np.inf, is_valid=False)
357
+ else:
358
+ return interval(np.arccosh(x))
359
+ elif isinstance(x, interval):
360
+ #Outside the domain
361
+ if x.end < 1:
362
+ return interval(-np.inf, np.inf, is_valid=False)
363
+ #Partly outside the domain
364
+ elif x.start < 1:
365
+ return interval(-np.inf, np.inf, is_valid=None)
366
+ else:
367
+ start = np.arccosh(x.start)
368
+ end = np.arccosh(x.end)
369
+ return interval(start, end, is_valid=x.is_valid)
370
+ else:
371
+ return NotImplementedError
372
+
373
+
374
+ #Monotonic
375
+ def asinh(x):
376
+ """Evaluates the inverse hyperbolic sine of an interval"""
377
+ np = import_module('numpy')
378
+ if isinstance(x, (int, float)):
379
+ return interval(np.arcsinh(x))
380
+ elif isinstance(x, interval):
381
+ start = np.arcsinh(x.start)
382
+ end = np.arcsinh(x.end)
383
+ return interval(start, end, is_valid=x.is_valid)
384
+ else:
385
+ return NotImplementedError
386
+
387
+
388
+ def atanh(x):
389
+ """Evaluates the inverse hyperbolic tangent of an interval"""
390
+ np = import_module('numpy')
391
+ if isinstance(x, (int, float)):
392
+ #Outside the domain
393
+ if abs(x) >= 1:
394
+ return interval(-np.inf, np.inf, is_valid=False)
395
+ else:
396
+ return interval(np.arctanh(x))
397
+ elif isinstance(x, interval):
398
+ #outside the domain
399
+ if x.is_valid is False or x.start >= 1 or x.end <= -1:
400
+ return interval(-np.inf, np.inf, is_valid=False)
401
+ #partly outside the domain
402
+ elif x.start <= -1 or x.end >= 1:
403
+ return interval(-np.inf, np.inf, is_valid=None)
404
+ else:
405
+ start = np.arctanh(x.start)
406
+ end = np.arctanh(x.end)
407
+ return interval(start, end, is_valid=x.is_valid)
408
+ else:
409
+ return NotImplementedError
410
+
411
+
412
+ #Three valued logic for interval plotting.
413
+
414
+ def And(*args):
415
+ """Defines the three valued ``And`` behaviour for a 2-tuple of
416
+ three valued logic values"""
417
+ def reduce_and(cmp_intervala, cmp_intervalb):
418
+ if cmp_intervala[0] is False or cmp_intervalb[0] is False:
419
+ first = False
420
+ elif cmp_intervala[0] is None or cmp_intervalb[0] is None:
421
+ first = None
422
+ else:
423
+ first = True
424
+ if cmp_intervala[1] is False or cmp_intervalb[1] is False:
425
+ second = False
426
+ elif cmp_intervala[1] is None or cmp_intervalb[1] is None:
427
+ second = None
428
+ else:
429
+ second = True
430
+ return (first, second)
431
+ return reduce(reduce_and, args)
432
+
433
+
434
+ def Or(*args):
435
+ """Defines the three valued ``Or`` behaviour for a 2-tuple of
436
+ three valued logic values"""
437
+ def reduce_or(cmp_intervala, cmp_intervalb):
438
+ if cmp_intervala[0] is True or cmp_intervalb[0] is True:
439
+ first = True
440
+ elif cmp_intervala[0] is None or cmp_intervalb[0] is None:
441
+ first = None
442
+ else:
443
+ first = False
444
+
445
+ if cmp_intervala[1] is True or cmp_intervalb[1] is True:
446
+ second = True
447
+ elif cmp_intervala[1] is None or cmp_intervalb[1] is None:
448
+ second = None
449
+ else:
450
+ second = False
451
+ return (first, second)
452
+ return reduce(reduce_or, args)
llmeval-env/lib/python3.10/site-packages/sympy/plotting/plot.py ADDED
@@ -0,0 +1,2637 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Plotting module for SymPy.
2
+
3
+ A plot is represented by the ``Plot`` class that contains a reference to the
4
+ backend and a list of the data series to be plotted. The data series are
5
+ instances of classes meant to simplify getting points and meshes from SymPy
6
+ expressions. ``plot_backends`` is a dictionary with all the backends.
7
+
8
+ This module gives only the essential. For all the fancy stuff use directly
9
+ the backend. You can get the backend wrapper for every plot from the
10
+ ``_backend`` attribute. Moreover the data series classes have various useful
11
+ methods like ``get_points``, ``get_meshes``, etc, that may
12
+ be useful if you wish to use another plotting library.
13
+
14
+ Especially if you need publication ready graphs and this module is not enough
15
+ for you - just get the ``_backend`` attribute and add whatever you want
16
+ directly to it. In the case of matplotlib (the common way to graph data in
17
+ python) just copy ``_backend.fig`` which is the figure and ``_backend.ax``
18
+ which is the axis and work on them as you would on any other matplotlib object.
19
+
20
+ Simplicity of code takes much greater importance than performance. Do not use it
21
+ if you care at all about performance. A new backend instance is initialized
22
+ every time you call ``show()`` and the old one is left to the garbage collector.
23
+ """
24
+
25
+
26
+ from collections.abc import Callable
27
+
28
+
29
+ from sympy.core.basic import Basic
30
+ from sympy.core.containers import Tuple
31
+ from sympy.core.expr import Expr
32
+ from sympy.core.function import arity, Function
33
+ from sympy.core.symbol import (Dummy, Symbol)
34
+ from sympy.core.sympify import sympify
35
+ from sympy.external import import_module
36
+ from sympy.printing.latex import latex
37
+ from sympy.utilities.exceptions import sympy_deprecation_warning
38
+ from sympy.utilities.iterables import is_sequence
39
+ from .experimental_lambdify import (vectorized_lambdify, lambdify)
40
+
41
+ # N.B.
42
+ # When changing the minimum module version for matplotlib, please change
43
+ # the same in the `SymPyDocTestFinder`` in `sympy/testing/runtests.py`
44
+
45
+ # Backend specific imports - textplot
46
+ from sympy.plotting.textplot import textplot
47
+
48
+ # Global variable
49
+ # Set to False when running tests / doctests so that the plots don't show.
50
+ _show = True
51
+
52
+
53
+ def unset_show():
54
+ """
55
+ Disable show(). For use in the tests.
56
+ """
57
+ global _show
58
+ _show = False
59
+
60
+ def _str_or_latex(label):
61
+ if isinstance(label, Basic):
62
+ return latex(label, mode='inline')
63
+ return str(label)
64
+
65
+ ##############################################################################
66
+ # The public interface
67
+ ##############################################################################
68
+
69
+
70
+ class Plot:
71
+ """The central class of the plotting module.
72
+
73
+ Explanation
74
+ ===========
75
+
76
+ For interactive work the function :func:`plot()` is better suited.
77
+
78
+ This class permits the plotting of SymPy expressions using numerous
79
+ backends (:external:mod:`matplotlib`, textplot, the old pyglet module for SymPy, Google
80
+ charts api, etc).
81
+
82
+ The figure can contain an arbitrary number of plots of SymPy expressions,
83
+ lists of coordinates of points, etc. Plot has a private attribute _series that
84
+ contains all data series to be plotted (expressions for lines or surfaces,
85
+ lists of points, etc (all subclasses of BaseSeries)). Those data series are
86
+ instances of classes not imported by ``from sympy import *``.
87
+
88
+ The customization of the figure is on two levels. Global options that
89
+ concern the figure as a whole (e.g. title, xlabel, scale, etc) and
90
+ per-data series options (e.g. name) and aesthetics (e.g. color, point shape,
91
+ line type, etc.).
92
+
93
+ The difference between options and aesthetics is that an aesthetic can be
94
+ a function of the coordinates (or parameters in a parametric plot). The
95
+ supported values for an aesthetic are:
96
+
97
+ - None (the backend uses default values)
98
+ - a constant
99
+ - a function of one variable (the first coordinate or parameter)
100
+ - a function of two variables (the first and second coordinate or parameters)
101
+ - a function of three variables (only in nonparametric 3D plots)
102
+
103
+ Their implementation depends on the backend so they may not work in some
104
+ backends.
105
+
106
+ If the plot is parametric and the arity of the aesthetic function permits
107
+ it the aesthetic is calculated over parameters and not over coordinates.
108
+ If the arity does not permit calculation over parameters the calculation is
109
+ done over coordinates.
110
+
111
+ Only cartesian coordinates are supported for the moment, but you can use
112
+ the parametric plots to plot in polar, spherical and cylindrical
113
+ coordinates.
114
+
115
+ The arguments for the constructor Plot must be subclasses of BaseSeries.
116
+
117
+ Any global option can be specified as a keyword argument.
118
+
119
+ The global options for a figure are:
120
+
121
+ - title : str
122
+ - xlabel : str or Symbol
123
+ - ylabel : str or Symbol
124
+ - zlabel : str or Symbol
125
+ - legend : bool
126
+ - xscale : {'linear', 'log'}
127
+ - yscale : {'linear', 'log'}
128
+ - axis : bool
129
+ - axis_center : tuple of two floats or {'center', 'auto'}
130
+ - xlim : tuple of two floats
131
+ - ylim : tuple of two floats
132
+ - aspect_ratio : tuple of two floats or {'auto'}
133
+ - autoscale : bool
134
+ - margin : float in [0, 1]
135
+ - backend : {'default', 'matplotlib', 'text'} or a subclass of BaseBackend
136
+ - size : optional tuple of two floats, (width, height); default: None
137
+
138
+ The per data series options and aesthetics are:
139
+ There are none in the base series. See below for options for subclasses.
140
+
141
+ Some data series support additional aesthetics or options:
142
+
143
+ :class:`~.LineOver1DRangeSeries`, :class:`~.Parametric2DLineSeries`, and
144
+ :class:`~.Parametric3DLineSeries` support the following:
145
+
146
+ Aesthetics:
147
+
148
+ - line_color : string, or float, or function, optional
149
+ Specifies the color for the plot, which depends on the backend being
150
+ used.
151
+
152
+ For example, if ``MatplotlibBackend`` is being used, then
153
+ Matplotlib string colors are acceptable (``"red"``, ``"r"``,
154
+ ``"cyan"``, ``"c"``, ...).
155
+ Alternatively, we can use a float number, 0 < color < 1, wrapped in a
156
+ string (for example, ``line_color="0.5"``) to specify grayscale colors.
157
+ Alternatively, We can specify a function returning a single
158
+ float value: this will be used to apply a color-loop (for example,
159
+ ``line_color=lambda x: math.cos(x)``).
160
+
161
+ Note that by setting line_color, it would be applied simultaneously
162
+ to all the series.
163
+
164
+ Options:
165
+
166
+ - label : str
167
+ - steps : bool
168
+ - integers_only : bool
169
+
170
+ :class:`~.SurfaceOver2DRangeSeries` and :class:`~.ParametricSurfaceSeries`
171
+ support the following:
172
+
173
+ Aesthetics:
174
+
175
+ - surface_color : function which returns a float.
176
+ """
177
+
178
+ def __init__(self, *args,
179
+ title=None, xlabel=None, ylabel=None, zlabel=None, aspect_ratio='auto',
180
+ xlim=None, ylim=None, axis_center='auto', axis=True,
181
+ xscale='linear', yscale='linear', legend=False, autoscale=True,
182
+ margin=0, annotations=None, markers=None, rectangles=None,
183
+ fill=None, backend='default', size=None, **kwargs):
184
+ super().__init__()
185
+
186
+ # Options for the graph as a whole.
187
+ # The possible values for each option are described in the docstring of
188
+ # Plot. They are based purely on convention, no checking is done.
189
+ self.title = title
190
+ self.xlabel = xlabel
191
+ self.ylabel = ylabel
192
+ self.zlabel = zlabel
193
+ self.aspect_ratio = aspect_ratio
194
+ self.axis_center = axis_center
195
+ self.axis = axis
196
+ self.xscale = xscale
197
+ self.yscale = yscale
198
+ self.legend = legend
199
+ self.autoscale = autoscale
200
+ self.margin = margin
201
+ self.annotations = annotations
202
+ self.markers = markers
203
+ self.rectangles = rectangles
204
+ self.fill = fill
205
+
206
+ # Contains the data objects to be plotted. The backend should be smart
207
+ # enough to iterate over this list.
208
+ self._series = []
209
+ self._series.extend(args)
210
+
211
+ # The backend type. On every show() a new backend instance is created
212
+ # in self._backend which is tightly coupled to the Plot instance
213
+ # (thanks to the parent attribute of the backend).
214
+ if isinstance(backend, str):
215
+ self.backend = plot_backends[backend]
216
+ elif (type(backend) == type) and issubclass(backend, BaseBackend):
217
+ self.backend = backend
218
+ else:
219
+ raise TypeError(
220
+ "backend must be either a string or a subclass of BaseBackend")
221
+
222
+ is_real = \
223
+ lambda lim: all(getattr(i, 'is_real', True) for i in lim)
224
+ is_finite = \
225
+ lambda lim: all(getattr(i, 'is_finite', True) for i in lim)
226
+
227
+ # reduce code repetition
228
+ def check_and_set(t_name, t):
229
+ if t:
230
+ if not is_real(t):
231
+ raise ValueError(
232
+ "All numbers from {}={} must be real".format(t_name, t))
233
+ if not is_finite(t):
234
+ raise ValueError(
235
+ "All numbers from {}={} must be finite".format(t_name, t))
236
+ setattr(self, t_name, (float(t[0]), float(t[1])))
237
+
238
+ self.xlim = None
239
+ check_and_set("xlim", xlim)
240
+ self.ylim = None
241
+ check_and_set("ylim", ylim)
242
+ self.size = None
243
+ check_and_set("size", size)
244
+
245
+
246
+ def show(self):
247
+ # TODO move this to the backend (also for save)
248
+ if hasattr(self, '_backend'):
249
+ self._backend.close()
250
+ self._backend = self.backend(self)
251
+ self._backend.show()
252
+
253
+ def save(self, path):
254
+ if hasattr(self, '_backend'):
255
+ self._backend.close()
256
+ self._backend = self.backend(self)
257
+ self._backend.save(path)
258
+
259
+ def __str__(self):
260
+ series_strs = [('[%d]: ' % i) + str(s)
261
+ for i, s in enumerate(self._series)]
262
+ return 'Plot object containing:\n' + '\n'.join(series_strs)
263
+
264
+ def __getitem__(self, index):
265
+ return self._series[index]
266
+
267
+ def __setitem__(self, index, *args):
268
+ if len(args) == 1 and isinstance(args[0], BaseSeries):
269
+ self._series[index] = args
270
+
271
+ def __delitem__(self, index):
272
+ del self._series[index]
273
+
274
+ def append(self, arg):
275
+ """Adds an element from a plot's series to an existing plot.
276
+
277
+ Examples
278
+ ========
279
+
280
+ Consider two ``Plot`` objects, ``p1`` and ``p2``. To add the
281
+ second plot's first series object to the first, use the
282
+ ``append`` method, like so:
283
+
284
+ .. plot::
285
+ :format: doctest
286
+ :include-source: True
287
+
288
+ >>> from sympy import symbols
289
+ >>> from sympy.plotting import plot
290
+ >>> x = symbols('x')
291
+ >>> p1 = plot(x*x, show=False)
292
+ >>> p2 = plot(x, show=False)
293
+ >>> p1.append(p2[0])
294
+ >>> p1
295
+ Plot object containing:
296
+ [0]: cartesian line: x**2 for x over (-10.0, 10.0)
297
+ [1]: cartesian line: x for x over (-10.0, 10.0)
298
+ >>> p1.show()
299
+
300
+ See Also
301
+ ========
302
+
303
+ extend
304
+
305
+ """
306
+ if isinstance(arg, BaseSeries):
307
+ self._series.append(arg)
308
+ else:
309
+ raise TypeError('Must specify element of plot to append.')
310
+
311
+ def extend(self, arg):
312
+ """Adds all series from another plot.
313
+
314
+ Examples
315
+ ========
316
+
317
+ Consider two ``Plot`` objects, ``p1`` and ``p2``. To add the
318
+ second plot to the first, use the ``extend`` method, like so:
319
+
320
+ .. plot::
321
+ :format: doctest
322
+ :include-source: True
323
+
324
+ >>> from sympy import symbols
325
+ >>> from sympy.plotting import plot
326
+ >>> x = symbols('x')
327
+ >>> p1 = plot(x**2, show=False)
328
+ >>> p2 = plot(x, -x, show=False)
329
+ >>> p1.extend(p2)
330
+ >>> p1
331
+ Plot object containing:
332
+ [0]: cartesian line: x**2 for x over (-10.0, 10.0)
333
+ [1]: cartesian line: x for x over (-10.0, 10.0)
334
+ [2]: cartesian line: -x for x over (-10.0, 10.0)
335
+ >>> p1.show()
336
+
337
+ """
338
+ if isinstance(arg, Plot):
339
+ self._series.extend(arg._series)
340
+ elif is_sequence(arg):
341
+ self._series.extend(arg)
342
+ else:
343
+ raise TypeError('Expecting Plot or sequence of BaseSeries')
344
+
345
+
346
+ class PlotGrid:
347
+ """This class helps to plot subplots from already created SymPy plots
348
+ in a single figure.
349
+
350
+ Examples
351
+ ========
352
+
353
+ .. plot::
354
+ :context: close-figs
355
+ :format: doctest
356
+ :include-source: True
357
+
358
+ >>> from sympy import symbols
359
+ >>> from sympy.plotting import plot, plot3d, PlotGrid
360
+ >>> x, y = symbols('x, y')
361
+ >>> p1 = plot(x, x**2, x**3, (x, -5, 5))
362
+ >>> p2 = plot((x**2, (x, -6, 6)), (x, (x, -5, 5)))
363
+ >>> p3 = plot(x**3, (x, -5, 5))
364
+ >>> p4 = plot3d(x*y, (x, -5, 5), (y, -5, 5))
365
+
366
+ Plotting vertically in a single line:
367
+
368
+ .. plot::
369
+ :context: close-figs
370
+ :format: doctest
371
+ :include-source: True
372
+
373
+ >>> PlotGrid(2, 1, p1, p2)
374
+ PlotGrid object containing:
375
+ Plot[0]:Plot object containing:
376
+ [0]: cartesian line: x for x over (-5.0, 5.0)
377
+ [1]: cartesian line: x**2 for x over (-5.0, 5.0)
378
+ [2]: cartesian line: x**3 for x over (-5.0, 5.0)
379
+ Plot[1]:Plot object containing:
380
+ [0]: cartesian line: x**2 for x over (-6.0, 6.0)
381
+ [1]: cartesian line: x for x over (-5.0, 5.0)
382
+
383
+ Plotting horizontally in a single line:
384
+
385
+ .. plot::
386
+ :context: close-figs
387
+ :format: doctest
388
+ :include-source: True
389
+
390
+ >>> PlotGrid(1, 3, p2, p3, p4)
391
+ PlotGrid object containing:
392
+ Plot[0]:Plot object containing:
393
+ [0]: cartesian line: x**2 for x over (-6.0, 6.0)
394
+ [1]: cartesian line: x for x over (-5.0, 5.0)
395
+ Plot[1]:Plot object containing:
396
+ [0]: cartesian line: x**3 for x over (-5.0, 5.0)
397
+ Plot[2]:Plot object containing:
398
+ [0]: cartesian surface: x*y for x over (-5.0, 5.0) and y over (-5.0, 5.0)
399
+
400
+ Plotting in a grid form:
401
+
402
+ .. plot::
403
+ :context: close-figs
404
+ :format: doctest
405
+ :include-source: True
406
+
407
+ >>> PlotGrid(2, 2, p1, p2, p3, p4)
408
+ PlotGrid object containing:
409
+ Plot[0]:Plot object containing:
410
+ [0]: cartesian line: x for x over (-5.0, 5.0)
411
+ [1]: cartesian line: x**2 for x over (-5.0, 5.0)
412
+ [2]: cartesian line: x**3 for x over (-5.0, 5.0)
413
+ Plot[1]:Plot object containing:
414
+ [0]: cartesian line: x**2 for x over (-6.0, 6.0)
415
+ [1]: cartesian line: x for x over (-5.0, 5.0)
416
+ Plot[2]:Plot object containing:
417
+ [0]: cartesian line: x**3 for x over (-5.0, 5.0)
418
+ Plot[3]:Plot object containing:
419
+ [0]: cartesian surface: x*y for x over (-5.0, 5.0) and y over (-5.0, 5.0)
420
+
421
+ """
422
+ def __init__(self, nrows, ncolumns, *args, show=True, size=None, **kwargs):
423
+ """
424
+ Parameters
425
+ ==========
426
+
427
+ nrows :
428
+ The number of rows that should be in the grid of the
429
+ required subplot.
430
+ ncolumns :
431
+ The number of columns that should be in the grid
432
+ of the required subplot.
433
+
434
+ nrows and ncolumns together define the required grid.
435
+
436
+ Arguments
437
+ =========
438
+
439
+ A list of predefined plot objects entered in a row-wise sequence
440
+ i.e. plot objects which are to be in the top row of the required
441
+ grid are written first, then the second row objects and so on
442
+
443
+ Keyword arguments
444
+ =================
445
+
446
+ show : Boolean
447
+ The default value is set to ``True``. Set show to ``False`` and
448
+ the function will not display the subplot. The returned instance
449
+ of the ``PlotGrid`` class can then be used to save or display the
450
+ plot by calling the ``save()`` and ``show()`` methods
451
+ respectively.
452
+ size : (float, float), optional
453
+ A tuple in the form (width, height) in inches to specify the size of
454
+ the overall figure. The default value is set to ``None``, meaning
455
+ the size will be set by the default backend.
456
+ """
457
+ self.nrows = nrows
458
+ self.ncolumns = ncolumns
459
+ self._series = []
460
+ self.args = args
461
+ for arg in args:
462
+ self._series.append(arg._series)
463
+ self.backend = DefaultBackend
464
+ self.size = size
465
+ if show:
466
+ self.show()
467
+
468
+ def show(self):
469
+ if hasattr(self, '_backend'):
470
+ self._backend.close()
471
+ self._backend = self.backend(self)
472
+ self._backend.show()
473
+
474
+ def save(self, path):
475
+ if hasattr(self, '_backend'):
476
+ self._backend.close()
477
+ self._backend = self.backend(self)
478
+ self._backend.save(path)
479
+
480
+ def __str__(self):
481
+ plot_strs = [('Plot[%d]:' % i) + str(plot)
482
+ for i, plot in enumerate(self.args)]
483
+
484
+ return 'PlotGrid object containing:\n' + '\n'.join(plot_strs)
485
+
486
+
487
+ ##############################################################################
488
+ # Data Series
489
+ ##############################################################################
490
+ #TODO more general way to calculate aesthetics (see get_color_array)
491
+
492
+ ### The base class for all series
493
+ class BaseSeries:
494
+ """Base class for the data objects containing stuff to be plotted.
495
+
496
+ Explanation
497
+ ===========
498
+
499
+ The backend should check if it supports the data series that is given.
500
+ (e.g. TextBackend supports only LineOver1DRangeSeries).
501
+ It is the backend responsibility to know how to use the class of
502
+ data series that is given.
503
+
504
+ Some data series classes are grouped (using a class attribute like is_2Dline)
505
+ according to the api they present (based only on convention). The backend is
506
+ not obliged to use that api (e.g. LineOver1DRangeSeries belongs to the
507
+ is_2Dline group and presents the get_points method, but the
508
+ TextBackend does not use the get_points method).
509
+ """
510
+
511
+ # Some flags follow. The rationale for using flags instead of checking base
512
+ # classes is that setting multiple flags is simpler than multiple
513
+ # inheritance.
514
+
515
+ is_2Dline = False
516
+ # Some of the backends expect:
517
+ # - get_points returning 1D np.arrays list_x, list_y
518
+ # - get_color_array returning 1D np.array (done in Line2DBaseSeries)
519
+ # with the colors calculated at the points from get_points
520
+
521
+ is_3Dline = False
522
+ # Some of the backends expect:
523
+ # - get_points returning 1D np.arrays list_x, list_y, list_y
524
+ # - get_color_array returning 1D np.array (done in Line2DBaseSeries)
525
+ # with the colors calculated at the points from get_points
526
+
527
+ is_3Dsurface = False
528
+ # Some of the backends expect:
529
+ # - get_meshes returning mesh_x, mesh_y, mesh_z (2D np.arrays)
530
+ # - get_points an alias for get_meshes
531
+
532
+ is_contour = False
533
+ # Some of the backends expect:
534
+ # - get_meshes returning mesh_x, mesh_y, mesh_z (2D np.arrays)
535
+ # - get_points an alias for get_meshes
536
+
537
+ is_implicit = False
538
+ # Some of the backends expect:
539
+ # - get_meshes returning mesh_x (1D array), mesh_y(1D array,
540
+ # mesh_z (2D np.arrays)
541
+ # - get_points an alias for get_meshes
542
+ # Different from is_contour as the colormap in backend will be
543
+ # different
544
+
545
+ is_parametric = False
546
+ # The calculation of aesthetics expects:
547
+ # - get_parameter_points returning one or two np.arrays (1D or 2D)
548
+ # used for calculation aesthetics
549
+
550
+ def __init__(self):
551
+ super().__init__()
552
+
553
+ @property
554
+ def is_3D(self):
555
+ flags3D = [
556
+ self.is_3Dline,
557
+ self.is_3Dsurface
558
+ ]
559
+ return any(flags3D)
560
+
561
+ @property
562
+ def is_line(self):
563
+ flagslines = [
564
+ self.is_2Dline,
565
+ self.is_3Dline
566
+ ]
567
+ return any(flagslines)
568
+
569
+
570
+ ### 2D lines
571
+ class Line2DBaseSeries(BaseSeries):
572
+ """A base class for 2D lines.
573
+
574
+ - adding the label, steps and only_integers options
575
+ - making is_2Dline true
576
+ - defining get_segments and get_color_array
577
+ """
578
+
579
+ is_2Dline = True
580
+
581
+ _dim = 2
582
+
583
+ def __init__(self):
584
+ super().__init__()
585
+ self.label = None
586
+ self.steps = False
587
+ self.only_integers = False
588
+ self.line_color = None
589
+
590
+ def get_data(self):
591
+ """ Return lists of coordinates for plotting the line.
592
+
593
+ Returns
594
+ =======
595
+ x : list
596
+ List of x-coordinates
597
+
598
+ y : list
599
+ List of y-coordinates
600
+
601
+ z : list
602
+ List of z-coordinates in case of Parametric3DLineSeries
603
+ """
604
+ np = import_module('numpy')
605
+ points = self.get_points()
606
+ if self.steps is True:
607
+ if len(points) == 2:
608
+ x = np.array((points[0], points[0])).T.flatten()[1:]
609
+ y = np.array((points[1], points[1])).T.flatten()[:-1]
610
+ points = (x, y)
611
+ else:
612
+ x = np.repeat(points[0], 3)[2:]
613
+ y = np.repeat(points[1], 3)[:-2]
614
+ z = np.repeat(points[2], 3)[1:-1]
615
+ points = (x, y, z)
616
+ return points
617
+
618
+ def get_segments(self):
619
+ sympy_deprecation_warning(
620
+ """
621
+ The Line2DBaseSeries.get_segments() method is deprecated.
622
+
623
+ Instead, use the MatplotlibBackend.get_segments() method, or use
624
+ The get_points() or get_data() methods.
625
+ """,
626
+ deprecated_since_version="1.9",
627
+ active_deprecations_target="deprecated-get-segments")
628
+
629
+ np = import_module('numpy')
630
+ points = type(self).get_data(self)
631
+ points = np.ma.array(points).T.reshape(-1, 1, self._dim)
632
+ return np.ma.concatenate([points[:-1], points[1:]], axis=1)
633
+
634
+ def get_color_array(self):
635
+ np = import_module('numpy')
636
+ c = self.line_color
637
+ if hasattr(c, '__call__'):
638
+ f = np.vectorize(c)
639
+ nargs = arity(c)
640
+ if nargs == 1 and self.is_parametric:
641
+ x = self.get_parameter_points()
642
+ return f(centers_of_segments(x))
643
+ else:
644
+ variables = list(map(centers_of_segments, self.get_points()))
645
+ if nargs == 1:
646
+ return f(variables[0])
647
+ elif nargs == 2:
648
+ return f(*variables[:2])
649
+ else: # only if the line is 3D (otherwise raises an error)
650
+ return f(*variables)
651
+ else:
652
+ return c*np.ones(self.nb_of_points)
653
+
654
+
655
+ class List2DSeries(Line2DBaseSeries):
656
+ """Representation for a line consisting of list of points."""
657
+
658
+ def __init__(self, list_x, list_y):
659
+ np = import_module('numpy')
660
+ super().__init__()
661
+ self.list_x = np.array(list_x)
662
+ self.list_y = np.array(list_y)
663
+ self.label = 'list'
664
+
665
+ def __str__(self):
666
+ return 'list plot'
667
+
668
+ def get_points(self):
669
+ return (self.list_x, self.list_y)
670
+
671
+
672
+ class LineOver1DRangeSeries(Line2DBaseSeries):
673
+ """Representation for a line consisting of a SymPy expression over a range."""
674
+
675
+ def __init__(self, expr, var_start_end, **kwargs):
676
+ super().__init__()
677
+ self.expr = sympify(expr)
678
+ self.label = kwargs.get('label', None) or self.expr
679
+ self.var = sympify(var_start_end[0])
680
+ self.start = float(var_start_end[1])
681
+ self.end = float(var_start_end[2])
682
+ self.nb_of_points = kwargs.get('nb_of_points', 300)
683
+ self.adaptive = kwargs.get('adaptive', True)
684
+ self.depth = kwargs.get('depth', 12)
685
+ self.line_color = kwargs.get('line_color', None)
686
+ self.xscale = kwargs.get('xscale', 'linear')
687
+
688
+ def __str__(self):
689
+ return 'cartesian line: %s for %s over %s' % (
690
+ str(self.expr), str(self.var), str((self.start, self.end)))
691
+
692
+ def get_points(self):
693
+ """ Return lists of coordinates for plotting. Depending on the
694
+ ``adaptive`` option, this function will either use an adaptive algorithm
695
+ or it will uniformly sample the expression over the provided range.
696
+
697
+ Returns
698
+ =======
699
+ x : list
700
+ List of x-coordinates
701
+
702
+ y : list
703
+ List of y-coordinates
704
+
705
+
706
+ Explanation
707
+ ===========
708
+
709
+ The adaptive sampling is done by recursively checking if three
710
+ points are almost collinear. If they are not collinear, then more
711
+ points are added between those points.
712
+
713
+ References
714
+ ==========
715
+
716
+ .. [1] Adaptive polygonal approximation of parametric curves,
717
+ Luiz Henrique de Figueiredo.
718
+
719
+ """
720
+ if self.only_integers or not self.adaptive:
721
+ return self._uniform_sampling()
722
+ else:
723
+ f = lambdify([self.var], self.expr)
724
+ x_coords = []
725
+ y_coords = []
726
+ np = import_module('numpy')
727
+ def sample(p, q, depth):
728
+ """ Samples recursively if three points are almost collinear.
729
+ For depth < 6, points are added irrespective of whether they
730
+ satisfy the collinearity condition or not. The maximum depth
731
+ allowed is 12.
732
+ """
733
+ # Randomly sample to avoid aliasing.
734
+ random = 0.45 + np.random.rand() * 0.1
735
+ if self.xscale == 'log':
736
+ xnew = 10**(np.log10(p[0]) + random * (np.log10(q[0]) -
737
+ np.log10(p[0])))
738
+ else:
739
+ xnew = p[0] + random * (q[0] - p[0])
740
+ ynew = f(xnew)
741
+ new_point = np.array([xnew, ynew])
742
+
743
+ # Maximum depth
744
+ if depth > self.depth:
745
+ x_coords.append(q[0])
746
+ y_coords.append(q[1])
747
+
748
+ # Sample irrespective of whether the line is flat till the
749
+ # depth of 6. We are not using linspace to avoid aliasing.
750
+ elif depth < 6:
751
+ sample(p, new_point, depth + 1)
752
+ sample(new_point, q, depth + 1)
753
+
754
+ # Sample ten points if complex values are encountered
755
+ # at both ends. If there is a real value in between, then
756
+ # sample those points further.
757
+ elif p[1] is None and q[1] is None:
758
+ if self.xscale == 'log':
759
+ xarray = np.logspace(p[0], q[0], 10)
760
+ else:
761
+ xarray = np.linspace(p[0], q[0], 10)
762
+ yarray = list(map(f, xarray))
763
+ if not all(y is None for y in yarray):
764
+ for i in range(len(yarray) - 1):
765
+ if not (yarray[i] is None and yarray[i + 1] is None):
766
+ sample([xarray[i], yarray[i]],
767
+ [xarray[i + 1], yarray[i + 1]], depth + 1)
768
+
769
+ # Sample further if one of the end points in None (i.e. a
770
+ # complex value) or the three points are not almost collinear.
771
+ elif (p[1] is None or q[1] is None or new_point[1] is None
772
+ or not flat(p, new_point, q)):
773
+ sample(p, new_point, depth + 1)
774
+ sample(new_point, q, depth + 1)
775
+ else:
776
+ x_coords.append(q[0])
777
+ y_coords.append(q[1])
778
+
779
+ f_start = f(self.start)
780
+ f_end = f(self.end)
781
+ x_coords.append(self.start)
782
+ y_coords.append(f_start)
783
+ sample(np.array([self.start, f_start]),
784
+ np.array([self.end, f_end]), 0)
785
+
786
+ return (x_coords, y_coords)
787
+
788
+ def _uniform_sampling(self):
789
+ np = import_module('numpy')
790
+ if self.only_integers is True:
791
+ if self.xscale == 'log':
792
+ list_x = np.logspace(int(self.start), int(self.end),
793
+ num=int(self.end) - int(self.start) + 1)
794
+ else:
795
+ list_x = np.linspace(int(self.start), int(self.end),
796
+ num=int(self.end) - int(self.start) + 1)
797
+ else:
798
+ if self.xscale == 'log':
799
+ list_x = np.logspace(self.start, self.end, num=self.nb_of_points)
800
+ else:
801
+ list_x = np.linspace(self.start, self.end, num=self.nb_of_points)
802
+ f = vectorized_lambdify([self.var], self.expr)
803
+ list_y = f(list_x)
804
+ return (list_x, list_y)
805
+
806
+
807
+ class Parametric2DLineSeries(Line2DBaseSeries):
808
+ """Representation for a line consisting of two parametric SymPy expressions
809
+ over a range."""
810
+
811
+ is_parametric = True
812
+
813
+ def __init__(self, expr_x, expr_y, var_start_end, **kwargs):
814
+ super().__init__()
815
+ self.expr_x = sympify(expr_x)
816
+ self.expr_y = sympify(expr_y)
817
+ self.label = kwargs.get('label', None) or \
818
+ Tuple(self.expr_x, self.expr_y)
819
+ self.var = sympify(var_start_end[0])
820
+ self.start = float(var_start_end[1])
821
+ self.end = float(var_start_end[2])
822
+ self.nb_of_points = kwargs.get('nb_of_points', 300)
823
+ self.adaptive = kwargs.get('adaptive', True)
824
+ self.depth = kwargs.get('depth', 12)
825
+ self.line_color = kwargs.get('line_color', None)
826
+
827
+ def __str__(self):
828
+ return 'parametric cartesian line: (%s, %s) for %s over %s' % (
829
+ str(self.expr_x), str(self.expr_y), str(self.var),
830
+ str((self.start, self.end)))
831
+
832
+ def get_parameter_points(self):
833
+ np = import_module('numpy')
834
+ return np.linspace(self.start, self.end, num=self.nb_of_points)
835
+
836
+ def _uniform_sampling(self):
837
+ param = self.get_parameter_points()
838
+ fx = vectorized_lambdify([self.var], self.expr_x)
839
+ fy = vectorized_lambdify([self.var], self.expr_y)
840
+ list_x = fx(param)
841
+ list_y = fy(param)
842
+ return (list_x, list_y)
843
+
844
+ def get_points(self):
845
+ """ Return lists of coordinates for plotting. Depending on the
846
+ ``adaptive`` option, this function will either use an adaptive algorithm
847
+ or it will uniformly sample the expression over the provided range.
848
+
849
+ Returns
850
+ =======
851
+ x : list
852
+ List of x-coordinates
853
+
854
+ y : list
855
+ List of y-coordinates
856
+
857
+
858
+ Explanation
859
+ ===========
860
+
861
+ The adaptive sampling is done by recursively checking if three
862
+ points are almost collinear. If they are not collinear, then more
863
+ points are added between those points.
864
+
865
+ References
866
+ ==========
867
+
868
+ .. [1] Adaptive polygonal approximation of parametric curves,
869
+ Luiz Henrique de Figueiredo.
870
+
871
+ """
872
+ if not self.adaptive:
873
+ return self._uniform_sampling()
874
+
875
+ f_x = lambdify([self.var], self.expr_x)
876
+ f_y = lambdify([self.var], self.expr_y)
877
+ x_coords = []
878
+ y_coords = []
879
+
880
+ def sample(param_p, param_q, p, q, depth):
881
+ """ Samples recursively if three points are almost collinear.
882
+ For depth < 6, points are added irrespective of whether they
883
+ satisfy the collinearity condition or not. The maximum depth
884
+ allowed is 12.
885
+ """
886
+ # Randomly sample to avoid aliasing.
887
+ np = import_module('numpy')
888
+ random = 0.45 + np.random.rand() * 0.1
889
+ param_new = param_p + random * (param_q - param_p)
890
+ xnew = f_x(param_new)
891
+ ynew = f_y(param_new)
892
+ new_point = np.array([xnew, ynew])
893
+
894
+ # Maximum depth
895
+ if depth > self.depth:
896
+ x_coords.append(q[0])
897
+ y_coords.append(q[1])
898
+
899
+ # Sample irrespective of whether the line is flat till the
900
+ # depth of 6. We are not using linspace to avoid aliasing.
901
+ elif depth < 6:
902
+ sample(param_p, param_new, p, new_point, depth + 1)
903
+ sample(param_new, param_q, new_point, q, depth + 1)
904
+
905
+ # Sample ten points if complex values are encountered
906
+ # at both ends. If there is a real value in between, then
907
+ # sample those points further.
908
+ elif ((p[0] is None and q[1] is None) or
909
+ (p[1] is None and q[1] is None)):
910
+ param_array = np.linspace(param_p, param_q, 10)
911
+ x_array = list(map(f_x, param_array))
912
+ y_array = list(map(f_y, param_array))
913
+ if not all(x is None and y is None
914
+ for x, y in zip(x_array, y_array)):
915
+ for i in range(len(y_array) - 1):
916
+ if ((x_array[i] is not None and y_array[i] is not None) or
917
+ (x_array[i + 1] is not None and y_array[i + 1] is not None)):
918
+ point_a = [x_array[i], y_array[i]]
919
+ point_b = [x_array[i + 1], y_array[i + 1]]
920
+ sample(param_array[i], param_array[i], point_a,
921
+ point_b, depth + 1)
922
+
923
+ # Sample further if one of the end points in None (i.e. a complex
924
+ # value) or the three points are not almost collinear.
925
+ elif (p[0] is None or p[1] is None
926
+ or q[1] is None or q[0] is None
927
+ or not flat(p, new_point, q)):
928
+ sample(param_p, param_new, p, new_point, depth + 1)
929
+ sample(param_new, param_q, new_point, q, depth + 1)
930
+ else:
931
+ x_coords.append(q[0])
932
+ y_coords.append(q[1])
933
+
934
+ f_start_x = f_x(self.start)
935
+ f_start_y = f_y(self.start)
936
+ start = [f_start_x, f_start_y]
937
+ f_end_x = f_x(self.end)
938
+ f_end_y = f_y(self.end)
939
+ end = [f_end_x, f_end_y]
940
+ x_coords.append(f_start_x)
941
+ y_coords.append(f_start_y)
942
+ sample(self.start, self.end, start, end, 0)
943
+
944
+ return x_coords, y_coords
945
+
946
+
947
+ ### 3D lines
948
+ class Line3DBaseSeries(Line2DBaseSeries):
949
+ """A base class for 3D lines.
950
+
951
+ Most of the stuff is derived from Line2DBaseSeries."""
952
+
953
+ is_2Dline = False
954
+ is_3Dline = True
955
+ _dim = 3
956
+
957
+ def __init__(self):
958
+ super().__init__()
959
+
960
+
961
+ class Parametric3DLineSeries(Line3DBaseSeries):
962
+ """Representation for a 3D line consisting of three parametric SymPy
963
+ expressions and a range."""
964
+
965
+ is_parametric = True
966
+
967
+ def __init__(self, expr_x, expr_y, expr_z, var_start_end, **kwargs):
968
+ super().__init__()
969
+ self.expr_x = sympify(expr_x)
970
+ self.expr_y = sympify(expr_y)
971
+ self.expr_z = sympify(expr_z)
972
+ self.label = kwargs.get('label', None) or \
973
+ Tuple(self.expr_x, self.expr_y)
974
+ self.var = sympify(var_start_end[0])
975
+ self.start = float(var_start_end[1])
976
+ self.end = float(var_start_end[2])
977
+ self.nb_of_points = kwargs.get('nb_of_points', 300)
978
+ self.line_color = kwargs.get('line_color', None)
979
+ self._xlim = None
980
+ self._ylim = None
981
+ self._zlim = None
982
+
983
+ def __str__(self):
984
+ return '3D parametric cartesian line: (%s, %s, %s) for %s over %s' % (
985
+ str(self.expr_x), str(self.expr_y), str(self.expr_z),
986
+ str(self.var), str((self.start, self.end)))
987
+
988
+ def get_parameter_points(self):
989
+ np = import_module('numpy')
990
+ return np.linspace(self.start, self.end, num=self.nb_of_points)
991
+
992
+ def get_points(self):
993
+ np = import_module('numpy')
994
+ param = self.get_parameter_points()
995
+ fx = vectorized_lambdify([self.var], self.expr_x)
996
+ fy = vectorized_lambdify([self.var], self.expr_y)
997
+ fz = vectorized_lambdify([self.var], self.expr_z)
998
+
999
+ list_x = fx(param)
1000
+ list_y = fy(param)
1001
+ list_z = fz(param)
1002
+
1003
+ list_x = np.array(list_x, dtype=np.float64)
1004
+ list_y = np.array(list_y, dtype=np.float64)
1005
+ list_z = np.array(list_z, dtype=np.float64)
1006
+
1007
+ list_x = np.ma.masked_invalid(list_x)
1008
+ list_y = np.ma.masked_invalid(list_y)
1009
+ list_z = np.ma.masked_invalid(list_z)
1010
+
1011
+ self._xlim = (np.amin(list_x), np.amax(list_x))
1012
+ self._ylim = (np.amin(list_y), np.amax(list_y))
1013
+ self._zlim = (np.amin(list_z), np.amax(list_z))
1014
+ return list_x, list_y, list_z
1015
+
1016
+
1017
+ ### Surfaces
1018
+ class SurfaceBaseSeries(BaseSeries):
1019
+ """A base class for 3D surfaces."""
1020
+
1021
+ is_3Dsurface = True
1022
+
1023
+ def __init__(self):
1024
+ super().__init__()
1025
+ self.surface_color = None
1026
+
1027
+ def get_color_array(self):
1028
+ np = import_module('numpy')
1029
+ c = self.surface_color
1030
+ if isinstance(c, Callable):
1031
+ f = np.vectorize(c)
1032
+ nargs = arity(c)
1033
+ if self.is_parametric:
1034
+ variables = list(map(centers_of_faces, self.get_parameter_meshes()))
1035
+ if nargs == 1:
1036
+ return f(variables[0])
1037
+ elif nargs == 2:
1038
+ return f(*variables)
1039
+ variables = list(map(centers_of_faces, self.get_meshes()))
1040
+ if nargs == 1:
1041
+ return f(variables[0])
1042
+ elif nargs == 2:
1043
+ return f(*variables[:2])
1044
+ else:
1045
+ return f(*variables)
1046
+ else:
1047
+ if isinstance(self, SurfaceOver2DRangeSeries):
1048
+ return c*np.ones(min(self.nb_of_points_x, self.nb_of_points_y))
1049
+ else:
1050
+ return c*np.ones(min(self.nb_of_points_u, self.nb_of_points_v))
1051
+
1052
+
1053
+ class SurfaceOver2DRangeSeries(SurfaceBaseSeries):
1054
+ """Representation for a 3D surface consisting of a SymPy expression and 2D
1055
+ range."""
1056
+ def __init__(self, expr, var_start_end_x, var_start_end_y, **kwargs):
1057
+ super().__init__()
1058
+ self.expr = sympify(expr)
1059
+ self.var_x = sympify(var_start_end_x[0])
1060
+ self.start_x = float(var_start_end_x[1])
1061
+ self.end_x = float(var_start_end_x[2])
1062
+ self.var_y = sympify(var_start_end_y[0])
1063
+ self.start_y = float(var_start_end_y[1])
1064
+ self.end_y = float(var_start_end_y[2])
1065
+ self.nb_of_points_x = kwargs.get('nb_of_points_x', 50)
1066
+ self.nb_of_points_y = kwargs.get('nb_of_points_y', 50)
1067
+ self.surface_color = kwargs.get('surface_color', None)
1068
+
1069
+ self._xlim = (self.start_x, self.end_x)
1070
+ self._ylim = (self.start_y, self.end_y)
1071
+
1072
+ def __str__(self):
1073
+ return ('cartesian surface: %s for'
1074
+ ' %s over %s and %s over %s') % (
1075
+ str(self.expr),
1076
+ str(self.var_x),
1077
+ str((self.start_x, self.end_x)),
1078
+ str(self.var_y),
1079
+ str((self.start_y, self.end_y)))
1080
+
1081
+ def get_meshes(self):
1082
+ np = import_module('numpy')
1083
+ mesh_x, mesh_y = np.meshgrid(np.linspace(self.start_x, self.end_x,
1084
+ num=self.nb_of_points_x),
1085
+ np.linspace(self.start_y, self.end_y,
1086
+ num=self.nb_of_points_y))
1087
+ f = vectorized_lambdify((self.var_x, self.var_y), self.expr)
1088
+ mesh_z = f(mesh_x, mesh_y)
1089
+ mesh_z = np.array(mesh_z, dtype=np.float64)
1090
+ mesh_z = np.ma.masked_invalid(mesh_z)
1091
+ self._zlim = (np.amin(mesh_z), np.amax(mesh_z))
1092
+ return mesh_x, mesh_y, mesh_z
1093
+
1094
+
1095
+ class ParametricSurfaceSeries(SurfaceBaseSeries):
1096
+ """Representation for a 3D surface consisting of three parametric SymPy
1097
+ expressions and a range."""
1098
+
1099
+ is_parametric = True
1100
+
1101
+ def __init__(
1102
+ self, expr_x, expr_y, expr_z, var_start_end_u, var_start_end_v,
1103
+ **kwargs):
1104
+ super().__init__()
1105
+ self.expr_x = sympify(expr_x)
1106
+ self.expr_y = sympify(expr_y)
1107
+ self.expr_z = sympify(expr_z)
1108
+ self.var_u = sympify(var_start_end_u[0])
1109
+ self.start_u = float(var_start_end_u[1])
1110
+ self.end_u = float(var_start_end_u[2])
1111
+ self.var_v = sympify(var_start_end_v[0])
1112
+ self.start_v = float(var_start_end_v[1])
1113
+ self.end_v = float(var_start_end_v[2])
1114
+ self.nb_of_points_u = kwargs.get('nb_of_points_u', 50)
1115
+ self.nb_of_points_v = kwargs.get('nb_of_points_v', 50)
1116
+ self.surface_color = kwargs.get('surface_color', None)
1117
+
1118
+ def __str__(self):
1119
+ return ('parametric cartesian surface: (%s, %s, %s) for'
1120
+ ' %s over %s and %s over %s') % (
1121
+ str(self.expr_x),
1122
+ str(self.expr_y),
1123
+ str(self.expr_z),
1124
+ str(self.var_u),
1125
+ str((self.start_u, self.end_u)),
1126
+ str(self.var_v),
1127
+ str((self.start_v, self.end_v)))
1128
+
1129
+ def get_parameter_meshes(self):
1130
+ np = import_module('numpy')
1131
+ return np.meshgrid(np.linspace(self.start_u, self.end_u,
1132
+ num=self.nb_of_points_u),
1133
+ np.linspace(self.start_v, self.end_v,
1134
+ num=self.nb_of_points_v))
1135
+
1136
+ def get_meshes(self):
1137
+ np = import_module('numpy')
1138
+
1139
+ mesh_u, mesh_v = self.get_parameter_meshes()
1140
+ fx = vectorized_lambdify((self.var_u, self.var_v), self.expr_x)
1141
+ fy = vectorized_lambdify((self.var_u, self.var_v), self.expr_y)
1142
+ fz = vectorized_lambdify((self.var_u, self.var_v), self.expr_z)
1143
+
1144
+ mesh_x = fx(mesh_u, mesh_v)
1145
+ mesh_y = fy(mesh_u, mesh_v)
1146
+ mesh_z = fz(mesh_u, mesh_v)
1147
+
1148
+ mesh_x = np.array(mesh_x, dtype=np.float64)
1149
+ mesh_y = np.array(mesh_y, dtype=np.float64)
1150
+ mesh_z = np.array(mesh_z, dtype=np.float64)
1151
+
1152
+ mesh_x = np.ma.masked_invalid(mesh_x)
1153
+ mesh_y = np.ma.masked_invalid(mesh_y)
1154
+ mesh_z = np.ma.masked_invalid(mesh_z)
1155
+
1156
+ self._xlim = (np.amin(mesh_x), np.amax(mesh_x))
1157
+ self._ylim = (np.amin(mesh_y), np.amax(mesh_y))
1158
+ self._zlim = (np.amin(mesh_z), np.amax(mesh_z))
1159
+
1160
+ return mesh_x, mesh_y, mesh_z
1161
+
1162
+
1163
+ ### Contours
1164
+ class ContourSeries(BaseSeries):
1165
+ """Representation for a contour plot."""
1166
+ # The code is mostly repetition of SurfaceOver2DRange.
1167
+ # Presently used in contour_plot function
1168
+
1169
+ is_contour = True
1170
+
1171
+ def __init__(self, expr, var_start_end_x, var_start_end_y):
1172
+ super().__init__()
1173
+ self.nb_of_points_x = 50
1174
+ self.nb_of_points_y = 50
1175
+ self.expr = sympify(expr)
1176
+ self.var_x = sympify(var_start_end_x[0])
1177
+ self.start_x = float(var_start_end_x[1])
1178
+ self.end_x = float(var_start_end_x[2])
1179
+ self.var_y = sympify(var_start_end_y[0])
1180
+ self.start_y = float(var_start_end_y[1])
1181
+ self.end_y = float(var_start_end_y[2])
1182
+
1183
+ self.get_points = self.get_meshes
1184
+
1185
+ self._xlim = (self.start_x, self.end_x)
1186
+ self._ylim = (self.start_y, self.end_y)
1187
+
1188
+ def __str__(self):
1189
+ return ('contour: %s for '
1190
+ '%s over %s and %s over %s') % (
1191
+ str(self.expr),
1192
+ str(self.var_x),
1193
+ str((self.start_x, self.end_x)),
1194
+ str(self.var_y),
1195
+ str((self.start_y, self.end_y)))
1196
+
1197
+ def get_meshes(self):
1198
+ np = import_module('numpy')
1199
+ mesh_x, mesh_y = np.meshgrid(np.linspace(self.start_x, self.end_x,
1200
+ num=self.nb_of_points_x),
1201
+ np.linspace(self.start_y, self.end_y,
1202
+ num=self.nb_of_points_y))
1203
+ f = vectorized_lambdify((self.var_x, self.var_y), self.expr)
1204
+ return (mesh_x, mesh_y, f(mesh_x, mesh_y))
1205
+
1206
+
1207
+ ##############################################################################
1208
+ # Backends
1209
+ ##############################################################################
1210
+
1211
+ class BaseBackend:
1212
+ """Base class for all backends. A backend represents the plotting library,
1213
+ which implements the necessary functionalities in order to use SymPy
1214
+ plotting functions.
1215
+
1216
+ How the plotting module works:
1217
+
1218
+ 1. Whenever a plotting function is called, the provided expressions are
1219
+ processed and a list of instances of the :class:`BaseSeries` class is
1220
+ created, containing the necessary information to plot the expressions
1221
+ (e.g. the expression, ranges, series name, ...). Eventually, these
1222
+ objects will generate the numerical data to be plotted.
1223
+ 2. A :class:`~.Plot` object is instantiated, which stores the list of
1224
+ series and the main attributes of the plot (e.g. axis labels, title, ...).
1225
+ 3. When the ``show`` command is executed, a new backend is instantiated,
1226
+ which loops through each series object to generate and plot the
1227
+ numerical data. The backend is also going to set the axis labels, title,
1228
+ ..., according to the values stored in the Plot instance.
1229
+
1230
+ The backend should check if it supports the data series that it is given
1231
+ (e.g. :class:`TextBackend` supports only :class:`LineOver1DRangeSeries`).
1232
+
1233
+ It is the backend responsibility to know how to use the class of data series
1234
+ that it's given. Note that the current implementation of the ``*Series``
1235
+ classes is "matplotlib-centric": the numerical data returned by the
1236
+ ``get_points`` and ``get_meshes`` methods is meant to be used directly by
1237
+ Matplotlib. Therefore, the new backend will have to pre-process the
1238
+ numerical data to make it compatible with the chosen plotting library.
1239
+ Keep in mind that future SymPy versions may improve the ``*Series`` classes
1240
+ in order to return numerical data "non-matplotlib-centric", hence if you code
1241
+ a new backend you have the responsibility to check if its working on each
1242
+ SymPy release.
1243
+
1244
+ Please explore the :class:`MatplotlibBackend` source code to understand how a
1245
+ backend should be coded.
1246
+
1247
+ Methods
1248
+ =======
1249
+
1250
+ In order to be used by SymPy plotting functions, a backend must implement
1251
+ the following methods:
1252
+
1253
+ * show(self): used to loop over the data series, generate the numerical
1254
+ data, plot it and set the axis labels, title, ...
1255
+ * save(self, path): used to save the current plot to the specified file
1256
+ path.
1257
+ * close(self): used to close the current plot backend (note: some plotting
1258
+ library does not support this functionality. In that case, just raise a
1259
+ warning).
1260
+
1261
+ See also
1262
+ ========
1263
+
1264
+ MatplotlibBackend
1265
+ """
1266
+ def __init__(self, parent):
1267
+ super().__init__()
1268
+ self.parent = parent
1269
+
1270
+ def show(self):
1271
+ raise NotImplementedError
1272
+
1273
+ def save(self, path):
1274
+ raise NotImplementedError
1275
+
1276
+ def close(self):
1277
+ raise NotImplementedError
1278
+
1279
+
1280
+ # Don't have to check for the success of importing matplotlib in each case;
1281
+ # we will only be using this backend if we can successfully import matploblib
1282
+ class MatplotlibBackend(BaseBackend):
1283
+ """ This class implements the functionalities to use Matplotlib with SymPy
1284
+ plotting functions.
1285
+ """
1286
+ def __init__(self, parent):
1287
+ super().__init__(parent)
1288
+ self.matplotlib = import_module('matplotlib',
1289
+ import_kwargs={'fromlist': ['pyplot', 'cm', 'collections']},
1290
+ min_module_version='1.1.0', catch=(RuntimeError,))
1291
+ self.plt = self.matplotlib.pyplot
1292
+ self.cm = self.matplotlib.cm
1293
+ self.LineCollection = self.matplotlib.collections.LineCollection
1294
+ aspect = getattr(self.parent, 'aspect_ratio', 'auto')
1295
+ if aspect != 'auto':
1296
+ aspect = float(aspect[1]) / aspect[0]
1297
+
1298
+ if isinstance(self.parent, Plot):
1299
+ nrows, ncolumns = 1, 1
1300
+ series_list = [self.parent._series]
1301
+ elif isinstance(self.parent, PlotGrid):
1302
+ nrows, ncolumns = self.parent.nrows, self.parent.ncolumns
1303
+ series_list = self.parent._series
1304
+
1305
+ self.ax = []
1306
+ self.fig = self.plt.figure(figsize=parent.size)
1307
+
1308
+ for i, series in enumerate(series_list):
1309
+ are_3D = [s.is_3D for s in series]
1310
+
1311
+ if any(are_3D) and not all(are_3D):
1312
+ raise ValueError('The matplotlib backend cannot mix 2D and 3D.')
1313
+ elif all(are_3D):
1314
+ # mpl_toolkits.mplot3d is necessary for
1315
+ # projection='3d'
1316
+ mpl_toolkits = import_module('mpl_toolkits', # noqa
1317
+ import_kwargs={'fromlist': ['mplot3d']})
1318
+ self.ax.append(self.fig.add_subplot(nrows, ncolumns, i + 1, projection='3d', aspect=aspect))
1319
+
1320
+ elif not any(are_3D):
1321
+ self.ax.append(self.fig.add_subplot(nrows, ncolumns, i + 1, aspect=aspect))
1322
+ self.ax[i].spines['left'].set_position('zero')
1323
+ self.ax[i].spines['right'].set_color('none')
1324
+ self.ax[i].spines['bottom'].set_position('zero')
1325
+ self.ax[i].spines['top'].set_color('none')
1326
+ self.ax[i].xaxis.set_ticks_position('bottom')
1327
+ self.ax[i].yaxis.set_ticks_position('left')
1328
+
1329
+ @staticmethod
1330
+ def get_segments(x, y, z=None):
1331
+ """ Convert two list of coordinates to a list of segments to be used
1332
+ with Matplotlib's :external:class:`~matplotlib.collections.LineCollection`.
1333
+
1334
+ Parameters
1335
+ ==========
1336
+ x : list
1337
+ List of x-coordinates
1338
+
1339
+ y : list
1340
+ List of y-coordinates
1341
+
1342
+ z : list
1343
+ List of z-coordinates for a 3D line.
1344
+ """
1345
+ np = import_module('numpy')
1346
+ if z is not None:
1347
+ dim = 3
1348
+ points = (x, y, z)
1349
+ else:
1350
+ dim = 2
1351
+ points = (x, y)
1352
+ points = np.ma.array(points).T.reshape(-1, 1, dim)
1353
+ return np.ma.concatenate([points[:-1], points[1:]], axis=1)
1354
+
1355
+ def _process_series(self, series, ax, parent):
1356
+ np = import_module('numpy')
1357
+ mpl_toolkits = import_module(
1358
+ 'mpl_toolkits', import_kwargs={'fromlist': ['mplot3d']})
1359
+
1360
+ # XXX Workaround for matplotlib issue
1361
+ # https://github.com/matplotlib/matplotlib/issues/17130
1362
+ xlims, ylims, zlims = [], [], []
1363
+
1364
+ for s in series:
1365
+ # Create the collections
1366
+ if s.is_2Dline:
1367
+ x, y = s.get_data()
1368
+ if (isinstance(s.line_color, (int, float)) or
1369
+ callable(s.line_color)):
1370
+ segments = self.get_segments(x, y)
1371
+ collection = self.LineCollection(segments)
1372
+ collection.set_array(s.get_color_array())
1373
+ ax.add_collection(collection)
1374
+ else:
1375
+ lbl = _str_or_latex(s.label)
1376
+ line, = ax.plot(x, y, label=lbl, color=s.line_color)
1377
+ elif s.is_contour:
1378
+ ax.contour(*s.get_meshes())
1379
+ elif s.is_3Dline:
1380
+ x, y, z = s.get_data()
1381
+ if (isinstance(s.line_color, (int, float)) or
1382
+ callable(s.line_color)):
1383
+ art3d = mpl_toolkits.mplot3d.art3d
1384
+ segments = self.get_segments(x, y, z)
1385
+ collection = art3d.Line3DCollection(segments)
1386
+ collection.set_array(s.get_color_array())
1387
+ ax.add_collection(collection)
1388
+ else:
1389
+ lbl = _str_or_latex(s.label)
1390
+ ax.plot(x, y, z, label=lbl, color=s.line_color)
1391
+
1392
+ xlims.append(s._xlim)
1393
+ ylims.append(s._ylim)
1394
+ zlims.append(s._zlim)
1395
+ elif s.is_3Dsurface:
1396
+ x, y, z = s.get_meshes()
1397
+ collection = ax.plot_surface(x, y, z,
1398
+ cmap=getattr(self.cm, 'viridis', self.cm.jet),
1399
+ rstride=1, cstride=1, linewidth=0.1)
1400
+ if isinstance(s.surface_color, (float, int, Callable)):
1401
+ color_array = s.get_color_array()
1402
+ color_array = color_array.reshape(color_array.size)
1403
+ collection.set_array(color_array)
1404
+ else:
1405
+ collection.set_color(s.surface_color)
1406
+
1407
+ xlims.append(s._xlim)
1408
+ ylims.append(s._ylim)
1409
+ zlims.append(s._zlim)
1410
+ elif s.is_implicit:
1411
+ points = s.get_raster()
1412
+ if len(points) == 2:
1413
+ # interval math plotting
1414
+ x, y = _matplotlib_list(points[0])
1415
+ ax.fill(x, y, facecolor=s.line_color, edgecolor='None')
1416
+ else:
1417
+ # use contourf or contour depending on whether it is
1418
+ # an inequality or equality.
1419
+ # XXX: ``contour`` plots multiple lines. Should be fixed.
1420
+ ListedColormap = self.matplotlib.colors.ListedColormap
1421
+ colormap = ListedColormap(["white", s.line_color])
1422
+ xarray, yarray, zarray, plot_type = points
1423
+ if plot_type == 'contour':
1424
+ ax.contour(xarray, yarray, zarray, cmap=colormap)
1425
+ else:
1426
+ ax.contourf(xarray, yarray, zarray, cmap=colormap)
1427
+ else:
1428
+ raise NotImplementedError(
1429
+ '{} is not supported in the SymPy plotting module '
1430
+ 'with matplotlib backend. Please report this issue.'
1431
+ .format(ax))
1432
+
1433
+ Axes3D = mpl_toolkits.mplot3d.Axes3D
1434
+ if not isinstance(ax, Axes3D):
1435
+ ax.autoscale_view(
1436
+ scalex=ax.get_autoscalex_on(),
1437
+ scaley=ax.get_autoscaley_on())
1438
+ else:
1439
+ # XXX Workaround for matplotlib issue
1440
+ # https://github.com/matplotlib/matplotlib/issues/17130
1441
+ if xlims:
1442
+ xlims = np.array(xlims)
1443
+ xlim = (np.amin(xlims[:, 0]), np.amax(xlims[:, 1]))
1444
+ ax.set_xlim(xlim)
1445
+ else:
1446
+ ax.set_xlim([0, 1])
1447
+
1448
+ if ylims:
1449
+ ylims = np.array(ylims)
1450
+ ylim = (np.amin(ylims[:, 0]), np.amax(ylims[:, 1]))
1451
+ ax.set_ylim(ylim)
1452
+ else:
1453
+ ax.set_ylim([0, 1])
1454
+
1455
+ if zlims:
1456
+ zlims = np.array(zlims)
1457
+ zlim = (np.amin(zlims[:, 0]), np.amax(zlims[:, 1]))
1458
+ ax.set_zlim(zlim)
1459
+ else:
1460
+ ax.set_zlim([0, 1])
1461
+
1462
+ # Set global options.
1463
+ # TODO The 3D stuff
1464
+ # XXX The order of those is important.
1465
+ if parent.xscale and not isinstance(ax, Axes3D):
1466
+ ax.set_xscale(parent.xscale)
1467
+ if parent.yscale and not isinstance(ax, Axes3D):
1468
+ ax.set_yscale(parent.yscale)
1469
+ if not isinstance(ax, Axes3D) or self.matplotlib.__version__ >= '1.2.0': # XXX in the distant future remove this check
1470
+ ax.set_autoscale_on(parent.autoscale)
1471
+ if parent.axis_center:
1472
+ val = parent.axis_center
1473
+ if isinstance(ax, Axes3D):
1474
+ pass
1475
+ elif val == 'center':
1476
+ ax.spines['left'].set_position('center')
1477
+ ax.spines['bottom'].set_position('center')
1478
+ elif val == 'auto':
1479
+ xl, xh = ax.get_xlim()
1480
+ yl, yh = ax.get_ylim()
1481
+ pos_left = ('data', 0) if xl*xh <= 0 else 'center'
1482
+ pos_bottom = ('data', 0) if yl*yh <= 0 else 'center'
1483
+ ax.spines['left'].set_position(pos_left)
1484
+ ax.spines['bottom'].set_position(pos_bottom)
1485
+ else:
1486
+ ax.spines['left'].set_position(('data', val[0]))
1487
+ ax.spines['bottom'].set_position(('data', val[1]))
1488
+ if not parent.axis:
1489
+ ax.set_axis_off()
1490
+ if parent.legend:
1491
+ if ax.legend():
1492
+ ax.legend_.set_visible(parent.legend)
1493
+ if parent.margin:
1494
+ ax.set_xmargin(parent.margin)
1495
+ ax.set_ymargin(parent.margin)
1496
+ if parent.title:
1497
+ ax.set_title(parent.title)
1498
+ if parent.xlabel:
1499
+ xlbl = _str_or_latex(parent.xlabel)
1500
+ ax.set_xlabel(xlbl, position=(1, 0))
1501
+ if parent.ylabel:
1502
+ ylbl = _str_or_latex(parent.ylabel)
1503
+ ax.set_ylabel(ylbl, position=(0, 1))
1504
+ if isinstance(ax, Axes3D) and parent.zlabel:
1505
+ zlbl = _str_or_latex(parent.zlabel)
1506
+ ax.set_zlabel(zlbl, position=(0, 1))
1507
+ if parent.annotations:
1508
+ for a in parent.annotations:
1509
+ ax.annotate(**a)
1510
+ if parent.markers:
1511
+ for marker in parent.markers:
1512
+ # make a copy of the marker dictionary
1513
+ # so that it doesn't get altered
1514
+ m = marker.copy()
1515
+ args = m.pop('args')
1516
+ ax.plot(*args, **m)
1517
+ if parent.rectangles:
1518
+ for r in parent.rectangles:
1519
+ rect = self.matplotlib.patches.Rectangle(**r)
1520
+ ax.add_patch(rect)
1521
+ if parent.fill:
1522
+ ax.fill_between(**parent.fill)
1523
+
1524
+ # xlim and ylim should always be set at last so that plot limits
1525
+ # doesn't get altered during the process.
1526
+ if parent.xlim:
1527
+ ax.set_xlim(parent.xlim)
1528
+ if parent.ylim:
1529
+ ax.set_ylim(parent.ylim)
1530
+
1531
+
1532
+ def process_series(self):
1533
+ """
1534
+ Iterates over every ``Plot`` object and further calls
1535
+ _process_series()
1536
+ """
1537
+ parent = self.parent
1538
+ if isinstance(parent, Plot):
1539
+ series_list = [parent._series]
1540
+ else:
1541
+ series_list = parent._series
1542
+
1543
+ for i, (series, ax) in enumerate(zip(series_list, self.ax)):
1544
+ if isinstance(self.parent, PlotGrid):
1545
+ parent = self.parent.args[i]
1546
+ self._process_series(series, ax, parent)
1547
+
1548
+ def show(self):
1549
+ self.process_series()
1550
+ #TODO after fixing https://github.com/ipython/ipython/issues/1255
1551
+ # you can uncomment the next line and remove the pyplot.show() call
1552
+ #self.fig.show()
1553
+ if _show:
1554
+ self.fig.tight_layout()
1555
+ self.plt.show()
1556
+ else:
1557
+ self.close()
1558
+
1559
+ def save(self, path):
1560
+ self.process_series()
1561
+ self.fig.savefig(path)
1562
+
1563
+ def close(self):
1564
+ self.plt.close(self.fig)
1565
+
1566
+
1567
+ class TextBackend(BaseBackend):
1568
+ def __init__(self, parent):
1569
+ super().__init__(parent)
1570
+
1571
+ def show(self):
1572
+ if not _show:
1573
+ return
1574
+ if len(self.parent._series) != 1:
1575
+ raise ValueError(
1576
+ 'The TextBackend supports only one graph per Plot.')
1577
+ elif not isinstance(self.parent._series[0], LineOver1DRangeSeries):
1578
+ raise ValueError(
1579
+ 'The TextBackend supports only expressions over a 1D range')
1580
+ else:
1581
+ ser = self.parent._series[0]
1582
+ textplot(ser.expr, ser.start, ser.end)
1583
+
1584
+ def close(self):
1585
+ pass
1586
+
1587
+
1588
+ class DefaultBackend(BaseBackend):
1589
+ def __new__(cls, parent):
1590
+ matplotlib = import_module('matplotlib', min_module_version='1.1.0', catch=(RuntimeError,))
1591
+ if matplotlib:
1592
+ return MatplotlibBackend(parent)
1593
+ else:
1594
+ return TextBackend(parent)
1595
+
1596
+
1597
+ plot_backends = {
1598
+ 'matplotlib': MatplotlibBackend,
1599
+ 'text': TextBackend,
1600
+ 'default': DefaultBackend
1601
+ }
1602
+
1603
+
1604
+ ##############################################################################
1605
+ # Finding the centers of line segments or mesh faces
1606
+ ##############################################################################
1607
+
1608
+ def centers_of_segments(array):
1609
+ np = import_module('numpy')
1610
+ return np.mean(np.vstack((array[:-1], array[1:])), 0)
1611
+
1612
+
1613
+ def centers_of_faces(array):
1614
+ np = import_module('numpy')
1615
+ return np.mean(np.dstack((array[:-1, :-1],
1616
+ array[1:, :-1],
1617
+ array[:-1, 1:],
1618
+ array[:-1, :-1],
1619
+ )), 2)
1620
+
1621
+
1622
+ def flat(x, y, z, eps=1e-3):
1623
+ """Checks whether three points are almost collinear"""
1624
+ np = import_module('numpy')
1625
+ # Workaround plotting piecewise (#8577):
1626
+ # workaround for `lambdify` in `.experimental_lambdify` fails
1627
+ # to return numerical values in some cases. Lower-level fix
1628
+ # in `lambdify` is possible.
1629
+ vector_a = (x - y).astype(np.float64)
1630
+ vector_b = (z - y).astype(np.float64)
1631
+ dot_product = np.dot(vector_a, vector_b)
1632
+ vector_a_norm = np.linalg.norm(vector_a)
1633
+ vector_b_norm = np.linalg.norm(vector_b)
1634
+ cos_theta = dot_product / (vector_a_norm * vector_b_norm)
1635
+ return abs(cos_theta + 1) < eps
1636
+
1637
+
1638
+ def _matplotlib_list(interval_list):
1639
+ """
1640
+ Returns lists for matplotlib ``fill`` command from a list of bounding
1641
+ rectangular intervals
1642
+ """
1643
+ xlist = []
1644
+ ylist = []
1645
+ if len(interval_list):
1646
+ for intervals in interval_list:
1647
+ intervalx = intervals[0]
1648
+ intervaly = intervals[1]
1649
+ xlist.extend([intervalx.start, intervalx.start,
1650
+ intervalx.end, intervalx.end, None])
1651
+ ylist.extend([intervaly.start, intervaly.end,
1652
+ intervaly.end, intervaly.start, None])
1653
+ else:
1654
+ #XXX Ugly hack. Matplotlib does not accept empty lists for ``fill``
1655
+ xlist.extend((None, None, None, None))
1656
+ ylist.extend((None, None, None, None))
1657
+ return xlist, ylist
1658
+
1659
+
1660
+ ####New API for plotting module ####
1661
+
1662
+ # TODO: Add color arrays for plots.
1663
+ # TODO: Add more plotting options for 3d plots.
1664
+ # TODO: Adaptive sampling for 3D plots.
1665
+
1666
+ def plot(*args, show=True, **kwargs):
1667
+ """Plots a function of a single variable as a curve.
1668
+
1669
+ Parameters
1670
+ ==========
1671
+
1672
+ args :
1673
+ The first argument is the expression representing the function
1674
+ of single variable to be plotted.
1675
+
1676
+ The last argument is a 3-tuple denoting the range of the free
1677
+ variable. e.g. ``(x, 0, 5)``
1678
+
1679
+ Typical usage examples are in the following:
1680
+
1681
+ - Plotting a single expression with a single range.
1682
+ ``plot(expr, range, **kwargs)``
1683
+ - Plotting a single expression with the default range (-10, 10).
1684
+ ``plot(expr, **kwargs)``
1685
+ - Plotting multiple expressions with a single range.
1686
+ ``plot(expr1, expr2, ..., range, **kwargs)``
1687
+ - Plotting multiple expressions with multiple ranges.
1688
+ ``plot((expr1, range1), (expr2, range2), ..., **kwargs)``
1689
+
1690
+ It is best practice to specify range explicitly because default
1691
+ range may change in the future if a more advanced default range
1692
+ detection algorithm is implemented.
1693
+
1694
+ show : bool, optional
1695
+ The default value is set to ``True``. Set show to ``False`` and
1696
+ the function will not display the plot. The returned instance of
1697
+ the ``Plot`` class can then be used to save or display the plot
1698
+ by calling the ``save()`` and ``show()`` methods respectively.
1699
+
1700
+ line_color : string, or float, or function, optional
1701
+ Specifies the color for the plot.
1702
+ See ``Plot`` to see how to set color for the plots.
1703
+ Note that by setting ``line_color``, it would be applied simultaneously
1704
+ to all the series.
1705
+
1706
+ title : str, optional
1707
+ Title of the plot. It is set to the latex representation of
1708
+ the expression, if the plot has only one expression.
1709
+
1710
+ label : str, optional
1711
+ The label of the expression in the plot. It will be used when
1712
+ called with ``legend``. Default is the name of the expression.
1713
+ e.g. ``sin(x)``
1714
+
1715
+ xlabel : str or expression, optional
1716
+ Label for the x-axis.
1717
+
1718
+ ylabel : str or expression, optional
1719
+ Label for the y-axis.
1720
+
1721
+ xscale : 'linear' or 'log', optional
1722
+ Sets the scaling of the x-axis.
1723
+
1724
+ yscale : 'linear' or 'log', optional
1725
+ Sets the scaling of the y-axis.
1726
+
1727
+ axis_center : (float, float), optional
1728
+ Tuple of two floats denoting the coordinates of the center or
1729
+ {'center', 'auto'}
1730
+
1731
+ xlim : (float, float), optional
1732
+ Denotes the x-axis limits, ``(min, max)```.
1733
+
1734
+ ylim : (float, float), optional
1735
+ Denotes the y-axis limits, ``(min, max)```.
1736
+
1737
+ annotations : list, optional
1738
+ A list of dictionaries specifying the type of annotation
1739
+ required. The keys in the dictionary should be equivalent
1740
+ to the arguments of the :external:mod:`matplotlib`'s
1741
+ :external:meth:`~matplotlib.axes.Axes.annotate` method.
1742
+
1743
+ markers : list, optional
1744
+ A list of dictionaries specifying the type the markers required.
1745
+ The keys in the dictionary should be equivalent to the arguments
1746
+ of the :external:mod:`matplotlib`'s :external:func:`~matplotlib.pyplot.plot()` function
1747
+ along with the marker related keyworded arguments.
1748
+
1749
+ rectangles : list, optional
1750
+ A list of dictionaries specifying the dimensions of the
1751
+ rectangles to be plotted. The keys in the dictionary should be
1752
+ equivalent to the arguments of the :external:mod:`matplotlib`'s
1753
+ :external:class:`~matplotlib.patches.Rectangle` class.
1754
+
1755
+ fill : dict, optional
1756
+ A dictionary specifying the type of color filling required in
1757
+ the plot. The keys in the dictionary should be equivalent to the
1758
+ arguments of the :external:mod:`matplotlib`'s
1759
+ :external:meth:`~matplotlib.axes.Axes.fill_between` method.
1760
+
1761
+ adaptive : bool, optional
1762
+ The default value is set to ``True``. Set adaptive to ``False``
1763
+ and specify ``nb_of_points`` if uniform sampling is required.
1764
+
1765
+ The plotting uses an adaptive algorithm which samples
1766
+ recursively to accurately plot. The adaptive algorithm uses a
1767
+ random point near the midpoint of two points that has to be
1768
+ further sampled. Hence the same plots can appear slightly
1769
+ different.
1770
+
1771
+ depth : int, optional
1772
+ Recursion depth of the adaptive algorithm. A depth of value
1773
+ `n` samples a maximum of `2^{n}` points.
1774
+
1775
+ If the ``adaptive`` flag is set to ``False``, this will be
1776
+ ignored.
1777
+
1778
+ nb_of_points : int, optional
1779
+ Used when the ``adaptive`` is set to ``False``. The function
1780
+ is uniformly sampled at ``nb_of_points`` number of points.
1781
+
1782
+ If the ``adaptive`` flag is set to ``True``, this will be
1783
+ ignored.
1784
+
1785
+ size : (float, float), optional
1786
+ A tuple in the form (width, height) in inches to specify the size of
1787
+ the overall figure. The default value is set to ``None``, meaning
1788
+ the size will be set by the default backend.
1789
+
1790
+ Examples
1791
+ ========
1792
+
1793
+ .. plot::
1794
+ :context: close-figs
1795
+ :format: doctest
1796
+ :include-source: True
1797
+
1798
+ >>> from sympy import symbols
1799
+ >>> from sympy.plotting import plot
1800
+ >>> x = symbols('x')
1801
+
1802
+ Single Plot
1803
+
1804
+ .. plot::
1805
+ :context: close-figs
1806
+ :format: doctest
1807
+ :include-source: True
1808
+
1809
+ >>> plot(x**2, (x, -5, 5))
1810
+ Plot object containing:
1811
+ [0]: cartesian line: x**2 for x over (-5.0, 5.0)
1812
+
1813
+ Multiple plots with single range.
1814
+
1815
+ .. plot::
1816
+ :context: close-figs
1817
+ :format: doctest
1818
+ :include-source: True
1819
+
1820
+ >>> plot(x, x**2, x**3, (x, -5, 5))
1821
+ Plot object containing:
1822
+ [0]: cartesian line: x for x over (-5.0, 5.0)
1823
+ [1]: cartesian line: x**2 for x over (-5.0, 5.0)
1824
+ [2]: cartesian line: x**3 for x over (-5.0, 5.0)
1825
+
1826
+ Multiple plots with different ranges.
1827
+
1828
+ .. plot::
1829
+ :context: close-figs
1830
+ :format: doctest
1831
+ :include-source: True
1832
+
1833
+ >>> plot((x**2, (x, -6, 6)), (x, (x, -5, 5)))
1834
+ Plot object containing:
1835
+ [0]: cartesian line: x**2 for x over (-6.0, 6.0)
1836
+ [1]: cartesian line: x for x over (-5.0, 5.0)
1837
+
1838
+ No adaptive sampling.
1839
+
1840
+ .. plot::
1841
+ :context: close-figs
1842
+ :format: doctest
1843
+ :include-source: True
1844
+
1845
+ >>> plot(x**2, adaptive=False, nb_of_points=400)
1846
+ Plot object containing:
1847
+ [0]: cartesian line: x**2 for x over (-10.0, 10.0)
1848
+
1849
+ See Also
1850
+ ========
1851
+
1852
+ Plot, LineOver1DRangeSeries
1853
+
1854
+ """
1855
+ args = list(map(sympify, args))
1856
+ free = set()
1857
+ for a in args:
1858
+ if isinstance(a, Expr):
1859
+ free |= a.free_symbols
1860
+ if len(free) > 1:
1861
+ raise ValueError(
1862
+ 'The same variable should be used in all '
1863
+ 'univariate expressions being plotted.')
1864
+ x = free.pop() if free else Symbol('x')
1865
+ kwargs.setdefault('xlabel', x)
1866
+ kwargs.setdefault('ylabel', Function('f')(x))
1867
+ series = []
1868
+ plot_expr = check_arguments(args, 1, 1)
1869
+ series = [LineOver1DRangeSeries(*arg, **kwargs) for arg in plot_expr]
1870
+
1871
+ plots = Plot(*series, **kwargs)
1872
+ if show:
1873
+ plots.show()
1874
+ return plots
1875
+
1876
+
1877
+ def plot_parametric(*args, show=True, **kwargs):
1878
+ """
1879
+ Plots a 2D parametric curve.
1880
+
1881
+ Parameters
1882
+ ==========
1883
+
1884
+ args
1885
+ Common specifications are:
1886
+
1887
+ - Plotting a single parametric curve with a range
1888
+ ``plot_parametric((expr_x, expr_y), range)``
1889
+ - Plotting multiple parametric curves with the same range
1890
+ ``plot_parametric((expr_x, expr_y), ..., range)``
1891
+ - Plotting multiple parametric curves with different ranges
1892
+ ``plot_parametric((expr_x, expr_y, range), ...)``
1893
+
1894
+ ``expr_x`` is the expression representing $x$ component of the
1895
+ parametric function.
1896
+
1897
+ ``expr_y`` is the expression representing $y$ component of the
1898
+ parametric function.
1899
+
1900
+ ``range`` is a 3-tuple denoting the parameter symbol, start and
1901
+ stop. For example, ``(u, 0, 5)``.
1902
+
1903
+ If the range is not specified, then a default range of (-10, 10)
1904
+ is used.
1905
+
1906
+ However, if the arguments are specified as
1907
+ ``(expr_x, expr_y, range), ...``, you must specify the ranges
1908
+ for each expressions manually.
1909
+
1910
+ Default range may change in the future if a more advanced
1911
+ algorithm is implemented.
1912
+
1913
+ adaptive : bool, optional
1914
+ Specifies whether to use the adaptive sampling or not.
1915
+
1916
+ The default value is set to ``True``. Set adaptive to ``False``
1917
+ and specify ``nb_of_points`` if uniform sampling is required.
1918
+
1919
+ depth : int, optional
1920
+ The recursion depth of the adaptive algorithm. A depth of
1921
+ value $n$ samples a maximum of $2^n$ points.
1922
+
1923
+ nb_of_points : int, optional
1924
+ Used when the ``adaptive`` flag is set to ``False``.
1925
+
1926
+ Specifies the number of the points used for the uniform
1927
+ sampling.
1928
+
1929
+ line_color : string, or float, or function, optional
1930
+ Specifies the color for the plot.
1931
+ See ``Plot`` to see how to set color for the plots.
1932
+ Note that by setting ``line_color``, it would be applied simultaneously
1933
+ to all the series.
1934
+
1935
+ label : str, optional
1936
+ The label of the expression in the plot. It will be used when
1937
+ called with ``legend``. Default is the name of the expression.
1938
+ e.g. ``sin(x)``
1939
+
1940
+ xlabel : str, optional
1941
+ Label for the x-axis.
1942
+
1943
+ ylabel : str, optional
1944
+ Label for the y-axis.
1945
+
1946
+ xscale : 'linear' or 'log', optional
1947
+ Sets the scaling of the x-axis.
1948
+
1949
+ yscale : 'linear' or 'log', optional
1950
+ Sets the scaling of the y-axis.
1951
+
1952
+ axis_center : (float, float), optional
1953
+ Tuple of two floats denoting the coordinates of the center or
1954
+ {'center', 'auto'}
1955
+
1956
+ xlim : (float, float), optional
1957
+ Denotes the x-axis limits, ``(min, max)```.
1958
+
1959
+ ylim : (float, float), optional
1960
+ Denotes the y-axis limits, ``(min, max)```.
1961
+
1962
+ size : (float, float), optional
1963
+ A tuple in the form (width, height) in inches to specify the size of
1964
+ the overall figure. The default value is set to ``None``, meaning
1965
+ the size will be set by the default backend.
1966
+
1967
+ Examples
1968
+ ========
1969
+
1970
+ .. plot::
1971
+ :context: reset
1972
+ :format: doctest
1973
+ :include-source: True
1974
+
1975
+ >>> from sympy import plot_parametric, symbols, cos, sin
1976
+ >>> u = symbols('u')
1977
+
1978
+ A parametric plot with a single expression:
1979
+
1980
+ .. plot::
1981
+ :context: close-figs
1982
+ :format: doctest
1983
+ :include-source: True
1984
+
1985
+ >>> plot_parametric((cos(u), sin(u)), (u, -5, 5))
1986
+ Plot object containing:
1987
+ [0]: parametric cartesian line: (cos(u), sin(u)) for u over (-5.0, 5.0)
1988
+
1989
+ A parametric plot with multiple expressions with the same range:
1990
+
1991
+ .. plot::
1992
+ :context: close-figs
1993
+ :format: doctest
1994
+ :include-source: True
1995
+
1996
+ >>> plot_parametric((cos(u), sin(u)), (u, cos(u)), (u, -10, 10))
1997
+ Plot object containing:
1998
+ [0]: parametric cartesian line: (cos(u), sin(u)) for u over (-10.0, 10.0)
1999
+ [1]: parametric cartesian line: (u, cos(u)) for u over (-10.0, 10.0)
2000
+
2001
+ A parametric plot with multiple expressions with different ranges
2002
+ for each curve:
2003
+
2004
+ .. plot::
2005
+ :context: close-figs
2006
+ :format: doctest
2007
+ :include-source: True
2008
+
2009
+ >>> plot_parametric((cos(u), sin(u), (u, -5, 5)),
2010
+ ... (cos(u), u, (u, -5, 5)))
2011
+ Plot object containing:
2012
+ [0]: parametric cartesian line: (cos(u), sin(u)) for u over (-5.0, 5.0)
2013
+ [1]: parametric cartesian line: (cos(u), u) for u over (-5.0, 5.0)
2014
+
2015
+ Notes
2016
+ =====
2017
+
2018
+ The plotting uses an adaptive algorithm which samples recursively to
2019
+ accurately plot the curve. The adaptive algorithm uses a random point
2020
+ near the midpoint of two points that has to be further sampled.
2021
+ Hence, repeating the same plot command can give slightly different
2022
+ results because of the random sampling.
2023
+
2024
+ If there are multiple plots, then the same optional arguments are
2025
+ applied to all the plots drawn in the same canvas. If you want to
2026
+ set these options separately, you can index the returned ``Plot``
2027
+ object and set it.
2028
+
2029
+ For example, when you specify ``line_color`` once, it would be
2030
+ applied simultaneously to both series.
2031
+
2032
+ .. plot::
2033
+ :context: close-figs
2034
+ :format: doctest
2035
+ :include-source: True
2036
+
2037
+ >>> from sympy import pi
2038
+ >>> expr1 = (u, cos(2*pi*u)/2 + 1/2)
2039
+ >>> expr2 = (u, sin(2*pi*u)/2 + 1/2)
2040
+ >>> p = plot_parametric(expr1, expr2, (u, 0, 1), line_color='blue')
2041
+
2042
+ If you want to specify the line color for the specific series, you
2043
+ should index each item and apply the property manually.
2044
+
2045
+ .. plot::
2046
+ :context: close-figs
2047
+ :format: doctest
2048
+ :include-source: True
2049
+
2050
+ >>> p[0].line_color = 'red'
2051
+ >>> p.show()
2052
+
2053
+ See Also
2054
+ ========
2055
+
2056
+ Plot, Parametric2DLineSeries
2057
+ """
2058
+ args = list(map(sympify, args))
2059
+ series = []
2060
+ plot_expr = check_arguments(args, 2, 1)
2061
+ series = [Parametric2DLineSeries(*arg, **kwargs) for arg in plot_expr]
2062
+ plots = Plot(*series, **kwargs)
2063
+ if show:
2064
+ plots.show()
2065
+ return plots
2066
+
2067
+
2068
+ def plot3d_parametric_line(*args, show=True, **kwargs):
2069
+ """
2070
+ Plots a 3D parametric line plot.
2071
+
2072
+ Usage
2073
+ =====
2074
+
2075
+ Single plot:
2076
+
2077
+ ``plot3d_parametric_line(expr_x, expr_y, expr_z, range, **kwargs)``
2078
+
2079
+ If the range is not specified, then a default range of (-10, 10) is used.
2080
+
2081
+ Multiple plots.
2082
+
2083
+ ``plot3d_parametric_line((expr_x, expr_y, expr_z, range), ..., **kwargs)``
2084
+
2085
+ Ranges have to be specified for every expression.
2086
+
2087
+ Default range may change in the future if a more advanced default range
2088
+ detection algorithm is implemented.
2089
+
2090
+ Arguments
2091
+ =========
2092
+
2093
+ expr_x : Expression representing the function along x.
2094
+
2095
+ expr_y : Expression representing the function along y.
2096
+
2097
+ expr_z : Expression representing the function along z.
2098
+
2099
+ range : (:class:`~.Symbol`, float, float)
2100
+ A 3-tuple denoting the range of the parameter variable, e.g., (u, 0, 5).
2101
+
2102
+ Keyword Arguments
2103
+ =================
2104
+
2105
+ Arguments for ``Parametric3DLineSeries`` class.
2106
+
2107
+ nb_of_points : The range is uniformly sampled at ``nb_of_points``
2108
+ number of points.
2109
+
2110
+ Aesthetics:
2111
+
2112
+ line_color : string, or float, or function, optional
2113
+ Specifies the color for the plot.
2114
+ See ``Plot`` to see how to set color for the plots.
2115
+ Note that by setting ``line_color``, it would be applied simultaneously
2116
+ to all the series.
2117
+
2118
+ label : str
2119
+ The label to the plot. It will be used when called with ``legend=True``
2120
+ to denote the function with the given label in the plot.
2121
+
2122
+ If there are multiple plots, then the same series arguments are applied to
2123
+ all the plots. If you want to set these options separately, you can index
2124
+ the returned ``Plot`` object and set it.
2125
+
2126
+ Arguments for ``Plot`` class.
2127
+
2128
+ title : str
2129
+ Title of the plot.
2130
+
2131
+ size : (float, float), optional
2132
+ A tuple in the form (width, height) in inches to specify the size of
2133
+ the overall figure. The default value is set to ``None``, meaning
2134
+ the size will be set by the default backend.
2135
+
2136
+ Examples
2137
+ ========
2138
+
2139
+ .. plot::
2140
+ :context: reset
2141
+ :format: doctest
2142
+ :include-source: True
2143
+
2144
+ >>> from sympy import symbols, cos, sin
2145
+ >>> from sympy.plotting import plot3d_parametric_line
2146
+ >>> u = symbols('u')
2147
+
2148
+ Single plot.
2149
+
2150
+ .. plot::
2151
+ :context: close-figs
2152
+ :format: doctest
2153
+ :include-source: True
2154
+
2155
+ >>> plot3d_parametric_line(cos(u), sin(u), u, (u, -5, 5))
2156
+ Plot object containing:
2157
+ [0]: 3D parametric cartesian line: (cos(u), sin(u), u) for u over (-5.0, 5.0)
2158
+
2159
+
2160
+ Multiple plots.
2161
+
2162
+ .. plot::
2163
+ :context: close-figs
2164
+ :format: doctest
2165
+ :include-source: True
2166
+
2167
+ >>> plot3d_parametric_line((cos(u), sin(u), u, (u, -5, 5)),
2168
+ ... (sin(u), u**2, u, (u, -5, 5)))
2169
+ Plot object containing:
2170
+ [0]: 3D parametric cartesian line: (cos(u), sin(u), u) for u over (-5.0, 5.0)
2171
+ [1]: 3D parametric cartesian line: (sin(u), u**2, u) for u over (-5.0, 5.0)
2172
+
2173
+
2174
+ See Also
2175
+ ========
2176
+
2177
+ Plot, Parametric3DLineSeries
2178
+
2179
+ """
2180
+ args = list(map(sympify, args))
2181
+ series = []
2182
+ plot_expr = check_arguments(args, 3, 1)
2183
+ series = [Parametric3DLineSeries(*arg, **kwargs) for arg in plot_expr]
2184
+ kwargs.setdefault("xlabel", "x")
2185
+ kwargs.setdefault("ylabel", "y")
2186
+ kwargs.setdefault("zlabel", "z")
2187
+ plots = Plot(*series, **kwargs)
2188
+ if show:
2189
+ plots.show()
2190
+ return plots
2191
+
2192
+
2193
+ def plot3d(*args, show=True, **kwargs):
2194
+ """
2195
+ Plots a 3D surface plot.
2196
+
2197
+ Usage
2198
+ =====
2199
+
2200
+ Single plot
2201
+
2202
+ ``plot3d(expr, range_x, range_y, **kwargs)``
2203
+
2204
+ If the ranges are not specified, then a default range of (-10, 10) is used.
2205
+
2206
+ Multiple plot with the same range.
2207
+
2208
+ ``plot3d(expr1, expr2, range_x, range_y, **kwargs)``
2209
+
2210
+ If the ranges are not specified, then a default range of (-10, 10) is used.
2211
+
2212
+ Multiple plots with different ranges.
2213
+
2214
+ ``plot3d((expr1, range_x, range_y), (expr2, range_x, range_y), ..., **kwargs)``
2215
+
2216
+ Ranges have to be specified for every expression.
2217
+
2218
+ Default range may change in the future if a more advanced default range
2219
+ detection algorithm is implemented.
2220
+
2221
+ Arguments
2222
+ =========
2223
+
2224
+ expr : Expression representing the function along x.
2225
+
2226
+ range_x : (:class:`~.Symbol`, float, float)
2227
+ A 3-tuple denoting the range of the x variable, e.g. (x, 0, 5).
2228
+
2229
+ range_y : (:class:`~.Symbol`, float, float)
2230
+ A 3-tuple denoting the range of the y variable, e.g. (y, 0, 5).
2231
+
2232
+ Keyword Arguments
2233
+ =================
2234
+
2235
+ Arguments for ``SurfaceOver2DRangeSeries`` class:
2236
+
2237
+ nb_of_points_x : int
2238
+ The x range is sampled uniformly at ``nb_of_points_x`` of points.
2239
+
2240
+ nb_of_points_y : int
2241
+ The y range is sampled uniformly at ``nb_of_points_y`` of points.
2242
+
2243
+ Aesthetics:
2244
+
2245
+ surface_color : Function which returns a float
2246
+ Specifies the color for the surface of the plot.
2247
+ See :class:`~.Plot` for more details.
2248
+
2249
+ If there are multiple plots, then the same series arguments are applied to
2250
+ all the plots. If you want to set these options separately, you can index
2251
+ the returned ``Plot`` object and set it.
2252
+
2253
+ Arguments for ``Plot`` class:
2254
+
2255
+ title : str
2256
+ Title of the plot.
2257
+
2258
+ size : (float, float), optional
2259
+ A tuple in the form (width, height) in inches to specify the size of the
2260
+ overall figure. The default value is set to ``None``, meaning the size will
2261
+ be set by the default backend.
2262
+
2263
+ Examples
2264
+ ========
2265
+
2266
+ .. plot::
2267
+ :context: reset
2268
+ :format: doctest
2269
+ :include-source: True
2270
+
2271
+ >>> from sympy import symbols
2272
+ >>> from sympy.plotting import plot3d
2273
+ >>> x, y = symbols('x y')
2274
+
2275
+ Single plot
2276
+
2277
+ .. plot::
2278
+ :context: close-figs
2279
+ :format: doctest
2280
+ :include-source: True
2281
+
2282
+ >>> plot3d(x*y, (x, -5, 5), (y, -5, 5))
2283
+ Plot object containing:
2284
+ [0]: cartesian surface: x*y for x over (-5.0, 5.0) and y over (-5.0, 5.0)
2285
+
2286
+
2287
+ Multiple plots with same range
2288
+
2289
+ .. plot::
2290
+ :context: close-figs
2291
+ :format: doctest
2292
+ :include-source: True
2293
+
2294
+ >>> plot3d(x*y, -x*y, (x, -5, 5), (y, -5, 5))
2295
+ Plot object containing:
2296
+ [0]: cartesian surface: x*y for x over (-5.0, 5.0) and y over (-5.0, 5.0)
2297
+ [1]: cartesian surface: -x*y for x over (-5.0, 5.0) and y over (-5.0, 5.0)
2298
+
2299
+
2300
+ Multiple plots with different ranges.
2301
+
2302
+ .. plot::
2303
+ :context: close-figs
2304
+ :format: doctest
2305
+ :include-source: True
2306
+
2307
+ >>> plot3d((x**2 + y**2, (x, -5, 5), (y, -5, 5)),
2308
+ ... (x*y, (x, -3, 3), (y, -3, 3)))
2309
+ Plot object containing:
2310
+ [0]: cartesian surface: x**2 + y**2 for x over (-5.0, 5.0) and y over (-5.0, 5.0)
2311
+ [1]: cartesian surface: x*y for x over (-3.0, 3.0) and y over (-3.0, 3.0)
2312
+
2313
+
2314
+ See Also
2315
+ ========
2316
+
2317
+ Plot, SurfaceOver2DRangeSeries
2318
+
2319
+ """
2320
+
2321
+ args = list(map(sympify, args))
2322
+ series = []
2323
+ plot_expr = check_arguments(args, 1, 2)
2324
+ series = [SurfaceOver2DRangeSeries(*arg, **kwargs) for arg in plot_expr]
2325
+ kwargs.setdefault("xlabel", series[0].var_x)
2326
+ kwargs.setdefault("ylabel", series[0].var_y)
2327
+ kwargs.setdefault("zlabel", Function('f')(series[0].var_x, series[0].var_y))
2328
+ plots = Plot(*series, **kwargs)
2329
+ if show:
2330
+ plots.show()
2331
+ return plots
2332
+
2333
+
2334
+ def plot3d_parametric_surface(*args, show=True, **kwargs):
2335
+ """
2336
+ Plots a 3D parametric surface plot.
2337
+
2338
+ Explanation
2339
+ ===========
2340
+
2341
+ Single plot.
2342
+
2343
+ ``plot3d_parametric_surface(expr_x, expr_y, expr_z, range_u, range_v, **kwargs)``
2344
+
2345
+ If the ranges is not specified, then a default range of (-10, 10) is used.
2346
+
2347
+ Multiple plots.
2348
+
2349
+ ``plot3d_parametric_surface((expr_x, expr_y, expr_z, range_u, range_v), ..., **kwargs)``
2350
+
2351
+ Ranges have to be specified for every expression.
2352
+
2353
+ Default range may change in the future if a more advanced default range
2354
+ detection algorithm is implemented.
2355
+
2356
+ Arguments
2357
+ =========
2358
+
2359
+ expr_x : Expression representing the function along ``x``.
2360
+
2361
+ expr_y : Expression representing the function along ``y``.
2362
+
2363
+ expr_z : Expression representing the function along ``z``.
2364
+
2365
+ range_u : (:class:`~.Symbol`, float, float)
2366
+ A 3-tuple denoting the range of the u variable, e.g. (u, 0, 5).
2367
+
2368
+ range_v : (:class:`~.Symbol`, float, float)
2369
+ A 3-tuple denoting the range of the v variable, e.g. (v, 0, 5).
2370
+
2371
+ Keyword Arguments
2372
+ =================
2373
+
2374
+ Arguments for ``ParametricSurfaceSeries`` class:
2375
+
2376
+ nb_of_points_u : int
2377
+ The ``u`` range is sampled uniformly at ``nb_of_points_v`` of points
2378
+
2379
+ nb_of_points_y : int
2380
+ The ``v`` range is sampled uniformly at ``nb_of_points_y`` of points
2381
+
2382
+ Aesthetics:
2383
+
2384
+ surface_color : Function which returns a float
2385
+ Specifies the color for the surface of the plot. See
2386
+ :class:`~Plot` for more details.
2387
+
2388
+ If there are multiple plots, then the same series arguments are applied for
2389
+ all the plots. If you want to set these options separately, you can index
2390
+ the returned ``Plot`` object and set it.
2391
+
2392
+
2393
+ Arguments for ``Plot`` class:
2394
+
2395
+ title : str
2396
+ Title of the plot.
2397
+
2398
+ size : (float, float), optional
2399
+ A tuple in the form (width, height) in inches to specify the size of the
2400
+ overall figure. The default value is set to ``None``, meaning the size will
2401
+ be set by the default backend.
2402
+
2403
+ Examples
2404
+ ========
2405
+
2406
+ .. plot::
2407
+ :context: reset
2408
+ :format: doctest
2409
+ :include-source: True
2410
+
2411
+ >>> from sympy import symbols, cos, sin
2412
+ >>> from sympy.plotting import plot3d_parametric_surface
2413
+ >>> u, v = symbols('u v')
2414
+
2415
+ Single plot.
2416
+
2417
+ .. plot::
2418
+ :context: close-figs
2419
+ :format: doctest
2420
+ :include-source: True
2421
+
2422
+ >>> plot3d_parametric_surface(cos(u + v), sin(u - v), u - v,
2423
+ ... (u, -5, 5), (v, -5, 5))
2424
+ Plot object containing:
2425
+ [0]: parametric cartesian surface: (cos(u + v), sin(u - v), u - v) for u over (-5.0, 5.0) and v over (-5.0, 5.0)
2426
+
2427
+
2428
+ See Also
2429
+ ========
2430
+
2431
+ Plot, ParametricSurfaceSeries
2432
+
2433
+ """
2434
+
2435
+ args = list(map(sympify, args))
2436
+ series = []
2437
+ plot_expr = check_arguments(args, 3, 2)
2438
+ series = [ParametricSurfaceSeries(*arg, **kwargs) for arg in plot_expr]
2439
+ kwargs.setdefault("xlabel", "x")
2440
+ kwargs.setdefault("ylabel", "y")
2441
+ kwargs.setdefault("zlabel", "z")
2442
+ plots = Plot(*series, **kwargs)
2443
+ if show:
2444
+ plots.show()
2445
+ return plots
2446
+
2447
+ def plot_contour(*args, show=True, **kwargs):
2448
+ """
2449
+ Draws contour plot of a function
2450
+
2451
+ Usage
2452
+ =====
2453
+
2454
+ Single plot
2455
+
2456
+ ``plot_contour(expr, range_x, range_y, **kwargs)``
2457
+
2458
+ If the ranges are not specified, then a default range of (-10, 10) is used.
2459
+
2460
+ Multiple plot with the same range.
2461
+
2462
+ ``plot_contour(expr1, expr2, range_x, range_y, **kwargs)``
2463
+
2464
+ If the ranges are not specified, then a default range of (-10, 10) is used.
2465
+
2466
+ Multiple plots with different ranges.
2467
+
2468
+ ``plot_contour((expr1, range_x, range_y), (expr2, range_x, range_y), ..., **kwargs)``
2469
+
2470
+ Ranges have to be specified for every expression.
2471
+
2472
+ Default range may change in the future if a more advanced default range
2473
+ detection algorithm is implemented.
2474
+
2475
+ Arguments
2476
+ =========
2477
+
2478
+ expr : Expression representing the function along x.
2479
+
2480
+ range_x : (:class:`Symbol`, float, float)
2481
+ A 3-tuple denoting the range of the x variable, e.g. (x, 0, 5).
2482
+
2483
+ range_y : (:class:`Symbol`, float, float)
2484
+ A 3-tuple denoting the range of the y variable, e.g. (y, 0, 5).
2485
+
2486
+ Keyword Arguments
2487
+ =================
2488
+
2489
+ Arguments for ``ContourSeries`` class:
2490
+
2491
+ nb_of_points_x : int
2492
+ The x range is sampled uniformly at ``nb_of_points_x`` of points.
2493
+
2494
+ nb_of_points_y : int
2495
+ The y range is sampled uniformly at ``nb_of_points_y`` of points.
2496
+
2497
+ Aesthetics:
2498
+
2499
+ surface_color : Function which returns a float
2500
+ Specifies the color for the surface of the plot. See
2501
+ :class:`sympy.plotting.Plot` for more details.
2502
+
2503
+ If there are multiple plots, then the same series arguments are applied to
2504
+ all the plots. If you want to set these options separately, you can index
2505
+ the returned ``Plot`` object and set it.
2506
+
2507
+ Arguments for ``Plot`` class:
2508
+
2509
+ title : str
2510
+ Title of the plot.
2511
+
2512
+ size : (float, float), optional
2513
+ A tuple in the form (width, height) in inches to specify the size of
2514
+ the overall figure. The default value is set to ``None``, meaning
2515
+ the size will be set by the default backend.
2516
+
2517
+ See Also
2518
+ ========
2519
+
2520
+ Plot, ContourSeries
2521
+
2522
+ """
2523
+
2524
+ args = list(map(sympify, args))
2525
+ plot_expr = check_arguments(args, 1, 2)
2526
+ series = [ContourSeries(*arg) for arg in plot_expr]
2527
+ plot_contours = Plot(*series, **kwargs)
2528
+ if len(plot_expr[0].free_symbols) > 2:
2529
+ raise ValueError('Contour Plot cannot Plot for more than two variables.')
2530
+ if show:
2531
+ plot_contours.show()
2532
+ return plot_contours
2533
+
2534
+ def check_arguments(args, expr_len, nb_of_free_symbols):
2535
+ """
2536
+ Checks the arguments and converts into tuples of the
2537
+ form (exprs, ranges).
2538
+
2539
+ Examples
2540
+ ========
2541
+
2542
+ .. plot::
2543
+ :context: reset
2544
+ :format: doctest
2545
+ :include-source: True
2546
+
2547
+ >>> from sympy import cos, sin, symbols
2548
+ >>> from sympy.plotting.plot import check_arguments
2549
+ >>> x = symbols('x')
2550
+ >>> check_arguments([cos(x), sin(x)], 2, 1)
2551
+ [(cos(x), sin(x), (x, -10, 10))]
2552
+
2553
+ >>> check_arguments([x, x**2], 1, 1)
2554
+ [(x, (x, -10, 10)), (x**2, (x, -10, 10))]
2555
+ """
2556
+ if not args:
2557
+ return []
2558
+ if expr_len > 1 and isinstance(args[0], Expr):
2559
+ # Multiple expressions same range.
2560
+ # The arguments are tuples when the expression length is
2561
+ # greater than 1.
2562
+ if len(args) < expr_len:
2563
+ raise ValueError("len(args) should not be less than expr_len")
2564
+ for i in range(len(args)):
2565
+ if isinstance(args[i], Tuple):
2566
+ break
2567
+ else:
2568
+ i = len(args) + 1
2569
+
2570
+ exprs = Tuple(*args[:i])
2571
+ free_symbols = list(set().union(*[e.free_symbols for e in exprs]))
2572
+ if len(args) == expr_len + nb_of_free_symbols:
2573
+ #Ranges given
2574
+ plots = [exprs + Tuple(*args[expr_len:])]
2575
+ else:
2576
+ default_range = Tuple(-10, 10)
2577
+ ranges = []
2578
+ for symbol in free_symbols:
2579
+ ranges.append(Tuple(symbol) + default_range)
2580
+
2581
+ for i in range(len(free_symbols) - nb_of_free_symbols):
2582
+ ranges.append(Tuple(Dummy()) + default_range)
2583
+ plots = [exprs + Tuple(*ranges)]
2584
+ return plots
2585
+
2586
+ if isinstance(args[0], Expr) or (isinstance(args[0], Tuple) and
2587
+ len(args[0]) == expr_len and
2588
+ expr_len != 3):
2589
+ # Cannot handle expressions with number of expression = 3. It is
2590
+ # not possible to differentiate between expressions and ranges.
2591
+ #Series of plots with same range
2592
+ for i in range(len(args)):
2593
+ if isinstance(args[i], Tuple) and len(args[i]) != expr_len:
2594
+ break
2595
+ if not isinstance(args[i], Tuple):
2596
+ args[i] = Tuple(args[i])
2597
+ else:
2598
+ i = len(args) + 1
2599
+
2600
+ exprs = args[:i]
2601
+ assert all(isinstance(e, Expr) for expr in exprs for e in expr)
2602
+ free_symbols = list(set().union(*[e.free_symbols for expr in exprs
2603
+ for e in expr]))
2604
+
2605
+ if len(free_symbols) > nb_of_free_symbols:
2606
+ raise ValueError("The number of free_symbols in the expression "
2607
+ "is greater than %d" % nb_of_free_symbols)
2608
+ if len(args) == i + nb_of_free_symbols and isinstance(args[i], Tuple):
2609
+ ranges = Tuple(*list(args[
2610
+ i:i + nb_of_free_symbols]))
2611
+ plots = [expr + ranges for expr in exprs]
2612
+ return plots
2613
+ else:
2614
+ # Use default ranges.
2615
+ default_range = Tuple(-10, 10)
2616
+ ranges = []
2617
+ for symbol in free_symbols:
2618
+ ranges.append(Tuple(symbol) + default_range)
2619
+
2620
+ for i in range(nb_of_free_symbols - len(free_symbols)):
2621
+ ranges.append(Tuple(Dummy()) + default_range)
2622
+ ranges = Tuple(*ranges)
2623
+ plots = [expr + ranges for expr in exprs]
2624
+ return plots
2625
+
2626
+ elif isinstance(args[0], Tuple) and len(args[0]) == expr_len + nb_of_free_symbols:
2627
+ # Multiple plots with different ranges.
2628
+ for arg in args:
2629
+ for i in range(expr_len):
2630
+ if not isinstance(arg[i], Expr):
2631
+ raise ValueError("Expected an expression, given %s" %
2632
+ str(arg[i]))
2633
+ for i in range(nb_of_free_symbols):
2634
+ if not len(arg[i + expr_len]) == 3:
2635
+ raise ValueError("The ranges should be a tuple of "
2636
+ "length 3, got %s" % str(arg[i + expr_len]))
2637
+ return args
llmeval-env/lib/python3.10/site-packages/sympy/plotting/plot_implicit.py ADDED
@@ -0,0 +1,432 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Implicit plotting module for SymPy.
2
+
3
+ Explanation
4
+ ===========
5
+
6
+ The module implements a data series called ImplicitSeries which is used by
7
+ ``Plot`` class to plot implicit plots for different backends. The module,
8
+ by default, implements plotting using interval arithmetic. It switches to a
9
+ fall back algorithm if the expression cannot be plotted using interval arithmetic.
10
+ It is also possible to specify to use the fall back algorithm for all plots.
11
+
12
+ Boolean combinations of expressions cannot be plotted by the fall back
13
+ algorithm.
14
+
15
+ See Also
16
+ ========
17
+
18
+ sympy.plotting.plot
19
+
20
+ References
21
+ ==========
22
+
23
+ .. [1] Jeffrey Allen Tupper. Reliable Two-Dimensional Graphing Methods for
24
+ Mathematical Formulae with Two Free Variables.
25
+
26
+ .. [2] Jeffrey Allen Tupper. Graphing Equations with Generalized Interval
27
+ Arithmetic. Master's thesis. University of Toronto, 1996
28
+
29
+ """
30
+
31
+
32
+ from .plot import BaseSeries, Plot
33
+ from .experimental_lambdify import experimental_lambdify, vectorized_lambdify
34
+ from .intervalmath import interval
35
+ from sympy.core.relational import (Equality, GreaterThan, LessThan,
36
+ Relational, StrictLessThan, StrictGreaterThan)
37
+ from sympy.core.containers import Tuple
38
+ from sympy.core.relational import Eq
39
+ from sympy.core.symbol import (Dummy, Symbol)
40
+ from sympy.core.sympify import sympify
41
+ from sympy.external import import_module
42
+ from sympy.logic.boolalg import BooleanFunction
43
+ from sympy.polys.polyutils import _sort_gens
44
+ from sympy.utilities.decorator import doctest_depends_on
45
+ from sympy.utilities.iterables import flatten
46
+ import warnings
47
+
48
+
49
+ class ImplicitSeries(BaseSeries):
50
+ """ Representation for Implicit plot """
51
+ is_implicit = True
52
+
53
+ def __init__(self, expr, var_start_end_x, var_start_end_y,
54
+ has_equality, use_interval_math, depth, nb_of_points,
55
+ line_color):
56
+ super().__init__()
57
+ self.expr = sympify(expr)
58
+ self.label = self.expr
59
+ self.var_x = sympify(var_start_end_x[0])
60
+ self.start_x = float(var_start_end_x[1])
61
+ self.end_x = float(var_start_end_x[2])
62
+ self.var_y = sympify(var_start_end_y[0])
63
+ self.start_y = float(var_start_end_y[1])
64
+ self.end_y = float(var_start_end_y[2])
65
+ self.get_points = self.get_raster
66
+ self.has_equality = has_equality # If the expression has equality, i.e.
67
+ #Eq, Greaterthan, LessThan.
68
+ self.nb_of_points = nb_of_points
69
+ self.use_interval_math = use_interval_math
70
+ self.depth = 4 + depth
71
+ self.line_color = line_color
72
+
73
+ def __str__(self):
74
+ return ('Implicit equation: %s for '
75
+ '%s over %s and %s over %s') % (
76
+ str(self.expr),
77
+ str(self.var_x),
78
+ str((self.start_x, self.end_x)),
79
+ str(self.var_y),
80
+ str((self.start_y, self.end_y)))
81
+
82
+ def get_raster(self):
83
+ func = experimental_lambdify((self.var_x, self.var_y), self.expr,
84
+ use_interval=True)
85
+ xinterval = interval(self.start_x, self.end_x)
86
+ yinterval = interval(self.start_y, self.end_y)
87
+ try:
88
+ func(xinterval, yinterval)
89
+ except AttributeError:
90
+ # XXX: AttributeError("'list' object has no attribute 'is_real'")
91
+ # That needs fixing somehow - we shouldn't be catching
92
+ # AttributeError here.
93
+ if self.use_interval_math:
94
+ warnings.warn("Adaptive meshing could not be applied to the"
95
+ " expression. Using uniform meshing.", stacklevel=7)
96
+ self.use_interval_math = False
97
+
98
+ if self.use_interval_math:
99
+ return self._get_raster_interval(func)
100
+ else:
101
+ return self._get_meshes_grid()
102
+
103
+ def _get_raster_interval(self, func):
104
+ """ Uses interval math to adaptively mesh and obtain the plot"""
105
+ k = self.depth
106
+ interval_list = []
107
+ #Create initial 32 divisions
108
+ np = import_module('numpy')
109
+ xsample = np.linspace(self.start_x, self.end_x, 33)
110
+ ysample = np.linspace(self.start_y, self.end_y, 33)
111
+
112
+ #Add a small jitter so that there are no false positives for equality.
113
+ # Ex: y==x becomes True for x interval(1, 2) and y interval(1, 2)
114
+ #which will draw a rectangle.
115
+ jitterx = (np.random.rand(
116
+ len(xsample)) * 2 - 1) * (self.end_x - self.start_x) / 2**20
117
+ jittery = (np.random.rand(
118
+ len(ysample)) * 2 - 1) * (self.end_y - self.start_y) / 2**20
119
+ xsample += jitterx
120
+ ysample += jittery
121
+
122
+ xinter = [interval(x1, x2) for x1, x2 in zip(xsample[:-1],
123
+ xsample[1:])]
124
+ yinter = [interval(y1, y2) for y1, y2 in zip(ysample[:-1],
125
+ ysample[1:])]
126
+ interval_list = [[x, y] for x in xinter for y in yinter]
127
+ plot_list = []
128
+
129
+ #recursive call refinepixels which subdivides the intervals which are
130
+ #neither True nor False according to the expression.
131
+ def refine_pixels(interval_list):
132
+ """ Evaluates the intervals and subdivides the interval if the
133
+ expression is partially satisfied."""
134
+ temp_interval_list = []
135
+ plot_list = []
136
+ for intervals in interval_list:
137
+
138
+ #Convert the array indices to x and y values
139
+ intervalx = intervals[0]
140
+ intervaly = intervals[1]
141
+ func_eval = func(intervalx, intervaly)
142
+ #The expression is valid in the interval. Change the contour
143
+ #array values to 1.
144
+ if func_eval[1] is False or func_eval[0] is False:
145
+ pass
146
+ elif func_eval == (True, True):
147
+ plot_list.append([intervalx, intervaly])
148
+ elif func_eval[1] is None or func_eval[0] is None:
149
+ #Subdivide
150
+ avgx = intervalx.mid
151
+ avgy = intervaly.mid
152
+ a = interval(intervalx.start, avgx)
153
+ b = interval(avgx, intervalx.end)
154
+ c = interval(intervaly.start, avgy)
155
+ d = interval(avgy, intervaly.end)
156
+ temp_interval_list.append([a, c])
157
+ temp_interval_list.append([a, d])
158
+ temp_interval_list.append([b, c])
159
+ temp_interval_list.append([b, d])
160
+ return temp_interval_list, plot_list
161
+
162
+ while k >= 0 and len(interval_list):
163
+ interval_list, plot_list_temp = refine_pixels(interval_list)
164
+ plot_list.extend(plot_list_temp)
165
+ k = k - 1
166
+ #Check whether the expression represents an equality
167
+ #If it represents an equality, then none of the intervals
168
+ #would have satisfied the expression due to floating point
169
+ #differences. Add all the undecided values to the plot.
170
+ if self.has_equality:
171
+ for intervals in interval_list:
172
+ intervalx = intervals[0]
173
+ intervaly = intervals[1]
174
+ func_eval = func(intervalx, intervaly)
175
+ if func_eval[1] and func_eval[0] is not False:
176
+ plot_list.append([intervalx, intervaly])
177
+ return plot_list, 'fill'
178
+
179
+ def _get_meshes_grid(self):
180
+ """Generates the mesh for generating a contour.
181
+
182
+ In the case of equality, ``contour`` function of matplotlib can
183
+ be used. In other cases, matplotlib's ``contourf`` is used.
184
+ """
185
+ equal = False
186
+ if isinstance(self.expr, Equality):
187
+ expr = self.expr.lhs - self.expr.rhs
188
+ equal = True
189
+
190
+ elif isinstance(self.expr, (GreaterThan, StrictGreaterThan)):
191
+ expr = self.expr.lhs - self.expr.rhs
192
+
193
+ elif isinstance(self.expr, (LessThan, StrictLessThan)):
194
+ expr = self.expr.rhs - self.expr.lhs
195
+ else:
196
+ raise NotImplementedError("The expression is not supported for "
197
+ "plotting in uniform meshed plot.")
198
+ np = import_module('numpy')
199
+ xarray = np.linspace(self.start_x, self.end_x, self.nb_of_points)
200
+ yarray = np.linspace(self.start_y, self.end_y, self.nb_of_points)
201
+ x_grid, y_grid = np.meshgrid(xarray, yarray)
202
+
203
+ func = vectorized_lambdify((self.var_x, self.var_y), expr)
204
+ z_grid = func(x_grid, y_grid)
205
+ z_grid[np.ma.where(z_grid < 0)] = -1
206
+ z_grid[np.ma.where(z_grid > 0)] = 1
207
+ if equal:
208
+ return xarray, yarray, z_grid, 'contour'
209
+ else:
210
+ return xarray, yarray, z_grid, 'contourf'
211
+
212
+
213
+ @doctest_depends_on(modules=('matplotlib',))
214
+ def plot_implicit(expr, x_var=None, y_var=None, adaptive=True, depth=0,
215
+ points=300, line_color="blue", show=True, **kwargs):
216
+ """A plot function to plot implicit equations / inequalities.
217
+
218
+ Arguments
219
+ =========
220
+
221
+ - expr : The equation / inequality that is to be plotted.
222
+ - x_var (optional) : symbol to plot on x-axis or tuple giving symbol
223
+ and range as ``(symbol, xmin, xmax)``
224
+ - y_var (optional) : symbol to plot on y-axis or tuple giving symbol
225
+ and range as ``(symbol, ymin, ymax)``
226
+
227
+ If neither ``x_var`` nor ``y_var`` are given then the free symbols in the
228
+ expression will be assigned in the order they are sorted.
229
+
230
+ The following keyword arguments can also be used:
231
+
232
+ - ``adaptive`` Boolean. The default value is set to True. It has to be
233
+ set to False if you want to use a mesh grid.
234
+
235
+ - ``depth`` integer. The depth of recursion for adaptive mesh grid.
236
+ Default value is 0. Takes value in the range (0, 4).
237
+
238
+ - ``points`` integer. The number of points if adaptive mesh grid is not
239
+ used. Default value is 300.
240
+
241
+ - ``show`` Boolean. Default value is True. If set to False, the plot will
242
+ not be shown. See ``Plot`` for further information.
243
+
244
+ - ``title`` string. The title for the plot.
245
+
246
+ - ``xlabel`` string. The label for the x-axis
247
+
248
+ - ``ylabel`` string. The label for the y-axis
249
+
250
+ Aesthetics options:
251
+
252
+ - ``line_color``: float or string. Specifies the color for the plot.
253
+ See ``Plot`` to see how to set color for the plots.
254
+ Default value is "Blue"
255
+
256
+ plot_implicit, by default, uses interval arithmetic to plot functions. If
257
+ the expression cannot be plotted using interval arithmetic, it defaults to
258
+ a generating a contour using a mesh grid of fixed number of points. By
259
+ setting adaptive to False, you can force plot_implicit to use the mesh
260
+ grid. The mesh grid method can be effective when adaptive plotting using
261
+ interval arithmetic, fails to plot with small line width.
262
+
263
+ Examples
264
+ ========
265
+
266
+ Plot expressions:
267
+
268
+ .. plot::
269
+ :context: reset
270
+ :format: doctest
271
+ :include-source: True
272
+
273
+ >>> from sympy import plot_implicit, symbols, Eq, And
274
+ >>> x, y = symbols('x y')
275
+
276
+ Without any ranges for the symbols in the expression:
277
+
278
+ .. plot::
279
+ :context: close-figs
280
+ :format: doctest
281
+ :include-source: True
282
+
283
+ >>> p1 = plot_implicit(Eq(x**2 + y**2, 5))
284
+
285
+ With the range for the symbols:
286
+
287
+ .. plot::
288
+ :context: close-figs
289
+ :format: doctest
290
+ :include-source: True
291
+
292
+ >>> p2 = plot_implicit(
293
+ ... Eq(x**2 + y**2, 3), (x, -3, 3), (y, -3, 3))
294
+
295
+ With depth of recursion as argument:
296
+
297
+ .. plot::
298
+ :context: close-figs
299
+ :format: doctest
300
+ :include-source: True
301
+
302
+ >>> p3 = plot_implicit(
303
+ ... Eq(x**2 + y**2, 5), (x, -4, 4), (y, -4, 4), depth = 2)
304
+
305
+ Using mesh grid and not using adaptive meshing:
306
+
307
+ .. plot::
308
+ :context: close-figs
309
+ :format: doctest
310
+ :include-source: True
311
+
312
+ >>> p4 = plot_implicit(
313
+ ... Eq(x**2 + y**2, 5), (x, -5, 5), (y, -2, 2),
314
+ ... adaptive=False)
315
+
316
+ Using mesh grid without using adaptive meshing with number of points
317
+ specified:
318
+
319
+ .. plot::
320
+ :context: close-figs
321
+ :format: doctest
322
+ :include-source: True
323
+
324
+ >>> p5 = plot_implicit(
325
+ ... Eq(x**2 + y**2, 5), (x, -5, 5), (y, -2, 2),
326
+ ... adaptive=False, points=400)
327
+
328
+ Plotting regions:
329
+
330
+ .. plot::
331
+ :context: close-figs
332
+ :format: doctest
333
+ :include-source: True
334
+
335
+ >>> p6 = plot_implicit(y > x**2)
336
+
337
+ Plotting Using boolean conjunctions:
338
+
339
+ .. plot::
340
+ :context: close-figs
341
+ :format: doctest
342
+ :include-source: True
343
+
344
+ >>> p7 = plot_implicit(And(y > x, y > -x))
345
+
346
+ When plotting an expression with a single variable (y - 1, for example),
347
+ specify the x or the y variable explicitly:
348
+
349
+ .. plot::
350
+ :context: close-figs
351
+ :format: doctest
352
+ :include-source: True
353
+
354
+ >>> p8 = plot_implicit(y - 1, y_var=y)
355
+ >>> p9 = plot_implicit(x - 1, x_var=x)
356
+ """
357
+ has_equality = False # Represents whether the expression contains an Equality,
358
+ #GreaterThan or LessThan
359
+
360
+ def arg_expand(bool_expr):
361
+ """
362
+ Recursively expands the arguments of an Boolean Function
363
+ """
364
+ for arg in bool_expr.args:
365
+ if isinstance(arg, BooleanFunction):
366
+ arg_expand(arg)
367
+ elif isinstance(arg, Relational):
368
+ arg_list.append(arg)
369
+
370
+ arg_list = []
371
+ if isinstance(expr, BooleanFunction):
372
+ arg_expand(expr)
373
+
374
+ #Check whether there is an equality in the expression provided.
375
+ if any(isinstance(e, (Equality, GreaterThan, LessThan))
376
+ for e in arg_list):
377
+ has_equality = True
378
+
379
+ elif not isinstance(expr, Relational):
380
+ expr = Eq(expr, 0)
381
+ has_equality = True
382
+ elif isinstance(expr, (Equality, GreaterThan, LessThan)):
383
+ has_equality = True
384
+
385
+ xyvar = [i for i in (x_var, y_var) if i is not None]
386
+ free_symbols = expr.free_symbols
387
+ range_symbols = Tuple(*flatten(xyvar)).free_symbols
388
+ undeclared = free_symbols - range_symbols
389
+ if len(free_symbols & range_symbols) > 2:
390
+ raise NotImplementedError("Implicit plotting is not implemented for "
391
+ "more than 2 variables")
392
+
393
+ #Create default ranges if the range is not provided.
394
+ default_range = Tuple(-5, 5)
395
+ def _range_tuple(s):
396
+ if isinstance(s, Symbol):
397
+ return Tuple(s) + default_range
398
+ if len(s) == 3:
399
+ return Tuple(*s)
400
+ raise ValueError('symbol or `(symbol, min, max)` expected but got %s' % s)
401
+
402
+ if len(xyvar) == 0:
403
+ xyvar = list(_sort_gens(free_symbols))
404
+ var_start_end_x = _range_tuple(xyvar[0])
405
+ x = var_start_end_x[0]
406
+ if len(xyvar) != 2:
407
+ if x in undeclared or not undeclared:
408
+ xyvar.append(Dummy('f(%s)' % x.name))
409
+ else:
410
+ xyvar.append(undeclared.pop())
411
+ var_start_end_y = _range_tuple(xyvar[1])
412
+
413
+ #Check whether the depth is greater than 4 or less than 0.
414
+ if depth > 4:
415
+ depth = 4
416
+ elif depth < 0:
417
+ depth = 0
418
+
419
+ series_argument = ImplicitSeries(expr, var_start_end_x, var_start_end_y,
420
+ has_equality, adaptive, depth,
421
+ points, line_color)
422
+
423
+ #set the x and y limits
424
+ kwargs['xlim'] = tuple(float(x) for x in var_start_end_x[1:])
425
+ kwargs['ylim'] = tuple(float(y) for y in var_start_end_y[1:])
426
+ # set the x and y labels
427
+ kwargs.setdefault('xlabel', var_start_end_x[0])
428
+ kwargs.setdefault('ylabel', var_start_end_y[0])
429
+ p = Plot(series_argument, **kwargs)
430
+ if show:
431
+ p.show()
432
+ return p
llmeval-env/lib/python3.10/site-packages/sympy/plotting/pygletplot/__init__.py ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Plotting module that can plot 2D and 3D functions
2
+ """
3
+
4
+ from sympy.utilities.decorator import doctest_depends_on
5
+
6
+ @doctest_depends_on(modules=('pyglet',))
7
+ def PygletPlot(*args, **kwargs):
8
+ """
9
+
10
+ Plot Examples
11
+ =============
12
+
13
+ See examples/advanced/pyglet_plotting.py for many more examples.
14
+
15
+ >>> from sympy.plotting.pygletplot import PygletPlot as Plot
16
+ >>> from sympy.abc import x, y, z
17
+
18
+ >>> Plot(x*y**3-y*x**3)
19
+ [0]: -x**3*y + x*y**3, 'mode=cartesian'
20
+
21
+ >>> p = Plot()
22
+ >>> p[1] = x*y
23
+ >>> p[1].color = z, (0.4,0.4,0.9), (0.9,0.4,0.4)
24
+
25
+ >>> p = Plot()
26
+ >>> p[1] = x**2+y**2
27
+ >>> p[2] = -x**2-y**2
28
+
29
+
30
+ Variable Intervals
31
+ ==================
32
+
33
+ The basic format is [var, min, max, steps], but the
34
+ syntax is flexible and arguments left out are taken
35
+ from the defaults for the current coordinate mode:
36
+
37
+ >>> Plot(x**2) # implies [x,-5,5,100]
38
+ [0]: x**2, 'mode=cartesian'
39
+
40
+ >>> Plot(x**2, [], []) # [x,-1,1,40], [y,-1,1,40]
41
+ [0]: x**2, 'mode=cartesian'
42
+ >>> Plot(x**2-y**2, [100], [100]) # [x,-1,1,100], [y,-1,1,100]
43
+ [0]: x**2 - y**2, 'mode=cartesian'
44
+ >>> Plot(x**2, [x,-13,13,100])
45
+ [0]: x**2, 'mode=cartesian'
46
+ >>> Plot(x**2, [-13,13]) # [x,-13,13,100]
47
+ [0]: x**2, 'mode=cartesian'
48
+ >>> Plot(x**2, [x,-13,13]) # [x,-13,13,100]
49
+ [0]: x**2, 'mode=cartesian'
50
+ >>> Plot(1*x, [], [x], mode='cylindrical')
51
+ ... # [unbound_theta,0,2*Pi,40], [x,-1,1,20]
52
+ [0]: x, 'mode=cartesian'
53
+
54
+
55
+ Coordinate Modes
56
+ ================
57
+
58
+ Plot supports several curvilinear coordinate modes, and
59
+ they independent for each plotted function. You can specify
60
+ a coordinate mode explicitly with the 'mode' named argument,
61
+ but it can be automatically determined for Cartesian or
62
+ parametric plots, and therefore must only be specified for
63
+ polar, cylindrical, and spherical modes.
64
+
65
+ Specifically, Plot(function arguments) and Plot[n] =
66
+ (function arguments) will interpret your arguments as a
67
+ Cartesian plot if you provide one function and a parametric
68
+ plot if you provide two or three functions. Similarly, the
69
+ arguments will be interpreted as a curve if one variable is
70
+ used, and a surface if two are used.
71
+
72
+ Supported mode names by number of variables:
73
+
74
+ 1: parametric, cartesian, polar
75
+ 2: parametric, cartesian, cylindrical = polar, spherical
76
+
77
+ >>> Plot(1, mode='spherical')
78
+
79
+
80
+ Calculator-like Interface
81
+ =========================
82
+
83
+ >>> p = Plot(visible=False)
84
+ >>> f = x**2
85
+ >>> p[1] = f
86
+ >>> p[2] = f.diff(x)
87
+ >>> p[3] = f.diff(x).diff(x)
88
+ >>> p
89
+ [1]: x**2, 'mode=cartesian'
90
+ [2]: 2*x, 'mode=cartesian'
91
+ [3]: 2, 'mode=cartesian'
92
+ >>> p.show()
93
+ >>> p.clear()
94
+ >>> p
95
+ <blank plot>
96
+ >>> p[1] = x**2+y**2
97
+ >>> p[1].style = 'solid'
98
+ >>> p[2] = -x**2-y**2
99
+ >>> p[2].style = 'wireframe'
100
+ >>> p[1].color = z, (0.4,0.4,0.9), (0.9,0.4,0.4)
101
+ >>> p[1].style = 'both'
102
+ >>> p[2].style = 'both'
103
+ >>> p.close()
104
+
105
+
106
+ Plot Window Keyboard Controls
107
+ =============================
108
+
109
+ Screen Rotation:
110
+ X,Y axis Arrow Keys, A,S,D,W, Numpad 4,6,8,2
111
+ Z axis Q,E, Numpad 7,9
112
+
113
+ Model Rotation:
114
+ Z axis Z,C, Numpad 1,3
115
+
116
+ Zoom: R,F, PgUp,PgDn, Numpad +,-
117
+
118
+ Reset Camera: X, Numpad 5
119
+
120
+ Camera Presets:
121
+ XY F1
122
+ XZ F2
123
+ YZ F3
124
+ Perspective F4
125
+
126
+ Sensitivity Modifier: SHIFT
127
+
128
+ Axes Toggle:
129
+ Visible F5
130
+ Colors F6
131
+
132
+ Close Window: ESCAPE
133
+
134
+ =============================
135
+ """
136
+
137
+ from sympy.plotting.pygletplot.plot import PygletPlot
138
+ return PygletPlot(*args, **kwargs)
llmeval-env/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (4 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/color_scheme.cpython-310.pyc ADDED
Binary file (9.99 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/managed_window.cpython-310.pyc ADDED
Binary file (3.31 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/plot.cpython-310.pyc ADDED
Binary file (13.7 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/plot_axes.cpython-310.pyc ADDED
Binary file (8.52 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/plot_camera.cpython-310.pyc ADDED
Binary file (4.32 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/plot_controller.cpython-310.pyc ADDED
Binary file (5.02 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/plot_curve.cpython-310.pyc ADDED
Binary file (2.93 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/plot_interval.cpython-310.pyc ADDED
Binary file (5.85 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/plot_mode.cpython-310.pyc ADDED
Binary file (9.37 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/plot_mode_base.cpython-310.pyc ADDED
Binary file (10.1 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/plot_modes.cpython-310.pyc ADDED
Binary file (7.34 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/plot_object.cpython-310.pyc ADDED
Binary file (806 Bytes). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/plot_rotation.cpython-310.pyc ADDED
Binary file (2.02 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/plot_surface.cpython-310.pyc ADDED
Binary file (3.34 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/plot_window.cpython-310.pyc ADDED
Binary file (3.89 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/plotting/pygletplot/__pycache__/util.cpython-310.pyc ADDED
Binary file (6.25 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/plotting/pygletplot/color_scheme.py ADDED
@@ -0,0 +1,336 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.basic import Basic
2
+ from sympy.core.symbol import (Symbol, symbols)
3
+ from sympy.utilities.lambdify import lambdify
4
+ from .util import interpolate, rinterpolate, create_bounds, update_bounds
5
+ from sympy.utilities.iterables import sift
6
+
7
+
8
+ class ColorGradient:
9
+ colors = [0.4, 0.4, 0.4], [0.9, 0.9, 0.9]
10
+ intervals = 0.0, 1.0
11
+
12
+ def __init__(self, *args):
13
+ if len(args) == 2:
14
+ self.colors = list(args)
15
+ self.intervals = [0.0, 1.0]
16
+ elif len(args) > 0:
17
+ if len(args) % 2 != 0:
18
+ raise ValueError("len(args) should be even")
19
+ self.colors = [args[i] for i in range(1, len(args), 2)]
20
+ self.intervals = [args[i] for i in range(0, len(args), 2)]
21
+ assert len(self.colors) == len(self.intervals)
22
+
23
+ def copy(self):
24
+ c = ColorGradient()
25
+ c.colors = [e[::] for e in self.colors]
26
+ c.intervals = self.intervals[::]
27
+ return c
28
+
29
+ def _find_interval(self, v):
30
+ m = len(self.intervals)
31
+ i = 0
32
+ while i < m - 1 and self.intervals[i] <= v:
33
+ i += 1
34
+ return i
35
+
36
+ def _interpolate_axis(self, axis, v):
37
+ i = self._find_interval(v)
38
+ v = rinterpolate(self.intervals[i - 1], self.intervals[i], v)
39
+ return interpolate(self.colors[i - 1][axis], self.colors[i][axis], v)
40
+
41
+ def __call__(self, r, g, b):
42
+ c = self._interpolate_axis
43
+ return c(0, r), c(1, g), c(2, b)
44
+
45
+ default_color_schemes = {} # defined at the bottom of this file
46
+
47
+
48
+ class ColorScheme:
49
+
50
+ def __init__(self, *args, **kwargs):
51
+ self.args = args
52
+ self.f, self.gradient = None, ColorGradient()
53
+
54
+ if len(args) == 1 and not isinstance(args[0], Basic) and callable(args[0]):
55
+ self.f = args[0]
56
+ elif len(args) == 1 and isinstance(args[0], str):
57
+ if args[0] in default_color_schemes:
58
+ cs = default_color_schemes[args[0]]
59
+ self.f, self.gradient = cs.f, cs.gradient.copy()
60
+ else:
61
+ self.f = lambdify('x,y,z,u,v', args[0])
62
+ else:
63
+ self.f, self.gradient = self._interpret_args(args)
64
+ self._test_color_function()
65
+ if not isinstance(self.gradient, ColorGradient):
66
+ raise ValueError("Color gradient not properly initialized. "
67
+ "(Not a ColorGradient instance.)")
68
+
69
+ def _interpret_args(self, args):
70
+ f, gradient = None, self.gradient
71
+ atoms, lists = self._sort_args(args)
72
+ s = self._pop_symbol_list(lists)
73
+ s = self._fill_in_vars(s)
74
+
75
+ # prepare the error message for lambdification failure
76
+ f_str = ', '.join(str(fa) for fa in atoms)
77
+ s_str = (str(sa) for sa in s)
78
+ s_str = ', '.join(sa for sa in s_str if sa.find('unbound') < 0)
79
+ f_error = ValueError("Could not interpret arguments "
80
+ "%s as functions of %s." % (f_str, s_str))
81
+
82
+ # try to lambdify args
83
+ if len(atoms) == 1:
84
+ fv = atoms[0]
85
+ try:
86
+ f = lambdify(s, [fv, fv, fv])
87
+ except TypeError:
88
+ raise f_error
89
+
90
+ elif len(atoms) == 3:
91
+ fr, fg, fb = atoms
92
+ try:
93
+ f = lambdify(s, [fr, fg, fb])
94
+ except TypeError:
95
+ raise f_error
96
+
97
+ else:
98
+ raise ValueError("A ColorScheme must provide 1 or 3 "
99
+ "functions in x, y, z, u, and/or v.")
100
+
101
+ # try to intrepret any given color information
102
+ if len(lists) == 0:
103
+ gargs = []
104
+
105
+ elif len(lists) == 1:
106
+ gargs = lists[0]
107
+
108
+ elif len(lists) == 2:
109
+ try:
110
+ (r1, g1, b1), (r2, g2, b2) = lists
111
+ except TypeError:
112
+ raise ValueError("If two color arguments are given, "
113
+ "they must be given in the format "
114
+ "(r1, g1, b1), (r2, g2, b2).")
115
+ gargs = lists
116
+
117
+ elif len(lists) == 3:
118
+ try:
119
+ (r1, r2), (g1, g2), (b1, b2) = lists
120
+ except Exception:
121
+ raise ValueError("If three color arguments are given, "
122
+ "they must be given in the format "
123
+ "(r1, r2), (g1, g2), (b1, b2). To create "
124
+ "a multi-step gradient, use the syntax "
125
+ "[0, colorStart, step1, color1, ..., 1, "
126
+ "colorEnd].")
127
+ gargs = [[r1, g1, b1], [r2, g2, b2]]
128
+
129
+ else:
130
+ raise ValueError("Don't know what to do with collection "
131
+ "arguments %s." % (', '.join(str(l) for l in lists)))
132
+
133
+ if gargs:
134
+ try:
135
+ gradient = ColorGradient(*gargs)
136
+ except Exception as ex:
137
+ raise ValueError(("Could not initialize a gradient "
138
+ "with arguments %s. Inner "
139
+ "exception: %s") % (gargs, str(ex)))
140
+
141
+ return f, gradient
142
+
143
+ def _pop_symbol_list(self, lists):
144
+ symbol_lists = []
145
+ for l in lists:
146
+ mark = True
147
+ for s in l:
148
+ if s is not None and not isinstance(s, Symbol):
149
+ mark = False
150
+ break
151
+ if mark:
152
+ lists.remove(l)
153
+ symbol_lists.append(l)
154
+ if len(symbol_lists) == 1:
155
+ return symbol_lists[0]
156
+ elif len(symbol_lists) == 0:
157
+ return []
158
+ else:
159
+ raise ValueError("Only one list of Symbols "
160
+ "can be given for a color scheme.")
161
+
162
+ def _fill_in_vars(self, args):
163
+ defaults = symbols('x,y,z,u,v')
164
+ v_error = ValueError("Could not find what to plot.")
165
+ if len(args) == 0:
166
+ return defaults
167
+ if not isinstance(args, (tuple, list)):
168
+ raise v_error
169
+ if len(args) == 0:
170
+ return defaults
171
+ for s in args:
172
+ if s is not None and not isinstance(s, Symbol):
173
+ raise v_error
174
+ # when vars are given explicitly, any vars
175
+ # not given are marked 'unbound' as to not
176
+ # be accidentally used in an expression
177
+ vars = [Symbol('unbound%i' % (i)) for i in range(1, 6)]
178
+ # interpret as t
179
+ if len(args) == 1:
180
+ vars[3] = args[0]
181
+ # interpret as u,v
182
+ elif len(args) == 2:
183
+ if args[0] is not None:
184
+ vars[3] = args[0]
185
+ if args[1] is not None:
186
+ vars[4] = args[1]
187
+ # interpret as x,y,z
188
+ elif len(args) >= 3:
189
+ # allow some of x,y,z to be
190
+ # left unbound if not given
191
+ if args[0] is not None:
192
+ vars[0] = args[0]
193
+ if args[1] is not None:
194
+ vars[1] = args[1]
195
+ if args[2] is not None:
196
+ vars[2] = args[2]
197
+ # interpret the rest as t
198
+ if len(args) >= 4:
199
+ vars[3] = args[3]
200
+ # ...or u,v
201
+ if len(args) >= 5:
202
+ vars[4] = args[4]
203
+ return vars
204
+
205
+ def _sort_args(self, args):
206
+ lists, atoms = sift(args,
207
+ lambda a: isinstance(a, (tuple, list)), binary=True)
208
+ return atoms, lists
209
+
210
+ def _test_color_function(self):
211
+ if not callable(self.f):
212
+ raise ValueError("Color function is not callable.")
213
+ try:
214
+ result = self.f(0, 0, 0, 0, 0)
215
+ if len(result) != 3:
216
+ raise ValueError("length should be equal to 3")
217
+ except TypeError:
218
+ raise ValueError("Color function needs to accept x,y,z,u,v, "
219
+ "as arguments even if it doesn't use all of them.")
220
+ except AssertionError:
221
+ raise ValueError("Color function needs to return 3-tuple r,g,b.")
222
+ except Exception:
223
+ pass # color function probably not valid at 0,0,0,0,0
224
+
225
+ def __call__(self, x, y, z, u, v):
226
+ try:
227
+ return self.f(x, y, z, u, v)
228
+ except Exception:
229
+ return None
230
+
231
+ def apply_to_curve(self, verts, u_set, set_len=None, inc_pos=None):
232
+ """
233
+ Apply this color scheme to a
234
+ set of vertices over a single
235
+ independent variable u.
236
+ """
237
+ bounds = create_bounds()
238
+ cverts = []
239
+ if callable(set_len):
240
+ set_len(len(u_set)*2)
241
+ # calculate f() = r,g,b for each vert
242
+ # and find the min and max for r,g,b
243
+ for _u in range(len(u_set)):
244
+ if verts[_u] is None:
245
+ cverts.append(None)
246
+ else:
247
+ x, y, z = verts[_u]
248
+ u, v = u_set[_u], None
249
+ c = self(x, y, z, u, v)
250
+ if c is not None:
251
+ c = list(c)
252
+ update_bounds(bounds, c)
253
+ cverts.append(c)
254
+ if callable(inc_pos):
255
+ inc_pos()
256
+ # scale and apply gradient
257
+ for _u in range(len(u_set)):
258
+ if cverts[_u] is not None:
259
+ for _c in range(3):
260
+ # scale from [f_min, f_max] to [0,1]
261
+ cverts[_u][_c] = rinterpolate(bounds[_c][0], bounds[_c][1],
262
+ cverts[_u][_c])
263
+ # apply gradient
264
+ cverts[_u] = self.gradient(*cverts[_u])
265
+ if callable(inc_pos):
266
+ inc_pos()
267
+ return cverts
268
+
269
+ def apply_to_surface(self, verts, u_set, v_set, set_len=None, inc_pos=None):
270
+ """
271
+ Apply this color scheme to a
272
+ set of vertices over two
273
+ independent variables u and v.
274
+ """
275
+ bounds = create_bounds()
276
+ cverts = []
277
+ if callable(set_len):
278
+ set_len(len(u_set)*len(v_set)*2)
279
+ # calculate f() = r,g,b for each vert
280
+ # and find the min and max for r,g,b
281
+ for _u in range(len(u_set)):
282
+ column = []
283
+ for _v in range(len(v_set)):
284
+ if verts[_u][_v] is None:
285
+ column.append(None)
286
+ else:
287
+ x, y, z = verts[_u][_v]
288
+ u, v = u_set[_u], v_set[_v]
289
+ c = self(x, y, z, u, v)
290
+ if c is not None:
291
+ c = list(c)
292
+ update_bounds(bounds, c)
293
+ column.append(c)
294
+ if callable(inc_pos):
295
+ inc_pos()
296
+ cverts.append(column)
297
+ # scale and apply gradient
298
+ for _u in range(len(u_set)):
299
+ for _v in range(len(v_set)):
300
+ if cverts[_u][_v] is not None:
301
+ # scale from [f_min, f_max] to [0,1]
302
+ for _c in range(3):
303
+ cverts[_u][_v][_c] = rinterpolate(bounds[_c][0],
304
+ bounds[_c][1], cverts[_u][_v][_c])
305
+ # apply gradient
306
+ cverts[_u][_v] = self.gradient(*cverts[_u][_v])
307
+ if callable(inc_pos):
308
+ inc_pos()
309
+ return cverts
310
+
311
+ def str_base(self):
312
+ return ", ".join(str(a) for a in self.args)
313
+
314
+ def __repr__(self):
315
+ return "%s" % (self.str_base())
316
+
317
+
318
+ x, y, z, t, u, v = symbols('x,y,z,t,u,v')
319
+
320
+ default_color_schemes['rainbow'] = ColorScheme(z, y, x)
321
+ default_color_schemes['zfade'] = ColorScheme(z, (0.4, 0.4, 0.97),
322
+ (0.97, 0.4, 0.4), (None, None, z))
323
+ default_color_schemes['zfade3'] = ColorScheme(z, (None, None, z),
324
+ [0.00, (0.2, 0.2, 1.0),
325
+ 0.35, (0.2, 0.8, 0.4),
326
+ 0.50, (0.3, 0.9, 0.3),
327
+ 0.65, (0.4, 0.8, 0.2),
328
+ 1.00, (1.0, 0.2, 0.2)])
329
+
330
+ default_color_schemes['zfade4'] = ColorScheme(z, (None, None, z),
331
+ [0.0, (0.3, 0.3, 1.0),
332
+ 0.30, (0.3, 1.0, 0.3),
333
+ 0.55, (0.95, 1.0, 0.2),
334
+ 0.65, (1.0, 0.95, 0.2),
335
+ 0.85, (1.0, 0.7, 0.2),
336
+ 1.0, (1.0, 0.3, 0.2)])
llmeval-env/lib/python3.10/site-packages/sympy/plotting/pygletplot/managed_window.py ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pyglet.window import Window
2
+ from pyglet.clock import Clock
3
+
4
+ from threading import Thread, Lock
5
+
6
+ gl_lock = Lock()
7
+
8
+
9
+ class ManagedWindow(Window):
10
+ """
11
+ A pyglet window with an event loop which executes automatically
12
+ in a separate thread. Behavior is added by creating a subclass
13
+ which overrides setup, update, and/or draw.
14
+ """
15
+ fps_limit = 30
16
+ default_win_args = {"width": 600,
17
+ "height": 500,
18
+ "vsync": False,
19
+ "resizable": True}
20
+
21
+ def __init__(self, **win_args):
22
+ """
23
+ It is best not to override this function in the child
24
+ class, unless you need to take additional arguments.
25
+ Do any OpenGL initialization calls in setup().
26
+ """
27
+
28
+ # check if this is run from the doctester
29
+ if win_args.get('runfromdoctester', False):
30
+ return
31
+
32
+ self.win_args = dict(self.default_win_args, **win_args)
33
+ self.Thread = Thread(target=self.__event_loop__)
34
+ self.Thread.start()
35
+
36
+ def __event_loop__(self, **win_args):
37
+ """
38
+ The event loop thread function. Do not override or call
39
+ directly (it is called by __init__).
40
+ """
41
+ gl_lock.acquire()
42
+ try:
43
+ try:
44
+ super().__init__(**self.win_args)
45
+ self.switch_to()
46
+ self.setup()
47
+ except Exception as e:
48
+ print("Window initialization failed: %s" % (str(e)))
49
+ self.has_exit = True
50
+ finally:
51
+ gl_lock.release()
52
+
53
+ clock = Clock()
54
+ clock.fps_limit = self.fps_limit
55
+ while not self.has_exit:
56
+ dt = clock.tick()
57
+ gl_lock.acquire()
58
+ try:
59
+ try:
60
+ self.switch_to()
61
+ self.dispatch_events()
62
+ self.clear()
63
+ self.update(dt)
64
+ self.draw()
65
+ self.flip()
66
+ except Exception as e:
67
+ print("Uncaught exception in event loop: %s" % str(e))
68
+ self.has_exit = True
69
+ finally:
70
+ gl_lock.release()
71
+ super().close()
72
+
73
+ def close(self):
74
+ """
75
+ Closes the window.
76
+ """
77
+ self.has_exit = True
78
+
79
+ def setup(self):
80
+ """
81
+ Called once before the event loop begins.
82
+ Override this method in a child class. This
83
+ is the best place to put things like OpenGL
84
+ initialization calls.
85
+ """
86
+ pass
87
+
88
+ def update(self, dt):
89
+ """
90
+ Called before draw during each iteration of
91
+ the event loop. dt is the elapsed time in
92
+ seconds since the last update. OpenGL rendering
93
+ calls are best put in draw() rather than here.
94
+ """
95
+ pass
96
+
97
+ def draw(self):
98
+ """
99
+ Called after update during each iteration of
100
+ the event loop. Put OpenGL rendering calls
101
+ here.
102
+ """
103
+ pass
104
+
105
+ if __name__ == '__main__':
106
+ ManagedWindow()
llmeval-env/lib/python3.10/site-packages/sympy/plotting/pygletplot/plot.py ADDED
@@ -0,0 +1,464 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from threading import RLock
2
+
3
+ # it is sufficient to import "pyglet" here once
4
+ try:
5
+ import pyglet.gl as pgl
6
+ except ImportError:
7
+ raise ImportError("pyglet is required for plotting.\n "
8
+ "visit https://pyglet.org/")
9
+
10
+ from sympy.core.numbers import Integer
11
+ from sympy.external.gmpy import SYMPY_INTS
12
+ from sympy.geometry.entity import GeometryEntity
13
+ from sympy.plotting.pygletplot.plot_axes import PlotAxes
14
+ from sympy.plotting.pygletplot.plot_mode import PlotMode
15
+ from sympy.plotting.pygletplot.plot_object import PlotObject
16
+ from sympy.plotting.pygletplot.plot_window import PlotWindow
17
+ from sympy.plotting.pygletplot.util import parse_option_string
18
+ from sympy.utilities.decorator import doctest_depends_on
19
+ from sympy.utilities.iterables import is_sequence
20
+
21
+ from time import sleep
22
+ from os import getcwd, listdir
23
+
24
+ import ctypes
25
+
26
+ @doctest_depends_on(modules=('pyglet',))
27
+ class PygletPlot:
28
+ """
29
+ Plot Examples
30
+ =============
31
+
32
+ See examples/advanced/pyglet_plotting.py for many more examples.
33
+
34
+ >>> from sympy.plotting.pygletplot import PygletPlot as Plot
35
+ >>> from sympy.abc import x, y, z
36
+
37
+ >>> Plot(x*y**3-y*x**3)
38
+ [0]: -x**3*y + x*y**3, 'mode=cartesian'
39
+
40
+ >>> p = Plot()
41
+ >>> p[1] = x*y
42
+ >>> p[1].color = z, (0.4,0.4,0.9), (0.9,0.4,0.4)
43
+
44
+ >>> p = Plot()
45
+ >>> p[1] = x**2+y**2
46
+ >>> p[2] = -x**2-y**2
47
+
48
+
49
+ Variable Intervals
50
+ ==================
51
+
52
+ The basic format is [var, min, max, steps], but the
53
+ syntax is flexible and arguments left out are taken
54
+ from the defaults for the current coordinate mode:
55
+
56
+ >>> Plot(x**2) # implies [x,-5,5,100]
57
+ [0]: x**2, 'mode=cartesian'
58
+ >>> Plot(x**2, [], []) # [x,-1,1,40], [y,-1,1,40]
59
+ [0]: x**2, 'mode=cartesian'
60
+ >>> Plot(x**2-y**2, [100], [100]) # [x,-1,1,100], [y,-1,1,100]
61
+ [0]: x**2 - y**2, 'mode=cartesian'
62
+ >>> Plot(x**2, [x,-13,13,100])
63
+ [0]: x**2, 'mode=cartesian'
64
+ >>> Plot(x**2, [-13,13]) # [x,-13,13,100]
65
+ [0]: x**2, 'mode=cartesian'
66
+ >>> Plot(x**2, [x,-13,13]) # [x,-13,13,10]
67
+ [0]: x**2, 'mode=cartesian'
68
+ >>> Plot(1*x, [], [x], mode='cylindrical')
69
+ ... # [unbound_theta,0,2*Pi,40], [x,-1,1,20]
70
+ [0]: x, 'mode=cartesian'
71
+
72
+
73
+ Coordinate Modes
74
+ ================
75
+
76
+ Plot supports several curvilinear coordinate modes, and
77
+ they independent for each plotted function. You can specify
78
+ a coordinate mode explicitly with the 'mode' named argument,
79
+ but it can be automatically determined for Cartesian or
80
+ parametric plots, and therefore must only be specified for
81
+ polar, cylindrical, and spherical modes.
82
+
83
+ Specifically, Plot(function arguments) and Plot[n] =
84
+ (function arguments) will interpret your arguments as a
85
+ Cartesian plot if you provide one function and a parametric
86
+ plot if you provide two or three functions. Similarly, the
87
+ arguments will be interpreted as a curve if one variable is
88
+ used, and a surface if two are used.
89
+
90
+ Supported mode names by number of variables:
91
+
92
+ 1: parametric, cartesian, polar
93
+ 2: parametric, cartesian, cylindrical = polar, spherical
94
+
95
+ >>> Plot(1, mode='spherical')
96
+
97
+
98
+ Calculator-like Interface
99
+ =========================
100
+
101
+ >>> p = Plot(visible=False)
102
+ >>> f = x**2
103
+ >>> p[1] = f
104
+ >>> p[2] = f.diff(x)
105
+ >>> p[3] = f.diff(x).diff(x)
106
+ >>> p
107
+ [1]: x**2, 'mode=cartesian'
108
+ [2]: 2*x, 'mode=cartesian'
109
+ [3]: 2, 'mode=cartesian'
110
+ >>> p.show()
111
+ >>> p.clear()
112
+ >>> p
113
+ <blank plot>
114
+ >>> p[1] = x**2+y**2
115
+ >>> p[1].style = 'solid'
116
+ >>> p[2] = -x**2-y**2
117
+ >>> p[2].style = 'wireframe'
118
+ >>> p[1].color = z, (0.4,0.4,0.9), (0.9,0.4,0.4)
119
+ >>> p[1].style = 'both'
120
+ >>> p[2].style = 'both'
121
+ >>> p.close()
122
+
123
+
124
+ Plot Window Keyboard Controls
125
+ =============================
126
+
127
+ Screen Rotation:
128
+ X,Y axis Arrow Keys, A,S,D,W, Numpad 4,6,8,2
129
+ Z axis Q,E, Numpad 7,9
130
+
131
+ Model Rotation:
132
+ Z axis Z,C, Numpad 1,3
133
+
134
+ Zoom: R,F, PgUp,PgDn, Numpad +,-
135
+
136
+ Reset Camera: X, Numpad 5
137
+
138
+ Camera Presets:
139
+ XY F1
140
+ XZ F2
141
+ YZ F3
142
+ Perspective F4
143
+
144
+ Sensitivity Modifier: SHIFT
145
+
146
+ Axes Toggle:
147
+ Visible F5
148
+ Colors F6
149
+
150
+ Close Window: ESCAPE
151
+
152
+ =============================
153
+
154
+ """
155
+
156
+ @doctest_depends_on(modules=('pyglet',))
157
+ def __init__(self, *fargs, **win_args):
158
+ """
159
+ Positional Arguments
160
+ ====================
161
+
162
+ Any given positional arguments are used to
163
+ initialize a plot function at index 1. In
164
+ other words...
165
+
166
+ >>> from sympy.plotting.pygletplot import PygletPlot as Plot
167
+ >>> from sympy.abc import x
168
+ >>> p = Plot(x**2, visible=False)
169
+
170
+ ...is equivalent to...
171
+
172
+ >>> p = Plot(visible=False)
173
+ >>> p[1] = x**2
174
+
175
+ Note that in earlier versions of the plotting
176
+ module, you were able to specify multiple
177
+ functions in the initializer. This functionality
178
+ has been dropped in favor of better automatic
179
+ plot plot_mode detection.
180
+
181
+
182
+ Named Arguments
183
+ ===============
184
+
185
+ axes
186
+ An option string of the form
187
+ "key1=value1; key2 = value2" which
188
+ can use the following options:
189
+
190
+ style = ordinate
191
+ none OR frame OR box OR ordinate
192
+
193
+ stride = 0.25
194
+ val OR (val_x, val_y, val_z)
195
+
196
+ overlay = True (draw on top of plot)
197
+ True OR False
198
+
199
+ colored = False (False uses Black,
200
+ True uses colors
201
+ R,G,B = X,Y,Z)
202
+ True OR False
203
+
204
+ label_axes = False (display axis names
205
+ at endpoints)
206
+ True OR False
207
+
208
+ visible = True (show immediately
209
+ True OR False
210
+
211
+
212
+ The following named arguments are passed as
213
+ arguments to window initialization:
214
+
215
+ antialiasing = True
216
+ True OR False
217
+
218
+ ortho = False
219
+ True OR False
220
+
221
+ invert_mouse_zoom = False
222
+ True OR False
223
+
224
+ """
225
+ # Register the plot modes
226
+ from . import plot_modes # noqa
227
+
228
+ self._win_args = win_args
229
+ self._window = None
230
+
231
+ self._render_lock = RLock()
232
+
233
+ self._functions = {}
234
+ self._pobjects = []
235
+ self._screenshot = ScreenShot(self)
236
+
237
+ axe_options = parse_option_string(win_args.pop('axes', ''))
238
+ self.axes = PlotAxes(**axe_options)
239
+ self._pobjects.append(self.axes)
240
+
241
+ self[0] = fargs
242
+ if win_args.get('visible', True):
243
+ self.show()
244
+
245
+ ## Window Interfaces
246
+
247
+ def show(self):
248
+ """
249
+ Creates and displays a plot window, or activates it
250
+ (gives it focus) if it has already been created.
251
+ """
252
+ if self._window and not self._window.has_exit:
253
+ self._window.activate()
254
+ else:
255
+ self._win_args['visible'] = True
256
+ self.axes.reset_resources()
257
+
258
+ #if hasattr(self, '_doctest_depends_on'):
259
+ # self._win_args['runfromdoctester'] = True
260
+
261
+ self._window = PlotWindow(self, **self._win_args)
262
+
263
+ def close(self):
264
+ """
265
+ Closes the plot window.
266
+ """
267
+ if self._window:
268
+ self._window.close()
269
+
270
+ def saveimage(self, outfile=None, format='', size=(600, 500)):
271
+ """
272
+ Saves a screen capture of the plot window to an
273
+ image file.
274
+
275
+ If outfile is given, it can either be a path
276
+ or a file object. Otherwise a png image will
277
+ be saved to the current working directory.
278
+ If the format is omitted, it is determined from
279
+ the filename extension.
280
+ """
281
+ self._screenshot.save(outfile, format, size)
282
+
283
+ ## Function List Interfaces
284
+
285
+ def clear(self):
286
+ """
287
+ Clears the function list of this plot.
288
+ """
289
+ self._render_lock.acquire()
290
+ self._functions = {}
291
+ self.adjust_all_bounds()
292
+ self._render_lock.release()
293
+
294
+ def __getitem__(self, i):
295
+ """
296
+ Returns the function at position i in the
297
+ function list.
298
+ """
299
+ return self._functions[i]
300
+
301
+ def __setitem__(self, i, args):
302
+ """
303
+ Parses and adds a PlotMode to the function
304
+ list.
305
+ """
306
+ if not (isinstance(i, (SYMPY_INTS, Integer)) and i >= 0):
307
+ raise ValueError("Function index must "
308
+ "be an integer >= 0.")
309
+
310
+ if isinstance(args, PlotObject):
311
+ f = args
312
+ else:
313
+ if (not is_sequence(args)) or isinstance(args, GeometryEntity):
314
+ args = [args]
315
+ if len(args) == 0:
316
+ return # no arguments given
317
+ kwargs = {"bounds_callback": self.adjust_all_bounds}
318
+ f = PlotMode(*args, **kwargs)
319
+
320
+ if f:
321
+ self._render_lock.acquire()
322
+ self._functions[i] = f
323
+ self._render_lock.release()
324
+ else:
325
+ raise ValueError("Failed to parse '%s'."
326
+ % ', '.join(str(a) for a in args))
327
+
328
+ def __delitem__(self, i):
329
+ """
330
+ Removes the function in the function list at
331
+ position i.
332
+ """
333
+ self._render_lock.acquire()
334
+ del self._functions[i]
335
+ self.adjust_all_bounds()
336
+ self._render_lock.release()
337
+
338
+ def firstavailableindex(self):
339
+ """
340
+ Returns the first unused index in the function list.
341
+ """
342
+ i = 0
343
+ self._render_lock.acquire()
344
+ while i in self._functions:
345
+ i += 1
346
+ self._render_lock.release()
347
+ return i
348
+
349
+ def append(self, *args):
350
+ """
351
+ Parses and adds a PlotMode to the function
352
+ list at the first available index.
353
+ """
354
+ self.__setitem__(self.firstavailableindex(), args)
355
+
356
+ def __len__(self):
357
+ """
358
+ Returns the number of functions in the function list.
359
+ """
360
+ return len(self._functions)
361
+
362
+ def __iter__(self):
363
+ """
364
+ Allows iteration of the function list.
365
+ """
366
+ return self._functions.itervalues()
367
+
368
+ def __repr__(self):
369
+ return str(self)
370
+
371
+ def __str__(self):
372
+ """
373
+ Returns a string containing a new-line separated
374
+ list of the functions in the function list.
375
+ """
376
+ s = ""
377
+ if len(self._functions) == 0:
378
+ s += "<blank plot>"
379
+ else:
380
+ self._render_lock.acquire()
381
+ s += "\n".join(["%s[%i]: %s" % ("", i, str(self._functions[i]))
382
+ for i in self._functions])
383
+ self._render_lock.release()
384
+ return s
385
+
386
+ def adjust_all_bounds(self):
387
+ self._render_lock.acquire()
388
+ self.axes.reset_bounding_box()
389
+ for f in self._functions:
390
+ self.axes.adjust_bounds(self._functions[f].bounds)
391
+ self._render_lock.release()
392
+
393
+ def wait_for_calculations(self):
394
+ sleep(0)
395
+ self._render_lock.acquire()
396
+ for f in self._functions:
397
+ a = self._functions[f]._get_calculating_verts
398
+ b = self._functions[f]._get_calculating_cverts
399
+ while a() or b():
400
+ sleep(0)
401
+ self._render_lock.release()
402
+
403
+ class ScreenShot:
404
+ def __init__(self, plot):
405
+ self._plot = plot
406
+ self.screenshot_requested = False
407
+ self.outfile = None
408
+ self.format = ''
409
+ self.invisibleMode = False
410
+ self.flag = 0
411
+
412
+ def __bool__(self):
413
+ return self.screenshot_requested
414
+
415
+ def _execute_saving(self):
416
+ if self.flag < 3:
417
+ self.flag += 1
418
+ return
419
+
420
+ size_x, size_y = self._plot._window.get_size()
421
+ size = size_x*size_y*4*ctypes.sizeof(ctypes.c_ubyte)
422
+ image = ctypes.create_string_buffer(size)
423
+ pgl.glReadPixels(0, 0, size_x, size_y, pgl.GL_RGBA, pgl.GL_UNSIGNED_BYTE, image)
424
+ from PIL import Image
425
+ im = Image.frombuffer('RGBA', (size_x, size_y),
426
+ image.raw, 'raw', 'RGBA', 0, 1)
427
+ im.transpose(Image.FLIP_TOP_BOTTOM).save(self.outfile, self.format)
428
+
429
+ self.flag = 0
430
+ self.screenshot_requested = False
431
+ if self.invisibleMode:
432
+ self._plot._window.close()
433
+
434
+ def save(self, outfile=None, format='', size=(600, 500)):
435
+ self.outfile = outfile
436
+ self.format = format
437
+ self.size = size
438
+ self.screenshot_requested = True
439
+
440
+ if not self._plot._window or self._plot._window.has_exit:
441
+ self._plot._win_args['visible'] = False
442
+
443
+ self._plot._win_args['width'] = size[0]
444
+ self._plot._win_args['height'] = size[1]
445
+
446
+ self._plot.axes.reset_resources()
447
+ self._plot._window = PlotWindow(self._plot, **self._plot._win_args)
448
+ self.invisibleMode = True
449
+
450
+ if self.outfile is None:
451
+ self.outfile = self._create_unique_path()
452
+ print(self.outfile)
453
+
454
+ def _create_unique_path(self):
455
+ cwd = getcwd()
456
+ l = listdir(cwd)
457
+ path = ''
458
+ i = 0
459
+ while True:
460
+ if not 'plot_%s.png' % i in l:
461
+ path = cwd + '/plot_%s.png' % i
462
+ break
463
+ i += 1
464
+ return path
llmeval-env/lib/python3.10/site-packages/sympy/plotting/pygletplot/plot_axes.py ADDED
@@ -0,0 +1,251 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pyglet.gl as pgl
2
+ from pyglet import font
3
+
4
+ from sympy.core import S
5
+ from sympy.plotting.pygletplot.plot_object import PlotObject
6
+ from sympy.plotting.pygletplot.util import billboard_matrix, dot_product, \
7
+ get_direction_vectors, strided_range, vec_mag, vec_sub
8
+ from sympy.utilities.iterables import is_sequence
9
+
10
+
11
+ class PlotAxes(PlotObject):
12
+
13
+ def __init__(self, *args,
14
+ style='', none=None, frame=None, box=None, ordinate=None,
15
+ stride=0.25,
16
+ visible='', overlay='', colored='', label_axes='', label_ticks='',
17
+ tick_length=0.1,
18
+ font_face='Arial', font_size=28,
19
+ **kwargs):
20
+ # initialize style parameter
21
+ style = style.lower()
22
+
23
+ # allow alias kwargs to override style kwarg
24
+ if none is not None:
25
+ style = 'none'
26
+ if frame is not None:
27
+ style = 'frame'
28
+ if box is not None:
29
+ style = 'box'
30
+ if ordinate is not None:
31
+ style = 'ordinate'
32
+
33
+ if style in ['', 'ordinate']:
34
+ self._render_object = PlotAxesOrdinate(self)
35
+ elif style in ['frame', 'box']:
36
+ self._render_object = PlotAxesFrame(self)
37
+ elif style in ['none']:
38
+ self._render_object = None
39
+ else:
40
+ raise ValueError(("Unrecognized axes style %s.") % (style))
41
+
42
+ # initialize stride parameter
43
+ try:
44
+ stride = eval(stride)
45
+ except TypeError:
46
+ pass
47
+ if is_sequence(stride):
48
+ if len(stride) != 3:
49
+ raise ValueError("length should be equal to 3")
50
+ self._stride = stride
51
+ else:
52
+ self._stride = [stride, stride, stride]
53
+ self._tick_length = float(tick_length)
54
+
55
+ # setup bounding box and ticks
56
+ self._origin = [0, 0, 0]
57
+ self.reset_bounding_box()
58
+
59
+ def flexible_boolean(input, default):
60
+ if input in [True, False]:
61
+ return input
62
+ if input in ('f', 'F', 'false', 'False'):
63
+ return False
64
+ if input in ('t', 'T', 'true', 'True'):
65
+ return True
66
+ return default
67
+
68
+ # initialize remaining parameters
69
+ self.visible = flexible_boolean(kwargs, True)
70
+ self._overlay = flexible_boolean(overlay, True)
71
+ self._colored = flexible_boolean(colored, False)
72
+ self._label_axes = flexible_boolean(label_axes, False)
73
+ self._label_ticks = flexible_boolean(label_ticks, True)
74
+
75
+ # setup label font
76
+ self.font_face = font_face
77
+ self.font_size = font_size
78
+
79
+ # this is also used to reinit the
80
+ # font on window close/reopen
81
+ self.reset_resources()
82
+
83
+ def reset_resources(self):
84
+ self.label_font = None
85
+
86
+ def reset_bounding_box(self):
87
+ self._bounding_box = [[None, None], [None, None], [None, None]]
88
+ self._axis_ticks = [[], [], []]
89
+
90
+ def draw(self):
91
+ if self._render_object:
92
+ pgl.glPushAttrib(pgl.GL_ENABLE_BIT | pgl.GL_POLYGON_BIT | pgl.GL_DEPTH_BUFFER_BIT)
93
+ if self._overlay:
94
+ pgl.glDisable(pgl.GL_DEPTH_TEST)
95
+ self._render_object.draw()
96
+ pgl.glPopAttrib()
97
+
98
+ def adjust_bounds(self, child_bounds):
99
+ b = self._bounding_box
100
+ c = child_bounds
101
+ for i in range(3):
102
+ if abs(c[i][0]) is S.Infinity or abs(c[i][1]) is S.Infinity:
103
+ continue
104
+ b[i][0] = c[i][0] if b[i][0] is None else min([b[i][0], c[i][0]])
105
+ b[i][1] = c[i][1] if b[i][1] is None else max([b[i][1], c[i][1]])
106
+ self._bounding_box = b
107
+ self._recalculate_axis_ticks(i)
108
+
109
+ def _recalculate_axis_ticks(self, axis):
110
+ b = self._bounding_box
111
+ if b[axis][0] is None or b[axis][1] is None:
112
+ self._axis_ticks[axis] = []
113
+ else:
114
+ self._axis_ticks[axis] = strided_range(b[axis][0], b[axis][1],
115
+ self._stride[axis])
116
+
117
+ def toggle_visible(self):
118
+ self.visible = not self.visible
119
+
120
+ def toggle_colors(self):
121
+ self._colored = not self._colored
122
+
123
+
124
+ class PlotAxesBase(PlotObject):
125
+
126
+ def __init__(self, parent_axes):
127
+ self._p = parent_axes
128
+
129
+ def draw(self):
130
+ color = [([0.2, 0.1, 0.3], [0.2, 0.1, 0.3], [0.2, 0.1, 0.3]),
131
+ ([0.9, 0.3, 0.5], [0.5, 1.0, 0.5], [0.3, 0.3, 0.9])][self._p._colored]
132
+ self.draw_background(color)
133
+ self.draw_axis(2, color[2])
134
+ self.draw_axis(1, color[1])
135
+ self.draw_axis(0, color[0])
136
+
137
+ def draw_background(self, color):
138
+ pass # optional
139
+
140
+ def draw_axis(self, axis, color):
141
+ raise NotImplementedError()
142
+
143
+ def draw_text(self, text, position, color, scale=1.0):
144
+ if len(color) == 3:
145
+ color = (color[0], color[1], color[2], 1.0)
146
+
147
+ if self._p.label_font is None:
148
+ self._p.label_font = font.load(self._p.font_face,
149
+ self._p.font_size,
150
+ bold=True, italic=False)
151
+
152
+ label = font.Text(self._p.label_font, text,
153
+ color=color,
154
+ valign=font.Text.BASELINE,
155
+ halign=font.Text.CENTER)
156
+
157
+ pgl.glPushMatrix()
158
+ pgl.glTranslatef(*position)
159
+ billboard_matrix()
160
+ scale_factor = 0.005 * scale
161
+ pgl.glScalef(scale_factor, scale_factor, scale_factor)
162
+ pgl.glColor4f(0, 0, 0, 0)
163
+ label.draw()
164
+ pgl.glPopMatrix()
165
+
166
+ def draw_line(self, v, color):
167
+ o = self._p._origin
168
+ pgl.glBegin(pgl.GL_LINES)
169
+ pgl.glColor3f(*color)
170
+ pgl.glVertex3f(v[0][0] + o[0], v[0][1] + o[1], v[0][2] + o[2])
171
+ pgl.glVertex3f(v[1][0] + o[0], v[1][1] + o[1], v[1][2] + o[2])
172
+ pgl.glEnd()
173
+
174
+
175
+ class PlotAxesOrdinate(PlotAxesBase):
176
+
177
+ def __init__(self, parent_axes):
178
+ super().__init__(parent_axes)
179
+
180
+ def draw_axis(self, axis, color):
181
+ ticks = self._p._axis_ticks[axis]
182
+ radius = self._p._tick_length / 2.0
183
+ if len(ticks) < 2:
184
+ return
185
+
186
+ # calculate the vector for this axis
187
+ axis_lines = [[0, 0, 0], [0, 0, 0]]
188
+ axis_lines[0][axis], axis_lines[1][axis] = ticks[0], ticks[-1]
189
+ axis_vector = vec_sub(axis_lines[1], axis_lines[0])
190
+
191
+ # calculate angle to the z direction vector
192
+ pos_z = get_direction_vectors()[2]
193
+ d = abs(dot_product(axis_vector, pos_z))
194
+ d = d / vec_mag(axis_vector)
195
+
196
+ # don't draw labels if we're looking down the axis
197
+ labels_visible = abs(d - 1.0) > 0.02
198
+
199
+ # draw the ticks and labels
200
+ for tick in ticks:
201
+ self.draw_tick_line(axis, color, radius, tick, labels_visible)
202
+
203
+ # draw the axis line and labels
204
+ self.draw_axis_line(axis, color, ticks[0], ticks[-1], labels_visible)
205
+
206
+ def draw_axis_line(self, axis, color, a_min, a_max, labels_visible):
207
+ axis_line = [[0, 0, 0], [0, 0, 0]]
208
+ axis_line[0][axis], axis_line[1][axis] = a_min, a_max
209
+ self.draw_line(axis_line, color)
210
+ if labels_visible:
211
+ self.draw_axis_line_labels(axis, color, axis_line)
212
+
213
+ def draw_axis_line_labels(self, axis, color, axis_line):
214
+ if not self._p._label_axes:
215
+ return
216
+ axis_labels = [axis_line[0][::], axis_line[1][::]]
217
+ axis_labels[0][axis] -= 0.3
218
+ axis_labels[1][axis] += 0.3
219
+ a_str = ['X', 'Y', 'Z'][axis]
220
+ self.draw_text("-" + a_str, axis_labels[0], color)
221
+ self.draw_text("+" + a_str, axis_labels[1], color)
222
+
223
+ def draw_tick_line(self, axis, color, radius, tick, labels_visible):
224
+ tick_axis = {0: 1, 1: 0, 2: 1}[axis]
225
+ tick_line = [[0, 0, 0], [0, 0, 0]]
226
+ tick_line[0][axis] = tick_line[1][axis] = tick
227
+ tick_line[0][tick_axis], tick_line[1][tick_axis] = -radius, radius
228
+ self.draw_line(tick_line, color)
229
+ if labels_visible:
230
+ self.draw_tick_line_label(axis, color, radius, tick)
231
+
232
+ def draw_tick_line_label(self, axis, color, radius, tick):
233
+ if not self._p._label_axes:
234
+ return
235
+ tick_label_vector = [0, 0, 0]
236
+ tick_label_vector[axis] = tick
237
+ tick_label_vector[{0: 1, 1: 0, 2: 1}[axis]] = [-1, 1, 1][
238
+ axis] * radius * 3.5
239
+ self.draw_text(str(tick), tick_label_vector, color, scale=0.5)
240
+
241
+
242
+ class PlotAxesFrame(PlotAxesBase):
243
+
244
+ def __init__(self, parent_axes):
245
+ super().__init__(parent_axes)
246
+
247
+ def draw_background(self, color):
248
+ pass
249
+
250
+ def draw_axis(self, axis, color):
251
+ raise NotImplementedError()
llmeval-env/lib/python3.10/site-packages/sympy/plotting/pygletplot/plot_camera.py ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pyglet.gl as pgl
2
+ from sympy.plotting.pygletplot.plot_rotation import get_spherical_rotatation
3
+ from sympy.plotting.pygletplot.util import get_model_matrix, model_to_screen, \
4
+ screen_to_model, vec_subs
5
+
6
+
7
+ class PlotCamera:
8
+
9
+ min_dist = 0.05
10
+ max_dist = 500.0
11
+
12
+ min_ortho_dist = 100.0
13
+ max_ortho_dist = 10000.0
14
+
15
+ _default_dist = 6.0
16
+ _default_ortho_dist = 600.0
17
+
18
+ rot_presets = {
19
+ 'xy': (0, 0, 0),
20
+ 'xz': (-90, 0, 0),
21
+ 'yz': (0, 90, 0),
22
+ 'perspective': (-45, 0, -45)
23
+ }
24
+
25
+ def __init__(self, window, ortho=False):
26
+ self.window = window
27
+ self.axes = self.window.plot.axes
28
+ self.ortho = ortho
29
+ self.reset()
30
+
31
+ def init_rot_matrix(self):
32
+ pgl.glPushMatrix()
33
+ pgl.glLoadIdentity()
34
+ self._rot = get_model_matrix()
35
+ pgl.glPopMatrix()
36
+
37
+ def set_rot_preset(self, preset_name):
38
+ self.init_rot_matrix()
39
+ try:
40
+ r = self.rot_presets[preset_name]
41
+ except AttributeError:
42
+ raise ValueError(
43
+ "%s is not a valid rotation preset." % preset_name)
44
+ try:
45
+ self.euler_rotate(r[0], 1, 0, 0)
46
+ self.euler_rotate(r[1], 0, 1, 0)
47
+ self.euler_rotate(r[2], 0, 0, 1)
48
+ except AttributeError:
49
+ pass
50
+
51
+ def reset(self):
52
+ self._dist = 0.0
53
+ self._x, self._y = 0.0, 0.0
54
+ self._rot = None
55
+ if self.ortho:
56
+ self._dist = self._default_ortho_dist
57
+ else:
58
+ self._dist = self._default_dist
59
+ self.init_rot_matrix()
60
+
61
+ def mult_rot_matrix(self, rot):
62
+ pgl.glPushMatrix()
63
+ pgl.glLoadMatrixf(rot)
64
+ pgl.glMultMatrixf(self._rot)
65
+ self._rot = get_model_matrix()
66
+ pgl.glPopMatrix()
67
+
68
+ def setup_projection(self):
69
+ pgl.glMatrixMode(pgl.GL_PROJECTION)
70
+ pgl.glLoadIdentity()
71
+ if self.ortho:
72
+ # yep, this is pseudo ortho (don't tell anyone)
73
+ pgl.gluPerspective(
74
+ 0.3, float(self.window.width)/float(self.window.height),
75
+ self.min_ortho_dist - 0.01, self.max_ortho_dist + 0.01)
76
+ else:
77
+ pgl.gluPerspective(
78
+ 30.0, float(self.window.width)/float(self.window.height),
79
+ self.min_dist - 0.01, self.max_dist + 0.01)
80
+ pgl.glMatrixMode(pgl.GL_MODELVIEW)
81
+
82
+ def _get_scale(self):
83
+ return 1.0, 1.0, 1.0
84
+
85
+ def apply_transformation(self):
86
+ pgl.glLoadIdentity()
87
+ pgl.glTranslatef(self._x, self._y, -self._dist)
88
+ if self._rot is not None:
89
+ pgl.glMultMatrixf(self._rot)
90
+ pgl.glScalef(*self._get_scale())
91
+
92
+ def spherical_rotate(self, p1, p2, sensitivity=1.0):
93
+ mat = get_spherical_rotatation(p1, p2, self.window.width,
94
+ self.window.height, sensitivity)
95
+ if mat is not None:
96
+ self.mult_rot_matrix(mat)
97
+
98
+ def euler_rotate(self, angle, x, y, z):
99
+ pgl.glPushMatrix()
100
+ pgl.glLoadMatrixf(self._rot)
101
+ pgl.glRotatef(angle, x, y, z)
102
+ self._rot = get_model_matrix()
103
+ pgl.glPopMatrix()
104
+
105
+ def zoom_relative(self, clicks, sensitivity):
106
+
107
+ if self.ortho:
108
+ dist_d = clicks * sensitivity * 50.0
109
+ min_dist = self.min_ortho_dist
110
+ max_dist = self.max_ortho_dist
111
+ else:
112
+ dist_d = clicks * sensitivity
113
+ min_dist = self.min_dist
114
+ max_dist = self.max_dist
115
+
116
+ new_dist = (self._dist - dist_d)
117
+ if (clicks < 0 and new_dist < max_dist) or new_dist > min_dist:
118
+ self._dist = new_dist
119
+
120
+ def mouse_translate(self, x, y, dx, dy):
121
+ pgl.glPushMatrix()
122
+ pgl.glLoadIdentity()
123
+ pgl.glTranslatef(0, 0, -self._dist)
124
+ z = model_to_screen(0, 0, 0)[2]
125
+ d = vec_subs(screen_to_model(x, y, z), screen_to_model(x - dx, y - dy, z))
126
+ pgl.glPopMatrix()
127
+ self._x += d[0]
128
+ self._y += d[1]
llmeval-env/lib/python3.10/site-packages/sympy/plotting/pygletplot/plot_controller.py ADDED
@@ -0,0 +1,218 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pyglet.window import key
2
+ from pyglet.window.mouse import LEFT, RIGHT, MIDDLE
3
+ from sympy.plotting.pygletplot.util import get_direction_vectors, get_basis_vectors
4
+
5
+
6
+ class PlotController:
7
+
8
+ normal_mouse_sensitivity = 4.0
9
+ modified_mouse_sensitivity = 1.0
10
+
11
+ normal_key_sensitivity = 160.0
12
+ modified_key_sensitivity = 40.0
13
+
14
+ keymap = {
15
+ key.LEFT: 'left',
16
+ key.A: 'left',
17
+ key.NUM_4: 'left',
18
+
19
+ key.RIGHT: 'right',
20
+ key.D: 'right',
21
+ key.NUM_6: 'right',
22
+
23
+ key.UP: 'up',
24
+ key.W: 'up',
25
+ key.NUM_8: 'up',
26
+
27
+ key.DOWN: 'down',
28
+ key.S: 'down',
29
+ key.NUM_2: 'down',
30
+
31
+ key.Z: 'rotate_z_neg',
32
+ key.NUM_1: 'rotate_z_neg',
33
+
34
+ key.C: 'rotate_z_pos',
35
+ key.NUM_3: 'rotate_z_pos',
36
+
37
+ key.Q: 'spin_left',
38
+ key.NUM_7: 'spin_left',
39
+ key.E: 'spin_right',
40
+ key.NUM_9: 'spin_right',
41
+
42
+ key.X: 'reset_camera',
43
+ key.NUM_5: 'reset_camera',
44
+
45
+ key.NUM_ADD: 'zoom_in',
46
+ key.PAGEUP: 'zoom_in',
47
+ key.R: 'zoom_in',
48
+
49
+ key.NUM_SUBTRACT: 'zoom_out',
50
+ key.PAGEDOWN: 'zoom_out',
51
+ key.F: 'zoom_out',
52
+
53
+ key.RSHIFT: 'modify_sensitivity',
54
+ key.LSHIFT: 'modify_sensitivity',
55
+
56
+ key.F1: 'rot_preset_xy',
57
+ key.F2: 'rot_preset_xz',
58
+ key.F3: 'rot_preset_yz',
59
+ key.F4: 'rot_preset_perspective',
60
+
61
+ key.F5: 'toggle_axes',
62
+ key.F6: 'toggle_axe_colors',
63
+
64
+ key.F8: 'save_image'
65
+ }
66
+
67
+ def __init__(self, window, *, invert_mouse_zoom=False, **kwargs):
68
+ self.invert_mouse_zoom = invert_mouse_zoom
69
+ self.window = window
70
+ self.camera = window.camera
71
+ self.action = {
72
+ # Rotation around the view Y (up) vector
73
+ 'left': False,
74
+ 'right': False,
75
+ # Rotation around the view X vector
76
+ 'up': False,
77
+ 'down': False,
78
+ # Rotation around the view Z vector
79
+ 'spin_left': False,
80
+ 'spin_right': False,
81
+ # Rotation around the model Z vector
82
+ 'rotate_z_neg': False,
83
+ 'rotate_z_pos': False,
84
+ # Reset to the default rotation
85
+ 'reset_camera': False,
86
+ # Performs camera z-translation
87
+ 'zoom_in': False,
88
+ 'zoom_out': False,
89
+ # Use alternative sensitivity (speed)
90
+ 'modify_sensitivity': False,
91
+ # Rotation presets
92
+ 'rot_preset_xy': False,
93
+ 'rot_preset_xz': False,
94
+ 'rot_preset_yz': False,
95
+ 'rot_preset_perspective': False,
96
+ # axes
97
+ 'toggle_axes': False,
98
+ 'toggle_axe_colors': False,
99
+ # screenshot
100
+ 'save_image': False
101
+ }
102
+
103
+ def update(self, dt):
104
+ z = 0
105
+ if self.action['zoom_out']:
106
+ z -= 1
107
+ if self.action['zoom_in']:
108
+ z += 1
109
+ if z != 0:
110
+ self.camera.zoom_relative(z/10.0, self.get_key_sensitivity()/10.0)
111
+
112
+ dx, dy, dz = 0, 0, 0
113
+ if self.action['left']:
114
+ dx -= 1
115
+ if self.action['right']:
116
+ dx += 1
117
+ if self.action['up']:
118
+ dy -= 1
119
+ if self.action['down']:
120
+ dy += 1
121
+ if self.action['spin_left']:
122
+ dz += 1
123
+ if self.action['spin_right']:
124
+ dz -= 1
125
+
126
+ if not self.is_2D():
127
+ if dx != 0:
128
+ self.camera.euler_rotate(dx*dt*self.get_key_sensitivity(),
129
+ *(get_direction_vectors()[1]))
130
+ if dy != 0:
131
+ self.camera.euler_rotate(dy*dt*self.get_key_sensitivity(),
132
+ *(get_direction_vectors()[0]))
133
+ if dz != 0:
134
+ self.camera.euler_rotate(dz*dt*self.get_key_sensitivity(),
135
+ *(get_direction_vectors()[2]))
136
+ else:
137
+ self.camera.mouse_translate(0, 0, dx*dt*self.get_key_sensitivity(),
138
+ -dy*dt*self.get_key_sensitivity())
139
+
140
+ rz = 0
141
+ if self.action['rotate_z_neg'] and not self.is_2D():
142
+ rz -= 1
143
+ if self.action['rotate_z_pos'] and not self.is_2D():
144
+ rz += 1
145
+
146
+ if rz != 0:
147
+ self.camera.euler_rotate(rz*dt*self.get_key_sensitivity(),
148
+ *(get_basis_vectors()[2]))
149
+
150
+ if self.action['reset_camera']:
151
+ self.camera.reset()
152
+
153
+ if self.action['rot_preset_xy']:
154
+ self.camera.set_rot_preset('xy')
155
+ if self.action['rot_preset_xz']:
156
+ self.camera.set_rot_preset('xz')
157
+ if self.action['rot_preset_yz']:
158
+ self.camera.set_rot_preset('yz')
159
+ if self.action['rot_preset_perspective']:
160
+ self.camera.set_rot_preset('perspective')
161
+
162
+ if self.action['toggle_axes']:
163
+ self.action['toggle_axes'] = False
164
+ self.camera.axes.toggle_visible()
165
+
166
+ if self.action['toggle_axe_colors']:
167
+ self.action['toggle_axe_colors'] = False
168
+ self.camera.axes.toggle_colors()
169
+
170
+ if self.action['save_image']:
171
+ self.action['save_image'] = False
172
+ self.window.plot.saveimage()
173
+
174
+ return True
175
+
176
+ def get_mouse_sensitivity(self):
177
+ if self.action['modify_sensitivity']:
178
+ return self.modified_mouse_sensitivity
179
+ else:
180
+ return self.normal_mouse_sensitivity
181
+
182
+ def get_key_sensitivity(self):
183
+ if self.action['modify_sensitivity']:
184
+ return self.modified_key_sensitivity
185
+ else:
186
+ return self.normal_key_sensitivity
187
+
188
+ def on_key_press(self, symbol, modifiers):
189
+ if symbol in self.keymap:
190
+ self.action[self.keymap[symbol]] = True
191
+
192
+ def on_key_release(self, symbol, modifiers):
193
+ if symbol in self.keymap:
194
+ self.action[self.keymap[symbol]] = False
195
+
196
+ def on_mouse_drag(self, x, y, dx, dy, buttons, modifiers):
197
+ if buttons & LEFT:
198
+ if self.is_2D():
199
+ self.camera.mouse_translate(x, y, dx, dy)
200
+ else:
201
+ self.camera.spherical_rotate((x - dx, y - dy), (x, y),
202
+ self.get_mouse_sensitivity())
203
+ if buttons & MIDDLE:
204
+ self.camera.zoom_relative([1, -1][self.invert_mouse_zoom]*dy,
205
+ self.get_mouse_sensitivity()/20.0)
206
+ if buttons & RIGHT:
207
+ self.camera.mouse_translate(x, y, dx, dy)
208
+
209
+ def on_mouse_scroll(self, x, y, dx, dy):
210
+ self.camera.zoom_relative([1, -1][self.invert_mouse_zoom]*dy,
211
+ self.get_mouse_sensitivity())
212
+
213
+ def is_2D(self):
214
+ functions = self.window.plot._functions
215
+ for i in functions:
216
+ if len(functions[i].i_vars) > 1 or len(functions[i].d_vars) > 2:
217
+ return False
218
+ return True
llmeval-env/lib/python3.10/site-packages/sympy/plotting/pygletplot/plot_curve.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pyglet.gl as pgl
2
+ from sympy.core import S
3
+ from sympy.plotting.pygletplot.plot_mode_base import PlotModeBase
4
+
5
+
6
+ class PlotCurve(PlotModeBase):
7
+
8
+ style_override = 'wireframe'
9
+
10
+ def _on_calculate_verts(self):
11
+ self.t_interval = self.intervals[0]
12
+ self.t_set = list(self.t_interval.frange())
13
+ self.bounds = [[S.Infinity, S.NegativeInfinity, 0],
14
+ [S.Infinity, S.NegativeInfinity, 0],
15
+ [S.Infinity, S.NegativeInfinity, 0]]
16
+ evaluate = self._get_evaluator()
17
+
18
+ self._calculating_verts_pos = 0.0
19
+ self._calculating_verts_len = float(self.t_interval.v_len)
20
+
21
+ self.verts = []
22
+ b = self.bounds
23
+ for t in self.t_set:
24
+ try:
25
+ _e = evaluate(t) # calculate vertex
26
+ except (NameError, ZeroDivisionError):
27
+ _e = None
28
+ if _e is not None: # update bounding box
29
+ for axis in range(3):
30
+ b[axis][0] = min([b[axis][0], _e[axis]])
31
+ b[axis][1] = max([b[axis][1], _e[axis]])
32
+ self.verts.append(_e)
33
+ self._calculating_verts_pos += 1.0
34
+
35
+ for axis in range(3):
36
+ b[axis][2] = b[axis][1] - b[axis][0]
37
+ if b[axis][2] == 0.0:
38
+ b[axis][2] = 1.0
39
+
40
+ self.push_wireframe(self.draw_verts(False))
41
+
42
+ def _on_calculate_cverts(self):
43
+ if not self.verts or not self.color:
44
+ return
45
+
46
+ def set_work_len(n):
47
+ self._calculating_cverts_len = float(n)
48
+
49
+ def inc_work_pos():
50
+ self._calculating_cverts_pos += 1.0
51
+ set_work_len(1)
52
+ self._calculating_cverts_pos = 0
53
+ self.cverts = self.color.apply_to_curve(self.verts,
54
+ self.t_set,
55
+ set_len=set_work_len,
56
+ inc_pos=inc_work_pos)
57
+ self.push_wireframe(self.draw_verts(True))
58
+
59
+ def calculate_one_cvert(self, t):
60
+ vert = self.verts[t]
61
+ return self.color(vert[0], vert[1], vert[2],
62
+ self.t_set[t], None)
63
+
64
+ def draw_verts(self, use_cverts):
65
+ def f():
66
+ pgl.glBegin(pgl.GL_LINE_STRIP)
67
+ for t in range(len(self.t_set)):
68
+ p = self.verts[t]
69
+ if p is None:
70
+ pgl.glEnd()
71
+ pgl.glBegin(pgl.GL_LINE_STRIP)
72
+ continue
73
+ if use_cverts:
74
+ c = self.cverts[t]
75
+ if c is None:
76
+ c = (0, 0, 0)
77
+ pgl.glColor3f(*c)
78
+ else:
79
+ pgl.glColor3f(*self.default_wireframe_color)
80
+ pgl.glVertex3f(*p)
81
+ pgl.glEnd()
82
+ return f
llmeval-env/lib/python3.10/site-packages/sympy/plotting/pygletplot/plot_interval.py ADDED
@@ -0,0 +1,181 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.singleton import S
2
+ from sympy.core.symbol import Symbol
3
+ from sympy.core.sympify import sympify
4
+ from sympy.core.numbers import Integer
5
+
6
+
7
+ class PlotInterval:
8
+ """
9
+ """
10
+ _v, _v_min, _v_max, _v_steps = None, None, None, None
11
+
12
+ def require_all_args(f):
13
+ def check(self, *args, **kwargs):
14
+ for g in [self._v, self._v_min, self._v_max, self._v_steps]:
15
+ if g is None:
16
+ raise ValueError("PlotInterval is incomplete.")
17
+ return f(self, *args, **kwargs)
18
+ return check
19
+
20
+ def __init__(self, *args):
21
+ if len(args) == 1:
22
+ if isinstance(args[0], PlotInterval):
23
+ self.fill_from(args[0])
24
+ return
25
+ elif isinstance(args[0], str):
26
+ try:
27
+ args = eval(args[0])
28
+ except TypeError:
29
+ s_eval_error = "Could not interpret string %s."
30
+ raise ValueError(s_eval_error % (args[0]))
31
+ elif isinstance(args[0], (tuple, list)):
32
+ args = args[0]
33
+ else:
34
+ raise ValueError("Not an interval.")
35
+ if not isinstance(args, (tuple, list)) or len(args) > 4:
36
+ f_error = "PlotInterval must be a tuple or list of length 4 or less."
37
+ raise ValueError(f_error)
38
+
39
+ args = list(args)
40
+ if len(args) > 0 and (args[0] is None or isinstance(args[0], Symbol)):
41
+ self.v = args.pop(0)
42
+ if len(args) in [2, 3]:
43
+ self.v_min = args.pop(0)
44
+ self.v_max = args.pop(0)
45
+ if len(args) == 1:
46
+ self.v_steps = args.pop(0)
47
+ elif len(args) == 1:
48
+ self.v_steps = args.pop(0)
49
+
50
+ def get_v(self):
51
+ return self._v
52
+
53
+ def set_v(self, v):
54
+ if v is None:
55
+ self._v = None
56
+ return
57
+ if not isinstance(v, Symbol):
58
+ raise ValueError("v must be a SymPy Symbol.")
59
+ self._v = v
60
+
61
+ def get_v_min(self):
62
+ return self._v_min
63
+
64
+ def set_v_min(self, v_min):
65
+ if v_min is None:
66
+ self._v_min = None
67
+ return
68
+ try:
69
+ self._v_min = sympify(v_min)
70
+ float(self._v_min.evalf())
71
+ except TypeError:
72
+ raise ValueError("v_min could not be interpreted as a number.")
73
+
74
+ def get_v_max(self):
75
+ return self._v_max
76
+
77
+ def set_v_max(self, v_max):
78
+ if v_max is None:
79
+ self._v_max = None
80
+ return
81
+ try:
82
+ self._v_max = sympify(v_max)
83
+ float(self._v_max.evalf())
84
+ except TypeError:
85
+ raise ValueError("v_max could not be interpreted as a number.")
86
+
87
+ def get_v_steps(self):
88
+ return self._v_steps
89
+
90
+ def set_v_steps(self, v_steps):
91
+ if v_steps is None:
92
+ self._v_steps = None
93
+ return
94
+ if isinstance(v_steps, int):
95
+ v_steps = Integer(v_steps)
96
+ elif not isinstance(v_steps, Integer):
97
+ raise ValueError("v_steps must be an int or SymPy Integer.")
98
+ if v_steps <= S.Zero:
99
+ raise ValueError("v_steps must be positive.")
100
+ self._v_steps = v_steps
101
+
102
+ @require_all_args
103
+ def get_v_len(self):
104
+ return self.v_steps + 1
105
+
106
+ v = property(get_v, set_v)
107
+ v_min = property(get_v_min, set_v_min)
108
+ v_max = property(get_v_max, set_v_max)
109
+ v_steps = property(get_v_steps, set_v_steps)
110
+ v_len = property(get_v_len)
111
+
112
+ def fill_from(self, b):
113
+ if b.v is not None:
114
+ self.v = b.v
115
+ if b.v_min is not None:
116
+ self.v_min = b.v_min
117
+ if b.v_max is not None:
118
+ self.v_max = b.v_max
119
+ if b.v_steps is not None:
120
+ self.v_steps = b.v_steps
121
+
122
+ @staticmethod
123
+ def try_parse(*args):
124
+ """
125
+ Returns a PlotInterval if args can be interpreted
126
+ as such, otherwise None.
127
+ """
128
+ if len(args) == 1 and isinstance(args[0], PlotInterval):
129
+ return args[0]
130
+ try:
131
+ return PlotInterval(*args)
132
+ except ValueError:
133
+ return None
134
+
135
+ def _str_base(self):
136
+ return ",".join([str(self.v), str(self.v_min),
137
+ str(self.v_max), str(self.v_steps)])
138
+
139
+ def __repr__(self):
140
+ """
141
+ A string representing the interval in class constructor form.
142
+ """
143
+ return "PlotInterval(%s)" % (self._str_base())
144
+
145
+ def __str__(self):
146
+ """
147
+ A string representing the interval in list form.
148
+ """
149
+ return "[%s]" % (self._str_base())
150
+
151
+ @require_all_args
152
+ def assert_complete(self):
153
+ pass
154
+
155
+ @require_all_args
156
+ def vrange(self):
157
+ """
158
+ Yields v_steps+1 SymPy numbers ranging from
159
+ v_min to v_max.
160
+ """
161
+ d = (self.v_max - self.v_min) / self.v_steps
162
+ for i in range(self.v_steps + 1):
163
+ a = self.v_min + (d * Integer(i))
164
+ yield a
165
+
166
+ @require_all_args
167
+ def vrange2(self):
168
+ """
169
+ Yields v_steps pairs of SymPy numbers ranging from
170
+ (v_min, v_min + step) to (v_max - step, v_max).
171
+ """
172
+ d = (self.v_max - self.v_min) / self.v_steps
173
+ a = self.v_min + (d * S.Zero)
174
+ for i in range(self.v_steps):
175
+ b = self.v_min + (d * Integer(i + 1))
176
+ yield a, b
177
+ a = b
178
+
179
+ def frange(self):
180
+ for i in self.vrange():
181
+ yield float(i.evalf())
llmeval-env/lib/python3.10/site-packages/sympy/plotting/pygletplot/plot_mode.py ADDED
@@ -0,0 +1,400 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .plot_interval import PlotInterval
2
+ from .plot_object import PlotObject
3
+ from .util import parse_option_string
4
+ from sympy.core.symbol import Symbol
5
+ from sympy.core.sympify import sympify
6
+ from sympy.geometry.entity import GeometryEntity
7
+ from sympy.utilities.iterables import is_sequence
8
+
9
+
10
+ class PlotMode(PlotObject):
11
+ """
12
+ Grandparent class for plotting
13
+ modes. Serves as interface for
14
+ registration, lookup, and init
15
+ of modes.
16
+
17
+ To create a new plot mode,
18
+ inherit from PlotModeBase
19
+ or one of its children, such
20
+ as PlotSurface or PlotCurve.
21
+ """
22
+
23
+ ## Class-level attributes
24
+ ## used to register and lookup
25
+ ## plot modes. See PlotModeBase
26
+ ## for descriptions and usage.
27
+
28
+ i_vars, d_vars = '', ''
29
+ intervals = []
30
+ aliases = []
31
+ is_default = False
32
+
33
+ ## Draw is the only method here which
34
+ ## is meant to be overridden in child
35
+ ## classes, and PlotModeBase provides
36
+ ## a base implementation.
37
+ def draw(self):
38
+ raise NotImplementedError()
39
+
40
+ ## Everything else in this file has to
41
+ ## do with registration and retrieval
42
+ ## of plot modes. This is where I've
43
+ ## hidden much of the ugliness of automatic
44
+ ## plot mode divination...
45
+
46
+ ## Plot mode registry data structures
47
+ _mode_alias_list = []
48
+ _mode_map = {
49
+ 1: {1: {}, 2: {}},
50
+ 2: {1: {}, 2: {}},
51
+ 3: {1: {}, 2: {}},
52
+ } # [d][i][alias_str]: class
53
+ _mode_default_map = {
54
+ 1: {},
55
+ 2: {},
56
+ 3: {},
57
+ } # [d][i]: class
58
+ _i_var_max, _d_var_max = 2, 3
59
+
60
+ def __new__(cls, *args, **kwargs):
61
+ """
62
+ This is the function which interprets
63
+ arguments given to Plot.__init__ and
64
+ Plot.__setattr__. Returns an initialized
65
+ instance of the appropriate child class.
66
+ """
67
+
68
+ newargs, newkwargs = PlotMode._extract_options(args, kwargs)
69
+ mode_arg = newkwargs.get('mode', '')
70
+
71
+ # Interpret the arguments
72
+ d_vars, intervals = PlotMode._interpret_args(newargs)
73
+ i_vars = PlotMode._find_i_vars(d_vars, intervals)
74
+ i, d = max([len(i_vars), len(intervals)]), len(d_vars)
75
+
76
+ # Find the appropriate mode
77
+ subcls = PlotMode._get_mode(mode_arg, i, d)
78
+
79
+ # Create the object
80
+ o = object.__new__(subcls)
81
+
82
+ # Do some setup for the mode instance
83
+ o.d_vars = d_vars
84
+ o._fill_i_vars(i_vars)
85
+ o._fill_intervals(intervals)
86
+ o.options = newkwargs
87
+
88
+ return o
89
+
90
+ @staticmethod
91
+ def _get_mode(mode_arg, i_var_count, d_var_count):
92
+ """
93
+ Tries to return an appropriate mode class.
94
+ Intended to be called only by __new__.
95
+
96
+ mode_arg
97
+ Can be a string or a class. If it is a
98
+ PlotMode subclass, it is simply returned.
99
+ If it is a string, it can an alias for
100
+ a mode or an empty string. In the latter
101
+ case, we try to find a default mode for
102
+ the i_var_count and d_var_count.
103
+
104
+ i_var_count
105
+ The number of independent variables
106
+ needed to evaluate the d_vars.
107
+
108
+ d_var_count
109
+ The number of dependent variables;
110
+ usually the number of functions to
111
+ be evaluated in plotting.
112
+
113
+ For example, a Cartesian function y = f(x) has
114
+ one i_var (x) and one d_var (y). A parametric
115
+ form x,y,z = f(u,v), f(u,v), f(u,v) has two
116
+ two i_vars (u,v) and three d_vars (x,y,z).
117
+ """
118
+ # if the mode_arg is simply a PlotMode class,
119
+ # check that the mode supports the numbers
120
+ # of independent and dependent vars, then
121
+ # return it
122
+ try:
123
+ m = None
124
+ if issubclass(mode_arg, PlotMode):
125
+ m = mode_arg
126
+ except TypeError:
127
+ pass
128
+ if m:
129
+ if not m._was_initialized:
130
+ raise ValueError(("To use unregistered plot mode %s "
131
+ "you must first call %s._init_mode().")
132
+ % (m.__name__, m.__name__))
133
+ if d_var_count != m.d_var_count:
134
+ raise ValueError(("%s can only plot functions "
135
+ "with %i dependent variables.")
136
+ % (m.__name__,
137
+ m.d_var_count))
138
+ if i_var_count > m.i_var_count:
139
+ raise ValueError(("%s cannot plot functions "
140
+ "with more than %i independent "
141
+ "variables.")
142
+ % (m.__name__,
143
+ m.i_var_count))
144
+ return m
145
+ # If it is a string, there are two possibilities.
146
+ if isinstance(mode_arg, str):
147
+ i, d = i_var_count, d_var_count
148
+ if i > PlotMode._i_var_max:
149
+ raise ValueError(var_count_error(True, True))
150
+ if d > PlotMode._d_var_max:
151
+ raise ValueError(var_count_error(False, True))
152
+ # If the string is '', try to find a suitable
153
+ # default mode
154
+ if not mode_arg:
155
+ return PlotMode._get_default_mode(i, d)
156
+ # Otherwise, interpret the string as a mode
157
+ # alias (e.g. 'cartesian', 'parametric', etc)
158
+ else:
159
+ return PlotMode._get_aliased_mode(mode_arg, i, d)
160
+ else:
161
+ raise ValueError("PlotMode argument must be "
162
+ "a class or a string")
163
+
164
+ @staticmethod
165
+ def _get_default_mode(i, d, i_vars=-1):
166
+ if i_vars == -1:
167
+ i_vars = i
168
+ try:
169
+ return PlotMode._mode_default_map[d][i]
170
+ except KeyError:
171
+ # Keep looking for modes in higher i var counts
172
+ # which support the given d var count until we
173
+ # reach the max i_var count.
174
+ if i < PlotMode._i_var_max:
175
+ return PlotMode._get_default_mode(i + 1, d, i_vars)
176
+ else:
177
+ raise ValueError(("Couldn't find a default mode "
178
+ "for %i independent and %i "
179
+ "dependent variables.") % (i_vars, d))
180
+
181
+ @staticmethod
182
+ def _get_aliased_mode(alias, i, d, i_vars=-1):
183
+ if i_vars == -1:
184
+ i_vars = i
185
+ if alias not in PlotMode._mode_alias_list:
186
+ raise ValueError(("Couldn't find a mode called"
187
+ " %s. Known modes: %s.")
188
+ % (alias, ", ".join(PlotMode._mode_alias_list)))
189
+ try:
190
+ return PlotMode._mode_map[d][i][alias]
191
+ except TypeError:
192
+ # Keep looking for modes in higher i var counts
193
+ # which support the given d var count and alias
194
+ # until we reach the max i_var count.
195
+ if i < PlotMode._i_var_max:
196
+ return PlotMode._get_aliased_mode(alias, i + 1, d, i_vars)
197
+ else:
198
+ raise ValueError(("Couldn't find a %s mode "
199
+ "for %i independent and %i "
200
+ "dependent variables.")
201
+ % (alias, i_vars, d))
202
+
203
+ @classmethod
204
+ def _register(cls):
205
+ """
206
+ Called once for each user-usable plot mode.
207
+ For Cartesian2D, it is invoked after the
208
+ class definition: Cartesian2D._register()
209
+ """
210
+ name = cls.__name__
211
+ cls._init_mode()
212
+
213
+ try:
214
+ i, d = cls.i_var_count, cls.d_var_count
215
+ # Add the mode to _mode_map under all
216
+ # given aliases
217
+ for a in cls.aliases:
218
+ if a not in PlotMode._mode_alias_list:
219
+ # Also track valid aliases, so
220
+ # we can quickly know when given
221
+ # an invalid one in _get_mode.
222
+ PlotMode._mode_alias_list.append(a)
223
+ PlotMode._mode_map[d][i][a] = cls
224
+ if cls.is_default:
225
+ # If this mode was marked as the
226
+ # default for this d,i combination,
227
+ # also set that.
228
+ PlotMode._mode_default_map[d][i] = cls
229
+
230
+ except Exception as e:
231
+ raise RuntimeError(("Failed to register "
232
+ "plot mode %s. Reason: %s")
233
+ % (name, (str(e))))
234
+
235
+ @classmethod
236
+ def _init_mode(cls):
237
+ """
238
+ Initializes the plot mode based on
239
+ the 'mode-specific parameters' above.
240
+ Only intended to be called by
241
+ PlotMode._register(). To use a mode without
242
+ registering it, you can directly call
243
+ ModeSubclass._init_mode().
244
+ """
245
+ def symbols_list(symbol_str):
246
+ return [Symbol(s) for s in symbol_str]
247
+
248
+ # Convert the vars strs into
249
+ # lists of symbols.
250
+ cls.i_vars = symbols_list(cls.i_vars)
251
+ cls.d_vars = symbols_list(cls.d_vars)
252
+
253
+ # Var count is used often, calculate
254
+ # it once here
255
+ cls.i_var_count = len(cls.i_vars)
256
+ cls.d_var_count = len(cls.d_vars)
257
+
258
+ if cls.i_var_count > PlotMode._i_var_max:
259
+ raise ValueError(var_count_error(True, False))
260
+ if cls.d_var_count > PlotMode._d_var_max:
261
+ raise ValueError(var_count_error(False, False))
262
+
263
+ # Try to use first alias as primary_alias
264
+ if len(cls.aliases) > 0:
265
+ cls.primary_alias = cls.aliases[0]
266
+ else:
267
+ cls.primary_alias = cls.__name__
268
+
269
+ di = cls.intervals
270
+ if len(di) != cls.i_var_count:
271
+ raise ValueError("Plot mode must provide a "
272
+ "default interval for each i_var.")
273
+ for i in range(cls.i_var_count):
274
+ # default intervals must be given [min,max,steps]
275
+ # (no var, but they must be in the same order as i_vars)
276
+ if len(di[i]) != 3:
277
+ raise ValueError("length should be equal to 3")
278
+
279
+ # Initialize an incomplete interval,
280
+ # to later be filled with a var when
281
+ # the mode is instantiated.
282
+ di[i] = PlotInterval(None, *di[i])
283
+
284
+ # To prevent people from using modes
285
+ # without these required fields set up.
286
+ cls._was_initialized = True
287
+
288
+ _was_initialized = False
289
+
290
+ ## Initializer Helper Methods
291
+
292
+ @staticmethod
293
+ def _find_i_vars(functions, intervals):
294
+ i_vars = []
295
+
296
+ # First, collect i_vars in the
297
+ # order they are given in any
298
+ # intervals.
299
+ for i in intervals:
300
+ if i.v is None:
301
+ continue
302
+ elif i.v in i_vars:
303
+ raise ValueError(("Multiple intervals given "
304
+ "for %s.") % (str(i.v)))
305
+ i_vars.append(i.v)
306
+
307
+ # Then, find any remaining
308
+ # i_vars in given functions
309
+ # (aka d_vars)
310
+ for f in functions:
311
+ for a in f.free_symbols:
312
+ if a not in i_vars:
313
+ i_vars.append(a)
314
+
315
+ return i_vars
316
+
317
+ def _fill_i_vars(self, i_vars):
318
+ # copy default i_vars
319
+ self.i_vars = [Symbol(str(i)) for i in self.i_vars]
320
+ # replace with given i_vars
321
+ for i in range(len(i_vars)):
322
+ self.i_vars[i] = i_vars[i]
323
+
324
+ def _fill_intervals(self, intervals):
325
+ # copy default intervals
326
+ self.intervals = [PlotInterval(i) for i in self.intervals]
327
+ # track i_vars used so far
328
+ v_used = []
329
+ # fill copy of default
330
+ # intervals with given info
331
+ for i in range(len(intervals)):
332
+ self.intervals[i].fill_from(intervals[i])
333
+ if self.intervals[i].v is not None:
334
+ v_used.append(self.intervals[i].v)
335
+ # Find any orphan intervals and
336
+ # assign them i_vars
337
+ for i in range(len(self.intervals)):
338
+ if self.intervals[i].v is None:
339
+ u = [v for v in self.i_vars if v not in v_used]
340
+ if len(u) == 0:
341
+ raise ValueError("length should not be equal to 0")
342
+ self.intervals[i].v = u[0]
343
+ v_used.append(u[0])
344
+
345
+ @staticmethod
346
+ def _interpret_args(args):
347
+ interval_wrong_order = "PlotInterval %s was given before any function(s)."
348
+ interpret_error = "Could not interpret %s as a function or interval."
349
+
350
+ functions, intervals = [], []
351
+ if isinstance(args[0], GeometryEntity):
352
+ for coords in list(args[0].arbitrary_point()):
353
+ functions.append(coords)
354
+ intervals.append(PlotInterval.try_parse(args[0].plot_interval()))
355
+ else:
356
+ for a in args:
357
+ i = PlotInterval.try_parse(a)
358
+ if i is not None:
359
+ if len(functions) == 0:
360
+ raise ValueError(interval_wrong_order % (str(i)))
361
+ else:
362
+ intervals.append(i)
363
+ else:
364
+ if is_sequence(a, include=str):
365
+ raise ValueError(interpret_error % (str(a)))
366
+ try:
367
+ f = sympify(a)
368
+ functions.append(f)
369
+ except TypeError:
370
+ raise ValueError(interpret_error % str(a))
371
+
372
+ return functions, intervals
373
+
374
+ @staticmethod
375
+ def _extract_options(args, kwargs):
376
+ newkwargs, newargs = {}, []
377
+ for a in args:
378
+ if isinstance(a, str):
379
+ newkwargs = dict(newkwargs, **parse_option_string(a))
380
+ else:
381
+ newargs.append(a)
382
+ newkwargs = dict(newkwargs, **kwargs)
383
+ return newargs, newkwargs
384
+
385
+
386
+ def var_count_error(is_independent, is_plotting):
387
+ """
388
+ Used to format an error message which differs
389
+ slightly in 4 places.
390
+ """
391
+ if is_plotting:
392
+ v = "Plotting"
393
+ else:
394
+ v = "Registering plot modes"
395
+ if is_independent:
396
+ n, s = PlotMode._i_var_max, "independent"
397
+ else:
398
+ n, s = PlotMode._d_var_max, "dependent"
399
+ return ("%s with more than %i %s variables "
400
+ "is not supported.") % (v, n, s)
llmeval-env/lib/python3.10/site-packages/sympy/plotting/pygletplot/plot_mode_base.py ADDED
@@ -0,0 +1,378 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pyglet.gl as pgl
2
+ from sympy.core import S
3
+ from sympy.plotting.pygletplot.color_scheme import ColorScheme
4
+ from sympy.plotting.pygletplot.plot_mode import PlotMode
5
+ from sympy.utilities.iterables import is_sequence
6
+ from time import sleep
7
+ from threading import Thread, Event, RLock
8
+ import warnings
9
+
10
+
11
+ class PlotModeBase(PlotMode):
12
+ """
13
+ Intended parent class for plotting
14
+ modes. Provides base functionality
15
+ in conjunction with its parent,
16
+ PlotMode.
17
+ """
18
+
19
+ ##
20
+ ## Class-Level Attributes
21
+ ##
22
+
23
+ """
24
+ The following attributes are meant
25
+ to be set at the class level, and serve
26
+ as parameters to the plot mode registry
27
+ (in PlotMode). See plot_modes.py for
28
+ concrete examples.
29
+ """
30
+
31
+ """
32
+ i_vars
33
+ 'x' for Cartesian2D
34
+ 'xy' for Cartesian3D
35
+ etc.
36
+
37
+ d_vars
38
+ 'y' for Cartesian2D
39
+ 'r' for Polar
40
+ etc.
41
+ """
42
+ i_vars, d_vars = '', ''
43
+
44
+ """
45
+ intervals
46
+ Default intervals for each i_var, and in the
47
+ same order. Specified [min, max, steps].
48
+ No variable can be given (it is bound later).
49
+ """
50
+ intervals = []
51
+
52
+ """
53
+ aliases
54
+ A list of strings which can be used to
55
+ access this mode.
56
+ 'cartesian' for Cartesian2D and Cartesian3D
57
+ 'polar' for Polar
58
+ 'cylindrical', 'polar' for Cylindrical
59
+
60
+ Note that _init_mode chooses the first alias
61
+ in the list as the mode's primary_alias, which
62
+ will be displayed to the end user in certain
63
+ contexts.
64
+ """
65
+ aliases = []
66
+
67
+ """
68
+ is_default
69
+ Whether to set this mode as the default
70
+ for arguments passed to PlotMode() containing
71
+ the same number of d_vars as this mode and
72
+ at most the same number of i_vars.
73
+ """
74
+ is_default = False
75
+
76
+ """
77
+ All of the above attributes are defined in PlotMode.
78
+ The following ones are specific to PlotModeBase.
79
+ """
80
+
81
+ """
82
+ A list of the render styles. Do not modify.
83
+ """
84
+ styles = {'wireframe': 1, 'solid': 2, 'both': 3}
85
+
86
+ """
87
+ style_override
88
+ Always use this style if not blank.
89
+ """
90
+ style_override = ''
91
+
92
+ """
93
+ default_wireframe_color
94
+ default_solid_color
95
+ Can be used when color is None or being calculated.
96
+ Used by PlotCurve and PlotSurface, but not anywhere
97
+ in PlotModeBase.
98
+ """
99
+
100
+ default_wireframe_color = (0.85, 0.85, 0.85)
101
+ default_solid_color = (0.6, 0.6, 0.9)
102
+ default_rot_preset = 'xy'
103
+
104
+ ##
105
+ ## Instance-Level Attributes
106
+ ##
107
+
108
+ ## 'Abstract' member functions
109
+ def _get_evaluator(self):
110
+ if self.use_lambda_eval:
111
+ try:
112
+ e = self._get_lambda_evaluator()
113
+ return e
114
+ except Exception:
115
+ warnings.warn("\nWarning: creating lambda evaluator failed. "
116
+ "Falling back on SymPy subs evaluator.")
117
+ return self._get_sympy_evaluator()
118
+
119
+ def _get_sympy_evaluator(self):
120
+ raise NotImplementedError()
121
+
122
+ def _get_lambda_evaluator(self):
123
+ raise NotImplementedError()
124
+
125
+ def _on_calculate_verts(self):
126
+ raise NotImplementedError()
127
+
128
+ def _on_calculate_cverts(self):
129
+ raise NotImplementedError()
130
+
131
+ ## Base member functions
132
+ def __init__(self, *args, bounds_callback=None, **kwargs):
133
+ self.verts = []
134
+ self.cverts = []
135
+ self.bounds = [[S.Infinity, S.NegativeInfinity, 0],
136
+ [S.Infinity, S.NegativeInfinity, 0],
137
+ [S.Infinity, S.NegativeInfinity, 0]]
138
+ self.cbounds = [[S.Infinity, S.NegativeInfinity, 0],
139
+ [S.Infinity, S.NegativeInfinity, 0],
140
+ [S.Infinity, S.NegativeInfinity, 0]]
141
+
142
+ self._draw_lock = RLock()
143
+
144
+ self._calculating_verts = Event()
145
+ self._calculating_cverts = Event()
146
+ self._calculating_verts_pos = 0.0
147
+ self._calculating_verts_len = 0.0
148
+ self._calculating_cverts_pos = 0.0
149
+ self._calculating_cverts_len = 0.0
150
+
151
+ self._max_render_stack_size = 3
152
+ self._draw_wireframe = [-1]
153
+ self._draw_solid = [-1]
154
+
155
+ self._style = None
156
+ self._color = None
157
+
158
+ self.predraw = []
159
+ self.postdraw = []
160
+
161
+ self.use_lambda_eval = self.options.pop('use_sympy_eval', None) is None
162
+ self.style = self.options.pop('style', '')
163
+ self.color = self.options.pop('color', 'rainbow')
164
+ self.bounds_callback = bounds_callback
165
+
166
+ self._on_calculate()
167
+
168
+ def synchronized(f):
169
+ def w(self, *args, **kwargs):
170
+ self._draw_lock.acquire()
171
+ try:
172
+ r = f(self, *args, **kwargs)
173
+ return r
174
+ finally:
175
+ self._draw_lock.release()
176
+ return w
177
+
178
+ @synchronized
179
+ def push_wireframe(self, function):
180
+ """
181
+ Push a function which performs gl commands
182
+ used to build a display list. (The list is
183
+ built outside of the function)
184
+ """
185
+ assert callable(function)
186
+ self._draw_wireframe.append(function)
187
+ if len(self._draw_wireframe) > self._max_render_stack_size:
188
+ del self._draw_wireframe[1] # leave marker element
189
+
190
+ @synchronized
191
+ def push_solid(self, function):
192
+ """
193
+ Push a function which performs gl commands
194
+ used to build a display list. (The list is
195
+ built outside of the function)
196
+ """
197
+ assert callable(function)
198
+ self._draw_solid.append(function)
199
+ if len(self._draw_solid) > self._max_render_stack_size:
200
+ del self._draw_solid[1] # leave marker element
201
+
202
+ def _create_display_list(self, function):
203
+ dl = pgl.glGenLists(1)
204
+ pgl.glNewList(dl, pgl.GL_COMPILE)
205
+ function()
206
+ pgl.glEndList()
207
+ return dl
208
+
209
+ def _render_stack_top(self, render_stack):
210
+ top = render_stack[-1]
211
+ if top == -1:
212
+ return -1 # nothing to display
213
+ elif callable(top):
214
+ dl = self._create_display_list(top)
215
+ render_stack[-1] = (dl, top)
216
+ return dl # display newly added list
217
+ elif len(top) == 2:
218
+ if pgl.GL_TRUE == pgl.glIsList(top[0]):
219
+ return top[0] # display stored list
220
+ dl = self._create_display_list(top[1])
221
+ render_stack[-1] = (dl, top[1])
222
+ return dl # display regenerated list
223
+
224
+ def _draw_solid_display_list(self, dl):
225
+ pgl.glPushAttrib(pgl.GL_ENABLE_BIT | pgl.GL_POLYGON_BIT)
226
+ pgl.glPolygonMode(pgl.GL_FRONT_AND_BACK, pgl.GL_FILL)
227
+ pgl.glCallList(dl)
228
+ pgl.glPopAttrib()
229
+
230
+ def _draw_wireframe_display_list(self, dl):
231
+ pgl.glPushAttrib(pgl.GL_ENABLE_BIT | pgl.GL_POLYGON_BIT)
232
+ pgl.glPolygonMode(pgl.GL_FRONT_AND_BACK, pgl.GL_LINE)
233
+ pgl.glEnable(pgl.GL_POLYGON_OFFSET_LINE)
234
+ pgl.glPolygonOffset(-0.005, -50.0)
235
+ pgl.glCallList(dl)
236
+ pgl.glPopAttrib()
237
+
238
+ @synchronized
239
+ def draw(self):
240
+ for f in self.predraw:
241
+ if callable(f):
242
+ f()
243
+ if self.style_override:
244
+ style = self.styles[self.style_override]
245
+ else:
246
+ style = self.styles[self._style]
247
+ # Draw solid component if style includes solid
248
+ if style & 2:
249
+ dl = self._render_stack_top(self._draw_solid)
250
+ if dl > 0 and pgl.GL_TRUE == pgl.glIsList(dl):
251
+ self._draw_solid_display_list(dl)
252
+ # Draw wireframe component if style includes wireframe
253
+ if style & 1:
254
+ dl = self._render_stack_top(self._draw_wireframe)
255
+ if dl > 0 and pgl.GL_TRUE == pgl.glIsList(dl):
256
+ self._draw_wireframe_display_list(dl)
257
+ for f in self.postdraw:
258
+ if callable(f):
259
+ f()
260
+
261
+ def _on_change_color(self, color):
262
+ Thread(target=self._calculate_cverts).start()
263
+
264
+ def _on_calculate(self):
265
+ Thread(target=self._calculate_all).start()
266
+
267
+ def _calculate_all(self):
268
+ self._calculate_verts()
269
+ self._calculate_cverts()
270
+
271
+ def _calculate_verts(self):
272
+ if self._calculating_verts.is_set():
273
+ return
274
+ self._calculating_verts.set()
275
+ try:
276
+ self._on_calculate_verts()
277
+ finally:
278
+ self._calculating_verts.clear()
279
+ if callable(self.bounds_callback):
280
+ self.bounds_callback()
281
+
282
+ def _calculate_cverts(self):
283
+ if self._calculating_verts.is_set():
284
+ return
285
+ while self._calculating_cverts.is_set():
286
+ sleep(0) # wait for previous calculation
287
+ self._calculating_cverts.set()
288
+ try:
289
+ self._on_calculate_cverts()
290
+ finally:
291
+ self._calculating_cverts.clear()
292
+
293
+ def _get_calculating_verts(self):
294
+ return self._calculating_verts.is_set()
295
+
296
+ def _get_calculating_verts_pos(self):
297
+ return self._calculating_verts_pos
298
+
299
+ def _get_calculating_verts_len(self):
300
+ return self._calculating_verts_len
301
+
302
+ def _get_calculating_cverts(self):
303
+ return self._calculating_cverts.is_set()
304
+
305
+ def _get_calculating_cverts_pos(self):
306
+ return self._calculating_cverts_pos
307
+
308
+ def _get_calculating_cverts_len(self):
309
+ return self._calculating_cverts_len
310
+
311
+ ## Property handlers
312
+ def _get_style(self):
313
+ return self._style
314
+
315
+ @synchronized
316
+ def _set_style(self, v):
317
+ if v is None:
318
+ return
319
+ if v == '':
320
+ step_max = 0
321
+ for i in self.intervals:
322
+ if i.v_steps is None:
323
+ continue
324
+ step_max = max([step_max, int(i.v_steps)])
325
+ v = ['both', 'solid'][step_max > 40]
326
+ if v not in self.styles:
327
+ raise ValueError("v should be there in self.styles")
328
+ if v == self._style:
329
+ return
330
+ self._style = v
331
+
332
+ def _get_color(self):
333
+ return self._color
334
+
335
+ @synchronized
336
+ def _set_color(self, v):
337
+ try:
338
+ if v is not None:
339
+ if is_sequence(v):
340
+ v = ColorScheme(*v)
341
+ else:
342
+ v = ColorScheme(v)
343
+ if repr(v) == repr(self._color):
344
+ return
345
+ self._on_change_color(v)
346
+ self._color = v
347
+ except Exception as e:
348
+ raise RuntimeError("Color change failed. "
349
+ "Reason: %s" % (str(e)))
350
+
351
+ style = property(_get_style, _set_style)
352
+ color = property(_get_color, _set_color)
353
+
354
+ calculating_verts = property(_get_calculating_verts)
355
+ calculating_verts_pos = property(_get_calculating_verts_pos)
356
+ calculating_verts_len = property(_get_calculating_verts_len)
357
+
358
+ calculating_cverts = property(_get_calculating_cverts)
359
+ calculating_cverts_pos = property(_get_calculating_cverts_pos)
360
+ calculating_cverts_len = property(_get_calculating_cverts_len)
361
+
362
+ ## String representations
363
+
364
+ def __str__(self):
365
+ f = ", ".join(str(d) for d in self.d_vars)
366
+ o = "'mode=%s'" % (self.primary_alias)
367
+ return ", ".join([f, o])
368
+
369
+ def __repr__(self):
370
+ f = ", ".join(str(d) for d in self.d_vars)
371
+ i = ", ".join(str(i) for i in self.intervals)
372
+ d = [('mode', self.primary_alias),
373
+ ('color', str(self.color)),
374
+ ('style', str(self.style))]
375
+
376
+ o = "'%s'" % ("; ".join("%s=%s" % (k, v)
377
+ for k, v in d if v != 'None'))
378
+ return ", ".join([f, i, o])
llmeval-env/lib/python3.10/site-packages/sympy/plotting/pygletplot/plot_modes.py ADDED
@@ -0,0 +1,209 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.utilities.lambdify import lambdify
2
+ from sympy.core.numbers import pi
3
+ from sympy.functions import sin, cos
4
+ from sympy.plotting.pygletplot.plot_curve import PlotCurve
5
+ from sympy.plotting.pygletplot.plot_surface import PlotSurface
6
+
7
+ from math import sin as p_sin
8
+ from math import cos as p_cos
9
+
10
+
11
+ def float_vec3(f):
12
+ def inner(*args):
13
+ v = f(*args)
14
+ return float(v[0]), float(v[1]), float(v[2])
15
+ return inner
16
+
17
+
18
+ class Cartesian2D(PlotCurve):
19
+ i_vars, d_vars = 'x', 'y'
20
+ intervals = [[-5, 5, 100]]
21
+ aliases = ['cartesian']
22
+ is_default = True
23
+
24
+ def _get_sympy_evaluator(self):
25
+ fy = self.d_vars[0]
26
+ x = self.t_interval.v
27
+
28
+ @float_vec3
29
+ def e(_x):
30
+ return (_x, fy.subs(x, _x), 0.0)
31
+ return e
32
+
33
+ def _get_lambda_evaluator(self):
34
+ fy = self.d_vars[0]
35
+ x = self.t_interval.v
36
+ return lambdify([x], [x, fy, 0.0])
37
+
38
+
39
+ class Cartesian3D(PlotSurface):
40
+ i_vars, d_vars = 'xy', 'z'
41
+ intervals = [[-1, 1, 40], [-1, 1, 40]]
42
+ aliases = ['cartesian', 'monge']
43
+ is_default = True
44
+
45
+ def _get_sympy_evaluator(self):
46
+ fz = self.d_vars[0]
47
+ x = self.u_interval.v
48
+ y = self.v_interval.v
49
+
50
+ @float_vec3
51
+ def e(_x, _y):
52
+ return (_x, _y, fz.subs(x, _x).subs(y, _y))
53
+ return e
54
+
55
+ def _get_lambda_evaluator(self):
56
+ fz = self.d_vars[0]
57
+ x = self.u_interval.v
58
+ y = self.v_interval.v
59
+ return lambdify([x, y], [x, y, fz])
60
+
61
+
62
+ class ParametricCurve2D(PlotCurve):
63
+ i_vars, d_vars = 't', 'xy'
64
+ intervals = [[0, 2*pi, 100]]
65
+ aliases = ['parametric']
66
+ is_default = True
67
+
68
+ def _get_sympy_evaluator(self):
69
+ fx, fy = self.d_vars
70
+ t = self.t_interval.v
71
+
72
+ @float_vec3
73
+ def e(_t):
74
+ return (fx.subs(t, _t), fy.subs(t, _t), 0.0)
75
+ return e
76
+
77
+ def _get_lambda_evaluator(self):
78
+ fx, fy = self.d_vars
79
+ t = self.t_interval.v
80
+ return lambdify([t], [fx, fy, 0.0])
81
+
82
+
83
+ class ParametricCurve3D(PlotCurve):
84
+ i_vars, d_vars = 't', 'xyz'
85
+ intervals = [[0, 2*pi, 100]]
86
+ aliases = ['parametric']
87
+ is_default = True
88
+
89
+ def _get_sympy_evaluator(self):
90
+ fx, fy, fz = self.d_vars
91
+ t = self.t_interval.v
92
+
93
+ @float_vec3
94
+ def e(_t):
95
+ return (fx.subs(t, _t), fy.subs(t, _t), fz.subs(t, _t))
96
+ return e
97
+
98
+ def _get_lambda_evaluator(self):
99
+ fx, fy, fz = self.d_vars
100
+ t = self.t_interval.v
101
+ return lambdify([t], [fx, fy, fz])
102
+
103
+
104
+ class ParametricSurface(PlotSurface):
105
+ i_vars, d_vars = 'uv', 'xyz'
106
+ intervals = [[-1, 1, 40], [-1, 1, 40]]
107
+ aliases = ['parametric']
108
+ is_default = True
109
+
110
+ def _get_sympy_evaluator(self):
111
+ fx, fy, fz = self.d_vars
112
+ u = self.u_interval.v
113
+ v = self.v_interval.v
114
+
115
+ @float_vec3
116
+ def e(_u, _v):
117
+ return (fx.subs(u, _u).subs(v, _v),
118
+ fy.subs(u, _u).subs(v, _v),
119
+ fz.subs(u, _u).subs(v, _v))
120
+ return e
121
+
122
+ def _get_lambda_evaluator(self):
123
+ fx, fy, fz = self.d_vars
124
+ u = self.u_interval.v
125
+ v = self.v_interval.v
126
+ return lambdify([u, v], [fx, fy, fz])
127
+
128
+
129
+ class Polar(PlotCurve):
130
+ i_vars, d_vars = 't', 'r'
131
+ intervals = [[0, 2*pi, 100]]
132
+ aliases = ['polar']
133
+ is_default = False
134
+
135
+ def _get_sympy_evaluator(self):
136
+ fr = self.d_vars[0]
137
+ t = self.t_interval.v
138
+
139
+ def e(_t):
140
+ _r = float(fr.subs(t, _t))
141
+ return (_r*p_cos(_t), _r*p_sin(_t), 0.0)
142
+ return e
143
+
144
+ def _get_lambda_evaluator(self):
145
+ fr = self.d_vars[0]
146
+ t = self.t_interval.v
147
+ fx, fy = fr*cos(t), fr*sin(t)
148
+ return lambdify([t], [fx, fy, 0.0])
149
+
150
+
151
+ class Cylindrical(PlotSurface):
152
+ i_vars, d_vars = 'th', 'r'
153
+ intervals = [[0, 2*pi, 40], [-1, 1, 20]]
154
+ aliases = ['cylindrical', 'polar']
155
+ is_default = False
156
+
157
+ def _get_sympy_evaluator(self):
158
+ fr = self.d_vars[0]
159
+ t = self.u_interval.v
160
+ h = self.v_interval.v
161
+
162
+ def e(_t, _h):
163
+ _r = float(fr.subs(t, _t).subs(h, _h))
164
+ return (_r*p_cos(_t), _r*p_sin(_t), _h)
165
+ return e
166
+
167
+ def _get_lambda_evaluator(self):
168
+ fr = self.d_vars[0]
169
+ t = self.u_interval.v
170
+ h = self.v_interval.v
171
+ fx, fy = fr*cos(t), fr*sin(t)
172
+ return lambdify([t, h], [fx, fy, h])
173
+
174
+
175
+ class Spherical(PlotSurface):
176
+ i_vars, d_vars = 'tp', 'r'
177
+ intervals = [[0, 2*pi, 40], [0, pi, 20]]
178
+ aliases = ['spherical']
179
+ is_default = False
180
+
181
+ def _get_sympy_evaluator(self):
182
+ fr = self.d_vars[0]
183
+ t = self.u_interval.v
184
+ p = self.v_interval.v
185
+
186
+ def e(_t, _p):
187
+ _r = float(fr.subs(t, _t).subs(p, _p))
188
+ return (_r*p_cos(_t)*p_sin(_p),
189
+ _r*p_sin(_t)*p_sin(_p),
190
+ _r*p_cos(_p))
191
+ return e
192
+
193
+ def _get_lambda_evaluator(self):
194
+ fr = self.d_vars[0]
195
+ t = self.u_interval.v
196
+ p = self.v_interval.v
197
+ fx = fr * cos(t) * sin(p)
198
+ fy = fr * sin(t) * sin(p)
199
+ fz = fr * cos(p)
200
+ return lambdify([t, p], [fx, fy, fz])
201
+
202
+ Cartesian2D._register()
203
+ Cartesian3D._register()
204
+ ParametricCurve2D._register()
205
+ ParametricCurve3D._register()
206
+ ParametricSurface._register()
207
+ Polar._register()
208
+ Cylindrical._register()
209
+ Spherical._register()
llmeval-env/lib/python3.10/site-packages/sympy/plotting/pygletplot/plot_object.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ class PlotObject:
2
+ """
3
+ Base class for objects which can be displayed in
4
+ a Plot.
5
+ """
6
+ visible = True
7
+
8
+ def _draw(self):
9
+ if self.visible:
10
+ self.draw()
11
+
12
+ def draw(self):
13
+ """
14
+ OpenGL rendering code for the plot object.
15
+ Override in base class.
16
+ """
17
+ pass
llmeval-env/lib/python3.10/site-packages/sympy/plotting/pygletplot/plot_rotation.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ try:
2
+ from ctypes import c_float
3
+ except ImportError:
4
+ pass
5
+
6
+ import pyglet.gl as pgl
7
+ from math import sqrt as _sqrt, acos as _acos
8
+
9
+
10
+ def cross(a, b):
11
+ return (a[1] * b[2] - a[2] * b[1],
12
+ a[2] * b[0] - a[0] * b[2],
13
+ a[0] * b[1] - a[1] * b[0])
14
+
15
+
16
+ def dot(a, b):
17
+ return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
18
+
19
+
20
+ def mag(a):
21
+ return _sqrt(a[0]**2 + a[1]**2 + a[2]**2)
22
+
23
+
24
+ def norm(a):
25
+ m = mag(a)
26
+ return (a[0] / m, a[1] / m, a[2] / m)
27
+
28
+
29
+ def get_sphere_mapping(x, y, width, height):
30
+ x = min([max([x, 0]), width])
31
+ y = min([max([y, 0]), height])
32
+
33
+ sr = _sqrt((width/2)**2 + (height/2)**2)
34
+ sx = ((x - width / 2) / sr)
35
+ sy = ((y - height / 2) / sr)
36
+
37
+ sz = 1.0 - sx**2 - sy**2
38
+
39
+ if sz > 0.0:
40
+ sz = _sqrt(sz)
41
+ return (sx, sy, sz)
42
+ else:
43
+ sz = 0
44
+ return norm((sx, sy, sz))
45
+
46
+ rad2deg = 180.0 / 3.141592
47
+
48
+
49
+ def get_spherical_rotatation(p1, p2, width, height, theta_multiplier):
50
+ v1 = get_sphere_mapping(p1[0], p1[1], width, height)
51
+ v2 = get_sphere_mapping(p2[0], p2[1], width, height)
52
+
53
+ d = min(max([dot(v1, v2), -1]), 1)
54
+
55
+ if abs(d - 1.0) < 0.000001:
56
+ return None
57
+
58
+ raxis = norm( cross(v1, v2) )
59
+ rtheta = theta_multiplier * rad2deg * _acos(d)
60
+
61
+ pgl.glPushMatrix()
62
+ pgl.glLoadIdentity()
63
+ pgl.glRotatef(rtheta, *raxis)
64
+ mat = (c_float*16)()
65
+ pgl.glGetFloatv(pgl.GL_MODELVIEW_MATRIX, mat)
66
+ pgl.glPopMatrix()
67
+
68
+ return mat
llmeval-env/lib/python3.10/site-packages/sympy/plotting/pygletplot/plot_surface.py ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pyglet.gl as pgl
2
+
3
+ from sympy.core import S
4
+ from sympy.plotting.pygletplot.plot_mode_base import PlotModeBase
5
+
6
+
7
+ class PlotSurface(PlotModeBase):
8
+
9
+ default_rot_preset = 'perspective'
10
+
11
+ def _on_calculate_verts(self):
12
+ self.u_interval = self.intervals[0]
13
+ self.u_set = list(self.u_interval.frange())
14
+ self.v_interval = self.intervals[1]
15
+ self.v_set = list(self.v_interval.frange())
16
+ self.bounds = [[S.Infinity, S.NegativeInfinity, 0],
17
+ [S.Infinity, S.NegativeInfinity, 0],
18
+ [S.Infinity, S.NegativeInfinity, 0]]
19
+ evaluate = self._get_evaluator()
20
+
21
+ self._calculating_verts_pos = 0.0
22
+ self._calculating_verts_len = float(
23
+ self.u_interval.v_len*self.v_interval.v_len)
24
+
25
+ verts = []
26
+ b = self.bounds
27
+ for u in self.u_set:
28
+ column = []
29
+ for v in self.v_set:
30
+ try:
31
+ _e = evaluate(u, v) # calculate vertex
32
+ except ZeroDivisionError:
33
+ _e = None
34
+ if _e is not None: # update bounding box
35
+ for axis in range(3):
36
+ b[axis][0] = min([b[axis][0], _e[axis]])
37
+ b[axis][1] = max([b[axis][1], _e[axis]])
38
+ column.append(_e)
39
+ self._calculating_verts_pos += 1.0
40
+
41
+ verts.append(column)
42
+ for axis in range(3):
43
+ b[axis][2] = b[axis][1] - b[axis][0]
44
+ if b[axis][2] == 0.0:
45
+ b[axis][2] = 1.0
46
+
47
+ self.verts = verts
48
+ self.push_wireframe(self.draw_verts(False, False))
49
+ self.push_solid(self.draw_verts(False, True))
50
+
51
+ def _on_calculate_cverts(self):
52
+ if not self.verts or not self.color:
53
+ return
54
+
55
+ def set_work_len(n):
56
+ self._calculating_cverts_len = float(n)
57
+
58
+ def inc_work_pos():
59
+ self._calculating_cverts_pos += 1.0
60
+ set_work_len(1)
61
+ self._calculating_cverts_pos = 0
62
+ self.cverts = self.color.apply_to_surface(self.verts,
63
+ self.u_set,
64
+ self.v_set,
65
+ set_len=set_work_len,
66
+ inc_pos=inc_work_pos)
67
+ self.push_solid(self.draw_verts(True, True))
68
+
69
+ def calculate_one_cvert(self, u, v):
70
+ vert = self.verts[u][v]
71
+ return self.color(vert[0], vert[1], vert[2],
72
+ self.u_set[u], self.v_set[v])
73
+
74
+ def draw_verts(self, use_cverts, use_solid_color):
75
+ def f():
76
+ for u in range(1, len(self.u_set)):
77
+ pgl.glBegin(pgl.GL_QUAD_STRIP)
78
+ for v in range(len(self.v_set)):
79
+ pa = self.verts[u - 1][v]
80
+ pb = self.verts[u][v]
81
+ if pa is None or pb is None:
82
+ pgl.glEnd()
83
+ pgl.glBegin(pgl.GL_QUAD_STRIP)
84
+ continue
85
+ if use_cverts:
86
+ ca = self.cverts[u - 1][v]
87
+ cb = self.cverts[u][v]
88
+ if ca is None:
89
+ ca = (0, 0, 0)
90
+ if cb is None:
91
+ cb = (0, 0, 0)
92
+ else:
93
+ if use_solid_color:
94
+ ca = cb = self.default_solid_color
95
+ else:
96
+ ca = cb = self.default_wireframe_color
97
+ pgl.glColor3f(*ca)
98
+ pgl.glVertex3f(*pa)
99
+ pgl.glColor3f(*cb)
100
+ pgl.glVertex3f(*pb)
101
+ pgl.glEnd()
102
+ return f
llmeval-env/lib/python3.10/site-packages/sympy/plotting/pygletplot/plot_window.py ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from time import perf_counter
2
+
3
+
4
+ import pyglet.gl as pgl
5
+
6
+ from sympy.plotting.pygletplot.managed_window import ManagedWindow
7
+ from sympy.plotting.pygletplot.plot_camera import PlotCamera
8
+ from sympy.plotting.pygletplot.plot_controller import PlotController
9
+
10
+
11
+ class PlotWindow(ManagedWindow):
12
+
13
+ def __init__(self, plot, antialiasing=True, ortho=False,
14
+ invert_mouse_zoom=False, linewidth=1.5, caption="SymPy Plot",
15
+ **kwargs):
16
+ """
17
+ Named Arguments
18
+ ===============
19
+
20
+ antialiasing = True
21
+ True OR False
22
+ ortho = False
23
+ True OR False
24
+ invert_mouse_zoom = False
25
+ True OR False
26
+ """
27
+ self.plot = plot
28
+
29
+ self.camera = None
30
+ self._calculating = False
31
+
32
+ self.antialiasing = antialiasing
33
+ self.ortho = ortho
34
+ self.invert_mouse_zoom = invert_mouse_zoom
35
+ self.linewidth = linewidth
36
+ self.title = caption
37
+ self.last_caption_update = 0
38
+ self.caption_update_interval = 0.2
39
+ self.drawing_first_object = True
40
+
41
+ super().__init__(**kwargs)
42
+
43
+ def setup(self):
44
+ self.camera = PlotCamera(self, ortho=self.ortho)
45
+ self.controller = PlotController(self,
46
+ invert_mouse_zoom=self.invert_mouse_zoom)
47
+ self.push_handlers(self.controller)
48
+
49
+ pgl.glClearColor(1.0, 1.0, 1.0, 0.0)
50
+ pgl.glClearDepth(1.0)
51
+
52
+ pgl.glDepthFunc(pgl.GL_LESS)
53
+ pgl.glEnable(pgl.GL_DEPTH_TEST)
54
+
55
+ pgl.glEnable(pgl.GL_LINE_SMOOTH)
56
+ pgl.glShadeModel(pgl.GL_SMOOTH)
57
+ pgl.glLineWidth(self.linewidth)
58
+
59
+ pgl.glEnable(pgl.GL_BLEND)
60
+ pgl.glBlendFunc(pgl.GL_SRC_ALPHA, pgl.GL_ONE_MINUS_SRC_ALPHA)
61
+
62
+ if self.antialiasing:
63
+ pgl.glHint(pgl.GL_LINE_SMOOTH_HINT, pgl.GL_NICEST)
64
+ pgl.glHint(pgl.GL_POLYGON_SMOOTH_HINT, pgl.GL_NICEST)
65
+
66
+ self.camera.setup_projection()
67
+
68
+ def on_resize(self, w, h):
69
+ super().on_resize(w, h)
70
+ if self.camera is not None:
71
+ self.camera.setup_projection()
72
+
73
+ def update(self, dt):
74
+ self.controller.update(dt)
75
+
76
+ def draw(self):
77
+ self.plot._render_lock.acquire()
78
+ self.camera.apply_transformation()
79
+
80
+ calc_verts_pos, calc_verts_len = 0, 0
81
+ calc_cverts_pos, calc_cverts_len = 0, 0
82
+
83
+ should_update_caption = (perf_counter() - self.last_caption_update >
84
+ self.caption_update_interval)
85
+
86
+ if len(self.plot._functions.values()) == 0:
87
+ self.drawing_first_object = True
88
+
89
+ iterfunctions = iter(self.plot._functions.values())
90
+
91
+ for r in iterfunctions:
92
+ if self.drawing_first_object:
93
+ self.camera.set_rot_preset(r.default_rot_preset)
94
+ self.drawing_first_object = False
95
+
96
+ pgl.glPushMatrix()
97
+ r._draw()
98
+ pgl.glPopMatrix()
99
+
100
+ # might as well do this while we are
101
+ # iterating and have the lock rather
102
+ # than locking and iterating twice
103
+ # per frame:
104
+
105
+ if should_update_caption:
106
+ try:
107
+ if r.calculating_verts:
108
+ calc_verts_pos += r.calculating_verts_pos
109
+ calc_verts_len += r.calculating_verts_len
110
+ if r.calculating_cverts:
111
+ calc_cverts_pos += r.calculating_cverts_pos
112
+ calc_cverts_len += r.calculating_cverts_len
113
+ except ValueError:
114
+ pass
115
+
116
+ for r in self.plot._pobjects:
117
+ pgl.glPushMatrix()
118
+ r._draw()
119
+ pgl.glPopMatrix()
120
+
121
+ if should_update_caption:
122
+ self.update_caption(calc_verts_pos, calc_verts_len,
123
+ calc_cverts_pos, calc_cverts_len)
124
+ self.last_caption_update = perf_counter()
125
+
126
+ if self.plot._screenshot:
127
+ self.plot._screenshot._execute_saving()
128
+
129
+ self.plot._render_lock.release()
130
+
131
+ def update_caption(self, calc_verts_pos, calc_verts_len,
132
+ calc_cverts_pos, calc_cverts_len):
133
+ caption = self.title
134
+ if calc_verts_len or calc_cverts_len:
135
+ caption += " (calculating"
136
+ if calc_verts_len > 0:
137
+ p = (calc_verts_pos / calc_verts_len) * 100
138
+ caption += " vertices %i%%" % (p)
139
+ if calc_cverts_len > 0:
140
+ p = (calc_cverts_pos / calc_cverts_len) * 100
141
+ caption += " colors %i%%" % (p)
142
+ caption += ")"
143
+ if self.caption != caption:
144
+ self.set_caption(caption)
llmeval-env/lib/python3.10/site-packages/sympy/plotting/pygletplot/tests/__init__.py ADDED
File without changes