julia.py 23 KB

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