图片解析应用
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

870 lines
30 KiB

  1. from sympy.core import (
  2. S, pi, oo, symbols, Rational, Integer, Float, Mod, GoldenRatio, EulerGamma, Catalan,
  3. Lambda, Dummy, nan, Mul, Pow, UnevaluatedExpr
  4. )
  5. from sympy.core.relational import (Eq, Ge, Gt, Le, Lt, Ne)
  6. from sympy.functions import (
  7. Abs, acos, acosh, asin, asinh, atan, atanh, atan2, ceiling, cos, cosh, erf,
  8. erfc, exp, floor, gamma, log, loggamma, Max, Min, Piecewise, sign, sin, sinh,
  9. sqrt, tan, tanh, fibonacci, lucas
  10. )
  11. from sympy.sets import Range
  12. from sympy.logic import ITE, Implies, Equivalent
  13. from sympy.codegen import For, aug_assign, Assignment
  14. from sympy.testing.pytest import raises, XFAIL, warns_deprecated_sympy
  15. from sympy.printing.c import C89CodePrinter, C99CodePrinter, get_math_macros
  16. from sympy.codegen.ast import (
  17. AddAugmentedAssignment, Element, Type, FloatType, Declaration, Pointer, Variable, value_const, pointer_const,
  18. While, Scope, Print, FunctionPrototype, FunctionDefinition, FunctionCall, Return,
  19. real, float32, float64, float80, float128, intc, Comment, CodeBlock
  20. )
  21. from sympy.codegen.cfunctions import expm1, log1p, exp2, log2, fma, log10, Cbrt, hypot, Sqrt
  22. from sympy.codegen.cnodes import restrict
  23. from sympy.utilities.lambdify import implemented_function
  24. from sympy.tensor import IndexedBase, Idx
  25. from sympy.matrices import Matrix, MatrixSymbol, SparseMatrix
  26. from sympy.printing.codeprinter import ccode
  27. x, y, z = symbols('x,y,z')
  28. def test_printmethod():
  29. class fabs(Abs):
  30. def _ccode(self, printer):
  31. return "fabs(%s)" % printer._print(self.args[0])
  32. assert ccode(fabs(x)) == "fabs(x)"
  33. def test_ccode_sqrt():
  34. assert ccode(sqrt(x)) == "sqrt(x)"
  35. assert ccode(x**0.5) == "sqrt(x)"
  36. assert ccode(sqrt(x)) == "sqrt(x)"
  37. def test_ccode_Pow():
  38. assert ccode(x**3) == "pow(x, 3)"
  39. assert ccode(x**(y**3)) == "pow(x, pow(y, 3))"
  40. g = implemented_function('g', Lambda(x, 2*x))
  41. assert ccode(1/(g(x)*3.5)**(x - y**x)/(x**2 + y)) == \
  42. "pow(3.5*2*x, -x + pow(y, x))/(pow(x, 2) + y)"
  43. assert ccode(x**-1.0) == '1.0/x'
  44. assert ccode(x**Rational(2, 3)) == 'pow(x, 2.0/3.0)'
  45. assert ccode(x**Rational(2, 3), type_aliases={real: float80}) == 'powl(x, 2.0L/3.0L)'
  46. _cond_cfunc = [(lambda base, exp: exp.is_integer, "dpowi"),
  47. (lambda base, exp: not exp.is_integer, "pow")]
  48. assert ccode(x**3, user_functions={'Pow': _cond_cfunc}) == 'dpowi(x, 3)'
  49. assert ccode(x**0.5, user_functions={'Pow': _cond_cfunc}) == 'pow(x, 0.5)'
  50. assert ccode(x**Rational(16, 5), user_functions={'Pow': _cond_cfunc}) == 'pow(x, 16.0/5.0)'
  51. _cond_cfunc2 = [(lambda base, exp: base == 2, lambda base, exp: 'exp2(%s)' % exp),
  52. (lambda base, exp: base != 2, 'pow')]
  53. # Related to gh-11353
  54. assert ccode(2**x, user_functions={'Pow': _cond_cfunc2}) == 'exp2(x)'
  55. assert ccode(x**2, user_functions={'Pow': _cond_cfunc2}) == 'pow(x, 2)'
  56. # For issue 14160
  57. assert ccode(Mul(-2, x, Pow(Mul(y,y,evaluate=False), -1, evaluate=False),
  58. evaluate=False)) == '-2*x/(y*y)'
  59. def test_ccode_Max():
  60. # Test for gh-11926
  61. assert ccode(Max(x,x*x),user_functions={"Max":"my_max", "Pow":"my_pow"}) == 'my_max(x, my_pow(x, 2))'
  62. def test_ccode_Min_performance():
  63. #Shouldn't take more than a few seconds
  64. big_min = Min(*symbols('a[0:50]'))
  65. for curr_standard in ('c89', 'c99', 'c11'):
  66. output = ccode(big_min, standard=curr_standard)
  67. assert output.count('(') == output.count(')')
  68. def test_ccode_constants_mathh():
  69. assert ccode(exp(1)) == "M_E"
  70. assert ccode(pi) == "M_PI"
  71. assert ccode(oo, standard='c89') == "HUGE_VAL"
  72. assert ccode(-oo, standard='c89') == "-HUGE_VAL"
  73. assert ccode(oo) == "INFINITY"
  74. assert ccode(-oo, standard='c99') == "-INFINITY"
  75. assert ccode(pi, type_aliases={real: float80}) == "M_PIl"
  76. def test_ccode_constants_other():
  77. assert ccode(2*GoldenRatio) == "const double GoldenRatio = %s;\n2*GoldenRatio" % GoldenRatio.evalf(17)
  78. assert ccode(
  79. 2*Catalan) == "const double Catalan = %s;\n2*Catalan" % Catalan.evalf(17)
  80. assert ccode(2*EulerGamma) == "const double EulerGamma = %s;\n2*EulerGamma" % EulerGamma.evalf(17)
  81. def test_ccode_Rational():
  82. assert ccode(Rational(3, 7)) == "3.0/7.0"
  83. assert ccode(Rational(3, 7), type_aliases={real: float80}) == "3.0L/7.0L"
  84. assert ccode(Rational(18, 9)) == "2"
  85. assert ccode(Rational(3, -7)) == "-3.0/7.0"
  86. assert ccode(Rational(3, -7), type_aliases={real: float80}) == "-3.0L/7.0L"
  87. assert ccode(Rational(-3, -7)) == "3.0/7.0"
  88. assert ccode(Rational(-3, -7), type_aliases={real: float80}) == "3.0L/7.0L"
  89. assert ccode(x + Rational(3, 7)) == "x + 3.0/7.0"
  90. assert ccode(x + Rational(3, 7), type_aliases={real: float80}) == "x + 3.0L/7.0L"
  91. assert ccode(Rational(3, 7)*x) == "(3.0/7.0)*x"
  92. assert ccode(Rational(3, 7)*x, type_aliases={real: float80}) == "(3.0L/7.0L)*x"
  93. def test_ccode_Integer():
  94. assert ccode(Integer(67)) == "67"
  95. assert ccode(Integer(-1)) == "-1"
  96. def test_ccode_functions():
  97. assert ccode(sin(x) ** cos(x)) == "pow(sin(x), cos(x))"
  98. def test_ccode_inline_function():
  99. x = symbols('x')
  100. g = implemented_function('g', Lambda(x, 2*x))
  101. assert ccode(g(x)) == "2*x"
  102. g = implemented_function('g', Lambda(x, 2*x/Catalan))
  103. assert ccode(
  104. g(x)) == "const double Catalan = %s;\n2*x/Catalan" % Catalan.evalf(17)
  105. A = IndexedBase('A')
  106. i = Idx('i', symbols('n', integer=True))
  107. g = implemented_function('g', Lambda(x, x*(1 + x)*(2 + x)))
  108. assert ccode(g(A[i]), assign_to=A[i]) == (
  109. "for (int i=0; i<n; i++){\n"
  110. " A[i] = (A[i] + 1)*(A[i] + 2)*A[i];\n"
  111. "}"
  112. )
  113. def test_ccode_exceptions():
  114. assert ccode(gamma(x), standard='C99') == "tgamma(x)"
  115. gamma_c89 = ccode(gamma(x), standard='C89')
  116. assert 'not supported in c' in gamma_c89.lower()
  117. gamma_c89 = ccode(gamma(x), standard='C89', allow_unknown_functions=False)
  118. assert 'not supported in c' in gamma_c89.lower()
  119. gamma_c89 = ccode(gamma(x), standard='C89', allow_unknown_functions=True)
  120. assert 'not supported in c' not in gamma_c89.lower()
  121. def test_ccode_functions2():
  122. assert ccode(ceiling(x)) == "ceil(x)"
  123. assert ccode(Abs(x)) == "fabs(x)"
  124. assert ccode(gamma(x)) == "tgamma(x)"
  125. r, s = symbols('r,s', real=True)
  126. assert ccode(Mod(ceiling(r), ceiling(s))) == '((ceil(r) % ceil(s)) + '\
  127. 'ceil(s)) % ceil(s)'
  128. assert ccode(Mod(r, s)) == "fmod(r, s)"
  129. p1, p2 = symbols('p1 p2', integer=True, positive=True)
  130. assert ccode(Mod(p1, p2)) == 'p1 % p2'
  131. assert ccode(Mod(p1, p2 + 3)) == 'p1 % (p2 + 3)'
  132. assert ccode(Mod(-3, -7, evaluate=False)) == '(-3) % (-7)'
  133. assert ccode(-Mod(3, 7, evaluate=False)) == '-(3 % 7)'
  134. assert ccode(r*Mod(p1, p2)) == 'r*(p1 % p2)'
  135. assert ccode(Mod(p1, p2)**s) == 'pow(p1 % p2, s)'
  136. n = symbols('n', integer=True, negative=True)
  137. assert ccode(Mod(-n, p2)) == '(-n) % p2'
  138. assert ccode(fibonacci(n)) == '(1.0/5.0)*pow(2, -n)*sqrt(5)*(-pow(1 - sqrt(5), n) + pow(1 + sqrt(5), n))'
  139. assert ccode(lucas(n)) == 'pow(2, -n)*(pow(1 - sqrt(5), n) + pow(1 + sqrt(5), n))'
  140. def test_ccode_user_functions():
  141. x = symbols('x', integer=False)
  142. n = symbols('n', integer=True)
  143. custom_functions = {
  144. "ceiling": "ceil",
  145. "Abs": [(lambda x: not x.is_integer, "fabs"), (lambda x: x.is_integer, "abs")],
  146. }
  147. assert ccode(ceiling(x), user_functions=custom_functions) == "ceil(x)"
  148. assert ccode(Abs(x), user_functions=custom_functions) == "fabs(x)"
  149. assert ccode(Abs(n), user_functions=custom_functions) == "abs(n)"
  150. def test_ccode_boolean():
  151. assert ccode(True) == "true"
  152. assert ccode(S.true) == "true"
  153. assert ccode(False) == "false"
  154. assert ccode(S.false) == "false"
  155. assert ccode(x & y) == "x && y"
  156. assert ccode(x | y) == "x || y"
  157. assert ccode(~x) == "!x"
  158. assert ccode(x & y & z) == "x && y && z"
  159. assert ccode(x | y | z) == "x || y || z"
  160. assert ccode((x & y) | z) == "z || x && y"
  161. assert ccode((x | y) & z) == "z && (x || y)"
  162. # Automatic rewrites
  163. assert ccode(x ^ y) == '(x || y) && (!x || !y)'
  164. assert ccode((x ^ y) ^ z) == '(x || y || z) && (x || !y || !z) && (y || !x || !z) && (z || !x || !y)'
  165. assert ccode(Implies(x, y)) == 'y || !x'
  166. assert ccode(Equivalent(x, z ^ y, Implies(z, x))) == '(x || (y || !z) && (z || !y)) && (z && !x || (y || z) && (!y || !z))'
  167. def test_ccode_Relational():
  168. assert ccode(Eq(x, y)) == "x == y"
  169. assert ccode(Ne(x, y)) == "x != y"
  170. assert ccode(Le(x, y)) == "x <= y"
  171. assert ccode(Lt(x, y)) == "x < y"
  172. assert ccode(Gt(x, y)) == "x > y"
  173. assert ccode(Ge(x, y)) == "x >= y"
  174. def test_ccode_Piecewise():
  175. expr = Piecewise((x, x < 1), (x**2, True))
  176. assert ccode(expr) == (
  177. "((x < 1) ? (\n"
  178. " x\n"
  179. ")\n"
  180. ": (\n"
  181. " pow(x, 2)\n"
  182. "))")
  183. assert ccode(expr, assign_to="c") == (
  184. "if (x < 1) {\n"
  185. " c = x;\n"
  186. "}\n"
  187. "else {\n"
  188. " c = pow(x, 2);\n"
  189. "}")
  190. expr = Piecewise((x, x < 1), (x + 1, x < 2), (x**2, True))
  191. assert ccode(expr) == (
  192. "((x < 1) ? (\n"
  193. " x\n"
  194. ")\n"
  195. ": ((x < 2) ? (\n"
  196. " x + 1\n"
  197. ")\n"
  198. ": (\n"
  199. " pow(x, 2)\n"
  200. ")))")
  201. assert ccode(expr, assign_to='c') == (
  202. "if (x < 1) {\n"
  203. " c = x;\n"
  204. "}\n"
  205. "else if (x < 2) {\n"
  206. " c = x + 1;\n"
  207. "}\n"
  208. "else {\n"
  209. " c = pow(x, 2);\n"
  210. "}")
  211. # Check that Piecewise without a True (default) condition error
  212. expr = Piecewise((x, x < 1), (x**2, x > 1), (sin(x), x > 0))
  213. raises(ValueError, lambda: ccode(expr))
  214. def test_ccode_sinc():
  215. from sympy.functions.elementary.trigonometric import sinc
  216. expr = sinc(x)
  217. assert ccode(expr) == (
  218. "((x != 0) ? (\n"
  219. " sin(x)/x\n"
  220. ")\n"
  221. ": (\n"
  222. " 1\n"
  223. "))")
  224. def test_ccode_Piecewise_deep():
  225. p = ccode(2*Piecewise((x, x < 1), (x + 1, x < 2), (x**2, True)))
  226. assert p == (
  227. "2*((x < 1) ? (\n"
  228. " x\n"
  229. ")\n"
  230. ": ((x < 2) ? (\n"
  231. " x + 1\n"
  232. ")\n"
  233. ": (\n"
  234. " pow(x, 2)\n"
  235. ")))")
  236. expr = x*y*z + x**2 + y**2 + Piecewise((0, x < 0.5), (1, True)) + cos(z) - 1
  237. assert ccode(expr) == (
  238. "pow(x, 2) + x*y*z + pow(y, 2) + ((x < 0.5) ? (\n"
  239. " 0\n"
  240. ")\n"
  241. ": (\n"
  242. " 1\n"
  243. ")) + cos(z) - 1")
  244. assert ccode(expr, assign_to='c') == (
  245. "c = pow(x, 2) + x*y*z + pow(y, 2) + ((x < 0.5) ? (\n"
  246. " 0\n"
  247. ")\n"
  248. ": (\n"
  249. " 1\n"
  250. ")) + cos(z) - 1;")
  251. def test_ccode_ITE():
  252. expr = ITE(x < 1, y, z)
  253. assert ccode(expr) == (
  254. "((x < 1) ? (\n"
  255. " y\n"
  256. ")\n"
  257. ": (\n"
  258. " z\n"
  259. "))")
  260. def test_ccode_settings():
  261. raises(TypeError, lambda: ccode(sin(x), method="garbage"))
  262. def test_ccode_Indexed():
  263. s, n, m, o = symbols('s n m o', integer=True)
  264. i, j, k = Idx('i', n), Idx('j', m), Idx('k', o)
  265. x = IndexedBase('x')[j]
  266. A = IndexedBase('A')[i, j]
  267. B = IndexedBase('B')[i, j, k]
  268. p = C99CodePrinter()
  269. assert p._print_Indexed(x) == 'x[j]'
  270. assert p._print_Indexed(A) == 'A[%s]' % (m*i+j)
  271. assert p._print_Indexed(B) == 'B[%s]' % (i*o*m+j*o+k)
  272. A = IndexedBase('A', shape=(5,3))[i, j]
  273. assert p._print_Indexed(A) == 'A[%s]' % (3*i + j)
  274. A = IndexedBase('A', shape=(5,3), strides='F')[i, j]
  275. assert ccode(A) == 'A[%s]' % (i + 5*j)
  276. A = IndexedBase('A', shape=(29,29), strides=(1, s), offset=o)[i, j]
  277. assert ccode(A) == 'A[o + s*j + i]'
  278. Abase = IndexedBase('A', strides=(s, m, n), offset=o)
  279. assert ccode(Abase[i, j, k]) == 'A[m*j + n*k + o + s*i]'
  280. assert ccode(Abase[2, 3, k]) == 'A[3*m + n*k + o + 2*s]'
  281. def test_Element():
  282. assert ccode(Element('x', 'ij')) == 'x[i][j]'
  283. assert ccode(Element('x', 'ij', strides='kl', offset='o')) == 'x[i*k + j*l + o]'
  284. assert ccode(Element('x', (3,))) == 'x[3]'
  285. assert ccode(Element('x', (3,4,5))) == 'x[3][4][5]'
  286. def test_ccode_Indexed_without_looking_for_contraction():
  287. len_y = 5
  288. y = IndexedBase('y', shape=(len_y,))
  289. x = IndexedBase('x', shape=(len_y,))
  290. Dy = IndexedBase('Dy', shape=(len_y-1,))
  291. i = Idx('i', len_y-1)
  292. e = Eq(Dy[i], (y[i+1]-y[i])/(x[i+1]-x[i]))
  293. code0 = ccode(e.rhs, assign_to=e.lhs, contract=False)
  294. assert code0 == 'Dy[i] = (y[%s] - y[i])/(x[%s] - x[i]);' % (i + 1, i + 1)
  295. def test_ccode_loops_matrix_vector():
  296. n, m = symbols('n m', integer=True)
  297. A = IndexedBase('A')
  298. x = IndexedBase('x')
  299. y = IndexedBase('y')
  300. i = Idx('i', m)
  301. j = Idx('j', n)
  302. s = (
  303. 'for (int i=0; i<m; i++){\n'
  304. ' y[i] = 0;\n'
  305. '}\n'
  306. 'for (int i=0; i<m; i++){\n'
  307. ' for (int j=0; j<n; j++){\n'
  308. ' y[i] = A[%s]*x[j] + y[i];\n' % (i*n + j) +\
  309. ' }\n'
  310. '}'
  311. )
  312. assert ccode(A[i, j]*x[j], assign_to=y[i]) == s
  313. def test_dummy_loops():
  314. i, m = symbols('i m', integer=True, cls=Dummy)
  315. x = IndexedBase('x')
  316. y = IndexedBase('y')
  317. i = Idx(i, m)
  318. expected = (
  319. 'for (int i_%(icount)i=0; i_%(icount)i<m_%(mcount)i; i_%(icount)i++){\n'
  320. ' y[i_%(icount)i] = x[i_%(icount)i];\n'
  321. '}'
  322. ) % {'icount': i.label.dummy_index, 'mcount': m.dummy_index}
  323. assert ccode(x[i], assign_to=y[i]) == expected
  324. def test_ccode_loops_add():
  325. n, m = symbols('n m', integer=True)
  326. A = IndexedBase('A')
  327. x = IndexedBase('x')
  328. y = IndexedBase('y')
  329. z = IndexedBase('z')
  330. i = Idx('i', m)
  331. j = Idx('j', n)
  332. s = (
  333. 'for (int i=0; i<m; i++){\n'
  334. ' y[i] = x[i] + z[i];\n'
  335. '}\n'
  336. 'for (int i=0; i<m; i++){\n'
  337. ' for (int j=0; j<n; j++){\n'
  338. ' y[i] = A[%s]*x[j] + y[i];\n' % (i*n + j) +\
  339. ' }\n'
  340. '}'
  341. )
  342. assert ccode(A[i, j]*x[j] + x[i] + z[i], assign_to=y[i]) == s
  343. def test_ccode_loops_multiple_contractions():
  344. n, m, o, p = symbols('n m o p', integer=True)
  345. a = IndexedBase('a')
  346. b = IndexedBase('b')
  347. y = IndexedBase('y')
  348. i = Idx('i', m)
  349. j = Idx('j', n)
  350. k = Idx('k', o)
  351. l = Idx('l', p)
  352. s = (
  353. 'for (int i=0; i<m; i++){\n'
  354. ' y[i] = 0;\n'
  355. '}\n'
  356. 'for (int i=0; i<m; i++){\n'
  357. ' for (int j=0; j<n; j++){\n'
  358. ' for (int k=0; k<o; k++){\n'
  359. ' for (int l=0; l<p; l++){\n'
  360. ' y[i] = a[%s]*b[%s] + y[i];\n' % (i*n*o*p + j*o*p + k*p + l, j*o*p + k*p + l) +\
  361. ' }\n'
  362. ' }\n'
  363. ' }\n'
  364. '}'
  365. )
  366. assert ccode(b[j, k, l]*a[i, j, k, l], assign_to=y[i]) == s
  367. def test_ccode_loops_addfactor():
  368. n, m, o, p = symbols('n m o p', integer=True)
  369. a = IndexedBase('a')
  370. b = IndexedBase('b')
  371. c = IndexedBase('c')
  372. y = IndexedBase('y')
  373. i = Idx('i', m)
  374. j = Idx('j', n)
  375. k = Idx('k', o)
  376. l = Idx('l', p)
  377. s = (
  378. 'for (int i=0; i<m; i++){\n'
  379. ' y[i] = 0;\n'
  380. '}\n'
  381. 'for (int i=0; i<m; i++){\n'
  382. ' for (int j=0; j<n; j++){\n'
  383. ' for (int k=0; k<o; k++){\n'
  384. ' for (int l=0; l<p; l++){\n'
  385. ' y[i] = (a[%s] + b[%s])*c[%s] + y[i];\n' % (i*n*o*p + j*o*p + k*p + l, i*n*o*p + j*o*p + k*p + l, j*o*p + k*p + l) +\
  386. ' }\n'
  387. ' }\n'
  388. ' }\n'
  389. '}'
  390. )
  391. assert ccode((a[i, j, k, l] + b[i, j, k, l])*c[j, k, l], assign_to=y[i]) == s
  392. def test_ccode_loops_multiple_terms():
  393. n, m, o, p = symbols('n m o p', integer=True)
  394. a = IndexedBase('a')
  395. b = IndexedBase('b')
  396. c = IndexedBase('c')
  397. y = IndexedBase('y')
  398. i = Idx('i', m)
  399. j = Idx('j', n)
  400. k = Idx('k', o)
  401. s0 = (
  402. 'for (int i=0; i<m; i++){\n'
  403. ' y[i] = 0;\n'
  404. '}\n'
  405. )
  406. s1 = (
  407. 'for (int i=0; i<m; i++){\n'
  408. ' for (int j=0; j<n; j++){\n'
  409. ' for (int k=0; k<o; k++){\n'
  410. ' y[i] = b[j]*b[k]*c[%s] + y[i];\n' % (i*n*o + j*o + k) +\
  411. ' }\n'
  412. ' }\n'
  413. '}\n'
  414. )
  415. s2 = (
  416. 'for (int i=0; i<m; i++){\n'
  417. ' for (int k=0; k<o; k++){\n'
  418. ' y[i] = a[%s]*b[k] + y[i];\n' % (i*o + k) +\
  419. ' }\n'
  420. '}\n'
  421. )
  422. s3 = (
  423. 'for (int i=0; i<m; i++){\n'
  424. ' for (int j=0; j<n; j++){\n'
  425. ' y[i] = a[%s]*b[j] + y[i];\n' % (i*n + j) +\
  426. ' }\n'
  427. '}\n'
  428. )
  429. c = ccode(b[j]*a[i, j] + b[k]*a[i, k] + b[j]*b[k]*c[i, j, k], assign_to=y[i])
  430. assert (c == s0 + s1 + s2 + s3[:-1] or
  431. c == s0 + s1 + s3 + s2[:-1] or
  432. c == s0 + s2 + s1 + s3[:-1] or
  433. c == s0 + s2 + s3 + s1[:-1] or
  434. c == s0 + s3 + s1 + s2[:-1] or
  435. c == s0 + s3 + s2 + s1[:-1])
  436. def test_dereference_printing():
  437. expr = x + y + sin(z) + z
  438. assert ccode(expr, dereference=[z]) == "x + y + (*z) + sin((*z))"
  439. def test_Matrix_printing():
  440. # Test returning a Matrix
  441. mat = Matrix([x*y, Piecewise((2 + x, y>0), (y, True)), sin(z)])
  442. A = MatrixSymbol('A', 3, 1)
  443. assert ccode(mat, A) == (
  444. "A[0] = x*y;\n"
  445. "if (y > 0) {\n"
  446. " A[1] = x + 2;\n"
  447. "}\n"
  448. "else {\n"
  449. " A[1] = y;\n"
  450. "}\n"
  451. "A[2] = sin(z);")
  452. # Test using MatrixElements in expressions
  453. expr = Piecewise((2*A[2, 0], x > 0), (A[2, 0], True)) + sin(A[1, 0]) + A[0, 0]
  454. assert ccode(expr) == (
  455. "((x > 0) ? (\n"
  456. " 2*A[2]\n"
  457. ")\n"
  458. ": (\n"
  459. " A[2]\n"
  460. ")) + sin(A[1]) + A[0]")
  461. # Test using MatrixElements in a Matrix
  462. q = MatrixSymbol('q', 5, 1)
  463. M = MatrixSymbol('M', 3, 3)
  464. m = Matrix([[sin(q[1,0]), 0, cos(q[2,0])],
  465. [q[1,0] + q[2,0], q[3, 0], 5],
  466. [2*q[4, 0]/q[1,0], sqrt(q[0,0]) + 4, 0]])
  467. assert ccode(m, M) == (
  468. "M[0] = sin(q[1]);\n"
  469. "M[1] = 0;\n"
  470. "M[2] = cos(q[2]);\n"
  471. "M[3] = q[1] + q[2];\n"
  472. "M[4] = q[3];\n"
  473. "M[5] = 5;\n"
  474. "M[6] = 2*q[4]/q[1];\n"
  475. "M[7] = sqrt(q[0]) + 4;\n"
  476. "M[8] = 0;")
  477. def test_sparse_matrix():
  478. # gh-15791
  479. assert 'Not supported in C' in ccode(SparseMatrix([[1, 2, 3]]))
  480. def test_ccode_reserved_words():
  481. x, y = symbols('x, if')
  482. with raises(ValueError):
  483. ccode(y**2, error_on_reserved=True, standard='C99')
  484. assert ccode(y**2) == 'pow(if_, 2)'
  485. assert ccode(x * y**2, dereference=[y]) == 'pow((*if_), 2)*x'
  486. assert ccode(y**2, reserved_word_suffix='_unreserved') == 'pow(if_unreserved, 2)'
  487. def test_ccode_sign():
  488. expr1, ref1 = sign(x) * y, 'y*(((x) > 0) - ((x) < 0))'
  489. expr2, ref2 = sign(cos(x)), '(((cos(x)) > 0) - ((cos(x)) < 0))'
  490. expr3, ref3 = sign(2 * x + x**2) * x + x**2, 'pow(x, 2) + x*(((pow(x, 2) + 2*x) > 0) - ((pow(x, 2) + 2*x) < 0))'
  491. assert ccode(expr1) == ref1
  492. assert ccode(expr1, 'z') == 'z = %s;' % ref1
  493. assert ccode(expr2) == ref2
  494. assert ccode(expr3) == ref3
  495. def test_ccode_Assignment():
  496. assert ccode(Assignment(x, y + z)) == 'x = y + z;'
  497. assert ccode(aug_assign(x, '+', y + z)) == 'x += y + z;'
  498. def test_ccode_For():
  499. f = For(x, Range(0, 10, 2), [aug_assign(y, '*', x)])
  500. assert ccode(f) == ("for (x = 0; x < 10; x += 2) {\n"
  501. " y *= x;\n"
  502. "}")
  503. def test_ccode_Max_Min():
  504. assert ccode(Max(x, 0), standard='C89') == '((0 > x) ? 0 : x)'
  505. assert ccode(Max(x, 0), standard='C99') == 'fmax(0, x)'
  506. assert ccode(Min(x, 0, sqrt(x)), standard='c89') == (
  507. '((0 < ((x < sqrt(x)) ? x : sqrt(x))) ? 0 : ((x < sqrt(x)) ? x : sqrt(x)))'
  508. )
  509. def test_ccode_standard():
  510. assert ccode(expm1(x), standard='c99') == 'expm1(x)'
  511. assert ccode(nan, standard='c99') == 'NAN'
  512. assert ccode(float('nan'), standard='c99') == 'NAN'
  513. def test_C89CodePrinter():
  514. c89printer = C89CodePrinter()
  515. assert c89printer.language == 'C'
  516. assert c89printer.standard == 'C89'
  517. assert 'void' in c89printer.reserved_words
  518. assert 'template' not in c89printer.reserved_words
  519. def test_C99CodePrinter():
  520. assert C99CodePrinter().doprint(expm1(x)) == 'expm1(x)'
  521. assert C99CodePrinter().doprint(log1p(x)) == 'log1p(x)'
  522. assert C99CodePrinter().doprint(exp2(x)) == 'exp2(x)'
  523. assert C99CodePrinter().doprint(log2(x)) == 'log2(x)'
  524. assert C99CodePrinter().doprint(fma(x, y, -z)) == 'fma(x, y, -z)'
  525. assert C99CodePrinter().doprint(log10(x)) == 'log10(x)'
  526. assert C99CodePrinter().doprint(Cbrt(x)) == 'cbrt(x)' # note Cbrt due to cbrt already taken.
  527. assert C99CodePrinter().doprint(hypot(x, y)) == 'hypot(x, y)'
  528. assert C99CodePrinter().doprint(loggamma(x)) == 'lgamma(x)'
  529. assert C99CodePrinter().doprint(Max(x, 3, x**2)) == 'fmax(3, fmax(x, pow(x, 2)))'
  530. assert C99CodePrinter().doprint(Min(x, 3)) == 'fmin(3, x)'
  531. c99printer = C99CodePrinter()
  532. assert c99printer.language == 'C'
  533. assert c99printer.standard == 'C99'
  534. assert 'restrict' in c99printer.reserved_words
  535. assert 'using' not in c99printer.reserved_words
  536. @XFAIL
  537. def test_C99CodePrinter__precision_f80():
  538. f80_printer = C99CodePrinter(dict(type_aliases={real: float80}))
  539. assert f80_printer.doprint(sin(x+Float('2.1'))) == 'sinl(x + 2.1L)'
  540. def test_C99CodePrinter__precision():
  541. n = symbols('n', integer=True)
  542. p = symbols('p', integer=True, positive=True)
  543. f32_printer = C99CodePrinter(dict(type_aliases={real: float32}))
  544. f64_printer = C99CodePrinter(dict(type_aliases={real: float64}))
  545. f80_printer = C99CodePrinter(dict(type_aliases={real: float80}))
  546. assert f32_printer.doprint(sin(x+2.1)) == 'sinf(x + 2.1F)'
  547. assert f64_printer.doprint(sin(x+2.1)) == 'sin(x + 2.1000000000000001)'
  548. assert f80_printer.doprint(sin(x+Float('2.0'))) == 'sinl(x + 2.0L)'
  549. for printer, suffix in zip([f32_printer, f64_printer, f80_printer], ['f', '', 'l']):
  550. def check(expr, ref):
  551. assert printer.doprint(expr) == ref.format(s=suffix, S=suffix.upper())
  552. check(Abs(n), 'abs(n)')
  553. check(Abs(x + 2.0), 'fabs{s}(x + 2.0{S})')
  554. check(sin(x + 4.0)**cos(x - 2.0), 'pow{s}(sin{s}(x + 4.0{S}), cos{s}(x - 2.0{S}))')
  555. check(exp(x*8.0), 'exp{s}(8.0{S}*x)')
  556. check(exp2(x), 'exp2{s}(x)')
  557. check(expm1(x*4.0), 'expm1{s}(4.0{S}*x)')
  558. check(Mod(p, 2), 'p % 2')
  559. check(Mod(2*p + 3, 3*p + 5, evaluate=False), '(2*p + 3) % (3*p + 5)')
  560. check(Mod(x + 2.0, 3.0), 'fmod{s}(1.0{S}*x + 2.0{S}, 3.0{S})')
  561. check(Mod(x, 2.0*x + 3.0), 'fmod{s}(1.0{S}*x, 2.0{S}*x + 3.0{S})')
  562. check(log(x/2), 'log{s}((1.0{S}/2.0{S})*x)')
  563. check(log10(3*x/2), 'log10{s}((3.0{S}/2.0{S})*x)')
  564. check(log2(x*8.0), 'log2{s}(8.0{S}*x)')
  565. check(log1p(x), 'log1p{s}(x)')
  566. check(2**x, 'pow{s}(2, x)')
  567. check(2.0**x, 'pow{s}(2.0{S}, x)')
  568. check(x**3, 'pow{s}(x, 3)')
  569. check(x**4.0, 'pow{s}(x, 4.0{S})')
  570. check(sqrt(3+x), 'sqrt{s}(x + 3)')
  571. check(Cbrt(x-2.0), 'cbrt{s}(x - 2.0{S})')
  572. check(hypot(x, y), 'hypot{s}(x, y)')
  573. check(sin(3.*x + 2.), 'sin{s}(3.0{S}*x + 2.0{S})')
  574. check(cos(3.*x - 1.), 'cos{s}(3.0{S}*x - 1.0{S})')
  575. check(tan(4.*y + 2.), 'tan{s}(4.0{S}*y + 2.0{S})')
  576. check(asin(3.*x + 2.), 'asin{s}(3.0{S}*x + 2.0{S})')
  577. check(acos(3.*x + 2.), 'acos{s}(3.0{S}*x + 2.0{S})')
  578. check(atan(3.*x + 2.), 'atan{s}(3.0{S}*x + 2.0{S})')
  579. check(atan2(3.*x, 2.*y), 'atan2{s}(3.0{S}*x, 2.0{S}*y)')
  580. check(sinh(3.*x + 2.), 'sinh{s}(3.0{S}*x + 2.0{S})')
  581. check(cosh(3.*x - 1.), 'cosh{s}(3.0{S}*x - 1.0{S})')
  582. check(tanh(4.0*y + 2.), 'tanh{s}(4.0{S}*y + 2.0{S})')
  583. check(asinh(3.*x + 2.), 'asinh{s}(3.0{S}*x + 2.0{S})')
  584. check(acosh(3.*x + 2.), 'acosh{s}(3.0{S}*x + 2.0{S})')
  585. check(atanh(3.*x + 2.), 'atanh{s}(3.0{S}*x + 2.0{S})')
  586. check(erf(42.*x), 'erf{s}(42.0{S}*x)')
  587. check(erfc(42.*x), 'erfc{s}(42.0{S}*x)')
  588. check(gamma(x), 'tgamma{s}(x)')
  589. check(loggamma(x), 'lgamma{s}(x)')
  590. check(ceiling(x + 2.), "ceil{s}(x + 2.0{S})")
  591. check(floor(x + 2.), "floor{s}(x + 2.0{S})")
  592. check(fma(x, y, -z), 'fma{s}(x, y, -z)')
  593. check(Max(x, 8.0, x**4.0), 'fmax{s}(8.0{S}, fmax{s}(x, pow{s}(x, 4.0{S})))')
  594. check(Min(x, 2.0), 'fmin{s}(2.0{S}, x)')
  595. def test_get_math_macros():
  596. macros = get_math_macros()
  597. assert macros[exp(1)] == 'M_E'
  598. assert macros[1/Sqrt(2)] == 'M_SQRT1_2'
  599. def test_ccode_Declaration():
  600. i = symbols('i', integer=True)
  601. var1 = Variable(i, type=Type.from_expr(i))
  602. dcl1 = Declaration(var1)
  603. assert ccode(dcl1) == 'int i'
  604. var2 = Variable(x, type=float32, attrs={value_const})
  605. dcl2a = Declaration(var2)
  606. assert ccode(dcl2a) == 'const float x'
  607. dcl2b = var2.as_Declaration(value=pi)
  608. assert ccode(dcl2b) == 'const float x = M_PI'
  609. var3 = Variable(y, type=Type('bool'))
  610. dcl3 = Declaration(var3)
  611. printer = C89CodePrinter()
  612. assert 'stdbool.h' not in printer.headers
  613. assert printer.doprint(dcl3) == 'bool y'
  614. assert 'stdbool.h' in printer.headers
  615. u = symbols('u', real=True)
  616. ptr4 = Pointer.deduced(u, attrs={pointer_const, restrict})
  617. dcl4 = Declaration(ptr4)
  618. assert ccode(dcl4) == 'double * const restrict u'
  619. var5 = Variable(x, Type('__float128'), attrs={value_const})
  620. dcl5a = Declaration(var5)
  621. assert ccode(dcl5a) == 'const __float128 x'
  622. var5b = Variable(var5.symbol, var5.type, pi, attrs=var5.attrs)
  623. dcl5b = Declaration(var5b)
  624. assert ccode(dcl5b) == 'const __float128 x = M_PI'
  625. def test_C99CodePrinter_custom_type():
  626. # We will look at __float128 (new in glibc 2.26)
  627. f128 = FloatType('_Float128', float128.nbits, float128.nmant, float128.nexp)
  628. p128 = C99CodePrinter(dict(
  629. type_aliases={real: f128},
  630. type_literal_suffixes={f128: 'Q'},
  631. type_func_suffixes={f128: 'f128'},
  632. type_math_macro_suffixes={
  633. real: 'f128',
  634. f128: 'f128'
  635. },
  636. type_macros={
  637. f128: ('__STDC_WANT_IEC_60559_TYPES_EXT__',)
  638. }
  639. ))
  640. assert p128.doprint(x) == 'x'
  641. assert not p128.headers
  642. assert not p128.libraries
  643. assert not p128.macros
  644. assert p128.doprint(2.0) == '2.0Q'
  645. assert not p128.headers
  646. assert not p128.libraries
  647. assert p128.macros == {'__STDC_WANT_IEC_60559_TYPES_EXT__'}
  648. assert p128.doprint(Rational(1, 2)) == '1.0Q/2.0Q'
  649. assert p128.doprint(sin(x)) == 'sinf128(x)'
  650. assert p128.doprint(cos(2., evaluate=False)) == 'cosf128(2.0Q)'
  651. assert p128.doprint(x**-1.0) == '1.0Q/x'
  652. var5 = Variable(x, f128, attrs={value_const})
  653. dcl5a = Declaration(var5)
  654. assert ccode(dcl5a) == 'const _Float128 x'
  655. var5b = Variable(x, f128, pi, attrs={value_const})
  656. dcl5b = Declaration(var5b)
  657. assert p128.doprint(dcl5b) == 'const _Float128 x = M_PIf128'
  658. var5b = Variable(x, f128, value=Catalan.evalf(38), attrs={value_const})
  659. dcl5c = Declaration(var5b)
  660. assert p128.doprint(dcl5c) == 'const _Float128 x = %sQ' % Catalan.evalf(f128.decimal_dig)
  661. def test_MatrixElement_printing():
  662. # test cases for issue #11821
  663. A = MatrixSymbol("A", 1, 3)
  664. B = MatrixSymbol("B", 1, 3)
  665. C = MatrixSymbol("C", 1, 3)
  666. assert(ccode(A[0, 0]) == "A[0]")
  667. assert(ccode(3 * A[0, 0]) == "3*A[0]")
  668. F = C[0, 0].subs(C, A - B)
  669. assert(ccode(F) == "(A - B)[0]")
  670. def test_ccode_math_macros():
  671. assert ccode(z + exp(1)) == 'z + M_E'
  672. assert ccode(z + log2(exp(1))) == 'z + M_LOG2E'
  673. assert ccode(z + 1/log(2)) == 'z + M_LOG2E'
  674. assert ccode(z + log(2)) == 'z + M_LN2'
  675. assert ccode(z + log(10)) == 'z + M_LN10'
  676. assert ccode(z + pi) == 'z + M_PI'
  677. assert ccode(z + pi/2) == 'z + M_PI_2'
  678. assert ccode(z + pi/4) == 'z + M_PI_4'
  679. assert ccode(z + 1/pi) == 'z + M_1_PI'
  680. assert ccode(z + 2/pi) == 'z + M_2_PI'
  681. assert ccode(z + 2/sqrt(pi)) == 'z + M_2_SQRTPI'
  682. assert ccode(z + 2/Sqrt(pi)) == 'z + M_2_SQRTPI'
  683. assert ccode(z + sqrt(2)) == 'z + M_SQRT2'
  684. assert ccode(z + Sqrt(2)) == 'z + M_SQRT2'
  685. assert ccode(z + 1/sqrt(2)) == 'z + M_SQRT1_2'
  686. assert ccode(z + 1/Sqrt(2)) == 'z + M_SQRT1_2'
  687. def test_ccode_Type():
  688. assert ccode(Type('float')) == 'float'
  689. assert ccode(intc) == 'int'
  690. def test_ccode_codegen_ast():
  691. assert ccode(Comment("this is a comment")) == "// this is a comment"
  692. assert ccode(While(abs(x) > 1, [aug_assign(x, '-', 1)])) == (
  693. 'while (fabs(x) > 1) {\n'
  694. ' x -= 1;\n'
  695. '}'
  696. )
  697. assert ccode(Scope([AddAugmentedAssignment(x, 1)])) == (
  698. '{\n'
  699. ' x += 1;\n'
  700. '}'
  701. )
  702. inp_x = Declaration(Variable(x, type=real))
  703. assert ccode(FunctionPrototype(real, 'pwer', [inp_x])) == 'double pwer(double x)'
  704. assert ccode(FunctionDefinition(real, 'pwer', [inp_x], [Assignment(x, x**2)])) == (
  705. 'double pwer(double x){\n'
  706. ' x = pow(x, 2);\n'
  707. '}'
  708. )
  709. # Elements of CodeBlock are formatted as statements:
  710. block = CodeBlock(
  711. x,
  712. Print([x, y], "%d %d"),
  713. FunctionCall('pwer', [x]),
  714. Return(x),
  715. )
  716. assert ccode(block) == '\n'.join([
  717. 'x;',
  718. 'printf("%d %d", x, y);',
  719. 'pwer(x);',
  720. 'return x;',
  721. ])
  722. def test_ccode_submodule():
  723. # Test the compatibility sympy.printing.ccode module imports
  724. with warns_deprecated_sympy():
  725. import sympy.printing.ccode # noqa:F401
  726. def test_ccode_UnevaluatedExpr():
  727. assert ccode(UnevaluatedExpr(y * x) + z) == "z + x*y"
  728. assert ccode(UnevaluatedExpr(y + x) + z) == "z + (x + y)" # gh-21955
  729. w = symbols('w')
  730. assert ccode(UnevaluatedExpr(y + x) + UnevaluatedExpr(z + w)) == "(w + z) + (x + y)"
  731. p, q, r = symbols("p q r", real=True)
  732. q_r = UnevaluatedExpr(q + r)
  733. expr = abs(exp(p+q_r))
  734. assert ccode(expr) == "exp(p + (q + r))"
  735. def test_ccode_array_like_containers():
  736. assert ccode([2,3,4]) == "{2, 3, 4}"
  737. assert ccode((2,3,4)) == "{2, 3, 4}"