passagemath-symbolics 10.8.1a1__cp311-cp311-macosx_13_0_arm64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (182) hide show
  1. passagemath_symbolics/.dylibs/libgmp.10.dylib +0 -0
  2. passagemath_symbolics/__init__.py +3 -0
  3. passagemath_symbolics-10.8.1a1.dist-info/METADATA +186 -0
  4. passagemath_symbolics-10.8.1a1.dist-info/RECORD +182 -0
  5. passagemath_symbolics-10.8.1a1.dist-info/WHEEL +6 -0
  6. passagemath_symbolics-10.8.1a1.dist-info/top_level.txt +3 -0
  7. sage/all__sagemath_symbolics.py +17 -0
  8. sage/calculus/all.py +14 -0
  9. sage/calculus/calculus.py +2838 -0
  10. sage/calculus/desolvers.py +1864 -0
  11. sage/calculus/predefined.py +51 -0
  12. sage/calculus/tests.py +225 -0
  13. sage/calculus/var.cpython-311-darwin.so +0 -0
  14. sage/calculus/var.pyx +401 -0
  15. sage/dynamics/all__sagemath_symbolics.py +6 -0
  16. sage/dynamics/complex_dynamics/all.py +5 -0
  17. sage/dynamics/complex_dynamics/mandel_julia.py +765 -0
  18. sage/dynamics/complex_dynamics/mandel_julia_helper.cpython-311-darwin.so +0 -0
  19. sage/dynamics/complex_dynamics/mandel_julia_helper.pyx +1034 -0
  20. sage/ext/all__sagemath_symbolics.py +1 -0
  21. sage/ext_data/kenzo/CP2.txt +45 -0
  22. sage/ext_data/kenzo/CP3.txt +349 -0
  23. sage/ext_data/kenzo/CP4.txt +4774 -0
  24. sage/ext_data/kenzo/README.txt +49 -0
  25. sage/ext_data/kenzo/S4.txt +20 -0
  26. sage/ext_data/magma/latex/latex.m +1021 -0
  27. sage/ext_data/magma/latex/latex.spec +1 -0
  28. sage/ext_data/magma/sage/basic.m +356 -0
  29. sage/ext_data/magma/sage/sage.spec +1 -0
  30. sage/ext_data/magma/spec +9 -0
  31. sage/geometry/all__sagemath_symbolics.py +8 -0
  32. sage/geometry/hyperbolic_space/all.py +5 -0
  33. sage/geometry/hyperbolic_space/hyperbolic_coercion.py +755 -0
  34. sage/geometry/hyperbolic_space/hyperbolic_constants.py +5 -0
  35. sage/geometry/hyperbolic_space/hyperbolic_geodesic.py +2419 -0
  36. sage/geometry/hyperbolic_space/hyperbolic_interface.py +206 -0
  37. sage/geometry/hyperbolic_space/hyperbolic_isometry.py +1083 -0
  38. sage/geometry/hyperbolic_space/hyperbolic_model.py +1502 -0
  39. sage/geometry/hyperbolic_space/hyperbolic_point.py +621 -0
  40. sage/geometry/riemannian_manifolds/all.py +7 -0
  41. sage/geometry/riemannian_manifolds/parametrized_surface3d.py +1632 -0
  42. sage/geometry/riemannian_manifolds/surface3d_generators.py +461 -0
  43. sage/interfaces/all__sagemath_symbolics.py +1 -0
  44. sage/interfaces/magma.py +2991 -0
  45. sage/interfaces/magma_free.py +90 -0
  46. sage/interfaces/maple.py +1402 -0
  47. sage/interfaces/mathematica.py +1345 -0
  48. sage/interfaces/mathics.py +1312 -0
  49. sage/interfaces/sympy.py +1398 -0
  50. sage/interfaces/sympy_wrapper.py +197 -0
  51. sage/interfaces/tides.py +938 -0
  52. sage/libs/all__sagemath_symbolics.py +6 -0
  53. sage/manifolds/all.py +7 -0
  54. sage/manifolds/calculus_method.py +553 -0
  55. sage/manifolds/catalog.py +437 -0
  56. sage/manifolds/chart.py +4010 -0
  57. sage/manifolds/chart_func.py +3416 -0
  58. sage/manifolds/continuous_map.py +2183 -0
  59. sage/manifolds/continuous_map_image.py +155 -0
  60. sage/manifolds/differentiable/affine_connection.py +2475 -0
  61. sage/manifolds/differentiable/all.py +1 -0
  62. sage/manifolds/differentiable/automorphismfield.py +1383 -0
  63. sage/manifolds/differentiable/automorphismfield_group.py +604 -0
  64. sage/manifolds/differentiable/bundle_connection.py +1445 -0
  65. sage/manifolds/differentiable/characteristic_cohomology_class.py +1840 -0
  66. sage/manifolds/differentiable/chart.py +1241 -0
  67. sage/manifolds/differentiable/curve.py +1028 -0
  68. sage/manifolds/differentiable/de_rham_cohomology.py +541 -0
  69. sage/manifolds/differentiable/degenerate.py +559 -0
  70. sage/manifolds/differentiable/degenerate_submanifold.py +1668 -0
  71. sage/manifolds/differentiable/diff_form.py +1660 -0
  72. sage/manifolds/differentiable/diff_form_module.py +1062 -0
  73. sage/manifolds/differentiable/diff_map.py +1315 -0
  74. sage/manifolds/differentiable/differentiable_submanifold.py +291 -0
  75. sage/manifolds/differentiable/examples/all.py +1 -0
  76. sage/manifolds/differentiable/examples/euclidean.py +2517 -0
  77. sage/manifolds/differentiable/examples/real_line.py +897 -0
  78. sage/manifolds/differentiable/examples/sphere.py +1186 -0
  79. sage/manifolds/differentiable/examples/symplectic_space.py +187 -0
  80. sage/manifolds/differentiable/examples/symplectic_space_test.py +40 -0
  81. sage/manifolds/differentiable/integrated_curve.py +4035 -0
  82. sage/manifolds/differentiable/levi_civita_connection.py +841 -0
  83. sage/manifolds/differentiable/manifold.py +4254 -0
  84. sage/manifolds/differentiable/manifold_homset.py +1826 -0
  85. sage/manifolds/differentiable/metric.py +3032 -0
  86. sage/manifolds/differentiable/mixed_form.py +1507 -0
  87. sage/manifolds/differentiable/mixed_form_algebra.py +559 -0
  88. sage/manifolds/differentiable/multivector_module.py +800 -0
  89. sage/manifolds/differentiable/multivectorfield.py +1522 -0
  90. sage/manifolds/differentiable/poisson_tensor.py +268 -0
  91. sage/manifolds/differentiable/pseudo_riemannian.py +755 -0
  92. sage/manifolds/differentiable/pseudo_riemannian_submanifold.py +1839 -0
  93. sage/manifolds/differentiable/scalarfield.py +1343 -0
  94. sage/manifolds/differentiable/scalarfield_algebra.py +472 -0
  95. sage/manifolds/differentiable/symplectic_form.py +912 -0
  96. sage/manifolds/differentiable/symplectic_form_test.py +220 -0
  97. sage/manifolds/differentiable/tangent_space.py +412 -0
  98. sage/manifolds/differentiable/tangent_vector.py +616 -0
  99. sage/manifolds/differentiable/tensorfield.py +4665 -0
  100. sage/manifolds/differentiable/tensorfield_module.py +963 -0
  101. sage/manifolds/differentiable/tensorfield_paral.py +2450 -0
  102. sage/manifolds/differentiable/tensorfield_paral_test.py +16 -0
  103. sage/manifolds/differentiable/vector_bundle.py +1725 -0
  104. sage/manifolds/differentiable/vectorfield.py +1717 -0
  105. sage/manifolds/differentiable/vectorfield_module.py +2445 -0
  106. sage/manifolds/differentiable/vectorframe.py +1832 -0
  107. sage/manifolds/family.py +270 -0
  108. sage/manifolds/local_frame.py +1490 -0
  109. sage/manifolds/manifold.py +3090 -0
  110. sage/manifolds/manifold_homset.py +452 -0
  111. sage/manifolds/operators.py +359 -0
  112. sage/manifolds/point.py +994 -0
  113. sage/manifolds/scalarfield.py +3718 -0
  114. sage/manifolds/scalarfield_algebra.py +629 -0
  115. sage/manifolds/section.py +3111 -0
  116. sage/manifolds/section_module.py +831 -0
  117. sage/manifolds/structure.py +229 -0
  118. sage/manifolds/subset.py +2721 -0
  119. sage/manifolds/subsets/all.py +1 -0
  120. sage/manifolds/subsets/closure.py +131 -0
  121. sage/manifolds/subsets/pullback.py +883 -0
  122. sage/manifolds/topological_submanifold.py +891 -0
  123. sage/manifolds/trivialization.py +733 -0
  124. sage/manifolds/utilities.py +1348 -0
  125. sage/manifolds/vector_bundle.py +1347 -0
  126. sage/manifolds/vector_bundle_fiber.py +332 -0
  127. sage/manifolds/vector_bundle_fiber_element.py +111 -0
  128. sage/matrix/all__sagemath_symbolics.py +1 -0
  129. sage/matrix/matrix_symbolic_dense.cpython-311-darwin.so +0 -0
  130. sage/matrix/matrix_symbolic_dense.pxd +6 -0
  131. sage/matrix/matrix_symbolic_dense.pyx +1030 -0
  132. sage/matrix/matrix_symbolic_sparse.cpython-311-darwin.so +0 -0
  133. sage/matrix/matrix_symbolic_sparse.pxd +6 -0
  134. sage/matrix/matrix_symbolic_sparse.pyx +1038 -0
  135. sage/modules/all__sagemath_symbolics.py +1 -0
  136. sage/modules/vector_callable_symbolic_dense.py +105 -0
  137. sage/modules/vector_symbolic_dense.py +116 -0
  138. sage/modules/vector_symbolic_sparse.py +118 -0
  139. sage/rings/all__sagemath_symbolics.py +4 -0
  140. sage/rings/asymptotic/all.py +6 -0
  141. sage/rings/asymptotic/asymptotic_expansion_generators.py +1485 -0
  142. sage/rings/asymptotic/asymptotic_ring.py +4858 -0
  143. sage/rings/asymptotic/asymptotics_multivariate_generating_functions.py +4106 -0
  144. sage/rings/asymptotic/growth_group.py +5373 -0
  145. sage/rings/asymptotic/growth_group_cartesian.py +1400 -0
  146. sage/rings/asymptotic/term_monoid.py +5205 -0
  147. sage/rings/function_field/all__sagemath_symbolics.py +2 -0
  148. sage/rings/polynomial/all__sagemath_symbolics.py +1 -0
  149. sage/symbolic/all.py +15 -0
  150. sage/symbolic/assumptions.py +987 -0
  151. sage/symbolic/benchmark.py +93 -0
  152. sage/symbolic/callable.py +456 -0
  153. sage/symbolic/callable.pyi +66 -0
  154. sage/symbolic/comparison_impl.pyi +38 -0
  155. sage/symbolic/complexity_measures.py +35 -0
  156. sage/symbolic/constants.py +1286 -0
  157. sage/symbolic/constants_c_impl.pyi +10 -0
  158. sage/symbolic/expression_conversion_algebraic.py +310 -0
  159. sage/symbolic/expression_conversion_sympy.py +317 -0
  160. sage/symbolic/expression_conversions.py +1727 -0
  161. sage/symbolic/function_factory.py +355 -0
  162. sage/symbolic/function_factory.pyi +41 -0
  163. sage/symbolic/getitem_impl.pyi +24 -0
  164. sage/symbolic/integration/all.py +1 -0
  165. sage/symbolic/integration/external.py +271 -0
  166. sage/symbolic/integration/integral.py +1075 -0
  167. sage/symbolic/maxima_wrapper.py +162 -0
  168. sage/symbolic/operators.py +267 -0
  169. sage/symbolic/operators.pyi +61 -0
  170. sage/symbolic/pynac_constant_impl.pyi +13 -0
  171. sage/symbolic/pynac_function_impl.pyi +8 -0
  172. sage/symbolic/random_tests.py +461 -0
  173. sage/symbolic/relation.py +2062 -0
  174. sage/symbolic/ring.cpython-311-darwin.so +0 -0
  175. sage/symbolic/ring.pxd +5 -0
  176. sage/symbolic/ring.pyi +110 -0
  177. sage/symbolic/ring.pyx +1393 -0
  178. sage/symbolic/series_impl.pyi +10 -0
  179. sage/symbolic/subring.py +1025 -0
  180. sage/symbolic/symengine.py +19 -0
  181. sage/symbolic/tests.py +40 -0
  182. sage/symbolic/units.py +1468 -0
