julia.py 23 KB

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