test_lambdarepr.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  1. from sympy.concrete.summations import Sum
  2. from sympy.core.expr import Expr
  3. from sympy.core.symbol import symbols
  4. from sympy.functions.elementary.miscellaneous import sqrt
  5. from sympy.functions.elementary.piecewise import Piecewise
  6. from sympy.functions.elementary.trigonometric import sin
  7. from sympy.matrices.dense import MutableDenseMatrix as Matrix
  8. from sympy.sets.sets import Interval
  9. from sympy.utilities.lambdify import lambdify
  10. from sympy.testing.pytest import raises
  11. from sympy.printing.tensorflow import TensorflowPrinter
  12. from sympy.printing.lambdarepr import lambdarepr, LambdaPrinter, NumExprPrinter
  13. x, y, z = symbols("x,y,z")
  14. i, a, b = symbols("i,a,b")
  15. j, c, d = symbols("j,c,d")
  16. def test_basic():
  17. assert lambdarepr(x*y) == "x*y"
  18. assert lambdarepr(x + y) in ["y + x", "x + y"]
  19. assert lambdarepr(x**y) == "x**y"
  20. def test_matrix():
  21. # Test printing a Matrix that has an element that is printed differently
  22. # with the LambdaPrinter than with the StrPrinter.
  23. e = x % 2
  24. assert lambdarepr(e) != str(e)
  25. assert lambdarepr(Matrix([e])) == 'ImmutableDenseMatrix([[x % 2]])'
  26. def test_piecewise():
  27. # In each case, test eval() the lambdarepr() to make sure there are a
  28. # correct number of parentheses. It will give a SyntaxError if there aren't.
  29. h = "lambda x: "
  30. p = Piecewise((x, x < 0))
  31. l = lambdarepr(p)
  32. eval(h + l)
  33. assert l == "((x) if (x < 0) else None)"
  34. p = Piecewise(
  35. (1, x < 1),
  36. (2, x < 2),
  37. (0, True)
  38. )
  39. l = lambdarepr(p)
  40. eval(h + l)
  41. assert l == "((1) if (x < 1) else (2) if (x < 2) else (0))"
  42. p = Piecewise(
  43. (1, x < 1),
  44. (2, x < 2),
  45. )
  46. l = lambdarepr(p)
  47. eval(h + l)
  48. assert l == "((1) if (x < 1) else (2) if (x < 2) else None)"
  49. p = Piecewise(
  50. (x, x < 1),
  51. (x**2, Interval(3, 4, True, False).contains(x)),
  52. (0, True),
  53. )
  54. l = lambdarepr(p)
  55. eval(h + l)
  56. assert l == "((x) if (x < 1) else (x**2) if (((x <= 4)) and ((x > 3))) else (0))"
  57. p = Piecewise(
  58. (x**2, x < 0),
  59. (x, x < 1),
  60. (2 - x, x >= 1),
  61. (0, True), evaluate=False
  62. )
  63. l = lambdarepr(p)
  64. eval(h + l)
  65. assert l == "((x**2) if (x < 0) else (x) if (x < 1)"\
  66. " else (2 - x) if (x >= 1) else (0))"
  67. p = Piecewise(
  68. (x**2, x < 0),
  69. (x, x < 1),
  70. (2 - x, x >= 1), evaluate=False
  71. )
  72. l = lambdarepr(p)
  73. eval(h + l)
  74. assert l == "((x**2) if (x < 0) else (x) if (x < 1)"\
  75. " else (2 - x) if (x >= 1) else None)"
  76. p = Piecewise(
  77. (1, x >= 1),
  78. (2, x >= 2),
  79. (3, x >= 3),
  80. (4, x >= 4),
  81. (5, x >= 5),
  82. (6, True)
  83. )
  84. l = lambdarepr(p)
  85. eval(h + l)
  86. assert l == "((1) if (x >= 1) else (2) if (x >= 2) else (3) if (x >= 3)"\
  87. " else (4) if (x >= 4) else (5) if (x >= 5) else (6))"
  88. p = Piecewise(
  89. (1, x <= 1),
  90. (2, x <= 2),
  91. (3, x <= 3),
  92. (4, x <= 4),
  93. (5, x <= 5),
  94. (6, True)
  95. )
  96. l = lambdarepr(p)
  97. eval(h + l)
  98. assert l == "((1) if (x <= 1) else (2) if (x <= 2) else (3) if (x <= 3)"\
  99. " else (4) if (x <= 4) else (5) if (x <= 5) else (6))"
  100. p = Piecewise(
  101. (1, x > 1),
  102. (2, x > 2),
  103. (3, x > 3),
  104. (4, x > 4),
  105. (5, x > 5),
  106. (6, True)
  107. )
  108. l = lambdarepr(p)
  109. eval(h + l)
  110. assert l =="((1) if (x > 1) else (2) if (x > 2) else (3) if (x > 3)"\
  111. " else (4) if (x > 4) else (5) if (x > 5) else (6))"
  112. p = Piecewise(
  113. (1, x < 1),
  114. (2, x < 2),
  115. (3, x < 3),
  116. (4, x < 4),
  117. (5, x < 5),
  118. (6, True)
  119. )
  120. l = lambdarepr(p)
  121. eval(h + l)
  122. assert l == "((1) if (x < 1) else (2) if (x < 2) else (3) if (x < 3)"\
  123. " else (4) if (x < 4) else (5) if (x < 5) else (6))"
  124. p = Piecewise(
  125. (Piecewise(
  126. (1, x > 0),
  127. (2, True)
  128. ), y > 0),
  129. (3, True)
  130. )
  131. l = lambdarepr(p)
  132. eval(h + l)
  133. assert l == "((((1) if (x > 0) else (2))) if (y > 0) else (3))"
  134. def test_sum__1():
  135. # In each case, test eval() the lambdarepr() to make sure that
  136. # it evaluates to the same results as the symbolic expression
  137. s = Sum(x ** i, (i, a, b))
  138. l = lambdarepr(s)
  139. assert l == "(builtins.sum(x**i for i in range(a, b+1)))"
  140. args = x, a, b
  141. f = lambdify(args, s)
  142. v = 2, 3, 8
  143. assert f(*v) == s.subs(zip(args, v)).doit()
  144. def test_sum__2():
  145. s = Sum(i * x, (i, a, b))
  146. l = lambdarepr(s)
  147. assert l == "(builtins.sum(i*x for i in range(a, b+1)))"
  148. args = x, a, b
  149. f = lambdify(args, s)
  150. v = 2, 3, 8
  151. assert f(*v) == s.subs(zip(args, v)).doit()
  152. def test_multiple_sums():
  153. s = Sum(i * x + j, (i, a, b), (j, c, d))
  154. l = lambdarepr(s)
  155. assert l == "(builtins.sum(i*x + j for i in range(a, b+1) for j in range(c, d+1)))"
  156. args = x, a, b, c, d
  157. f = lambdify(args, s)
  158. vals = 2, 3, 4, 5, 6
  159. f_ref = s.subs(zip(args, vals)).doit()
  160. f_res = f(*vals)
  161. assert f_res == f_ref
  162. def test_sqrt():
  163. prntr = LambdaPrinter({'standard' : 'python3'})
  164. assert prntr._print_Pow(sqrt(x), rational=False) == 'sqrt(x)'
  165. assert prntr._print_Pow(sqrt(x), rational=True) == 'x**(1/2)'
  166. def test_settings():
  167. raises(TypeError, lambda: lambdarepr(sin(x), method="garbage"))
  168. def test_numexpr():
  169. # test ITE rewrite as Piecewise
  170. from sympy.logic.boolalg import ITE
  171. expr = ITE(x > 0, True, False, evaluate=False)
  172. assert NumExprPrinter().doprint(expr) == \
  173. "numexpr.evaluate('where((x > 0), True, False)', truediv=True)"
  174. from sympy.codegen.ast import Return, FunctionDefinition, Variable, Assignment
  175. func_def = FunctionDefinition(None, 'foo', [Variable(x)], [Assignment(y,x), Return(y**2)])
  176. expected = "def foo(x):\n"\
  177. " y = numexpr.evaluate('x', truediv=True)\n"\
  178. " return numexpr.evaluate('y**2', truediv=True)"
  179. assert NumExprPrinter().doprint(func_def) == expected
  180. class CustomPrintedObject(Expr):
  181. def _lambdacode(self, printer):
  182. return 'lambda'
  183. def _tensorflowcode(self, printer):
  184. return 'tensorflow'
  185. def _numpycode(self, printer):
  186. return 'numpy'
  187. def _numexprcode(self, printer):
  188. return 'numexpr'
  189. def _mpmathcode(self, printer):
  190. return 'mpmath'
  191. def test_printmethod():
  192. # In each case, printmethod is called to test
  193. # its working
  194. obj = CustomPrintedObject()
  195. assert LambdaPrinter().doprint(obj) == 'lambda'
  196. assert TensorflowPrinter().doprint(obj) == 'tensorflow'
  197. assert NumExprPrinter().doprint(obj) == "numexpr.evaluate('numexpr', truediv=True)"
  198. assert NumExprPrinter().doprint(Piecewise((y, x >= 0), (z, x < 0))) == \
  199. "numexpr.evaluate('where((x >= 0), y, z)', truediv=True)"