@@ -0,0 +1,1312 @@
1
+ # sage_setup: distribution = sagemath-symbolics
2
+ r"""
3
+ Interface to Mathics
4
+
5
+ Mathics is an open source interpreter for the Wolfram Language.
6
+ From the introduction of its reference manual:
7
+
8
+ .. NOTE::
9
+
10
+ Mathics — to be pronounced like “Mathematics” without the
11
+ “emat” — is a general-purpose computer algebra system (CAS).
12
+ It is meant to be a free, light-weight alternative to
13
+ Mathematica®. It is free both as in “free beer” and as in
14
+ “freedom”. There are various online mirrors running
15
+ Mathics but it is also possible to run Mathics locally.
16
+ A list of mirrors can be found at the Mathics homepage,
17
+ http://mathics.github.io.
18
+
19
+ The programming language of Mathics is meant to resemble
20
+ Wolfram’s famous Mathematica® as much as possible. However,
21
+ Mathics is in no way affiliated or supported by Wolfram.
22
+ Mathics will probably never have the power to compete with
23
+ Mathematica® in industrial applications; yet, it might be
24
+ an interesting alternative for educational purposes.
25
+
26
+ The Mathics interface will only work if the optional Sage package Mathics
27
+ is installed. The interface lets you send certain Sage objects to Mathics,
28
+ run Mathics functions, import certain Mathics expressions to Sage,
29
+ or any combination of the above.
30
+
31
+ To send a Sage object ``sobj`` to Mathics, call ``mathics(sobj)``.
32
+ This exports the Sage object to Mathics and returns a new Sage object
33
+ wrapping the Mathics expression/variable, so that you can use the
34
+ Mathics variable from within Sage. You can then call Mathics
35
+ functions on the new object; for example::
36
+
37
+ sage: from sage.interfaces.mathics import mathics
38
+ sage: mobj = mathics(x^2-1); mobj # optional - mathics
39
+ -1 + x ^ 2
40
+ sage: mobj.Factor() # optional - mathics
41
+ (-1 + x) (1 + x)
42
+
43
+ In the above example the factorization is done using Mathics's
44
+ ``Factor[]`` function.
45
+
46
+ To see Mathics's output you can simply print the Mathics wrapper
47
+ object. However if you want to import Mathics's output back to Sage,
48
+ call the Mathics wrapper object's ``sage()`` method. This method returns
49
+ a native Sage object::
50
+
51
+ sage: # optional - mathics
52
+ sage: mobj = mathics(x^2-1)
53
+ sage: mobj2 = mobj.Factor(); mobj2
54
+ (-1 + x) (1 + x)
55
+ sage: mobj2.parent()
56
+ Mathics
57
+ sage: sobj = mobj2.sage(); sobj
58
+ (x + 1)*(x - 1)
59
+ sage: sobj.parent()
60
+ Symbolic Ring
61
+
62
+
63
+ If you want to run a Mathics function and don't already have the input
64
+ in the form of a Sage object, then it might be simpler to input a string to
65
+ ``mathics(expr)``. This string will be evaluated as if you had typed it
66
+ into Mathics::
67
+
68
+ sage: mathics('Factor[x^2-1]') # optional - mathics
69
+ (-1 + x) (1 + x)
70
+ sage: mathics('Range[3]') # optional - mathics
71
+ {1, 2, 3}
72
+
73
+ If you want work with the internal Mathics expression, then you can call
74
+ ``mathics.eval(expr)``, which returns an instance of
75
+ :class:`mathics.core.expression.Expression`. If you want the result to
76
+ be a string formatted like Mathics's InputForm, call ``repr(mobj)`` on
77
+ the wrapper object ``mobj``. If you want a string formatted in Sage style,
78
+ call ``mobj._sage_repr()``::
79
+
80
+ sage: mathics.eval('x^2 - 1') # optional - mathics
81
+ '-1 + x ^ 2'
82
+ sage: repr(mathics('Range[3]')) # optional - mathics
83
+ '{1, 2, 3}'
84
+ sage: mathics('Range[3]')._sage_repr() # optional - mathics
85
+ '[1, 2, 3]'
86
+
87
+ Finally, if you just want to use a Mathics command line from within
88
+ Sage, the function ``mathics_console()`` dumps you into an interactive
89
+ command-line Mathics session.
90
+
91
+ Tutorial
92
+ --------
93
+
94
+ We follow some of the tutorial from
95
+ http://library.wolfram.com/conferences/devconf99/withoff/Basic1.html/.
96
+
97
+
98
+ Syntax
99
+ ~~~~~~
100
+
101
+ Now make 1 and add it to itself. The result is a Mathics
102
+ object.
103
+
104
+ ::
105
+
106
+ sage: m = mathics
107
+ sage: a = m(1) + m(1); a # optional - mathics
108
+ 2
109
+ sage: a.parent() # optional - mathics
110
+ Mathics
111
+ sage: m('1+1') # optional - mathics
112
+ 2
113
+ sage: m(3)**m(50) # optional - mathics
114
+ 717897987691852588770249
115
+
116
+ The following is equivalent to ``Plus[2, 3]`` in
117
+ Mathics::
118
+
119
+ sage: m = mathics
120
+ sage: m(2).Plus(m(3)) # optional - mathics
121
+ 5
122
+
123
+ We can also compute `7(2+3)`.
124
+
125
+ ::
126
+
127
+ sage: m(7).Times(m(2).Plus(m(3))) # optional - mathics
128
+ 35
129
+ sage: m('7(2+3)') # optional - mathics
130
+ 35
131
+
132
+ Some typical input
133
+ ~~~~~~~~~~~~~~~~~~
134
+
135
+ We solve an equation and a system of two equations::
136
+
137
+ sage: # optional - mathics
138
+ sage: eqn = mathics('3x + 5 == 14')
139
+ sage: eqn
140
+ 5 + 3 x == 14
141
+ sage: eqn.Solve('x')
142
+ {{x -> 3}}
143
+ sage: sys = mathics('{x^2 - 3y == 3, 2x - y == 1}')
144
+ sage: print(sys)
145
+ {x ^ 2 - 3 y == 3, 2 x - y == 1}
146
+ sage: sys.Solve('{x, y}')
147
+ {{x -> 0, y -> -1}, {x -> 6, y -> 11}}
148
+
149
+ Assignments and definitions
150
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
151
+
152
+ If you assign the mathics `5` to a variable `c`
153
+ in Sage, this does not affect the `c` in Mathics.
154
+
155
+ ::
156
+
157
+ sage: c = m(5) # optional - mathics
158
+ sage: print(m('b + c x')) # optional - mathics
159
+ b + c x
160
+ sage: print(m('b') + c*m('x')) # optional - mathics
161
+ b + 5 x
162
+
163
+ The Sage interfaces changes Sage lists into Mathics lists::
164
+
165
+ sage: m = mathics
166
+ sage: eq1 = m('x^2 - 3y == 3') # optional - mathics
167
+ sage: eq2 = m('2x - y == 1') # optional - mathics
168
+ sage: v = m([eq1, eq2]); v # optional - mathics
169
+ {x ^ 2 - 3 y == 3, 2 x - y == 1}
170
+ sage: v.Solve(['x', 'y']) # optional - mathics
171
+ {{x -> 0, y -> -1}, {x -> 6, y -> 11}}
172
+
173
+ Function definitions
174
+ ~~~~~~~~~~~~~~~~~~~~
175
+
176
+ Define mathics functions by simply sending the definition to
177
+ the interpreter.
178
+
179
+ ::
180
+
181
+ sage: m = mathics
182
+ sage: _ = mathics('f[p_] = p^2'); # optional - mathics
183
+ sage: m('f[9]') # optional - mathics
184
+ 81
185
+
186
+ Numerical Calculations
187
+ ~~~~~~~~~~~~~~~~~~~~~~
188
+
189
+ We find the `x` such that `e^x - 3x = 0`.
190
+
191
+ ::
192
+
193
+ sage: eqn = mathics('Exp[x] - 3x == 0') # optional - mathics
194
+ sage: eqn.FindRoot(['x', 2]) # optional - mathics
195
+ {x -> 1.51213}
196
+
197
+ Note that this agrees with what the PARI interpreter gp produces::
198
+
199
+ sage: gp('solve(x=1,2,exp(x)-3*x)') # needs sage.libs.pari
200
+ 1.5121345516578424738967396780720387046
201
+
202
+ Next we find the minimum of a polynomial using the two different
203
+ ways of accessing Mathics::
204
+
205
+ sage: mathics('FindMinimum[x^3 - 6x^2 + 11x - 5, {x,3}]') # not tested (since not supported, so far)
206
+ {0.6150998205402516, {x -> 2.5773502699629733}}
207
+ sage: f = mathics('x^3 - 6x^2 + 11x - 5') # optional - mathics
208
+ sage: f.FindMinimum(['x', 3]) # not tested (since not supported, so far)
209
+ {0.6150998205402516, {x -> 2.5773502699629733}}
210
+
211
+ Polynomial and Integer Factorization
212
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
213
+
214
+ We factor a polynomial of degree 200 over the integers.
215
+
216
+ ::
217
+
218
+ sage: R.<x> = PolynomialRing(ZZ)
219
+ sage: f = (x**100+17*x+5)*(x**100-5*x+20)
220
+ sage: f
221
+ x^200 + 12*x^101 + 25*x^100 - 85*x^2 + 315*x + 100
222
+ sage: g = mathics(str(f)) # optional - mathics
223
+ sage: print(g) # optional - mathics
224
+ 100 + 315 x - 85 x ^ 2 + 25 x ^ 100 + 12 x ^ 101 + x ^ 200
225
+ sage: g # optional - mathics
226
+ 100 + 315 x - 85 x ^ 2 + 25 x ^ 100 + 12 x ^ 101 + x ^ 200
227
+ sage: print(g.Factor()) # optional - mathics
228
+ (5 + 17 x + x ^ 100) (20 - 5 x + x ^ 100)
229
+
230
+ We can also factor a multivariate polynomial::
231
+
232
+ sage: f = mathics('x^6 + (-y - 2)*x^5 + (y^3 + 2*y)*x^4 - y^4*x^3') # optional - mathics
233
+ sage: print(f.Factor()) # optional - mathics
234
+ x ^ 3 (x - y) (-2 x + x ^ 2 + y ^ 3)
235
+
236
+ We factor an integer::
237
+
238
+ sage: # optional - mathics
239
+ sage: n = mathics(2434500)
240
+ sage: n.FactorInteger()
241
+ {{2, 2}, {3, 2}, {5, 3}, {541, 1}}
242
+ sage: n = mathics(2434500)
243
+ sage: F = n.FactorInteger(); F
244
+ {{2, 2}, {3, 2}, {5, 3}, {541, 1}}
245
+ sage: F[1]
246
+ {2, 2}
247
+ sage: F[4]
248
+ {541, 1}
249
+
250
+
251
+ Long Input
252
+ ----------
253
+
254
+ The Mathics interface reads in even very long input (using
255
+ files) in a robust manner.
256
+
257
+ ::
258
+
259
+ sage: t = '"%s"'%10^10000 # ten thousand character string.
260
+ sage: a = mathics(t) # optional - mathics
261
+ sage: a = mathics.eval(t) # optional - mathics
262
+
263
+ Loading and saving
264
+ ------------------
265
+
266
+ Mathics has an excellent ``InputForm`` function,
267
+ which makes saving and loading Mathics objects possible. The
268
+ first examples test saving and loading to strings.
269
+
270
+ ::
271
+
272
+ sage: # optional - mathics
273
+ sage: x = mathics(pi/2)
274
+ sage: print(x)
275
+ Pi / 2
276
+ sage: loads(dumps(x)) == x
277
+ True
278
+ sage: n = x.N(50)
279
+ sage: print(n)
280
+ 1.5707963267948966192313216916397514420985846996876
281
+ sage: loads(dumps(n)) == n
282
+ True
283
+
284
+ Complicated translations
285
+ ------------------------
286
+
287
+ The ``mobj.sage()`` method tries to convert a Mathics object to a Sage
288
+ object. In many cases, it will just work. In particular, it should be able to
289
+ convert expressions entirely consisting of:
290
+
291
+ - numbers, i.e. integers, floats, complex numbers;
292
+ - functions and named constants also present in Sage, where:
293
+
294
+ - Sage knows how to translate the function or constant's name from
295
+ Mathics's, or
296
+ - the Sage name for the function or constant is trivially related to
297
+ Mathics's;
298
+
299
+ - symbolic variables whose names don't pathologically overlap with
300
+ objects already defined in Sage.
301
+
302
+ This method will not work when Mathics's output includes:
303
+
304
+ - strings;
305
+ - functions unknown to Sage;
306
+ - Mathics functions with different parameters/parameter order to
307
+ the Sage equivalent.
308
+
309
+ If you want to convert more complicated Mathics expressions, you can
310
+ instead call ``mobj._sage_()`` and supply a translation dictionary::
311
+
312
+ sage: x = var('x')
313
+ sage: m = mathics('NewFn[x]') # optional - mathics
314
+ sage: m._sage_(locals={'NewFn': sin, 'x':x}) # optional - mathics
315
+ sin(x)
316
+
317
+ For more details, see the documentation for ``._sage_()``.
318
+
319
+
320
+ OTHER Examples::
321
+
322
+ sage: def math_bessel_K(nu, x):
323
+ ....: return mathics(nu).BesselK(x).N(20)
324
+ sage: math_bessel_K(2,I) # optional - mathics
325
+ -2.5928861754911969782 + 0.18048997206696202663 I
326
+
327
+ ::
328
+
329
+ sage: slist = [[1, 2], 3., 4 + I]
330
+ sage: mlist = mathics(slist); mlist # optional - mathics
331
+ {{1, 2}, 3., 4 + I}
332
+ sage: slist2 = list(mlist); slist2 # optional - mathics
333
+ [{1, 2}, 3., 4 + I]
334
+ sage: slist2[0] # optional - mathics
335
+ {1, 2}
336
+ sage: slist2[0].parent() # optional - mathics
337
+ Mathics
338
+ sage: slist3 = mlist.sage(); slist3 # optional - mathics
339
+ [[1, 2], 3.00000000000000, 4.00000000000000 + 1.00000000000000*I]
340
+
341
+ ::
342
+
343
+ sage: mathics('10.^80') # optional - mathics
344
+ 1.×10^80
345
+ sage: mathics('10.^80').sage() # optional - mathics
346
+ 1.00000000000000e80
347
+
348
+ AUTHORS:
349
+
350
+ - Sebastian Oehms (2021): first version from a copy of the Mathematica interface (see :issue:`31778`).
351
+
352
+
353
+ Thanks to Rocky Bernstein and Juan Mauricio Matera for their support. For further acknowledgments see `this list <https://github.com/mathics/Mathics/blob/master/AUTHORS.txt>`__.
354
+
355
+ TESTS:
356
+
357
+ Check that numerical approximations via Mathics's `N[]` function work
358
+ correctly (:issue:`18888`, :issue:`28907`)::
359
+
360
+ sage: # optional - mathics
361
+ sage: mathics('Pi/2').N(10)
362
+ 1.570796327
363
+ sage: mathics('Pi').N(10)
364
+ 3.141592654
365
+ sage: mathics('Pi').N(50)
366
+ 3.1415926535897932384626433832795028841971693993751
367
+ sage: str(mathics('Pi*x^2-1/2').N())
368
+ '-0.5 + 3.14159 x ^ 2.'
369
+
370
+ Check that Mathics's `E` exponential symbol is correctly backtranslated
371
+ as Sage's `e` (:issue:`29833`)::
372
+
373
+ sage: (e^x)._mathics_().sage() # optional -- mathics
374
+ e^x
375
+ sage: exp(x)._mathics_().sage() # optional -- mathics
376
+ e^x
377
+ """
378
+
379
+ ##############################################################################
380
+ # Copyright (C) 2021 Sebastian Oehms <seb.oehms@gmail.com>
381
+ #
382
+ # This program is free software: you can redistribute it and/or modify
383
+ # it under the terms of the GNU General Public License as published by
384
+ # the Free Software Foundation, either version 2 of the License, or
385
+ # (at your option) any later version.
386
+ # https://www.gnu.org/licenses/
387
+ ##############################################################################
388
+
389
+ import os
390
+
391
+ from sage.misc.cachefunc import cached_method
392
+ from sage.interfaces.interface import Interface, InterfaceElement, InterfaceFunction, InterfaceFunctionElement
393
+ from sage.interfaces.tab_completion import ExtraTabCompletion
394
+ from sage.misc.instancedoc import instancedoc
395
+ from sage.structure.richcmp import rich_to_bool
396
+
397
+
398
+ def _mathics_sympysage_symbol(self):
399
+ r"""
400
+ Convert a Sympy symbol ``self`` to a corresponding element
401
+ in Sage's symbolic ring.
402
+
403
+ This function replaces ``_sympysage_symbol`` to
404
+ take care of the special names used in Mathics.
405
+ It is set to the method ``_sage_`` of the Sympy class
406
+ :class:`sympy.core.symbol.Sympol`.
407
+
408
+ EXAMPLES::
409
+
410
+ sage: # optional - mathics
411
+ sage: from sage.interfaces.mathics import _mathics_sympysage_symbol
412
+ sage: mt = mathics('t')
413
+ sage: st = mt.to_sympy(); st
414
+ _Mathics_User_Global`t
415
+ sage: _mathics_sympysage_symbol(st)
416
+ t
417
+ sage: bool(_ == st._sage_())
418
+ True
419
+ sage: type(st._sage_())
420
+ <class 'sage.symbolic.expression.Expression'>
421
+ """
422
+ from sage.symbolic.ring import SR
423
+ try:
424
+ name = self.name
425
+ if name.startswith('_Mathics_User_'):
426
+ name = name.split('`')[1]
427
+ if name == mathics._true_symbol():
428
+ return True
429
+ if name == mathics._false_symbol():
430
+ return False
431
+ return SR.var(name)
432
+ except ValueError:
433
+ # sympy sometimes returns dummy variables
434
+ # with name = 'None', str rep = '_None'
435
+ # in particular in inverse Laplace and inverse Mellin transforms
436
+ return SR.var(str(self))
437
+
438
+
439
+ class Mathics(Interface):
440
+ r"""
441
+ Interface to the Mathics interpreter.
442
+
443
+ Implemented according to the Mathematica interface but avoiding Pexpect
444
+ functionality.
445
+
446
+ EXAMPLES::
447
+
448
+ sage: # optional - mathics
449
+ sage: t = mathics('Tan[I + 0.5]')
450
+ sage: t.parent()
451
+ Mathics
452
+ sage: ts = t.sage()
453
+ sage: ts.parent()
454
+ Complex Field with 53 bits of precision
455
+ sage: t == mathics(ts)
456
+ True
457
+ sage: mtan = mathics.Tan
458
+ sage: mt = mtan(I+1/2)
459
+ sage: mt == t
460
+ True
461
+ sage: u = mathics(I+1/2)
462
+ sage: u.Tan() == mt
463
+ True
464
+
465
+
466
+ More examples can be found in the module header.
467
+ """
468
+ def __init__(self,
469
+ maxread=None,
470
+ logfile=None,
471
+ init_list_length=1024,
472
+ seed=None):
473
+ r"""
474
+ Python constructor.
475
+
476
+ EXAMPLES::
477
+
478
+ sage: mathics._mathics_init_ == mathics._mathematica_init_
479
+ True
480
+ """
481
+
482
+ Interface.__init__(self, name='mathics')
483
+ self._seed = seed
484
+ self._initialized = False # done lazily
485
+ self._session = None
486
+ os.environ['MATHICS_CHARACTER_ENCODING'] = 'ASCII' # see :issue:`37395`
487
+
488
+ def _lazy_init(self):
489
+ r"""
490
+ Initialize the Mathics interpreter.
491
+
492
+ Implemented according to R interface.
493
+
494
+ EXAMPLES::
495
+
496
+ sage: mathics._lazy_init() # optional - mathics
497
+ """
498
+ if not self._initialized:
499
+ self._initialized = True
500
+ self._start()
501
+
502
+ def _start(self):
503
+ """
504
+ Start up the Mathics interpreter and sets the initial prompt and options.
505
+
506
+ This is called the first time the Mathics interface is actually used.
507
+
508
+ EXAMPLES::
509
+
510
+ sage: mathics._start() # optional - mathics
511
+ sage: type(mathics._session) # optional - mathics
512
+ <class 'mathics.session.MathicsSession'>
513
+ """
514
+ if not self._session:
515
+ from mathics.session import MathicsSession
516
+ from mathics.core.load_builtin import import_and_load_builtins
517
+ import_and_load_builtins()
518
+ self._session = MathicsSession()
519
+ from sage.interfaces.sympy import sympy_init
520
+ sympy_init()
521
+ from sympy import Symbol
522
+ Symbol._sage_ = _mathics_sympysage_symbol
523
+
524
+ def _read_in_file_command(self, filename):
525
+ r"""
526
+ EXAMPLES::
527
+
528
+ sage: from sage.misc.temporary_file import tmp_filename
529
+ sage: fn = tmp_filename()
530
+ sage: mathics('40!>>%s' %fn) # optional - mathics
531
+ 815915283247897734345611269596115894272000000000
532
+ sage: mathics(mathics._read_in_file_command(fn)) # optional - mathics
533
+ 815915283247897734345611269596115894272000000000
534
+ sage: os.system('rm %s' %fn) # optional - mathics
535
+ 0
536
+ """
537
+ return '<<"%s"' % filename
538
+
539
+ def _install_hints(self):
540
+ """
541
+ Hints for installing mathics on your computer.
542
+
543
+ EXAMPLES::
544
+
545
+ sage: len(mathics._install_hints()) # optional - mathics
546
+ 101
547
+ """
548
+ return """
549
+ In order to use the Mathics interface you need to have the
550
+ optional Sage package Mathics installed.
551
+ """
552
+
553
+ def _eval(self, code):
554
+ """
555
+ Evaluates a command inside the Mathics interpreter and returns the output
556
+ as a Mathics result.
557
+
558
+ EXAMPLES::
559
+
560
+ sage: mathics._eval('1+1').last_eval # optional - mathics
561
+ <Integer: 2>
562
+ """
563
+ self._lazy_init()
564
+ S = self._session
565
+ expr = S.evaluate(code)
566
+ from mathics.core.evaluation import Evaluation
567
+ ev = Evaluation(S.definitions)
568
+ return ev.evaluate(expr)
569
+
570
+ def eval(self, code, *args, **kwds):
571
+ """
572
+ Evaluates a command inside the Mathics interpreter and returns the output
573
+ in printable form.
574
+
575
+ EXAMPLES::
576
+
577
+ sage: mathics.eval('1+1') # optional - mathics
578
+ '2'
579
+ """
580
+ res = self._eval(code)
581
+ if res.result == 'Null':
582
+ if len(res.out) == 1:
583
+ return str(res.out[0])
584
+ return res.result
585
+
586
+ def set(self, var, value):
587
+ """
588
+ Set the variable var to the given value.
589
+
590
+ EXAMPLES::
591
+
592
+ sage: mathics.set('u', '2*x +E') # optional - mathics
593
+ sage: bool(mathics('u').sage() == 2*x+e) # optional - mathics
594
+ True
595
+ """
596
+ cmd = f'{var}={value};'
597
+ _ = self.eval(cmd)
598
+
599
+ def get(self, var):
600
+ """
601
+ Get the value of the variable var.
602
+
603
+ EXAMPLES::
604
+
605
+ sage: mathics.set('u', '2*x +E') # optional - mathics
606
+ sage: mathics.get('u') # optional - mathics
607
+ '2 x + E'
608
+ """
609
+ return self.eval(var)
610
+
611
+ def _function_call_string(self, function, args, kwds):
612
+ """
613
+ Return the string used to make function calls.
614
+
615
+ EXAMPLES::
616
+
617
+ sage: mathics._function_call_string('Sin', ['x'], [])
618
+ 'Sin[x]'
619
+ """
620
+ return "{}[{}]".format(function, ",".join(args))
621
+
622
+ def _left_list_delim(self):
623
+ r"""
624
+ EXAMPLES::
625
+
626
+ sage: mathics._left_list_delim()
627
+ '{'
628
+ """
629
+ return "{"
630
+
631
+ def _right_list_delim(self):
632
+ r"""
633
+ EXAMPLES::
634
+
635
+ sage: mathics._right_list_delim()
636
+ '}'
637
+ """
638
+ return "}"
639
+
640
+ def _left_func_delim(self):
641
+ r"""
642
+ EXAMPLES::
643
+
644
+ sage: mathics._left_func_delim()
645
+ '['
646
+ """
647
+ return "["
648
+
649
+ def _right_func_delim(self):
650
+ r"""
651
+ EXAMPLES::
652
+
653
+ sage: mathics._right_func_delim()
654
+ ']'
655
+ """
656
+ return "]"
657
+
658
+ # #########################################
659
+ # System -- change directory, etc.
660
+ # #########################################
661
+ def chdir(self, dir):
662
+ """
663
+ Change Mathics's current working directory.
664
+
665
+ EXAMPLES::
666
+
667
+ sage: mathics.chdir('/') # optional - mathics
668
+ sage: mathics('Directory[]') # optional - mathics
669
+ /
670
+ """
671
+ self.eval('SetDirectory["%s"]' % dir)
672
+
673
+ def _true_symbol(self):
674
+ r"""
675
+ EXAMPLES::
676
+
677
+ sage: mathics._true_symbol()
678
+ 'True'
679
+ """
680
+ return 'True'
681
+
682
+ def _false_symbol(self):
683
+ r"""
684
+ EXAMPLES::
685
+
686
+ sage: mathics._false_symbol()
687
+ 'False'
688
+ """
689
+ return 'False'
690
+
691
+ def _equality_symbol(self):
692
+ r"""
693
+ EXAMPLES::
694
+
695
+ sage: mathics._equality_symbol()
696
+ '=='
697
+ """
698
+ return '=='
699
+
700
+ def _assign_symbol(self):
701
+ r"""
702
+ EXAMPLES::
703
+
704
+ sage: mathics._assign_symbol()
705
+ ':='
706
+ """
707
+ return ':='
708
+
709
+ def _exponent_symbol(self):
710
+ r"""
711
+ Return the symbol used to denote the exponent of a number in
712
+ Mathics.
713
+
714
+ EXAMPLES::
715
+
716
+ sage: mathics._exponent_symbol()
717
+ '*^'
718
+
719
+ ::
720
+
721
+ sage: bignum = mathics('10.^80') # optional - mathics
722
+ sage: repr(bignum) # optional - mathics
723
+ '1.×10^80'
724
+ sage: repr(bignum).replace(mathics._exponent_symbol(), 'e').strip() # optional - mathics
725
+ '1.×10^80'
726
+ """
727
+ return '*^'
728
+
729
+ def _object_class(self):
730
+ r"""
731
+ Return the element class of this parent.
732
+ This is used in the interface class.
733
+
734
+ EXAMPLES::
735
+
736
+ sage: mathics._object_class()
737
+ <class 'sage.interfaces.mathics.MathicsElement'>
738
+ """
739
+ return MathicsElement
740
+
741
+ def console(self):
742
+ r"""
743
+ Spawn a new Mathics command-line session.
744
+
745
+ EXAMPLES::
746
+
747
+ sage: mathics.console() # not tested
748
+
749
+ Mathics 2.1.1.dev0
750
+ on CPython 3.9.2 (default, Mar 19 2021, 22:23:28)
751
+ using SymPy 1.7, mpmath 1.2.1, numpy 1.19.5, cython 0.29.21
752
+
753
+ Copyright (C) 2011-2021 The Mathics Team.
754
+ This program comes with ABSOLUTELY NO WARRANTY.
755
+ This is free software, and you are welcome to redistribute it
756
+ under certain conditions.
757
+ See the documentation for the full license.
758
+
759
+ Quit by evaluating Quit[] or by pressing CONTROL-D.
760
+
761
+ In[1]:= Sin[0.5]
762
+ Out[1]= 0.479426
763
+
764
+ Goodbye!
765
+
766
+ sage:
767
+ """
768
+ mathics_console()
769
+
770
+ def help(self, cmd, long=False):
771
+ r"""
772
+ Return the Mathics documentation of the given command.
773
+
774
+ EXAMPLES::
775
+
776
+ sage: mathics.help('Sin') # optional - mathics
777
+ 'sine function\n'
778
+
779
+ sage: print(_) # optional - mathics
780
+ sine function
781
+ <BLANKLINE>
782
+
783
+ sage: print(mathics.help('Sin', long=True)) # optional - mathics
784
+ sine function
785
+ <BLANKLINE>
786
+ Attributes[Sin] = {Listable, NumericFunction, Protected}
787
+ <BLANKLINE>
788
+
789
+ sage: print(mathics.Factorial.__doc__) # optional - mathics
790
+ factorial
791
+ <BLANKLINE>
792
+
793
+ sage: u = mathics('Pi') # optional - mathics
794
+ sage: print(u.Cos.__doc__) # optional - mathics
795
+ cosine function
796
+ <BLANKLINE>
797
+ """
798
+ if long:
799
+ return self.eval('Information[%s]' % cmd)
800
+ else:
801
+ return self.eval('? %s' % cmd)
802
+
803
+ def __getattr__(self, attrname):
804
+ r"""
805
+ EXAMPLES::
806
+
807
+ sage: msin = mathics.Sin # optional - mathics
808
+ sage: msin(0.2) # optional - mathics
809
+ 0.19866933079506123
810
+ sage: _ == sin(0.2) # optional - mathics
811
+ True
812
+ """
813
+ if attrname[:1] == "_":
814
+ raise AttributeError
815
+ return InterfaceFunction(self, attrname)
816
+
817
+
818
+ @instancedoc
819
+ class MathicsElement(ExtraTabCompletion, InterfaceElement):
820
+ r"""
821
+ Element class of the Mathics interface.
822
+
823
+ Its instances are usually constructed via the instance call of its parent.
824
+ It wrapes the Mathics library for this object. In a session Mathics methods
825
+ can be obtained using tab completion.
826
+
827
+ EXAMPLES::
828
+
829
+ sage: # optional - mathics
830
+ sage: me=mathics(e); me
831
+ E
832
+ sage: type(me)
833
+ <class 'sage.interfaces.mathics.MathicsElement'>
834
+ sage: P = me.parent(); P
835
+ Mathics
836
+ sage: type(P)
837
+ <class 'sage.interfaces.mathics.Mathics'>
838
+
839
+ Access to the Mathics expression objects::
840
+
841
+ sage: # optional - mathics
842
+ sage: res = me._mathics_result
843
+ sage: type(res)
844
+ <class 'mathics.core.evaluation.Result'>
845
+ sage: expr = res.last_eval; expr
846
+ <Symbol: System`E>
847
+ sage: type(expr)
848
+ <class 'mathics.core.symbols.Symbol'>
849
+
850
+ Applying Mathics methods::
851
+
852
+ sage: # optional - mathics
853
+ sage: me.to_sympy()
854
+ E
855
+ sage: me.get_name()
856
+ 'System`E'
857
+ sage: me.is_inexact()
858
+ False
859
+
860
+ Conversion to Sage::
861
+
862
+ sage: bool(me.sage() == e) # optional - mathics
863
+ True
864
+ """
865
+
866
+ def _tab_completion(self):
867
+ r"""
868
+ Return a list of all methods of this object.
869
+
870
+ .. NOTE::
871
+
872
+ Currently returns all methods of :class:`mathics.expression.Expression`.
873
+
874
+ EXAMPLES::
875
+
876
+ sage: a = mathics(5*x) # optional - mathics
877
+ sage: t = a._tab_completion() # optional - mathics
878
+ sage: len(t) > 100 # optional - mathics
879
+ True
880
+ """
881
+ return dir(self._mathics_result.last_eval)
882
+
883
+ def __getitem__(self, n):
884
+ r"""
885
+ EXAMPLES::
886
+
887
+ sage: l = mathics('{1, x, .15}') # optional - mathics
888
+ sage: l[0] # optional - mathics
889
+ List
890
+ sage: for i in l: print(i) # optional - mathics
891
+ 1
892
+ x
893
+ 0.15
894
+ """
895
+ return self.parent().new(f'{self._name}[[{n}]]')
896
+
897
+ def __getattr__(self, attrname):
898
+ r"""
899
+ EXAMPLES::
900
+
901
+ sage: # optional - mathics
902
+ sage: a = mathics(5*x)
903
+ sage: res = a._mathics_result
904
+ sage: str(a) == res.result
905
+ True
906
+ sage: t = mathics._eval('5*x')
907
+ sage: t.last_eval == res.last_eval
908
+ True
909
+ """
910
+ P = self._check_valid()
911
+ if attrname == '_mathics_result':
912
+ self._mathics_result = P._eval(self.name())
913
+ return self._mathics_result
914
+ elif attrname[:1] == "_":
915
+ raise AttributeError
916
+ else:
917
+ expr = self._mathics_result.last_eval
918
+ if hasattr(expr, attrname):
919
+ return expr.__getattribute__(attrname)
920
+ return InterfaceFunctionElement(self, attrname)
921
+
922
+ def __float__(self, precision=16):
923
+ r"""
924
+ EXAMPLES::
925
+
926
+ sage: float(mathics('Pi')) == float(pi) # optional - mathics
927
+ True
928
+ """
929
+ P = self.parent()
930
+ return float(P._eval(f'N[{self.name()},{precision}]').last_eval.to_mpmath())
931
+
932
+ def _reduce(self):
933
+ r"""
934
+ EXAMPLES::
935
+
936
+ sage: slist = [[1, 2], 3., 4 + I]
937
+ sage: mlist = mathics(slist) # optional - mathics
938
+ sage: mlist._reduce() # optional - mathics
939
+ '{{1, 2}, 3., 4 + I}'
940
+ """
941
+ return str(self)
942
+
943
+ def __reduce__(self):
944
+ r"""
945
+ EXAMPLES::
946
+
947
+ sage: mpol = mathics('x + y*z') # optional - mathics
948
+ sage: loads(dumps(mpol)) == mpol # optional - mathics
949
+ True
950
+ """
951
+ return reduce_load, (self._reduce(), )
952
+
953
+ def _latex_(self):
954
+ r"""
955
+ EXAMPLES::
956
+
957
+ sage: Q = mathics('Sin[x Cos[y]]/Sqrt[1-x^2]') # optional - mathics
958
+ sage: latex(Q) # optional - mathics
959
+ \frac{\text{Sin}\left[x \text{Cos}\left[y\right]\right]}{\sqrt{1-x^2}}
960
+ """
961
+ z = str(self.parent()('TeXForm[%s]' % self.name()))
962
+ i = z.find('=')
963
+ return z[i + 1:]
964
+
965
+ def _repr_(self):
966
+ r"""
967
+ EXAMPLES::
968
+
969
+ sage: Q = mathics('Sin[x Cos[y]]/Sqrt[1-x^2]') # optional - mathics
970
+ sage: repr(Q) # optional - mathics
971
+ 'Sin[x Cos[y]] / Sqrt[1 - x ^ 2]'
972
+ """
973
+ return self._mathics_result.result
974
+
975
+ def _sage_(self, locals={}):
976
+ r"""
977
+ Attempt to return a Sage version of this object.
978
+
979
+ This method works successfully when Mathics returns a result
980
+ or list of results that consist only of:
981
+
982
+ - numbers, i.e. integers, floats, complex numbers;
983
+ - functions and named constants also present in Sage, where:
984
+ - Sage knows how to translate the function or constant's name
985
+ from Mathics's naming scheme, or
986
+ - you provide a translation dictionary `locals`, or
987
+ - the Sage name for the function or constant is simply the
988
+ Mathics name in lower case;
989
+
990
+ - symbolic variables whose names do not pathologically overlap with
991
+ objects already defined in Sage.
992
+
993
+ This method will not work when Mathics's output includes:
994
+
995
+ - strings;
996
+ - functions unknown to Sage;
997
+ - Mathics functions with different parameters/parameter order to
998
+ the Sage equivalent. In this case, define a function to do the
999
+ parameter conversion, and pass it in via the locals dictionary.
1000
+
1001
+ EXAMPLES:
1002
+
1003
+ Mathics lists of numbers/constants become Sage lists of
1004
+ numbers/constants::
1005
+
1006
+ sage: # optional - mathics
1007
+ sage: m = mathics('{{1., 4}, Pi, 3.2e100, I}')
1008
+ sage: s = m.sage(); s
1009
+ [[1.00000000000000, 4], pi, 3.20000000000000*e100, 1.00000000000000*I]
1010
+ sage: s[1].n()
1011
+ 3.14159265358979
1012
+ sage: s[3]^2
1013
+ -1.00000000000000
1014
+
1015
+ ::
1016
+
1017
+ sage: m = mathics('x^2 + 5*y') # optional - mathics
1018
+ sage: m.sage() # optional - mathics
1019
+ x^2 + 5*y
1020
+
1021
+ ::
1022
+
1023
+ sage: m = mathics('Sin[Sqrt[1-x^2]] * (1 - Cos[1/x])^2') # optional - mathics
1024
+ sage: m.sage() # optional - mathics
1025
+ (cos(1/x) - 1)^2*sin(sqrt(-x^2 + 1))
1026
+
1027
+ ::
1028
+
1029
+ sage: m = mathics('NewFn[x]') # optional - mathics
1030
+ sage: m._sage_(locals={'NewFn': sin, 'x':x}) # optional - mathics
1031
+ sin(x)
1032
+
1033
+ ::
1034
+
1035
+ sage: var('bla') # optional - mathics
1036
+ bla
1037
+ sage: m = mathics('bla^2') # optional - mathics
1038
+ sage: bla^2 - m.sage() # optional - mathics
1039
+ 0
1040
+
1041
+ ::
1042
+
1043
+ sage: # optional - mathics
1044
+ sage: m = mathics('bla^2')
1045
+ sage: mb = m.sage()
1046
+ sage: var('bla')
1047
+ bla
1048
+ sage: bla^2 - mb
1049
+ 0
1050
+ """
1051
+ if locals:
1052
+ # if locals are given we use `_sage_repr`
1053
+ # surely this only covers simple cases
1054
+ from sage.misc.sage_eval import sage_eval
1055
+ return sage_eval(self._sage_repr(), locals=locals)
1056
+
1057
+ self._check_valid()
1058
+ if self.is_inexact():
1059
+ m = self.to_mpmath()
1060
+ if self is not m and m is not None:
1061
+ from sage.libs.mpmath.utils import mpmath_to_sage
1062
+ return mpmath_to_sage(m, self.get_precision())
1063
+ s = self.to_sympy()
1064
+ if self is not s and s is not None:
1065
+ if hasattr(s, '_sage_'):
1066
+ try:
1067
+ return s._sage_()
1068
+ except NotImplementedError: # see :issue:`33584`
1069
+ pass
1070
+ p = self.to_python()
1071
+ if self is not p and p is not None:
1072
+ def conv(i):
1073
+ return self.parent()(i).sage()
1074
+ if isinstance(p, list):
1075
+ return [conv(i) for i in p]
1076
+ elif isinstance(p, tuple):
1077
+ return tuple([conv(i) for i in p])
1078
+ elif type(p) is dict:
1079
+ return {conv(k): conv(v) for k, v in p.items()}
1080
+ else:
1081
+ return p
1082
+ return s
1083
+
1084
+ def __len__(self):
1085
+ """
1086
+ Return the object's length, evaluated by mathics.
1087
+
1088
+ EXAMPLES::
1089
+
1090
+ sage: len(mathics([1,1.,2])) # optional - mathics
1091
+ 3
1092
+ """
1093
+ return int(self.Length())
1094
+
1095
+ @cached_method
1096
+ def _is_graphics(self):
1097
+ """
1098
+ Test whether the mathics expression is graphics.
1099
+
1100
+ OUTPUT: boolean
1101
+
1102
+ EXAMPLES::
1103
+
1104
+ sage: P = mathics('Plot[Sin[x],{x,-2Pi,4Pi}]') # optional - mathics
1105
+ sage: P._is_graphics() # optional - mathics
1106
+ True
1107
+ """
1108
+ return str(self).startswith('-Graphics-')
1109
+
1110
+ def save_image(self, filename, ImageSize=600):
1111
+ r"""
1112
+ Save a mathics graphics.
1113
+
1114
+ INPUT:
1115
+
1116
+ - ``filename`` -- string; the filename to save as. The
1117
+ extension determines the image file format
1118
+
1119
+ - ``ImageSize`` -- integer; the size of the resulting image
1120
+
1121
+ EXAMPLES::
1122
+
1123
+ sage: P = mathics('Plot[Sin[x],{x,-2Pi,4Pi}]') # optional - mathics
1124
+ sage: filename = tmp_filename() # optional - mathics
1125
+ sage: P.save_image(filename, ImageSize=800) # optional - mathics
1126
+ """
1127
+ P = self._check_valid()
1128
+ if not self._is_graphics():
1129
+ raise ValueError('mathics expression is not graphics')
1130
+ filename = os.path.abspath(filename)
1131
+ s = f'Export["{filename}", {self.name()}, ImageSize->{ImageSize}]'
1132
+ P.eval(s)
1133
+
1134
+ def _rich_repr_(self, display_manager, **kwds):
1135
+ """
1136
+ Rich Output Magic Method.
1137
+
1138
+ See :mod:`sage.repl.rich_output` for details.
1139
+
1140
+ EXAMPLES::
1141
+
1142
+ sage: from sage.repl.rich_output import get_display_manager
1143
+ sage: dm = get_display_manager()
1144
+ sage: P = mathics('Plot[Sin[x],{x,-2Pi,4Pi}]') # optional - mathics
1145
+
1146
+ The following test requires a working X display on Linux so that the
1147
+ Mathematica frontend can do the rendering (:issue:`23112`)::
1148
+
1149
+ sage: P._rich_repr_(dm) # optional - mathics
1150
+ OutputImageSvg container
1151
+ """
1152
+ if self._is_graphics():
1153
+ OutputImageSvg = display_manager.types.OutputImageSvg
1154
+ if display_manager.preferences.graphics == 'disable':
1155
+ return
1156
+ if OutputImageSvg in display_manager.supported_output():
1157
+ return display_manager.graphics_from_save(
1158
+ self.save_image, kwds, '.svg', OutputImageSvg)
1159
+ else:
1160
+ OutputLatex = display_manager.types.OutputLatex
1161
+ dmp = display_manager.preferences.text
1162
+ if dmp is None or dmp == 'plain':
1163
+ return
1164
+ if dmp == 'latex' and OutputLatex in display_manager.supported_output():
1165
+ return OutputLatex(self._latex_())
1166
+
1167
+ def show(self, ImageSize=600):
1168
+ r"""
1169
+ Show a mathics expression immediately.
1170
+
1171
+ This method attempts to display the graphics immediately,
1172
+ without waiting for the currently running code (if any) to
1173
+ return to the command line. Be careful, calling it from within
1174
+ a loop will potentially launch a large number of external
1175
+ viewer programs.
1176
+
1177
+ INPUT:
1178
+
1179
+ - ``ImageSize`` -- integer; the size of the resulting image
1180
+
1181
+ OUTPUT:
1182
+
1183
+ This method does not return anything. Use :meth:`save` if you
1184
+ want to save the figure as an image.
1185
+
1186
+ EXAMPLES::
1187
+
1188
+ sage: Q = mathics('Sin[x Cos[y]]/Sqrt[1-x^2]') # optional - mathics
1189
+ sage: show(Q) # optional - mathics
1190
+ Sin[x Cos[y]] / Sqrt[1 - x ^ 2]
1191
+
1192
+ sage: P = mathics('Plot[Sin[x],{x,-2Pi,4Pi}]') # optional - mathics
1193
+ sage: show(P) # optional - mathics
1194
+ sage: P.show(ImageSize=800) # optional - mathics
1195
+ """
1196
+ from sage.repl.rich_output import get_display_manager
1197
+ dm = get_display_manager()
1198
+ dm.display_immediately(self, ImageSize=ImageSize)
1199
+
1200
+ def _richcmp_(self, other, op):
1201
+ r"""
1202
+ EXAMPLES::
1203
+
1204
+ sage: # optional - mathics
1205
+ sage: mobj1 = mathics([x^2-1, 2])
1206
+ sage: mobj2 = mathics('{x^2-1, 2}')
1207
+ sage: mobj3 = mathics('5*x + y')
1208
+ sage: mobj1 == mobj2
1209
+ True
1210
+ sage: mobj1 < mobj2
1211
+ False
1212
+ sage: mobj1 == mobj3
1213
+ False
1214
+ """
1215
+ P = self.parent()
1216
+ if str(P(f"{self.name()} < {other.name()}")) == P._true_symbol():
1217
+ return rich_to_bool(op, -1)
1218
+ elif str(P(f"{self.name()} > {other.name()}")) == P._true_symbol():
1219
+ return rich_to_bool(op, 1)
1220
+ elif str(P(f"{self.name()} == {other.name()}")) == P._true_symbol():
1221
+ return rich_to_bool(op, 0)
1222
+ return NotImplemented
1223
+
1224
+ def __bool__(self):
1225
+ """
1226
+ Return whether this Mathics element is not identical to ``False``.
1227
+
1228
+ EXAMPLES::
1229
+
1230
+ sage: bool(mathics(True)) # optional - mathics
1231
+ True
1232
+ sage: bool(mathics(False)) # optional - mathics
1233
+ False
1234
+
1235
+ In Mathics, `0` cannot be used to express falsity::
1236
+
1237
+ sage: bool(mathics(0)) # optional - mathics
1238
+ True
1239
+ """
1240
+ P = self._check_valid()
1241
+ cmd = f'{self._name}==={P._false_symbol()}'
1242
+ return not str(P(cmd)) == P._true_symbol()
1243
+
1244
+ def n(self, *args, **kwargs):
1245
+ r"""
1246
+ Numerical approximation by converting to Sage object first.
1247
+
1248
+ Convert the object into a Sage object and return its numerical
1249
+ approximation. See documentation of the function
1250
+ :func:`sage.misc.functional.n` for details.
1251
+
1252
+ EXAMPLES::
1253
+
1254
+ sage: mathics('Pi').n(10) # optional -- mathics
1255
+ 3.1
1256
+ sage: mathics('Pi').n() # optional -- mathics
1257
+ 3.14159265358979
1258
+ sage: mathics('Pi').n(digits=10) # optional -- mathics
1259
+ 3.141592654
1260
+ """
1261
+ return self._sage_().n(*args, **kwargs)
1262
+
1263
+
1264
+ # An instance
1265
+ mathics = Mathics()
1266
+
1267
+
1268
+ def reduce_load(X):
1269
+ """
1270
+ Used in unpickling a Mathics element.
1271
+
1272
+ This function is just the ``__call__`` method of the interface instance.
1273
+
1274
+ EXAMPLES::
1275
+
1276
+ sage: sage.interfaces.mathics.reduce_load('Denominator[a / b]') # optional -- mathics
1277
+ b
1278
+ """
1279
+
1280
+ return mathics(X)
1281
+
1282
+
1283
+ def mathics_console():
1284
+ r"""
1285
+ Spawn a new Mathics command-line session.
1286
+
1287
+ EXAMPLES::
1288
+
1289
+ sage: mathics_console() # not tested
1290
+
1291
+ Mathics 2.1.1.dev0
1292
+ on CPython 3.9.2 (default, Mar 19 2021, 22:23:28)
1293
+ using SymPy 1.7, mpmath 1.2.1, numpy 1.19.5, cython 0.29.21
1294
+
1295
+ Copyright (C) 2011-2021 The Mathics Team.
1296
+ This program comes with ABSOLUTELY NO WARRANTY.
1297
+ This is free software, and you are welcome to redistribute it
1298
+ under certain conditions.
1299
+ See the documentation for the full license.
1300
+
1301
+ Quit by evaluating Quit[] or by pressing CONTROL-D.
1302
+
1303
+ In[1]:= Sin[0.5]
1304
+ Out[1]= 0.479426
1305
+
1306
+ Goodbye!
1307
+ """
1308
+ from sage.repl.rich_output.display_manager import get_display_manager
1309
+ if not get_display_manager().is_in_terminal():
1310
+ raise RuntimeError('Can use the console only in the terminal. Try %%mathics magics instead.')
1311
+ from mathics import main
1312
+ main.main()