test_julia.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  1. from sympy.core import (S, pi, oo, symbols, Function, Rational, Integer,
  2. Tuple, Symbol, Eq, Ne, Le, Lt, Gt, Ge)
  3. from sympy.core import EulerGamma, GoldenRatio, Catalan, Lambda, Mul, Pow
  4. from sympy.functions import Piecewise, sqrt, ceiling, exp, sin, cos
  5. from sympy.testing.pytest import raises
  6. from sympy.utilities.lambdify import implemented_function
  7. from sympy.matrices import (eye, Matrix, MatrixSymbol, Identity,
  8. HadamardProduct, SparseMatrix)
  9. from sympy.functions.special.bessel import (jn, yn, besselj, bessely, besseli,
  10. besselk, hankel1, hankel2, airyai,
  11. airybi, airyaiprime, airybiprime)
  12. from sympy.testing.pytest import XFAIL
  13. from sympy.printing.julia import julia_code
  14. x, y, z = symbols('x,y,z')
  15. def test_Integer():
  16. assert julia_code(Integer(67)) == "67"
  17. assert julia_code(Integer(-1)) == "-1"
  18. def test_Rational():
  19. assert julia_code(Rational(3, 7)) == "3 // 7"
  20. assert julia_code(Rational(18, 9)) == "2"
  21. assert julia_code(Rational(3, -7)) == "-3 // 7"
  22. assert julia_code(Rational(-3, -7)) == "3 // 7"
  23. assert julia_code(x + Rational(3, 7)) == "x + 3 // 7"
  24. assert julia_code(Rational(3, 7)*x) == "(3 // 7) * x"
  25. def test_Relational():
  26. assert julia_code(Eq(x, y)) == "x == y"
  27. assert julia_code(Ne(x, y)) == "x != y"
  28. assert julia_code(Le(x, y)) == "x <= y"
  29. assert julia_code(Lt(x, y)) == "x < y"
  30. assert julia_code(Gt(x, y)) == "x > y"
  31. assert julia_code(Ge(x, y)) == "x >= y"
  32. def test_Function():
  33. assert julia_code(sin(x) ** cos(x)) == "sin(x) .^ cos(x)"
  34. assert julia_code(abs(x)) == "abs(x)"
  35. assert julia_code(ceiling(x)) == "ceil(x)"
  36. def test_Pow():
  37. assert julia_code(x**3) == "x .^ 3"
  38. assert julia_code(x**(y**3)) == "x .^ (y .^ 3)"
  39. assert julia_code(x**Rational(2, 3)) == 'x .^ (2 // 3)'
  40. g = implemented_function('g', Lambda(x, 2*x))
  41. assert julia_code(1/(g(x)*3.5)**(x - y**x)/(x**2 + y)) == \
  42. "(3.5 * 2 * x) .^ (-x + y .^ x) ./ (x .^ 2 + y)"
  43. # For issue 14160
  44. assert julia_code(Mul(-2, x, Pow(Mul(y,y,evaluate=False), -1, evaluate=False),
  45. evaluate=False)) == '-2 * x ./ (y .* y)'
  46. def test_basic_ops():
  47. assert julia_code(x*y) == "x .* y"
  48. assert julia_code(x + y) == "x + y"
  49. assert julia_code(x - y) == "x - y"
  50. assert julia_code(-x) == "-x"
  51. def test_1_over_x_and_sqrt():
  52. # 1.0 and 0.5 would do something different in regular StrPrinter,
  53. # but these are exact in IEEE floating point so no different here.
  54. assert julia_code(1/x) == '1 ./ x'
  55. assert julia_code(x**-1) == julia_code(x**-1.0) == '1 ./ x'
  56. assert julia_code(1/sqrt(x)) == '1 ./ sqrt(x)'
  57. assert julia_code(x**-S.Half) == julia_code(x**-0.5) == '1 ./ sqrt(x)'
  58. assert julia_code(sqrt(x)) == 'sqrt(x)'
  59. assert julia_code(x**S.Half) == julia_code(x**0.5) == 'sqrt(x)'
  60. assert julia_code(1/pi) == '1 / pi'
  61. assert julia_code(pi**-1) == julia_code(pi**-1.0) == '1 / pi'
  62. assert julia_code(pi**-0.5) == '1 / sqrt(pi)'
  63. def test_mix_number_mult_symbols():
  64. assert julia_code(3*x) == "3 * x"
  65. assert julia_code(pi*x) == "pi * x"
  66. assert julia_code(3/x) == "3 ./ x"
  67. assert julia_code(pi/x) == "pi ./ x"
  68. assert julia_code(x/3) == "x / 3"
  69. assert julia_code(x/pi) == "x / pi"
  70. assert julia_code(x*y) == "x .* y"
  71. assert julia_code(3*x*y) == "3 * x .* y"
  72. assert julia_code(3*pi*x*y) == "3 * pi * x .* y"
  73. assert julia_code(x/y) == "x ./ y"
  74. assert julia_code(3*x/y) == "3 * x ./ y"
  75. assert julia_code(x*y/z) == "x .* y ./ z"
  76. assert julia_code(x/y*z) == "x .* z ./ y"
  77. assert julia_code(1/x/y) == "1 ./ (x .* y)"
  78. assert julia_code(2*pi*x/y/z) == "2 * pi * x ./ (y .* z)"
  79. assert julia_code(3*pi/x) == "3 * pi ./ x"
  80. assert julia_code(S(3)/5) == "3 // 5"
  81. assert julia_code(S(3)/5*x) == "(3 // 5) * x"
  82. assert julia_code(x/y/z) == "x ./ (y .* z)"
  83. assert julia_code((x+y)/z) == "(x + y) ./ z"
  84. assert julia_code((x+y)/(z+x)) == "(x + y) ./ (x + z)"
  85. assert julia_code((x+y)/EulerGamma) == "(x + y) / eulergamma"
  86. assert julia_code(x/3/pi) == "x / (3 * pi)"
  87. assert julia_code(S(3)/5*x*y/pi) == "(3 // 5) * x .* y / pi"
  88. def test_mix_number_pow_symbols():
  89. assert julia_code(pi**3) == 'pi ^ 3'
  90. assert julia_code(x**2) == 'x .^ 2'
  91. assert julia_code(x**(pi**3)) == 'x .^ (pi ^ 3)'
  92. assert julia_code(x**y) == 'x .^ y'
  93. assert julia_code(x**(y**z)) == 'x .^ (y .^ z)'
  94. assert julia_code((x**y)**z) == '(x .^ y) .^ z'
  95. def test_imag():
  96. I = S('I')
  97. assert julia_code(I) == "im"
  98. assert julia_code(5*I) == "5im"
  99. assert julia_code((S(3)/2)*I) == "(3 // 2) * im"
  100. assert julia_code(3+4*I) == "3 + 4im"
  101. def test_constants():
  102. assert julia_code(pi) == "pi"
  103. assert julia_code(oo) == "Inf"
  104. assert julia_code(-oo) == "-Inf"
  105. assert julia_code(S.NegativeInfinity) == "-Inf"
  106. assert julia_code(S.NaN) == "NaN"
  107. assert julia_code(S.Exp1) == "e"
  108. assert julia_code(exp(1)) == "e"
  109. def test_constants_other():
  110. assert julia_code(2*GoldenRatio) == "2 * golden"
  111. assert julia_code(2*Catalan) == "2 * catalan"
  112. assert julia_code(2*EulerGamma) == "2 * eulergamma"
  113. def test_boolean():
  114. assert julia_code(x & y) == "x && y"
  115. assert julia_code(x | y) == "x || y"
  116. assert julia_code(~x) == "!x"
  117. assert julia_code(x & y & z) == "x && y && z"
  118. assert julia_code(x | y | z) == "x || y || z"
  119. assert julia_code((x & y) | z) == "z || x && y"
  120. assert julia_code((x | y) & z) == "z && (x || y)"
  121. def test_Matrices():
  122. assert julia_code(Matrix(1, 1, [10])) == "[10]"
  123. A = Matrix([[1, sin(x/2), abs(x)],
  124. [0, 1, pi],
  125. [0, exp(1), ceiling(x)]]);
  126. expected = ("[1 sin(x / 2) abs(x);\n"
  127. "0 1 pi;\n"
  128. "0 e ceil(x)]")
  129. assert julia_code(A) == expected
  130. # row and columns
  131. assert julia_code(A[:,0]) == "[1, 0, 0]"
  132. assert julia_code(A[0,:]) == "[1 sin(x / 2) abs(x)]"
  133. # empty matrices
  134. assert julia_code(Matrix(0, 0, [])) == 'zeros(0, 0)'
  135. assert julia_code(Matrix(0, 3, [])) == 'zeros(0, 3)'
  136. # annoying to read but correct
  137. assert julia_code(Matrix([[x, x - y, -y]])) == "[x x - y -y]"
  138. def test_vector_entries_hadamard():
  139. # For a row or column, user might to use the other dimension
  140. A = Matrix([[1, sin(2/x), 3*pi/x/5]])
  141. assert julia_code(A) == "[1 sin(2 ./ x) (3 // 5) * pi ./ x]"
  142. assert julia_code(A.T) == "[1, sin(2 ./ x), (3 // 5) * pi ./ x]"
  143. @XFAIL
  144. def test_Matrices_entries_not_hadamard():
  145. # For Matrix with col >= 2, row >= 2, they need to be scalars
  146. # FIXME: is it worth worrying about this? Its not wrong, just
  147. # leave it user's responsibility to put scalar data for x.
  148. A = Matrix([[1, sin(2/x), 3*pi/x/5], [1, 2, x*y]])
  149. expected = ("[1 sin(2/x) 3*pi/(5*x);\n"
  150. "1 2 x*y]") # <- we give x.*y
  151. assert julia_code(A) == expected
  152. def test_MatrixSymbol():
  153. n = Symbol('n', integer=True)
  154. A = MatrixSymbol('A', n, n)
  155. B = MatrixSymbol('B', n, n)
  156. assert julia_code(A*B) == "A * B"
  157. assert julia_code(B*A) == "B * A"
  158. assert julia_code(2*A*B) == "2 * A * B"
  159. assert julia_code(B*2*A) == "2 * B * A"
  160. assert julia_code(A*(B + 3*Identity(n))) == "A * (3 * eye(n) + B)"
  161. assert julia_code(A**(x**2)) == "A ^ (x .^ 2)"
  162. assert julia_code(A**3) == "A ^ 3"
  163. assert julia_code(A**S.Half) == "A ^ (1 // 2)"
  164. def test_special_matrices():
  165. assert julia_code(6*Identity(3)) == "6 * eye(3)"
  166. def test_containers():
  167. assert julia_code([1, 2, 3, [4, 5, [6, 7]], 8, [9, 10], 11]) == \
  168. "Any[1, 2, 3, Any[4, 5, Any[6, 7]], 8, Any[9, 10], 11]"
  169. assert julia_code((1, 2, (3, 4))) == "(1, 2, (3, 4))"
  170. assert julia_code([1]) == "Any[1]"
  171. assert julia_code((1,)) == "(1,)"
  172. assert julia_code(Tuple(*[1, 2, 3])) == "(1, 2, 3)"
  173. assert julia_code((1, x*y, (3, x**2))) == "(1, x .* y, (3, x .^ 2))"
  174. # scalar, matrix, empty matrix and empty list
  175. assert julia_code((1, eye(3), Matrix(0, 0, []), [])) == "(1, [1 0 0;\n0 1 0;\n0 0 1], zeros(0, 0), Any[])"
  176. def test_julia_noninline():
  177. source = julia_code((x+y)/Catalan, assign_to='me', inline=False)
  178. expected = (
  179. "const Catalan = %s\n"
  180. "me = (x + y) / Catalan"
  181. ) % Catalan.evalf(17)
  182. assert source == expected
  183. def test_julia_piecewise():
  184. expr = Piecewise((x, x < 1), (x**2, True))
  185. assert julia_code(expr) == "((x < 1) ? (x) : (x .^ 2))"
  186. assert julia_code(expr, assign_to="r") == (
  187. "r = ((x < 1) ? (x) : (x .^ 2))")
  188. assert julia_code(expr, assign_to="r", inline=False) == (
  189. "if (x < 1)\n"
  190. " r = x\n"
  191. "else\n"
  192. " r = x .^ 2\n"
  193. "end")
  194. expr = Piecewise((x**2, x < 1), (x**3, x < 2), (x**4, x < 3), (x**5, True))
  195. expected = ("((x < 1) ? (x .^ 2) :\n"
  196. "(x < 2) ? (x .^ 3) :\n"
  197. "(x < 3) ? (x .^ 4) : (x .^ 5))")
  198. assert julia_code(expr) == expected
  199. assert julia_code(expr, assign_to="r") == "r = " + expected
  200. assert julia_code(expr, assign_to="r", inline=False) == (
  201. "if (x < 1)\n"
  202. " r = x .^ 2\n"
  203. "elseif (x < 2)\n"
  204. " r = x .^ 3\n"
  205. "elseif (x < 3)\n"
  206. " r = x .^ 4\n"
  207. "else\n"
  208. " r = x .^ 5\n"
  209. "end")
  210. # Check that Piecewise without a True (default) condition error
  211. expr = Piecewise((x, x < 1), (x**2, x > 1), (sin(x), x > 0))
  212. raises(ValueError, lambda: julia_code(expr))
  213. def test_julia_piecewise_times_const():
  214. pw = Piecewise((x, x < 1), (x**2, True))
  215. assert julia_code(2*pw) == "2 * ((x < 1) ? (x) : (x .^ 2))"
  216. assert julia_code(pw/x) == "((x < 1) ? (x) : (x .^ 2)) ./ x"
  217. assert julia_code(pw/(x*y)) == "((x < 1) ? (x) : (x .^ 2)) ./ (x .* y)"
  218. assert julia_code(pw/3) == "((x < 1) ? (x) : (x .^ 2)) / 3"
  219. def test_julia_matrix_assign_to():
  220. A = Matrix([[1, 2, 3]])
  221. assert julia_code(A, assign_to='a') == "a = [1 2 3]"
  222. A = Matrix([[1, 2], [3, 4]])
  223. assert julia_code(A, assign_to='A') == "A = [1 2;\n3 4]"
  224. def test_julia_matrix_assign_to_more():
  225. # assigning to Symbol or MatrixSymbol requires lhs/rhs match
  226. A = Matrix([[1, 2, 3]])
  227. B = MatrixSymbol('B', 1, 3)
  228. C = MatrixSymbol('C', 2, 3)
  229. assert julia_code(A, assign_to=B) == "B = [1 2 3]"
  230. raises(ValueError, lambda: julia_code(A, assign_to=x))
  231. raises(ValueError, lambda: julia_code(A, assign_to=C))
  232. def test_julia_matrix_1x1():
  233. A = Matrix([[3]])
  234. B = MatrixSymbol('B', 1, 1)
  235. C = MatrixSymbol('C', 1, 2)
  236. assert julia_code(A, assign_to=B) == "B = [3]"
  237. # FIXME?
  238. #assert julia_code(A, assign_to=x) == "x = [3]"
  239. raises(ValueError, lambda: julia_code(A, assign_to=C))
  240. def test_julia_matrix_elements():
  241. A = Matrix([[x, 2, x*y]])
  242. assert julia_code(A[0, 0]**2 + A[0, 1] + A[0, 2]) == "x .^ 2 + x .* y + 2"
  243. A = MatrixSymbol('AA', 1, 3)
  244. assert julia_code(A) == "AA"
  245. assert julia_code(A[0, 0]**2 + sin(A[0,1]) + A[0,2]) == \
  246. "sin(AA[1,2]) + AA[1,1] .^ 2 + AA[1,3]"
  247. assert julia_code(sum(A)) == "AA[1,1] + AA[1,2] + AA[1,3]"
  248. def test_julia_boolean():
  249. assert julia_code(True) == "true"
  250. assert julia_code(S.true) == "true"
  251. assert julia_code(False) == "false"
  252. assert julia_code(S.false) == "false"
  253. def test_julia_not_supported():
  254. assert julia_code(S.ComplexInfinity) == (
  255. "# Not supported in Julia:\n"
  256. "# ComplexInfinity\n"
  257. "zoo"
  258. )
  259. f = Function('f')
  260. assert julia_code(f(x).diff(x)) == (
  261. "# Not supported in Julia:\n"
  262. "# Derivative\n"
  263. "Derivative(f(x), x)"
  264. )
  265. def test_trick_indent_with_end_else_words():
  266. # words starting with "end" or "else" do not confuse the indenter
  267. t1 = S('endless');
  268. t2 = S('elsewhere');
  269. pw = Piecewise((t1, x < 0), (t2, x <= 1), (1, True))
  270. assert julia_code(pw, inline=False) == (
  271. "if (x < 0)\n"
  272. " endless\n"
  273. "elseif (x <= 1)\n"
  274. " elsewhere\n"
  275. "else\n"
  276. " 1\n"
  277. "end")
  278. def test_haramard():
  279. A = MatrixSymbol('A', 3, 3)
  280. B = MatrixSymbol('B', 3, 3)
  281. v = MatrixSymbol('v', 3, 1)
  282. h = MatrixSymbol('h', 1, 3)
  283. C = HadamardProduct(A, B)
  284. assert julia_code(C) == "A .* B"
  285. assert julia_code(C*v) == "(A .* B) * v"
  286. assert julia_code(h*C*v) == "h * (A .* B) * v"
  287. assert julia_code(C*A) == "(A .* B) * A"
  288. # mixing Hadamard and scalar strange b/c we vectorize scalars
  289. assert julia_code(C*x*y) == "(x .* y) * (A .* B)"
  290. def test_sparse():
  291. M = SparseMatrix(5, 6, {})
  292. M[2, 2] = 10;
  293. M[1, 2] = 20;
  294. M[1, 3] = 22;
  295. M[0, 3] = 30;
  296. M[3, 0] = x*y;
  297. assert julia_code(M) == (
  298. "sparse([4, 2, 3, 1, 2], [1, 3, 3, 4, 4], [x .* y, 20, 10, 30, 22], 5, 6)"
  299. )
  300. def test_specfun():
  301. n = Symbol('n')
  302. for f in [besselj, bessely, besseli, besselk]:
  303. assert julia_code(f(n, x)) == f.__name__ + '(n, x)'
  304. for f in [airyai, airyaiprime, airybi, airybiprime]:
  305. assert julia_code(f(x)) == f.__name__ + '(x)'
  306. assert julia_code(hankel1(n, x)) == 'hankelh1(n, x)'
  307. assert julia_code(hankel2(n, x)) == 'hankelh2(n, x)'
  308. assert julia_code(jn(n, x)) == 'sqrt(2) * sqrt(pi) * sqrt(1 ./ x) .* besselj(n + 1 // 2, x) / 2'
  309. assert julia_code(yn(n, x)) == 'sqrt(2) * sqrt(pi) * sqrt(1 ./ x) .* bessely(n + 1 // 2, x) / 2'
  310. def test_MatrixElement_printing():
  311. # test cases for issue #11821
  312. A = MatrixSymbol("A", 1, 3)
  313. B = MatrixSymbol("B", 1, 3)
  314. C = MatrixSymbol("C", 1, 3)
  315. assert(julia_code(A[0, 0]) == "A[1,1]")
  316. assert(julia_code(3 * A[0, 0]) == "3 * A[1,1]")
  317. F = C[0, 0].subs(C, A - B)
  318. assert(julia_code(F) == "(A - B)[1,1]")