octave.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717
  1. """
  2. Octave (and Matlab) code printer
  3. The `OctaveCodePrinter` converts SymPy expressions into Octave expressions.
  4. It uses a subset of the Octave language for Matlab compatibility.
  5. A complete code generator, which uses `octave_code` extensively, can be found
  6. in `sympy.utilities.codegen`. The `codegen` module can be used to generate
  7. complete source code files.
  8. """
  9. from typing import Any, Dict as tDict
  10. from sympy.core import Mul, Pow, S, Rational
  11. from sympy.core.mul import _keep_coeff
  12. from sympy.printing.codeprinter import CodePrinter
  13. from sympy.printing.precedence import precedence, PRECEDENCE
  14. from re import search
  15. # List of known functions. First, those that have the same name in
  16. # SymPy and Octave. This is almost certainly incomplete!
  17. known_fcns_src1 = ["sin", "cos", "tan", "cot", "sec", "csc",
  18. "asin", "acos", "acot", "atan", "atan2", "asec", "acsc",
  19. "sinh", "cosh", "tanh", "coth", "csch", "sech",
  20. "asinh", "acosh", "atanh", "acoth", "asech", "acsch",
  21. "erfc", "erfi", "erf", "erfinv", "erfcinv",
  22. "besseli", "besselj", "besselk", "bessely",
  23. "bernoulli", "beta", "euler", "exp", "factorial", "floor",
  24. "fresnelc", "fresnels", "gamma", "harmonic", "log",
  25. "polylog", "sign", "zeta", "legendre"]
  26. # These functions have different names ("SymPy": "Octave"), more
  27. # generally a mapping to (argument_conditions, octave_function).
  28. known_fcns_src2 = {
  29. "Abs": "abs",
  30. "arg": "angle", # arg/angle ok in Octave but only angle in Matlab
  31. "binomial": "bincoeff",
  32. "ceiling": "ceil",
  33. "chebyshevu": "chebyshevU",
  34. "chebyshevt": "chebyshevT",
  35. "Chi": "coshint",
  36. "Ci": "cosint",
  37. "conjugate": "conj",
  38. "DiracDelta": "dirac",
  39. "Heaviside": "heaviside",
  40. "im": "imag",
  41. "laguerre": "laguerreL",
  42. "LambertW": "lambertw",
  43. "li": "logint",
  44. "loggamma": "gammaln",
  45. "Max": "max",
  46. "Min": "min",
  47. "Mod": "mod",
  48. "polygamma": "psi",
  49. "re": "real",
  50. "RisingFactorial": "pochhammer",
  51. "Shi": "sinhint",
  52. "Si": "sinint",
  53. }
  54. class OctaveCodePrinter(CodePrinter):
  55. """
  56. A printer to convert expressions to strings of Octave/Matlab code.
  57. """
  58. printmethod = "_octave"
  59. language = "Octave"
  60. _operators = {
  61. 'and': '&',
  62. 'or': '|',
  63. 'not': '~',
  64. }
  65. _default_settings = {
  66. 'order': None,
  67. 'full_prec': 'auto',
  68. 'precision': 17,
  69. 'user_functions': {},
  70. 'human': True,
  71. 'allow_unknown_functions': False,
  72. 'contract': True,
  73. 'inline': True,
  74. } # type: tDict[str, Any]
  75. # Note: contract is for expressing tensors as loops (if True), or just
  76. # assignment (if False). FIXME: this should be looked a more carefully
  77. # for Octave.
  78. def __init__(self, settings={}):
  79. super().__init__(settings)
  80. self.known_functions = dict(zip(known_fcns_src1, known_fcns_src1))
  81. self.known_functions.update(dict(known_fcns_src2))
  82. userfuncs = settings.get('user_functions', {})
  83. self.known_functions.update(userfuncs)
  84. def _rate_index_position(self, p):
  85. return p*5
  86. def _get_statement(self, codestring):
  87. return "%s;" % codestring
  88. def _get_comment(self, text):
  89. return "% {}".format(text)
  90. def _declare_number_const(self, name, value):
  91. return "{} = {};".format(name, value)
  92. def _format_code(self, lines):
  93. return self.indent_code(lines)
  94. def _traverse_matrix_indices(self, mat):
  95. # Octave uses Fortran order (column-major)
  96. rows, cols = mat.shape
  97. return ((i, j) for j in range(cols) for i in range(rows))
  98. def _get_loop_opening_ending(self, indices):
  99. open_lines = []
  100. close_lines = []
  101. for i in indices:
  102. # Octave arrays start at 1 and end at dimension
  103. var, start, stop = map(self._print,
  104. [i.label, i.lower + 1, i.upper + 1])
  105. open_lines.append("for %s = %s:%s" % (var, start, stop))
  106. close_lines.append("end")
  107. return open_lines, close_lines
  108. def _print_Mul(self, expr):
  109. # print complex numbers nicely in Octave
  110. if (expr.is_number and expr.is_imaginary and
  111. (S.ImaginaryUnit*expr).is_Integer):
  112. return "%si" % self._print(-S.ImaginaryUnit*expr)
  113. # cribbed from str.py
  114. prec = precedence(expr)
  115. c, e = expr.as_coeff_Mul()
  116. if c < 0:
  117. expr = _keep_coeff(-c, e)
  118. sign = "-"
  119. else:
  120. sign = ""
  121. a = [] # items in the numerator
  122. b = [] # items that are in the denominator (if any)
  123. pow_paren = [] # Will collect all pow with more than one base element and exp = -1
  124. if self.order not in ('old', 'none'):
  125. args = expr.as_ordered_factors()
  126. else:
  127. # use make_args in case expr was something like -x -> x
  128. args = Mul.make_args(expr)
  129. # Gather args for numerator/denominator
  130. for item in args:
  131. if (item.is_commutative and item.is_Pow and item.exp.is_Rational
  132. and item.exp.is_negative):
  133. if item.exp != -1:
  134. b.append(Pow(item.base, -item.exp, evaluate=False))
  135. else:
  136. if len(item.args[0].args) != 1 and isinstance(item.base, Mul): # To avoid situations like #14160
  137. pow_paren.append(item)
  138. b.append(Pow(item.base, -item.exp))
  139. elif item.is_Rational and item is not S.Infinity:
  140. if item.p != 1:
  141. a.append(Rational(item.p))
  142. if item.q != 1:
  143. b.append(Rational(item.q))
  144. else:
  145. a.append(item)
  146. a = a or [S.One]
  147. a_str = [self.parenthesize(x, prec) for x in a]
  148. b_str = [self.parenthesize(x, prec) for x in b]
  149. # To parenthesize Pow with exp = -1 and having more than one Symbol
  150. for item in pow_paren:
  151. if item.base in b:
  152. b_str[b.index(item.base)] = "(%s)" % b_str[b.index(item.base)]
  153. # from here it differs from str.py to deal with "*" and ".*"
  154. def multjoin(a, a_str):
  155. # here we probably are assuming the constants will come first
  156. r = a_str[0]
  157. for i in range(1, len(a)):
  158. mulsym = '*' if a[i-1].is_number else '.*'
  159. r = r + mulsym + a_str[i]
  160. return r
  161. if not b:
  162. return sign + multjoin(a, a_str)
  163. elif len(b) == 1:
  164. divsym = '/' if b[0].is_number else './'
  165. return sign + multjoin(a, a_str) + divsym + b_str[0]
  166. else:
  167. divsym = '/' if all(bi.is_number for bi in b) else './'
  168. return (sign + multjoin(a, a_str) +
  169. divsym + "(%s)" % multjoin(b, b_str))
  170. def _print_Relational(self, expr):
  171. lhs_code = self._print(expr.lhs)
  172. rhs_code = self._print(expr.rhs)
  173. op = expr.rel_op
  174. return "{} {} {}".format(lhs_code, op, rhs_code)
  175. def _print_Pow(self, expr):
  176. powsymbol = '^' if all(x.is_number for x in expr.args) else '.^'
  177. PREC = precedence(expr)
  178. if expr.exp == S.Half:
  179. return "sqrt(%s)" % self._print(expr.base)
  180. if expr.is_commutative:
  181. if expr.exp == -S.Half:
  182. sym = '/' if expr.base.is_number else './'
  183. return "1" + sym + "sqrt(%s)" % self._print(expr.base)
  184. if expr.exp == -S.One:
  185. sym = '/' if expr.base.is_number else './'
  186. return "1" + sym + "%s" % self.parenthesize(expr.base, PREC)
  187. return '%s%s%s' % (self.parenthesize(expr.base, PREC), powsymbol,
  188. self.parenthesize(expr.exp, PREC))
  189. def _print_MatPow(self, expr):
  190. PREC = precedence(expr)
  191. return '%s^%s' % (self.parenthesize(expr.base, PREC),
  192. self.parenthesize(expr.exp, PREC))
  193. def _print_MatrixSolve(self, expr):
  194. PREC = precedence(expr)
  195. return "%s \\ %s" % (self.parenthesize(expr.matrix, PREC),
  196. self.parenthesize(expr.vector, PREC))
  197. def _print_Pi(self, expr):
  198. return 'pi'
  199. def _print_ImaginaryUnit(self, expr):
  200. return "1i"
  201. def _print_Exp1(self, expr):
  202. return "exp(1)"
  203. def _print_GoldenRatio(self, expr):
  204. # FIXME: how to do better, e.g., for octave_code(2*GoldenRatio)?
  205. #return self._print((1+sqrt(S(5)))/2)
  206. return "(1+sqrt(5))/2"
  207. def _print_Assignment(self, expr):
  208. from sympy.codegen.ast import Assignment
  209. from sympy.functions.elementary.piecewise import Piecewise
  210. from sympy.tensor.indexed import IndexedBase
  211. # Copied from codeprinter, but remove special MatrixSymbol treatment
  212. lhs = expr.lhs
  213. rhs = expr.rhs
  214. # We special case assignments that take multiple lines
  215. if not self._settings["inline"] and isinstance(expr.rhs, Piecewise):
  216. # Here we modify Piecewise so each expression is now
  217. # an Assignment, and then continue on the print.
  218. expressions = []
  219. conditions = []
  220. for (e, c) in rhs.args:
  221. expressions.append(Assignment(lhs, e))
  222. conditions.append(c)
  223. temp = Piecewise(*zip(expressions, conditions))
  224. return self._print(temp)
  225. if self._settings["contract"] and (lhs.has(IndexedBase) or
  226. rhs.has(IndexedBase)):
  227. # Here we check if there is looping to be done, and if so
  228. # print the required loops.
  229. return self._doprint_loops(rhs, lhs)
  230. else:
  231. lhs_code = self._print(lhs)
  232. rhs_code = self._print(rhs)
  233. return self._get_statement("%s = %s" % (lhs_code, rhs_code))
  234. def _print_Infinity(self, expr):
  235. return 'inf'
  236. def _print_NegativeInfinity(self, expr):
  237. return '-inf'
  238. def _print_NaN(self, expr):
  239. return 'NaN'
  240. def _print_list(self, expr):
  241. return '{' + ', '.join(self._print(a) for a in expr) + '}'
  242. _print_tuple = _print_list
  243. _print_Tuple = _print_list
  244. _print_List = _print_list
  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 (A.rows, A.cols) == (0, 0):
  256. return '[]'
  257. elif S.Zero in A.shape:
  258. return 'zeros(%s, %s)' % (A.rows, A.cols)
  259. elif (A.rows, A.cols) == (1, 1):
  260. # Octave does not distinguish between scalars and 1x1 matrices
  261. return self._print(A[0, 0])
  262. return "[%s]" % "; ".join(" ".join([self._print(a) for a in A[r, :]])
  263. for r in range(A.rows))
  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_Idx(self, expr):
  299. return self._print(expr.label)
  300. def _print_KroneckerDelta(self, expr):
  301. prec = PRECEDENCE["Pow"]
  302. return "double(%s == %s)" % tuple(self.parenthesize(x, prec)
  303. for x in expr.args)
  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. def _print_Identity(self, expr):
  314. shape = expr.shape
  315. if len(shape) == 2 and shape[0] == shape[1]:
  316. shape = [shape[0]]
  317. s = ", ".join(self._print(n) for n in shape)
  318. return "eye(" + s + ")"
  319. def _print_lowergamma(self, expr):
  320. # Octave implements regularized incomplete gamma function
  321. return "(gammainc({1}, {0}).*gamma({0}))".format(
  322. self._print(expr.args[0]), self._print(expr.args[1]))
  323. def _print_uppergamma(self, expr):
  324. return "(gammainc({1}, {0}, 'upper').*gamma({0}))".format(
  325. self._print(expr.args[0]), self._print(expr.args[1]))
  326. def _print_sinc(self, expr):
  327. #Note: Divide by pi because Octave implements normalized sinc function.
  328. return "sinc(%s)" % self._print(expr.args[0]/S.Pi)
  329. def _print_hankel1(self, expr):
  330. return "besselh(%s, 1, %s)" % (self._print(expr.order),
  331. self._print(expr.argument))
  332. def _print_hankel2(self, expr):
  333. return "besselh(%s, 2, %s)" % (self._print(expr.order),
  334. self._print(expr.argument))
  335. # Note: as of 2015, Octave doesn't have spherical Bessel functions
  336. def _print_jn(self, expr):
  337. from sympy.functions import sqrt, besselj
  338. x = expr.argument
  339. expr2 = sqrt(S.Pi/(2*x))*besselj(expr.order + S.Half, x)
  340. return self._print(expr2)
  341. def _print_yn(self, expr):
  342. from sympy.functions import sqrt, bessely
  343. x = expr.argument
  344. expr2 = sqrt(S.Pi/(2*x))*bessely(expr.order + S.Half, x)
  345. return self._print(expr2)
  346. def _print_airyai(self, expr):
  347. return "airy(0, %s)" % self._print(expr.args[0])
  348. def _print_airyaiprime(self, expr):
  349. return "airy(1, %s)" % self._print(expr.args[0])
  350. def _print_airybi(self, expr):
  351. return "airy(2, %s)" % self._print(expr.args[0])
  352. def _print_airybiprime(self, expr):
  353. return "airy(3, %s)" % self._print(expr.args[0])
  354. def _print_expint(self, expr):
  355. mu, x = expr.args
  356. if mu != 1:
  357. return self._print_not_supported(expr)
  358. return "expint(%s)" % self._print(x)
  359. def _one_or_two_reversed_args(self, expr):
  360. assert len(expr.args) <= 2
  361. return '{name}({args})'.format(
  362. name=self.known_functions[expr.__class__.__name__],
  363. args=", ".join([self._print(x) for x in reversed(expr.args)])
  364. )
  365. _print_DiracDelta = _print_LambertW = _one_or_two_reversed_args
  366. def _nested_binary_math_func(self, expr):
  367. return '{name}({arg1}, {arg2})'.format(
  368. name=self.known_functions[expr.__class__.__name__],
  369. arg1=self._print(expr.args[0]),
  370. arg2=self._print(expr.func(*expr.args[1:]))
  371. )
  372. _print_Max = _print_Min = _nested_binary_math_func
  373. def _print_Piecewise(self, expr):
  374. if expr.args[-1].cond != True:
  375. # We need the last conditional to be a True, otherwise the resulting
  376. # function may not return a result.
  377. raise ValueError("All Piecewise expressions must contain an "
  378. "(expr, True) statement to be used as a default "
  379. "condition. Without one, the generated "
  380. "expression may not evaluate to anything under "
  381. "some condition.")
  382. lines = []
  383. if self._settings["inline"]:
  384. # Express each (cond, expr) pair in a nested Horner form:
  385. # (condition) .* (expr) + (not cond) .* (<others>)
  386. # Expressions that result in multiple statements won't work here.
  387. ecpairs = ["({0}).*({1}) + (~({0})).*(".format
  388. (self._print(c), self._print(e))
  389. for e, c in expr.args[:-1]]
  390. elast = "%s" % self._print(expr.args[-1].expr)
  391. pw = " ...\n".join(ecpairs) + elast + ")"*len(ecpairs)
  392. # Note: current need these outer brackets for 2*pw. Would be
  393. # nicer to teach parenthesize() to do this for us when needed!
  394. return "(" + pw + ")"
  395. else:
  396. for i, (e, c) in enumerate(expr.args):
  397. if i == 0:
  398. lines.append("if (%s)" % self._print(c))
  399. elif i == len(expr.args) - 1 and c == True:
  400. lines.append("else")
  401. else:
  402. lines.append("elseif (%s)" % self._print(c))
  403. code0 = self._print(e)
  404. lines.append(code0)
  405. if i == len(expr.args) - 1:
  406. lines.append("end")
  407. return "\n".join(lines)
  408. def _print_zeta(self, expr):
  409. if len(expr.args) == 1:
  410. return "zeta(%s)" % self._print(expr.args[0])
  411. else:
  412. # Matlab two argument zeta is not equivalent to SymPy's
  413. return self._print_not_supported(expr)
  414. def indent_code(self, code):
  415. """Accepts a string of code or a list of code lines"""
  416. # code mostly copied from ccode
  417. if isinstance(code, str):
  418. code_lines = self.indent_code(code.splitlines(True))
  419. return ''.join(code_lines)
  420. tab = " "
  421. inc_regex = ('^function ', '^if ', '^elseif ', '^else$', '^for ')
  422. dec_regex = ('^end$', '^elseif ', '^else$')
  423. # pre-strip left-space from the code
  424. code = [ line.lstrip(' \t') for line in code ]
  425. increase = [ int(any(search(re, line) for re in inc_regex))
  426. for line in code ]
  427. decrease = [ int(any(search(re, line) for re in dec_regex))
  428. for line in code ]
  429. pretty = []
  430. level = 0
  431. for n, line in enumerate(code):
  432. if line in ('', '\n'):
  433. pretty.append(line)
  434. continue
  435. level -= decrease[n]
  436. pretty.append("%s%s" % (tab*level, line))
  437. level += increase[n]
  438. return pretty
  439. def octave_code(expr, assign_to=None, **settings):
  440. r"""Converts `expr` to a string of Octave (or Matlab) code.
  441. The string uses a subset of the Octave language for Matlab compatibility.
  442. Parameters
  443. ==========
  444. expr : Expr
  445. A SymPy expression to be converted.
  446. assign_to : optional
  447. When given, the argument is used as the name of the variable to which
  448. the expression is assigned. Can be a string, ``Symbol``,
  449. ``MatrixSymbol``, or ``Indexed`` type. This can be helpful for
  450. expressions that generate multi-line statements.
  451. precision : integer, optional
  452. The precision for numbers such as pi [default=16].
  453. user_functions : dict, optional
  454. A dictionary where keys are ``FunctionClass`` instances and values are
  455. their string representations. Alternatively, the dictionary value can
  456. be a list of tuples i.e. [(argument_test, cfunction_string)]. See
  457. below for examples.
  458. human : bool, optional
  459. If True, the result is a single string that may contain some constant
  460. declarations for the number symbols. If False, the same information is
  461. returned in a tuple of (symbols_to_declare, not_supported_functions,
  462. code_text). [default=True].
  463. contract: bool, optional
  464. If True, ``Indexed`` instances are assumed to obey tensor contraction
  465. rules and the corresponding nested loops over indices are generated.
  466. Setting contract=False will not generate loops, instead the user is
  467. responsible to provide values for the indices in the code.
  468. [default=True].
  469. inline: bool, optional
  470. If True, we try to create single-statement code instead of multiple
  471. statements. [default=True].
  472. Examples
  473. ========
  474. >>> from sympy import octave_code, symbols, sin, pi
  475. >>> x = symbols('x')
  476. >>> octave_code(sin(x).series(x).removeO())
  477. 'x.^5/120 - x.^3/6 + x'
  478. >>> from sympy import Rational, ceiling
  479. >>> x, y, tau = symbols("x, y, tau")
  480. >>> octave_code((2*tau)**Rational(7, 2))
  481. '8*sqrt(2)*tau.^(7/2)'
  482. Note that element-wise (Hadamard) operations are used by default between
  483. symbols. This is because its very common in Octave to write "vectorized"
  484. code. It is harmless if the values are scalars.
  485. >>> octave_code(sin(pi*x*y), assign_to="s")
  486. 's = sin(pi*x.*y);'
  487. If you need a matrix product "*" or matrix power "^", you can specify the
  488. symbol as a ``MatrixSymbol``.
  489. >>> from sympy import Symbol, MatrixSymbol
  490. >>> n = Symbol('n', integer=True, positive=True)
  491. >>> A = MatrixSymbol('A', n, n)
  492. >>> octave_code(3*pi*A**3)
  493. '(3*pi)*A^3'
  494. This class uses several rules to decide which symbol to use a product.
  495. Pure numbers use "*", Symbols use ".*" and MatrixSymbols use "*".
  496. A HadamardProduct can be used to specify componentwise multiplication ".*"
  497. of two MatrixSymbols. There is currently there is no easy way to specify
  498. scalar symbols, so sometimes the code might have some minor cosmetic
  499. issues. For example, suppose x and y are scalars and A is a Matrix, then
  500. while a human programmer might write "(x^2*y)*A^3", we generate:
  501. >>> octave_code(x**2*y*A**3)
  502. '(x.^2.*y)*A^3'
  503. Matrices are supported using Octave inline notation. When using
  504. ``assign_to`` with matrices, the name can be specified either as a string
  505. or as a ``MatrixSymbol``. The dimensions must align in the latter case.
  506. >>> from sympy import Matrix, MatrixSymbol
  507. >>> mat = Matrix([[x**2, sin(x), ceiling(x)]])
  508. >>> octave_code(mat, assign_to='A')
  509. 'A = [x.^2 sin(x) ceil(x)];'
  510. ``Piecewise`` expressions are implemented with logical masking by default.
  511. Alternatively, you can pass "inline=False" to use if-else conditionals.
  512. Note that if the ``Piecewise`` lacks a default term, represented by
  513. ``(expr, True)`` then an error will be thrown. This is to prevent
  514. generating an expression that may not evaluate to anything.
  515. >>> from sympy import Piecewise
  516. >>> pw = Piecewise((x + 1, x > 0), (x, True))
  517. >>> octave_code(pw, assign_to=tau)
  518. 'tau = ((x > 0).*(x + 1) + (~(x > 0)).*(x));'
  519. Note that any expression that can be generated normally can also exist
  520. inside a Matrix:
  521. >>> mat = Matrix([[x**2, pw, sin(x)]])
  522. >>> octave_code(mat, assign_to='A')
  523. 'A = [x.^2 ((x > 0).*(x + 1) + (~(x > 0)).*(x)) sin(x)];'
  524. Custom printing can be defined for certain types by passing a dictionary of
  525. "type" : "function" to the ``user_functions`` kwarg. Alternatively, the
  526. dictionary value can be a list of tuples i.e., [(argument_test,
  527. cfunction_string)]. This can be used to call a custom Octave function.
  528. >>> from sympy import Function
  529. >>> f = Function('f')
  530. >>> g = Function('g')
  531. >>> custom_functions = {
  532. ... "f": "existing_octave_fcn",
  533. ... "g": [(lambda x: x.is_Matrix, "my_mat_fcn"),
  534. ... (lambda x: not x.is_Matrix, "my_fcn")]
  535. ... }
  536. >>> mat = Matrix([[1, x]])
  537. >>> octave_code(f(x) + g(x) + g(mat), user_functions=custom_functions)
  538. 'existing_octave_fcn(x) + my_fcn(x) + my_mat_fcn([1 x])'
  539. Support for loops is provided through ``Indexed`` types. With
  540. ``contract=True`` these expressions will be turned into loops, whereas
  541. ``contract=False`` will just print the assignment expression that should be
  542. looped over:
  543. >>> from sympy import Eq, IndexedBase, Idx
  544. >>> len_y = 5
  545. >>> y = IndexedBase('y', shape=(len_y,))
  546. >>> t = IndexedBase('t', shape=(len_y,))
  547. >>> Dy = IndexedBase('Dy', shape=(len_y-1,))
  548. >>> i = Idx('i', len_y-1)
  549. >>> e = Eq(Dy[i], (y[i+1]-y[i])/(t[i+1]-t[i]))
  550. >>> octave_code(e.rhs, assign_to=e.lhs, contract=False)
  551. 'Dy(i) = (y(i + 1) - y(i))./(t(i + 1) - t(i));'
  552. """
  553. return OctaveCodePrinter(settings).doprint(expr, assign_to)
  554. def print_octave_code(expr, **settings):
  555. """Prints the Octave (or Matlab) representation of the given expression.
  556. See `octave_code` for the meaning of the optional arguments.
  557. """
  558. print(octave_code(expr, **settings))