julia.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634
  1. """
  2. Julia code printer
  3. The `JuliaCodePrinter` converts SymPy expressions into Julia expressions.
  4. A complete code generator, which uses `julia_code` extensively, can be found
  5. in `sympy.utilities.codegen`. The `codegen` module can be used to generate
  6. complete source code files.
  7. """
  8. from typing import Any, Dict as tDict
  9. from sympy.core import Mul, Pow, S, Rational
  10. from sympy.core.mul import _keep_coeff
  11. from sympy.printing.codeprinter import CodePrinter
  12. from sympy.printing.precedence import precedence, PRECEDENCE
  13. from re import search
  14. # List of known functions. First, those that have the same name in
  15. # SymPy and Julia. This is almost certainly incomplete!
  16. known_fcns_src1 = ["sin", "cos", "tan", "cot", "sec", "csc",
  17. "asin", "acos", "atan", "acot", "asec", "acsc",
  18. "sinh", "cosh", "tanh", "coth", "sech", "csch",
  19. "asinh", "acosh", "atanh", "acoth", "asech", "acsch",
  20. "sinc", "atan2", "sign", "floor", "log", "exp",
  21. "cbrt", "sqrt", "erf", "erfc", "erfi",
  22. "factorial", "gamma", "digamma", "trigamma",
  23. "polygamma", "beta",
  24. "airyai", "airyaiprime", "airybi", "airybiprime",
  25. "besselj", "bessely", "besseli", "besselk",
  26. "erfinv", "erfcinv"]
  27. # These functions have different names ("SymPy": "Julia"), more
  28. # generally a mapping to (argument_conditions, julia_function).
  29. known_fcns_src2 = {
  30. "Abs": "abs",
  31. "ceiling": "ceil",
  32. "conjugate": "conj",
  33. "hankel1": "hankelh1",
  34. "hankel2": "hankelh2",
  35. "im": "imag",
  36. "re": "real"
  37. }
  38. class JuliaCodePrinter(CodePrinter):
  39. """
  40. A printer to convert expressions to strings of Julia code.
  41. """
  42. printmethod = "_julia"
  43. language = "Julia"
  44. _operators = {
  45. 'and': '&&',
  46. 'or': '||',
  47. 'not': '!',
  48. }
  49. _default_settings = {
  50. 'order': None,
  51. 'full_prec': 'auto',
  52. 'precision': 17,
  53. 'user_functions': {},
  54. 'human': True,
  55. 'allow_unknown_functions': False,
  56. 'contract': True,
  57. 'inline': True,
  58. } # type: tDict[str, Any]
  59. # Note: contract is for expressing tensors as loops (if True), or just
  60. # assignment (if False). FIXME: this should be looked a more carefully
  61. # for Julia.
  62. def __init__(self, settings={}):
  63. super().__init__(settings)
  64. self.known_functions = dict(zip(known_fcns_src1, known_fcns_src1))
  65. self.known_functions.update(dict(known_fcns_src2))
  66. userfuncs = settings.get('user_functions', {})
  67. self.known_functions.update(userfuncs)
  68. def _rate_index_position(self, p):
  69. return p*5
  70. def _get_statement(self, codestring):
  71. return "%s" % codestring
  72. def _get_comment(self, text):
  73. return "# {}".format(text)
  74. def _declare_number_const(self, name, value):
  75. return "const {} = {}".format(name, value)
  76. def _format_code(self, lines):
  77. return self.indent_code(lines)
  78. def _traverse_matrix_indices(self, mat):
  79. # Julia uses Fortran order (column-major)
  80. rows, cols = mat.shape
  81. return ((i, j) for j in range(cols) for i in range(rows))
  82. def _get_loop_opening_ending(self, indices):
  83. open_lines = []
  84. close_lines = []
  85. for i in indices:
  86. # Julia arrays start at 1 and end at dimension
  87. var, start, stop = map(self._print,
  88. [i.label, i.lower + 1, i.upper + 1])
  89. open_lines.append("for %s = %s:%s" % (var, start, stop))
  90. close_lines.append("end")
  91. return open_lines, close_lines
  92. def _print_Mul(self, expr):
  93. # print complex numbers nicely in Julia
  94. if (expr.is_number and expr.is_imaginary and
  95. expr.as_coeff_Mul()[0].is_integer):
  96. return "%sim" % self._print(-S.ImaginaryUnit*expr)
  97. # cribbed from str.py
  98. prec = precedence(expr)
  99. c, e = expr.as_coeff_Mul()
  100. if c < 0:
  101. expr = _keep_coeff(-c, e)
  102. sign = "-"
  103. else:
  104. sign = ""
  105. a = [] # items in the numerator
  106. b = [] # items that are in the denominator (if any)
  107. pow_paren = [] # Will collect all pow with more than one base element and exp = -1
  108. if self.order not in ('old', 'none'):
  109. args = expr.as_ordered_factors()
  110. else:
  111. # use make_args in case expr was something like -x -> x
  112. args = Mul.make_args(expr)
  113. # Gather args for numerator/denominator
  114. for item in args:
  115. if (item.is_commutative and item.is_Pow and item.exp.is_Rational
  116. and item.exp.is_negative):
  117. if item.exp != -1:
  118. b.append(Pow(item.base, -item.exp, evaluate=False))
  119. else:
  120. if len(item.args[0].args) != 1 and isinstance(item.base, Mul): # To avoid situations like #14160
  121. pow_paren.append(item)
  122. b.append(Pow(item.base, -item.exp))
  123. elif item.is_Rational and item is not S.Infinity:
  124. if item.p != 1:
  125. a.append(Rational(item.p))
  126. if item.q != 1:
  127. b.append(Rational(item.q))
  128. else:
  129. a.append(item)
  130. a = a or [S.One]
  131. a_str = [self.parenthesize(x, prec) for x in a]
  132. b_str = [self.parenthesize(x, prec) for x in b]
  133. # To parenthesize Pow with exp = -1 and having more than one Symbol
  134. for item in pow_paren:
  135. if item.base in b:
  136. b_str[b.index(item.base)] = "(%s)" % b_str[b.index(item.base)]
  137. # from here it differs from str.py to deal with "*" and ".*"
  138. def multjoin(a, a_str):
  139. # here we probably are assuming the constants will come first
  140. r = a_str[0]
  141. for i in range(1, len(a)):
  142. mulsym = '*' if a[i-1].is_number else '.*'
  143. r = r + mulsym + a_str[i]
  144. return r
  145. if not b:
  146. return sign + multjoin(a, a_str)
  147. elif len(b) == 1:
  148. divsym = '/' if b[0].is_number else './'
  149. return sign + multjoin(a, a_str) + divsym + b_str[0]
  150. else:
  151. divsym = '/' if all(bi.is_number for bi in b) else './'
  152. return (sign + multjoin(a, a_str) +
  153. divsym + "(%s)" % multjoin(b, b_str))
  154. def _print_Relational(self, expr):
  155. lhs_code = self._print(expr.lhs)
  156. rhs_code = self._print(expr.rhs)
  157. op = expr.rel_op
  158. return "{} {} {}".format(lhs_code, op, rhs_code)
  159. def _print_Pow(self, expr):
  160. powsymbol = '^' if all(x.is_number for x in expr.args) else '.^'
  161. PREC = precedence(expr)
  162. if expr.exp == S.Half:
  163. return "sqrt(%s)" % self._print(expr.base)
  164. if expr.is_commutative:
  165. if expr.exp == -S.Half:
  166. sym = '/' if expr.base.is_number else './'
  167. return "1" + sym + "sqrt(%s)" % self._print(expr.base)
  168. if expr.exp == -S.One:
  169. sym = '/' if expr.base.is_number else './'
  170. return "1" + sym + "%s" % self.parenthesize(expr.base, PREC)
  171. return '%s%s%s' % (self.parenthesize(expr.base, PREC), powsymbol,
  172. self.parenthesize(expr.exp, PREC))
  173. def _print_MatPow(self, expr):
  174. PREC = precedence(expr)
  175. return '%s^%s' % (self.parenthesize(expr.base, PREC),
  176. self.parenthesize(expr.exp, PREC))
  177. def _print_Pi(self, expr):
  178. if self._settings["inline"]:
  179. return "pi"
  180. else:
  181. return super()._print_NumberSymbol(expr)
  182. def _print_ImaginaryUnit(self, expr):
  183. return "im"
  184. def _print_Exp1(self, expr):
  185. if self._settings["inline"]:
  186. return "e"
  187. else:
  188. return super()._print_NumberSymbol(expr)
  189. def _print_EulerGamma(self, expr):
  190. if self._settings["inline"]:
  191. return "eulergamma"
  192. else:
  193. return super()._print_NumberSymbol(expr)
  194. def _print_Catalan(self, expr):
  195. if self._settings["inline"]:
  196. return "catalan"
  197. else:
  198. return super()._print_NumberSymbol(expr)
  199. def _print_GoldenRatio(self, expr):
  200. if self._settings["inline"]:
  201. return "golden"
  202. else:
  203. return super()._print_NumberSymbol(expr)
  204. def _print_Assignment(self, expr):
  205. from sympy.codegen.ast import Assignment
  206. from sympy.functions.elementary.piecewise import Piecewise
  207. from sympy.tensor.indexed import IndexedBase
  208. # Copied from codeprinter, but remove special MatrixSymbol treatment
  209. lhs = expr.lhs
  210. rhs = expr.rhs
  211. # We special case assignments that take multiple lines
  212. if not self._settings["inline"] and isinstance(expr.rhs, Piecewise):
  213. # Here we modify Piecewise so each expression is now
  214. # an Assignment, and then continue on the print.
  215. expressions = []
  216. conditions = []
  217. for (e, c) in rhs.args:
  218. expressions.append(Assignment(lhs, e))
  219. conditions.append(c)
  220. temp = Piecewise(*zip(expressions, conditions))
  221. return self._print(temp)
  222. if self._settings["contract"] and (lhs.has(IndexedBase) or
  223. rhs.has(IndexedBase)):
  224. # Here we check if there is looping to be done, and if so
  225. # print the required loops.
  226. return self._doprint_loops(rhs, lhs)
  227. else:
  228. lhs_code = self._print(lhs)
  229. rhs_code = self._print(rhs)
  230. return self._get_statement("%s = %s" % (lhs_code, rhs_code))
  231. def _print_Infinity(self, expr):
  232. return 'Inf'
  233. def _print_NegativeInfinity(self, expr):
  234. return '-Inf'
  235. def _print_NaN(self, expr):
  236. return 'NaN'
  237. def _print_list(self, expr):
  238. return 'Any[' + ', '.join(self._print(a) for a in expr) + ']'
  239. def _print_tuple(self, expr):
  240. if len(expr) == 1:
  241. return "(%s,)" % self._print(expr[0])
  242. else:
  243. return "(%s)" % self.stringify(expr, ", ")
  244. _print_Tuple = _print_tuple
  245. def _print_BooleanTrue(self, expr):
  246. return "true"
  247. def _print_BooleanFalse(self, expr):
  248. return "false"
  249. def _print_bool(self, expr):
  250. return str(expr).lower()
  251. # Could generate quadrature code for definite Integrals?
  252. #_print_Integral = _print_not_supported
  253. def _print_MatrixBase(self, A):
  254. # Handle zero dimensions:
  255. if S.Zero in A.shape:
  256. return 'zeros(%s, %s)' % (A.rows, A.cols)
  257. elif (A.rows, A.cols) == (1, 1):
  258. return "[%s]" % A[0, 0]
  259. elif A.rows == 1:
  260. return "[%s]" % A.table(self, rowstart='', rowend='', colsep=' ')
  261. elif A.cols == 1:
  262. # note .table would unnecessarily equispace the rows
  263. return "[%s]" % ", ".join([self._print(a) for a in A])
  264. return "[%s]" % A.table(self, rowstart='', rowend='',
  265. rowsep=';\n', colsep=' ')
  266. def _print_SparseRepMatrix(self, A):
  267. from sympy.matrices import Matrix
  268. L = A.col_list();
  269. # make row vectors of the indices and entries
  270. I = Matrix([k[0] + 1 for k in L])
  271. J = Matrix([k[1] + 1 for k in L])
  272. AIJ = Matrix([k[2] for k in L])
  273. return "sparse(%s, %s, %s, %s, %s)" % (self._print(I), self._print(J),
  274. self._print(AIJ), A.rows, A.cols)
  275. def _print_MatrixElement(self, expr):
  276. return self.parenthesize(expr.parent, PRECEDENCE["Atom"], strict=True) \
  277. + '[%s,%s]' % (expr.i + 1, expr.j + 1)
  278. def _print_MatrixSlice(self, expr):
  279. def strslice(x, lim):
  280. l = x[0] + 1
  281. h = x[1]
  282. step = x[2]
  283. lstr = self._print(l)
  284. hstr = 'end' if h == lim else self._print(h)
  285. if step == 1:
  286. if l == 1 and h == lim:
  287. return ':'
  288. if l == h:
  289. return lstr
  290. else:
  291. return lstr + ':' + hstr
  292. else:
  293. return ':'.join((lstr, self._print(step), hstr))
  294. return (self._print(expr.parent) + '[' +
  295. strslice(expr.rowslice, expr.parent.shape[0]) + ',' +
  296. strslice(expr.colslice, expr.parent.shape[1]) + ']')
  297. def _print_Indexed(self, expr):
  298. inds = [ self._print(i) for i in expr.indices ]
  299. return "%s[%s]" % (self._print(expr.base.label), ",".join(inds))
  300. def _print_Idx(self, expr):
  301. return self._print(expr.label)
  302. def _print_Identity(self, expr):
  303. return "eye(%s)" % self._print(expr.shape[0])
  304. def _print_HadamardProduct(self, expr):
  305. return '.*'.join([self.parenthesize(arg, precedence(expr))
  306. for arg in expr.args])
  307. def _print_HadamardPower(self, expr):
  308. PREC = precedence(expr)
  309. return '.**'.join([
  310. self.parenthesize(expr.base, PREC),
  311. self.parenthesize(expr.exp, PREC)
  312. ])
  313. # Note: as of 2015, Julia doesn't have spherical Bessel functions
  314. def _print_jn(self, expr):
  315. from sympy.functions import sqrt, besselj
  316. x = expr.argument
  317. expr2 = sqrt(S.Pi/(2*x))*besselj(expr.order + S.Half, x)
  318. return self._print(expr2)
  319. def _print_yn(self, expr):
  320. from sympy.functions import sqrt, bessely
  321. x = expr.argument
  322. expr2 = sqrt(S.Pi/(2*x))*bessely(expr.order + S.Half, x)
  323. return self._print(expr2)
  324. def _print_Piecewise(self, expr):
  325. if expr.args[-1].cond != True:
  326. # We need the last conditional to be a True, otherwise the resulting
  327. # function may not return a result.
  328. raise ValueError("All Piecewise expressions must contain an "
  329. "(expr, True) statement to be used as a default "
  330. "condition. Without one, the generated "
  331. "expression may not evaluate to anything under "
  332. "some condition.")
  333. lines = []
  334. if self._settings["inline"]:
  335. # Express each (cond, expr) pair in a nested Horner form:
  336. # (condition) .* (expr) + (not cond) .* (<others>)
  337. # Expressions that result in multiple statements won't work here.
  338. ecpairs = ["({}) ? ({}) :".format
  339. (self._print(c), self._print(e))
  340. for e, c in expr.args[:-1]]
  341. elast = " (%s)" % self._print(expr.args[-1].expr)
  342. pw = "\n".join(ecpairs) + elast
  343. # Note: current need these outer brackets for 2*pw. Would be
  344. # nicer to teach parenthesize() to do this for us when needed!
  345. return "(" + pw + ")"
  346. else:
  347. for i, (e, c) in enumerate(expr.args):
  348. if i == 0:
  349. lines.append("if (%s)" % self._print(c))
  350. elif i == len(expr.args) - 1 and c == True:
  351. lines.append("else")
  352. else:
  353. lines.append("elseif (%s)" % self._print(c))
  354. code0 = self._print(e)
  355. lines.append(code0)
  356. if i == len(expr.args) - 1:
  357. lines.append("end")
  358. return "\n".join(lines)
  359. def indent_code(self, code):
  360. """Accepts a string of code or a list of code lines"""
  361. # code mostly copied from ccode
  362. if isinstance(code, str):
  363. code_lines = self.indent_code(code.splitlines(True))
  364. return ''.join(code_lines)
  365. tab = " "
  366. inc_regex = ('^function ', '^if ', '^elseif ', '^else$', '^for ')
  367. dec_regex = ('^end$', '^elseif ', '^else$')
  368. # pre-strip left-space from the code
  369. code = [ line.lstrip(' \t') for line in code ]
  370. increase = [ int(any(search(re, line) for re in inc_regex))
  371. for line in code ]
  372. decrease = [ int(any(search(re, line) for re in dec_regex))
  373. for line in code ]
  374. pretty = []
  375. level = 0
  376. for n, line in enumerate(code):
  377. if line in ('', '\n'):
  378. pretty.append(line)
  379. continue
  380. level -= decrease[n]
  381. pretty.append("%s%s" % (tab*level, line))
  382. level += increase[n]
  383. return pretty
  384. def julia_code(expr, assign_to=None, **settings):
  385. r"""Converts `expr` to a string of Julia code.
  386. Parameters
  387. ==========
  388. expr : Expr
  389. A SymPy expression to be converted.
  390. assign_to : optional
  391. When given, the argument is used as the name of the variable to which
  392. the expression is assigned. Can be a string, ``Symbol``,
  393. ``MatrixSymbol``, or ``Indexed`` type. This can be helpful for
  394. expressions that generate multi-line statements.
  395. precision : integer, optional
  396. The precision for numbers such as pi [default=16].
  397. user_functions : dict, optional
  398. A dictionary where keys are ``FunctionClass`` instances and values are
  399. their string representations. Alternatively, the dictionary value can
  400. be a list of tuples i.e. [(argument_test, cfunction_string)]. See
  401. below for examples.
  402. human : bool, optional
  403. If True, the result is a single string that may contain some constant
  404. declarations for the number symbols. If False, the same information is
  405. returned in a tuple of (symbols_to_declare, not_supported_functions,
  406. code_text). [default=True].
  407. contract: bool, optional
  408. If True, ``Indexed`` instances are assumed to obey tensor contraction
  409. rules and the corresponding nested loops over indices are generated.
  410. Setting contract=False will not generate loops, instead the user is
  411. responsible to provide values for the indices in the code.
  412. [default=True].
  413. inline: bool, optional
  414. If True, we try to create single-statement code instead of multiple
  415. statements. [default=True].
  416. Examples
  417. ========
  418. >>> from sympy import julia_code, symbols, sin, pi
  419. >>> x = symbols('x')
  420. >>> julia_code(sin(x).series(x).removeO())
  421. 'x.^5/120 - x.^3/6 + x'
  422. >>> from sympy import Rational, ceiling
  423. >>> x, y, tau = symbols("x, y, tau")
  424. >>> julia_code((2*tau)**Rational(7, 2))
  425. '8*sqrt(2)*tau.^(7/2)'
  426. Note that element-wise (Hadamard) operations are used by default between
  427. symbols. This is because its possible in Julia to write "vectorized"
  428. code. It is harmless if the values are scalars.
  429. >>> julia_code(sin(pi*x*y), assign_to="s")
  430. 's = sin(pi*x.*y)'
  431. If you need a matrix product "*" or matrix power "^", you can specify the
  432. symbol as a ``MatrixSymbol``.
  433. >>> from sympy import Symbol, MatrixSymbol
  434. >>> n = Symbol('n', integer=True, positive=True)
  435. >>> A = MatrixSymbol('A', n, n)
  436. >>> julia_code(3*pi*A**3)
  437. '(3*pi)*A^3'
  438. This class uses several rules to decide which symbol to use a product.
  439. Pure numbers use "*", Symbols use ".*" and MatrixSymbols use "*".
  440. A HadamardProduct can be used to specify componentwise multiplication ".*"
  441. of two MatrixSymbols. There is currently there is no easy way to specify
  442. scalar symbols, so sometimes the code might have some minor cosmetic
  443. issues. For example, suppose x and y are scalars and A is a Matrix, then
  444. while a human programmer might write "(x^2*y)*A^3", we generate:
  445. >>> julia_code(x**2*y*A**3)
  446. '(x.^2.*y)*A^3'
  447. Matrices are supported using Julia inline notation. When using
  448. ``assign_to`` with matrices, the name can be specified either as a string
  449. or as a ``MatrixSymbol``. The dimensions must align in the latter case.
  450. >>> from sympy import Matrix, MatrixSymbol
  451. >>> mat = Matrix([[x**2, sin(x), ceiling(x)]])
  452. >>> julia_code(mat, assign_to='A')
  453. 'A = [x.^2 sin(x) ceil(x)]'
  454. ``Piecewise`` expressions are implemented with logical masking by default.
  455. Alternatively, you can pass "inline=False" to use if-else conditionals.
  456. Note that if the ``Piecewise`` lacks a default term, represented by
  457. ``(expr, True)`` then an error will be thrown. This is to prevent
  458. generating an expression that may not evaluate to anything.
  459. >>> from sympy import Piecewise
  460. >>> pw = Piecewise((x + 1, x > 0), (x, True))
  461. >>> julia_code(pw, assign_to=tau)
  462. 'tau = ((x > 0) ? (x + 1) : (x))'
  463. Note that any expression that can be generated normally can also exist
  464. inside a Matrix:
  465. >>> mat = Matrix([[x**2, pw, sin(x)]])
  466. >>> julia_code(mat, assign_to='A')
  467. 'A = [x.^2 ((x > 0) ? (x + 1) : (x)) sin(x)]'
  468. Custom printing can be defined for certain types by passing a dictionary of
  469. "type" : "function" to the ``user_functions`` kwarg. Alternatively, the
  470. dictionary value can be a list of tuples i.e., [(argument_test,
  471. cfunction_string)]. This can be used to call a custom Julia function.
  472. >>> from sympy import Function
  473. >>> f = Function('f')
  474. >>> g = Function('g')
  475. >>> custom_functions = {
  476. ... "f": "existing_julia_fcn",
  477. ... "g": [(lambda x: x.is_Matrix, "my_mat_fcn"),
  478. ... (lambda x: not x.is_Matrix, "my_fcn")]
  479. ... }
  480. >>> mat = Matrix([[1, x]])
  481. >>> julia_code(f(x) + g(x) + g(mat), user_functions=custom_functions)
  482. 'existing_julia_fcn(x) + my_fcn(x) + my_mat_fcn([1 x])'
  483. Support for loops is provided through ``Indexed`` types. With
  484. ``contract=True`` these expressions will be turned into loops, whereas
  485. ``contract=False`` will just print the assignment expression that should be
  486. looped over:
  487. >>> from sympy import Eq, IndexedBase, Idx
  488. >>> len_y = 5
  489. >>> y = IndexedBase('y', shape=(len_y,))
  490. >>> t = IndexedBase('t', shape=(len_y,))
  491. >>> Dy = IndexedBase('Dy', shape=(len_y-1,))
  492. >>> i = Idx('i', len_y-1)
  493. >>> e = Eq(Dy[i], (y[i+1]-y[i])/(t[i+1]-t[i]))
  494. >>> julia_code(e.rhs, assign_to=e.lhs, contract=False)
  495. 'Dy[i] = (y[i + 1] - y[i])./(t[i + 1] - t[i])'
  496. """
  497. return JuliaCodePrinter(settings).doprint(expr, assign_to)
  498. def print_julia_code(expr, **settings):
  499. """Prints the Julia representation of the given expression.
  500. See `julia_code` for the meaning of the optional arguments.
  501. """
  502. print(julia_code(expr, **settings))