test_repr.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  1. from __future__ import annotations
  2. from typing import Any
  3. from sympy.external.gmpy import GROUND_TYPES
  4. from sympy.testing.pytest import raises, warns_deprecated_sympy
  5. from sympy.assumptions.ask import Q
  6. from sympy.core.function import (Function, WildFunction)
  7. from sympy.core.numbers import (AlgebraicNumber, Float, Integer, Rational)
  8. from sympy.core.singleton import S
  9. from sympy.core.symbol import (Dummy, Symbol, Wild, symbols)
  10. from sympy.core.sympify import sympify
  11. from sympy.functions.elementary.complexes import Abs
  12. from sympy.functions.elementary.miscellaneous import (root, sqrt)
  13. from sympy.functions.elementary.trigonometric import sin
  14. from sympy.functions.special.delta_functions import Heaviside
  15. from sympy.logic.boolalg import (false, true)
  16. from sympy.matrices.dense import (Matrix, ones)
  17. from sympy.matrices.expressions.matexpr import MatrixSymbol
  18. from sympy.matrices.immutable import ImmutableDenseMatrix
  19. from sympy.combinatorics import Cycle, Permutation
  20. from sympy.core.symbol import Str
  21. from sympy.geometry import Point, Ellipse
  22. from sympy.printing import srepr
  23. from sympy.polys import ring, field, ZZ, QQ, lex, grlex, Poly
  24. from sympy.polys.polyclasses import DMP
  25. from sympy.polys.agca.extensions import FiniteExtension
  26. x, y = symbols('x,y')
  27. # eval(srepr(expr)) == expr has to succeed in the right environment. The right
  28. # environment is the scope of "from sympy import *" for most cases.
  29. ENV: dict[str, Any] = {"Str": Str}
  30. exec("from sympy import *", ENV)
  31. def sT(expr, string, import_stmt=None, **kwargs):
  32. """
  33. sT := sreprTest
  34. Tests that srepr delivers the expected string and that
  35. the condition eval(srepr(expr))==expr holds.
  36. """
  37. if import_stmt is None:
  38. ENV2 = ENV
  39. else:
  40. ENV2 = ENV.copy()
  41. exec(import_stmt, ENV2)
  42. assert srepr(expr, **kwargs) == string
  43. assert eval(string, ENV2) == expr
  44. def test_printmethod():
  45. class R(Abs):
  46. def _sympyrepr(self, printer):
  47. return "foo(%s)" % printer._print(self.args[0])
  48. assert srepr(R(x)) == "foo(Symbol('x'))"
  49. def test_Add():
  50. sT(x + y, "Add(Symbol('x'), Symbol('y'))")
  51. assert srepr(x**2 + 1, order='lex') == "Add(Pow(Symbol('x'), Integer(2)), Integer(1))"
  52. assert srepr(x**2 + 1, order='old') == "Add(Integer(1), Pow(Symbol('x'), Integer(2)))"
  53. assert srepr(sympify('x + 3 - 2', evaluate=False), order='none') == "Add(Symbol('x'), Integer(3), Mul(Integer(-1), Integer(2)))"
  54. def test_more_than_255_args_issue_10259():
  55. from sympy.core.add import Add
  56. from sympy.core.mul import Mul
  57. for op in (Add, Mul):
  58. expr = op(*symbols('x:256'))
  59. assert eval(srepr(expr)) == expr
  60. def test_Function():
  61. sT(Function("f")(x), "Function('f')(Symbol('x'))")
  62. # test unapplied Function
  63. sT(Function('f'), "Function('f')")
  64. sT(sin(x), "sin(Symbol('x'))")
  65. sT(sin, "sin")
  66. def test_Heaviside():
  67. sT(Heaviside(x), "Heaviside(Symbol('x'))")
  68. sT(Heaviside(x, 1), "Heaviside(Symbol('x'), Integer(1))")
  69. def test_Geometry():
  70. sT(Point(0, 0), "Point2D(Integer(0), Integer(0))")
  71. sT(Ellipse(Point(0, 0), 5, 1),
  72. "Ellipse(Point2D(Integer(0), Integer(0)), Integer(5), Integer(1))")
  73. # TODO more tests
  74. def test_Singletons():
  75. sT(S.Catalan, 'Catalan')
  76. sT(S.ComplexInfinity, 'zoo')
  77. sT(S.EulerGamma, 'EulerGamma')
  78. sT(S.Exp1, 'E')
  79. sT(S.GoldenRatio, 'GoldenRatio')
  80. sT(S.TribonacciConstant, 'TribonacciConstant')
  81. sT(S.Half, 'Rational(1, 2)')
  82. sT(S.ImaginaryUnit, 'I')
  83. sT(S.Infinity, 'oo')
  84. sT(S.NaN, 'nan')
  85. sT(S.NegativeInfinity, '-oo')
  86. sT(S.NegativeOne, 'Integer(-1)')
  87. sT(S.One, 'Integer(1)')
  88. sT(S.Pi, 'pi')
  89. sT(S.Zero, 'Integer(0)')
  90. sT(S.Complexes, 'Complexes')
  91. sT(S.EmptySequence, 'EmptySequence')
  92. sT(S.EmptySet, 'EmptySet')
  93. # sT(S.IdentityFunction, 'Lambda(_x, _x)')
  94. sT(S.Naturals, 'Naturals')
  95. sT(S.Naturals0, 'Naturals0')
  96. sT(S.Rationals, 'Rationals')
  97. sT(S.Reals, 'Reals')
  98. sT(S.UniversalSet, 'UniversalSet')
  99. def test_Integer():
  100. sT(Integer(4), "Integer(4)")
  101. def test_list():
  102. sT([x, Integer(4)], "[Symbol('x'), Integer(4)]")
  103. def test_Matrix():
  104. for cls, name in [(Matrix, "MutableDenseMatrix"), (ImmutableDenseMatrix, "ImmutableDenseMatrix")]:
  105. sT(cls([[x**+1, 1], [y, x + y]]),
  106. "%s([[Symbol('x'), Integer(1)], [Symbol('y'), Add(Symbol('x'), Symbol('y'))]])" % name)
  107. sT(cls(), "%s([])" % name)
  108. sT(cls([[x**+1, 1], [y, x + y]]), "%s([[Symbol('x'), Integer(1)], [Symbol('y'), Add(Symbol('x'), Symbol('y'))]])" % name)
  109. def test_empty_Matrix():
  110. sT(ones(0, 3), "MutableDenseMatrix(0, 3, [])")
  111. sT(ones(4, 0), "MutableDenseMatrix(4, 0, [])")
  112. sT(ones(0, 0), "MutableDenseMatrix([])")
  113. def test_Rational():
  114. sT(Rational(1, 3), "Rational(1, 3)")
  115. sT(Rational(-1, 3), "Rational(-1, 3)")
  116. def test_Float():
  117. sT(Float('1.23', dps=3), "Float('1.22998', precision=13)")
  118. sT(Float('1.23456789', dps=9), "Float('1.23456788994', precision=33)")
  119. sT(Float('1.234567890123456789', dps=19),
  120. "Float('1.234567890123456789013', precision=66)")
  121. sT(Float('0.60038617995049726', dps=15),
  122. "Float('0.60038617995049726', precision=53)")
  123. sT(Float('1.23', precision=13), "Float('1.22998', precision=13)")
  124. sT(Float('1.23456789', precision=33),
  125. "Float('1.23456788994', precision=33)")
  126. sT(Float('1.234567890123456789', precision=66),
  127. "Float('1.234567890123456789013', precision=66)")
  128. sT(Float('0.60038617995049726', precision=53),
  129. "Float('0.60038617995049726', precision=53)")
  130. sT(Float('0.60038617995049726', 15),
  131. "Float('0.60038617995049726', precision=53)")
  132. def test_Symbol():
  133. sT(x, "Symbol('x')")
  134. sT(y, "Symbol('y')")
  135. sT(Symbol('x', negative=True), "Symbol('x', negative=True)")
  136. def test_Symbol_two_assumptions():
  137. x = Symbol('x', negative=0, integer=1)
  138. # order could vary
  139. s1 = "Symbol('x', integer=True, negative=False)"
  140. s2 = "Symbol('x', negative=False, integer=True)"
  141. assert srepr(x) in (s1, s2)
  142. assert eval(srepr(x), ENV) == x
  143. def test_Symbol_no_special_commutative_treatment():
  144. sT(Symbol('x'), "Symbol('x')")
  145. sT(Symbol('x', commutative=False), "Symbol('x', commutative=False)")
  146. sT(Symbol('x', commutative=0), "Symbol('x', commutative=False)")
  147. sT(Symbol('x', commutative=True), "Symbol('x', commutative=True)")
  148. sT(Symbol('x', commutative=1), "Symbol('x', commutative=True)")
  149. def test_Wild():
  150. sT(Wild('x', even=True), "Wild('x', even=True)")
  151. def test_Dummy():
  152. d = Dummy('d')
  153. sT(d, "Dummy('d', dummy_index=%s)" % str(d.dummy_index))
  154. def test_Dummy_assumption():
  155. d = Dummy('d', nonzero=True)
  156. assert d == eval(srepr(d))
  157. s1 = "Dummy('d', dummy_index=%s, nonzero=True)" % str(d.dummy_index)
  158. s2 = "Dummy('d', nonzero=True, dummy_index=%s)" % str(d.dummy_index)
  159. assert srepr(d) in (s1, s2)
  160. def test_Dummy_from_Symbol():
  161. # should not get the full dictionary of assumptions
  162. n = Symbol('n', integer=True)
  163. d = n.as_dummy()
  164. assert srepr(d
  165. ) == "Dummy('n', dummy_index=%s)" % str(d.dummy_index)
  166. def test_tuple():
  167. sT((x,), "(Symbol('x'),)")
  168. sT((x, y), "(Symbol('x'), Symbol('y'))")
  169. def test_WildFunction():
  170. sT(WildFunction('w'), "WildFunction('w')")
  171. def test_settins():
  172. raises(TypeError, lambda: srepr(x, method="garbage"))
  173. def test_Mul():
  174. sT(3*x**3*y, "Mul(Integer(3), Pow(Symbol('x'), Integer(3)), Symbol('y'))")
  175. assert srepr(3*x**3*y, order='old') == "Mul(Integer(3), Symbol('y'), Pow(Symbol('x'), Integer(3)))"
  176. assert srepr(sympify('(x+4)*2*x*7', evaluate=False), order='none') == "Mul(Add(Symbol('x'), Integer(4)), Integer(2), Symbol('x'), Integer(7))"
  177. def test_AlgebraicNumber():
  178. a = AlgebraicNumber(sqrt(2))
  179. sT(a, "AlgebraicNumber(Pow(Integer(2), Rational(1, 2)), [Integer(1), Integer(0)])")
  180. a = AlgebraicNumber(root(-2, 3))
  181. sT(a, "AlgebraicNumber(Pow(Integer(-2), Rational(1, 3)), [Integer(1), Integer(0)])")
  182. def test_PolyRing():
  183. assert srepr(ring("x", ZZ, lex)[0]) == "PolyRing((Symbol('x'),), ZZ, lex)"
  184. assert srepr(ring("x,y", QQ, grlex)[0]) == "PolyRing((Symbol('x'), Symbol('y')), QQ, grlex)"
  185. assert srepr(ring("x,y,z", ZZ["t"], lex)[0]) == "PolyRing((Symbol('x'), Symbol('y'), Symbol('z')), ZZ[t], lex)"
  186. def test_FracField():
  187. assert srepr(field("x", ZZ, lex)[0]) == "FracField((Symbol('x'),), ZZ, lex)"
  188. assert srepr(field("x,y", QQ, grlex)[0]) == "FracField((Symbol('x'), Symbol('y')), QQ, grlex)"
  189. assert srepr(field("x,y,z", ZZ["t"], lex)[0]) == "FracField((Symbol('x'), Symbol('y'), Symbol('z')), ZZ[t], lex)"
  190. def test_PolyElement():
  191. R, x, y = ring("x,y", ZZ)
  192. assert srepr(3*x**2*y + 1) == "PolyElement(PolyRing((Symbol('x'), Symbol('y')), ZZ, lex), [((2, 1), 3), ((0, 0), 1)])"
  193. def test_FracElement():
  194. F, x, y = field("x,y", ZZ)
  195. assert srepr((3*x**2*y + 1)/(x - y**2)) == "FracElement(FracField((Symbol('x'), Symbol('y')), ZZ, lex), [((2, 1), 3), ((0, 0), 1)], [((1, 0), 1), ((0, 2), -1)])"
  196. def test_FractionField():
  197. assert srepr(QQ.frac_field(x)) == \
  198. "FractionField(FracField((Symbol('x'),), QQ, lex))"
  199. assert srepr(QQ.frac_field(x, y, order=grlex)) == \
  200. "FractionField(FracField((Symbol('x'), Symbol('y')), QQ, grlex))"
  201. def test_PolynomialRingBase():
  202. assert srepr(ZZ.old_poly_ring(x)) == \
  203. "GlobalPolynomialRing(ZZ, Symbol('x'))"
  204. assert srepr(ZZ[x].old_poly_ring(y)) == \
  205. "GlobalPolynomialRing(ZZ[x], Symbol('y'))"
  206. assert srepr(QQ.frac_field(x).old_poly_ring(y)) == \
  207. "GlobalPolynomialRing(FractionField(FracField((Symbol('x'),), QQ, lex)), Symbol('y'))"
  208. def test_DMP():
  209. p1 = DMP([1, 2], ZZ)
  210. p2 = ZZ.old_poly_ring(x)([1, 2])
  211. if GROUND_TYPES != 'flint':
  212. assert srepr(p1) == "DMP_Python([1, 2], ZZ)"
  213. assert srepr(p2) == "DMP_Python([1, 2], ZZ)"
  214. else:
  215. assert srepr(p1) == "DUP_Flint([1, 2], ZZ)"
  216. assert srepr(p2) == "DUP_Flint([1, 2], ZZ)"
  217. def test_FiniteExtension():
  218. assert srepr(FiniteExtension(Poly(x**2 + 1, x))) == \
  219. "FiniteExtension(Poly(x**2 + 1, x, domain='ZZ'))"
  220. def test_ExtensionElement():
  221. A = FiniteExtension(Poly(x**2 + 1, x))
  222. if GROUND_TYPES != 'flint':
  223. ans = "ExtElem(DMP_Python([1, 0], ZZ), FiniteExtension(Poly(x**2 + 1, x, domain='ZZ')))"
  224. else:
  225. ans = "ExtElem(DUP_Flint([1, 0], ZZ), FiniteExtension(Poly(x**2 + 1, x, domain='ZZ')))"
  226. assert srepr(A.generator) == ans
  227. def test_BooleanAtom():
  228. assert srepr(true) == "true"
  229. assert srepr(false) == "false"
  230. def test_Integers():
  231. sT(S.Integers, "Integers")
  232. def test_Naturals():
  233. sT(S.Naturals, "Naturals")
  234. def test_Naturals0():
  235. sT(S.Naturals0, "Naturals0")
  236. def test_Reals():
  237. sT(S.Reals, "Reals")
  238. def test_matrix_expressions():
  239. n = symbols('n', integer=True)
  240. A = MatrixSymbol("A", n, n)
  241. B = MatrixSymbol("B", n, n)
  242. sT(A, "MatrixSymbol(Str('A'), Symbol('n', integer=True), Symbol('n', integer=True))")
  243. sT(A*B, "MatMul(MatrixSymbol(Str('A'), Symbol('n', integer=True), Symbol('n', integer=True)), MatrixSymbol(Str('B'), Symbol('n', integer=True), Symbol('n', integer=True)))")
  244. sT(A + B, "MatAdd(MatrixSymbol(Str('A'), Symbol('n', integer=True), Symbol('n', integer=True)), MatrixSymbol(Str('B'), Symbol('n', integer=True), Symbol('n', integer=True)))")
  245. def test_Cycle():
  246. # FIXME: sT fails because Cycle is not immutable and calling srepr(Cycle(1, 2))
  247. # adds keys to the Cycle dict (GH-17661)
  248. #import_stmt = "from sympy.combinatorics import Cycle"
  249. #sT(Cycle(1, 2), "Cycle(1, 2)", import_stmt)
  250. assert srepr(Cycle(1, 2)) == "Cycle(1, 2)"
  251. def test_Permutation():
  252. import_stmt = "from sympy.combinatorics import Permutation"
  253. sT(Permutation(1, 2)(3, 4), "Permutation([0, 2, 1, 4, 3])", import_stmt, perm_cyclic=False)
  254. sT(Permutation(1, 2)(3, 4), "Permutation(1, 2)(3, 4)", import_stmt, perm_cyclic=True)
  255. with warns_deprecated_sympy():
  256. old_print_cyclic = Permutation.print_cyclic
  257. Permutation.print_cyclic = False
  258. sT(Permutation(1, 2)(3, 4), "Permutation([0, 2, 1, 4, 3])", import_stmt)
  259. Permutation.print_cyclic = old_print_cyclic
  260. def test_dict():
  261. from sympy.abc import x, y, z
  262. d = {}
  263. assert srepr(d) == "{}"
  264. d = {x: y}
  265. assert srepr(d) == "{Symbol('x'): Symbol('y')}"
  266. d = {x: y, y: z}
  267. assert srepr(d) in (
  268. "{Symbol('x'): Symbol('y'), Symbol('y'): Symbol('z')}",
  269. "{Symbol('y'): Symbol('z'), Symbol('x'): Symbol('y')}",
  270. )
  271. d = {x: {y: z}}
  272. assert srepr(d) == "{Symbol('x'): {Symbol('y'): Symbol('z')}}"
  273. def test_set():
  274. from sympy.abc import x, y
  275. s = set()
  276. assert srepr(s) == "set()"
  277. s = {x, y}
  278. assert srepr(s) in ("{Symbol('x'), Symbol('y')}", "{Symbol('y'), Symbol('x')}")
  279. def test_Predicate():
  280. sT(Q.even, "Q.even")
  281. def test_AppliedPredicate():
  282. sT(Q.even(Symbol('z')), "AppliedPredicate(Q.even, Symbol('z'))")