codeprinter.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865
  1. from typing import Any, Dict as tDict, Set as tSet, Tuple as tTuple
  2. from functools import wraps
  3. from sympy.core import Add, Expr, Mul, Pow, S, sympify, Float
  4. from sympy.core.basic import Basic
  5. from sympy.core.expr import UnevaluatedExpr
  6. from sympy.core.function import Lambda
  7. from sympy.core.mul import _keep_coeff
  8. from sympy.core.sorting import default_sort_key
  9. from sympy.core.symbol import Symbol
  10. from sympy.functions.elementary.complexes import re
  11. from sympy.printing.str import StrPrinter
  12. from sympy.printing.precedence import precedence, PRECEDENCE
  13. class requires:
  14. """ Decorator for registering requirements on print methods. """
  15. def __init__(self, **kwargs):
  16. self._req = kwargs
  17. def __call__(self, method):
  18. def _method_wrapper(self_, *args, **kwargs):
  19. for k, v in self._req.items():
  20. getattr(self_, k).update(v)
  21. return method(self_, *args, **kwargs)
  22. return wraps(method)(_method_wrapper)
  23. class AssignmentError(Exception):
  24. """
  25. Raised if an assignment variable for a loop is missing.
  26. """
  27. pass
  28. def _convert_python_lists(arg):
  29. if isinstance(arg, list):
  30. from sympy.codegen.abstract_nodes import List
  31. return List(*(_convert_python_lists(e) for e in arg))
  32. elif isinstance(arg, tuple):
  33. return tuple(_convert_python_lists(e) for e in arg)
  34. else:
  35. return arg
  36. class CodePrinter(StrPrinter):
  37. """
  38. The base class for code-printing subclasses.
  39. """
  40. _operators = {
  41. 'and': '&&',
  42. 'or': '||',
  43. 'not': '!',
  44. }
  45. _default_settings = {
  46. 'order': None,
  47. 'full_prec': 'auto',
  48. 'error_on_reserved': False,
  49. 'reserved_word_suffix': '_',
  50. 'human': True,
  51. 'inline': False,
  52. 'allow_unknown_functions': False,
  53. } # type: tDict[str, Any]
  54. # Functions which are "simple" to rewrite to other functions that
  55. # may be supported
  56. # function_to_rewrite : (function_to_rewrite_to, iterable_with_other_functions_required)
  57. _rewriteable_functions = {
  58. 'catalan': ('gamma', []),
  59. 'fibonacci': ('sqrt', []),
  60. 'lucas': ('sqrt', []),
  61. 'beta': ('gamma', []),
  62. 'sinc': ('sin', ['Piecewise']),
  63. 'Mod': ('floor', []),
  64. 'factorial': ('gamma', []),
  65. 'factorial2': ('gamma', ['Piecewise']),
  66. 'subfactorial': ('uppergamma', []),
  67. 'RisingFactorial': ('gamma', ['Piecewise']),
  68. 'FallingFactorial': ('gamma', ['Piecewise']),
  69. 'binomial': ('gamma', []),
  70. 'frac': ('floor', []),
  71. 'Max': ('Piecewise', []),
  72. 'Min': ('Piecewise', []),
  73. 'Heaviside': ('Piecewise', []),
  74. 'erf2': ('erf', []),
  75. 'erfc': ('erf', []),
  76. 'Li': ('li', []),
  77. 'Ei': ('li', []),
  78. 'dirichlet_eta': ('zeta', []),
  79. 'riemann_xi': ('zeta', ['gamma']),
  80. }
  81. def __init__(self, settings=None):
  82. super().__init__(settings=settings)
  83. if not hasattr(self, 'reserved_words'):
  84. self.reserved_words = set()
  85. def _handle_UnevaluatedExpr(self, expr):
  86. return expr.replace(re, lambda arg: arg if isinstance(
  87. arg, UnevaluatedExpr) and arg.args[0].is_real else re(arg))
  88. def doprint(self, expr, assign_to=None):
  89. """
  90. Print the expression as code.
  91. Parameters
  92. ----------
  93. expr : Expression
  94. The expression to be printed.
  95. assign_to : Symbol, string, MatrixSymbol, list of strings or Symbols (optional)
  96. If provided, the printed code will set the expression to a variable or multiple variables
  97. with the name or names given in ``assign_to``.
  98. """
  99. from sympy.matrices.expressions.matexpr import MatrixSymbol
  100. from sympy.codegen.ast import CodeBlock, Assignment
  101. def _handle_assign_to(expr, assign_to):
  102. if assign_to is None:
  103. return sympify(expr)
  104. if isinstance(assign_to, (list, tuple)):
  105. if len(expr) != len(assign_to):
  106. raise ValueError('Failed to assign an expression of length {} to {} variables'.format(len(expr), len(assign_to)))
  107. return CodeBlock(*[_handle_assign_to(lhs, rhs) for lhs, rhs in zip(expr, assign_to)])
  108. if isinstance(assign_to, str):
  109. if expr.is_Matrix:
  110. assign_to = MatrixSymbol(assign_to, *expr.shape)
  111. else:
  112. assign_to = Symbol(assign_to)
  113. elif not isinstance(assign_to, Basic):
  114. raise TypeError("{} cannot assign to object of type {}".format(
  115. type(self).__name__, type(assign_to)))
  116. return Assignment(assign_to, expr)
  117. expr = _convert_python_lists(expr)
  118. expr = _handle_assign_to(expr, assign_to)
  119. # Remove re(...) nodes due to UnevaluatedExpr.is_real always is None:
  120. expr = self._handle_UnevaluatedExpr(expr)
  121. # keep a set of expressions that are not strictly translatable to Code
  122. # and number constants that must be declared and initialized
  123. self._not_supported = set()
  124. self._number_symbols = set() # type: tSet[tTuple[Expr, Float]]
  125. lines = self._print(expr).splitlines()
  126. # format the output
  127. if self._settings["human"]:
  128. frontlines = []
  129. if self._not_supported:
  130. frontlines.append(self._get_comment(
  131. "Not supported in {}:".format(self.language)))
  132. for expr in sorted(self._not_supported, key=str):
  133. frontlines.append(self._get_comment(type(expr).__name__))
  134. for name, value in sorted(self._number_symbols, key=str):
  135. frontlines.append(self._declare_number_const(name, value))
  136. lines = frontlines + lines
  137. lines = self._format_code(lines)
  138. result = "\n".join(lines)
  139. else:
  140. lines = self._format_code(lines)
  141. num_syms = {(k, self._print(v)) for k, v in self._number_symbols}
  142. result = (num_syms, self._not_supported, "\n".join(lines))
  143. self._not_supported = set()
  144. self._number_symbols = set()
  145. return result
  146. def _doprint_loops(self, expr, assign_to=None):
  147. # Here we print an expression that contains Indexed objects, they
  148. # correspond to arrays in the generated code. The low-level implementation
  149. # involves looping over array elements and possibly storing results in temporary
  150. # variables or accumulate it in the assign_to object.
  151. if self._settings.get('contract', True):
  152. from sympy.tensor import get_contraction_structure
  153. # Setup loops over non-dummy indices -- all terms need these
  154. indices = self._get_expression_indices(expr, assign_to)
  155. # Setup loops over dummy indices -- each term needs separate treatment
  156. dummies = get_contraction_structure(expr)
  157. else:
  158. indices = []
  159. dummies = {None: (expr,)}
  160. openloop, closeloop = self._get_loop_opening_ending(indices)
  161. # terms with no summations first
  162. if None in dummies:
  163. text = StrPrinter.doprint(self, Add(*dummies[None]))
  164. else:
  165. # If all terms have summations we must initialize array to Zero
  166. text = StrPrinter.doprint(self, 0)
  167. # skip redundant assignments (where lhs == rhs)
  168. lhs_printed = self._print(assign_to)
  169. lines = []
  170. if text != lhs_printed:
  171. lines.extend(openloop)
  172. if assign_to is not None:
  173. text = self._get_statement("%s = %s" % (lhs_printed, text))
  174. lines.append(text)
  175. lines.extend(closeloop)
  176. # then terms with summations
  177. for d in dummies:
  178. if isinstance(d, tuple):
  179. indices = self._sort_optimized(d, expr)
  180. openloop_d, closeloop_d = self._get_loop_opening_ending(
  181. indices)
  182. for term in dummies[d]:
  183. if term in dummies and not ([list(f.keys()) for f in dummies[term]]
  184. == [[None] for f in dummies[term]]):
  185. # If one factor in the term has it's own internal
  186. # contractions, those must be computed first.
  187. # (temporary variables?)
  188. raise NotImplementedError(
  189. "FIXME: no support for contractions in factor yet")
  190. else:
  191. # We need the lhs expression as an accumulator for
  192. # the loops, i.e
  193. #
  194. # for (int d=0; d < dim; d++){
  195. # lhs[] = lhs[] + term[][d]
  196. # } ^.................. the accumulator
  197. #
  198. # We check if the expression already contains the
  199. # lhs, and raise an exception if it does, as that
  200. # syntax is currently undefined. FIXME: What would be
  201. # a good interpretation?
  202. if assign_to is None:
  203. raise AssignmentError(
  204. "need assignment variable for loops")
  205. if term.has(assign_to):
  206. raise ValueError("FIXME: lhs present in rhs,\
  207. this is undefined in CodePrinter")
  208. lines.extend(openloop)
  209. lines.extend(openloop_d)
  210. text = "%s = %s" % (lhs_printed, StrPrinter.doprint(
  211. self, assign_to + term))
  212. lines.append(self._get_statement(text))
  213. lines.extend(closeloop_d)
  214. lines.extend(closeloop)
  215. return "\n".join(lines)
  216. def _get_expression_indices(self, expr, assign_to):
  217. from sympy.tensor import get_indices
  218. rinds, junk = get_indices(expr)
  219. linds, junk = get_indices(assign_to)
  220. # support broadcast of scalar
  221. if linds and not rinds:
  222. rinds = linds
  223. if rinds != linds:
  224. raise ValueError("lhs indices must match non-dummy"
  225. " rhs indices in %s" % expr)
  226. return self._sort_optimized(rinds, assign_to)
  227. def _sort_optimized(self, indices, expr):
  228. from sympy.tensor.indexed import Indexed
  229. if not indices:
  230. return []
  231. # determine optimized loop order by giving a score to each index
  232. # the index with the highest score are put in the innermost loop.
  233. score_table = {}
  234. for i in indices:
  235. score_table[i] = 0
  236. arrays = expr.atoms(Indexed)
  237. for arr in arrays:
  238. for p, ind in enumerate(arr.indices):
  239. try:
  240. score_table[ind] += self._rate_index_position(p)
  241. except KeyError:
  242. pass
  243. return sorted(indices, key=lambda x: score_table[x])
  244. def _rate_index_position(self, p):
  245. """function to calculate score based on position among indices
  246. This method is used to sort loops in an optimized order, see
  247. CodePrinter._sort_optimized()
  248. """
  249. raise NotImplementedError("This function must be implemented by "
  250. "subclass of CodePrinter.")
  251. def _get_statement(self, codestring):
  252. """Formats a codestring with the proper line ending."""
  253. raise NotImplementedError("This function must be implemented by "
  254. "subclass of CodePrinter.")
  255. def _get_comment(self, text):
  256. """Formats a text string as a comment."""
  257. raise NotImplementedError("This function must be implemented by "
  258. "subclass of CodePrinter.")
  259. def _declare_number_const(self, name, value):
  260. """Declare a numeric constant at the top of a function"""
  261. raise NotImplementedError("This function must be implemented by "
  262. "subclass of CodePrinter.")
  263. def _format_code(self, lines):
  264. """Take in a list of lines of code, and format them accordingly.
  265. This may include indenting, wrapping long lines, etc..."""
  266. raise NotImplementedError("This function must be implemented by "
  267. "subclass of CodePrinter.")
  268. def _get_loop_opening_ending(self, indices):
  269. """Returns a tuple (open_lines, close_lines) containing lists
  270. of codelines"""
  271. raise NotImplementedError("This function must be implemented by "
  272. "subclass of CodePrinter.")
  273. def _print_Dummy(self, expr):
  274. if expr.name.startswith('Dummy_'):
  275. return '_' + expr.name
  276. else:
  277. return '%s_%d' % (expr.name, expr.dummy_index)
  278. def _print_CodeBlock(self, expr):
  279. return '\n'.join([self._print(i) for i in expr.args])
  280. def _print_String(self, string):
  281. return str(string)
  282. def _print_QuotedString(self, arg):
  283. return '"%s"' % arg.text
  284. def _print_Comment(self, string):
  285. return self._get_comment(str(string))
  286. def _print_Assignment(self, expr):
  287. from sympy.codegen.ast import Assignment
  288. from sympy.functions.elementary.piecewise import Piecewise
  289. from sympy.matrices.expressions.matexpr import MatrixSymbol
  290. from sympy.tensor.indexed import IndexedBase
  291. lhs = expr.lhs
  292. rhs = expr.rhs
  293. # We special case assignments that take multiple lines
  294. if isinstance(expr.rhs, Piecewise):
  295. # Here we modify Piecewise so each expression is now
  296. # an Assignment, and then continue on the print.
  297. expressions = []
  298. conditions = []
  299. for (e, c) in rhs.args:
  300. expressions.append(Assignment(lhs, e))
  301. conditions.append(c)
  302. temp = Piecewise(*zip(expressions, conditions))
  303. return self._print(temp)
  304. elif isinstance(lhs, MatrixSymbol):
  305. # Here we form an Assignment for each element in the array,
  306. # printing each one.
  307. lines = []
  308. for (i, j) in self._traverse_matrix_indices(lhs):
  309. temp = Assignment(lhs[i, j], rhs[i, j])
  310. code0 = self._print(temp)
  311. lines.append(code0)
  312. return "\n".join(lines)
  313. elif self._settings.get("contract", False) and (lhs.has(IndexedBase) or
  314. rhs.has(IndexedBase)):
  315. # Here we check if there is looping to be done, and if so
  316. # print the required loops.
  317. return self._doprint_loops(rhs, lhs)
  318. else:
  319. lhs_code = self._print(lhs)
  320. rhs_code = self._print(rhs)
  321. return self._get_statement("%s = %s" % (lhs_code, rhs_code))
  322. def _print_AugmentedAssignment(self, expr):
  323. lhs_code = self._print(expr.lhs)
  324. rhs_code = self._print(expr.rhs)
  325. return self._get_statement("{} {} {}".format(
  326. *map(lambda arg: self._print(arg),
  327. [lhs_code, expr.op, rhs_code])))
  328. def _print_FunctionCall(self, expr):
  329. return '%s(%s)' % (
  330. expr.name,
  331. ', '.join(map(lambda arg: self._print(arg),
  332. expr.function_args)))
  333. def _print_Variable(self, expr):
  334. return self._print(expr.symbol)
  335. def _print_Symbol(self, expr):
  336. name = super()._print_Symbol(expr)
  337. if name in self.reserved_words:
  338. if self._settings['error_on_reserved']:
  339. msg = ('This expression includes the symbol "{}" which is a '
  340. 'reserved keyword in this language.')
  341. raise ValueError(msg.format(name))
  342. return name + self._settings['reserved_word_suffix']
  343. else:
  344. return name
  345. def _can_print(self, name):
  346. """ Check if function ``name`` is either a known function or has its own
  347. printing method. Used to check if rewriting is possible."""
  348. return name in self.known_functions or getattr(self, '_print_{}'.format(name), False)
  349. def _print_Function(self, expr):
  350. if expr.func.__name__ in self.known_functions:
  351. cond_func = self.known_functions[expr.func.__name__]
  352. func = None
  353. if isinstance(cond_func, str):
  354. func = cond_func
  355. else:
  356. for cond, func in cond_func:
  357. if cond(*expr.args):
  358. break
  359. if func is not None:
  360. try:
  361. return func(*[self.parenthesize(item, 0) for item in expr.args])
  362. except TypeError:
  363. return "%s(%s)" % (func, self.stringify(expr.args, ", "))
  364. elif hasattr(expr, '_imp_') and isinstance(expr._imp_, Lambda):
  365. # inlined function
  366. return self._print(expr._imp_(*expr.args))
  367. elif expr.func.__name__ in self._rewriteable_functions:
  368. # Simple rewrite to supported function possible
  369. target_f, required_fs = self._rewriteable_functions[expr.func.__name__]
  370. if self._can_print(target_f) and all(self._can_print(f) for f in required_fs):
  371. return self._print(expr.rewrite(target_f))
  372. if expr.is_Function and self._settings.get('allow_unknown_functions', False):
  373. return '%s(%s)' % (self._print(expr.func), ', '.join(map(self._print, expr.args)))
  374. else:
  375. return self._print_not_supported(expr)
  376. _print_Expr = _print_Function
  377. # Don't inherit the str-printer method for Heaviside to the code printers
  378. _print_Heaviside = None
  379. def _print_NumberSymbol(self, expr):
  380. if self._settings.get("inline", False):
  381. return self._print(Float(expr.evalf(self._settings["precision"])))
  382. else:
  383. # A Number symbol that is not implemented here or with _printmethod
  384. # is registered and evaluated
  385. self._number_symbols.add((expr,
  386. Float(expr.evalf(self._settings["precision"]))))
  387. return str(expr)
  388. def _print_Catalan(self, expr):
  389. return self._print_NumberSymbol(expr)
  390. def _print_EulerGamma(self, expr):
  391. return self._print_NumberSymbol(expr)
  392. def _print_GoldenRatio(self, expr):
  393. return self._print_NumberSymbol(expr)
  394. def _print_TribonacciConstant(self, expr):
  395. return self._print_NumberSymbol(expr)
  396. def _print_Exp1(self, expr):
  397. return self._print_NumberSymbol(expr)
  398. def _print_Pi(self, expr):
  399. return self._print_NumberSymbol(expr)
  400. def _print_And(self, expr):
  401. PREC = precedence(expr)
  402. return (" %s " % self._operators['and']).join(self.parenthesize(a, PREC)
  403. for a in sorted(expr.args, key=default_sort_key))
  404. def _print_Or(self, expr):
  405. PREC = precedence(expr)
  406. return (" %s " % self._operators['or']).join(self.parenthesize(a, PREC)
  407. for a in sorted(expr.args, key=default_sort_key))
  408. def _print_Xor(self, expr):
  409. if self._operators.get('xor') is None:
  410. return self._print(expr.to_nnf())
  411. PREC = precedence(expr)
  412. return (" %s " % self._operators['xor']).join(self.parenthesize(a, PREC)
  413. for a in expr.args)
  414. def _print_Equivalent(self, expr):
  415. if self._operators.get('equivalent') is None:
  416. return self._print(expr.to_nnf())
  417. PREC = precedence(expr)
  418. return (" %s " % self._operators['equivalent']).join(self.parenthesize(a, PREC)
  419. for a in expr.args)
  420. def _print_Not(self, expr):
  421. PREC = precedence(expr)
  422. return self._operators['not'] + self.parenthesize(expr.args[0], PREC)
  423. def _print_BooleanFunction(self, expr):
  424. return self._print(expr.to_nnf())
  425. def _print_Mul(self, expr):
  426. prec = precedence(expr)
  427. c, e = expr.as_coeff_Mul()
  428. if c < 0:
  429. expr = _keep_coeff(-c, e)
  430. sign = "-"
  431. else:
  432. sign = ""
  433. a = [] # items in the numerator
  434. b = [] # items that are in the denominator (if any)
  435. pow_paren = [] # Will collect all pow with more than one base element and exp = -1
  436. if self.order not in ('old', 'none'):
  437. args = expr.as_ordered_factors()
  438. else:
  439. # use make_args in case expr was something like -x -> x
  440. args = Mul.make_args(expr)
  441. # Gather args for numerator/denominator
  442. for item in args:
  443. if item.is_commutative and item.is_Pow and item.exp.is_Rational and item.exp.is_negative:
  444. if item.exp != -1:
  445. b.append(Pow(item.base, -item.exp, evaluate=False))
  446. else:
  447. if len(item.args[0].args) != 1 and isinstance(item.base, Mul): # To avoid situations like #14160
  448. pow_paren.append(item)
  449. b.append(Pow(item.base, -item.exp))
  450. else:
  451. a.append(item)
  452. a = a or [S.One]
  453. if len(a) == 1 and sign == "-":
  454. # Unary minus does not have a SymPy class, and hence there's no
  455. # precedence weight associated with it, Python's unary minus has
  456. # an operator precedence between multiplication and exponentiation,
  457. # so we use this to compute a weight.
  458. a_str = [self.parenthesize(a[0], 0.5*(PRECEDENCE["Pow"]+PRECEDENCE["Mul"]))]
  459. else:
  460. a_str = [self.parenthesize(x, prec) for x in a]
  461. b_str = [self.parenthesize(x, prec) for x in b]
  462. # To parenthesize Pow with exp = -1 and having more than one Symbol
  463. for item in pow_paren:
  464. if item.base in b:
  465. b_str[b.index(item.base)] = "(%s)" % b_str[b.index(item.base)]
  466. if not b:
  467. return sign + '*'.join(a_str)
  468. elif len(b) == 1:
  469. return sign + '*'.join(a_str) + "/" + b_str[0]
  470. else:
  471. return sign + '*'.join(a_str) + "/(%s)" % '*'.join(b_str)
  472. def _print_not_supported(self, expr):
  473. try:
  474. self._not_supported.add(expr)
  475. except TypeError:
  476. # not hashable
  477. pass
  478. return self.emptyPrinter(expr)
  479. # The following can not be simply translated into C or Fortran
  480. _print_Basic = _print_not_supported
  481. _print_ComplexInfinity = _print_not_supported
  482. _print_Derivative = _print_not_supported
  483. _print_ExprCondPair = _print_not_supported
  484. _print_GeometryEntity = _print_not_supported
  485. _print_Infinity = _print_not_supported
  486. _print_Integral = _print_not_supported
  487. _print_Interval = _print_not_supported
  488. _print_AccumulationBounds = _print_not_supported
  489. _print_Limit = _print_not_supported
  490. _print_MatrixBase = _print_not_supported
  491. _print_DeferredVector = _print_not_supported
  492. _print_NaN = _print_not_supported
  493. _print_NegativeInfinity = _print_not_supported
  494. _print_Order = _print_not_supported
  495. _print_RootOf = _print_not_supported
  496. _print_RootsOf = _print_not_supported
  497. _print_RootSum = _print_not_supported
  498. _print_Uniform = _print_not_supported
  499. _print_Unit = _print_not_supported
  500. _print_Wild = _print_not_supported
  501. _print_WildFunction = _print_not_supported
  502. _print_Relational = _print_not_supported
  503. # Code printer functions. These are included in this file so that they can be
  504. # imported in the top-level __init__.py without importing the sympy.codegen
  505. # module.
  506. def ccode(expr, assign_to=None, standard='c99', **settings):
  507. """Converts an expr to a string of c code
  508. Parameters
  509. ==========
  510. expr : Expr
  511. A SymPy expression to be converted.
  512. assign_to : optional
  513. When given, the argument is used as the name of the variable to which
  514. the expression is assigned. Can be a string, ``Symbol``,
  515. ``MatrixSymbol``, or ``Indexed`` type. This is helpful in case of
  516. line-wrapping, or for expressions that generate multi-line statements.
  517. standard : str, optional
  518. String specifying the standard. If your compiler supports a more modern
  519. standard you may set this to 'c99' to allow the printer to use more math
  520. functions. [default='c89'].
  521. precision : integer, optional
  522. The precision for numbers such as pi [default=17].
  523. user_functions : dict, optional
  524. A dictionary where the keys are string representations of either
  525. ``FunctionClass`` or ``UndefinedFunction`` instances and the values
  526. are their desired C string representations. Alternatively, the
  527. dictionary value can be a list of tuples i.e. [(argument_test,
  528. cfunction_string)] or [(argument_test, cfunction_formater)]. See below
  529. for examples.
  530. dereference : iterable, optional
  531. An iterable of symbols that should be dereferenced in the printed code
  532. expression. These would be values passed by address to the function.
  533. For example, if ``dereference=[a]``, the resulting code would print
  534. ``(*a)`` instead of ``a``.
  535. human : bool, optional
  536. If True, the result is a single string that may contain some constant
  537. declarations for the number symbols. If False, the same information is
  538. returned in a tuple of (symbols_to_declare, not_supported_functions,
  539. code_text). [default=True].
  540. contract: bool, optional
  541. If True, ``Indexed`` instances are assumed to obey tensor contraction
  542. rules and the corresponding nested loops over indices are generated.
  543. Setting contract=False will not generate loops, instead the user is
  544. responsible to provide values for the indices in the code.
  545. [default=True].
  546. Examples
  547. ========
  548. >>> from sympy import ccode, symbols, Rational, sin, ceiling, Abs, Function
  549. >>> x, tau = symbols("x, tau")
  550. >>> expr = (2*tau)**Rational(7, 2)
  551. >>> ccode(expr)
  552. '8*M_SQRT2*pow(tau, 7.0/2.0)'
  553. >>> ccode(expr, math_macros={})
  554. '8*sqrt(2)*pow(tau, 7.0/2.0)'
  555. >>> ccode(sin(x), assign_to="s")
  556. 's = sin(x);'
  557. >>> from sympy.codegen.ast import real, float80
  558. >>> ccode(expr, type_aliases={real: float80})
  559. '8*M_SQRT2l*powl(tau, 7.0L/2.0L)'
  560. Simple custom printing can be defined for certain types by passing a
  561. dictionary of {"type" : "function"} to the ``user_functions`` kwarg.
  562. Alternatively, the dictionary value can be a list of tuples i.e.
  563. [(argument_test, cfunction_string)].
  564. >>> custom_functions = {
  565. ... "ceiling": "CEIL",
  566. ... "Abs": [(lambda x: not x.is_integer, "fabs"),
  567. ... (lambda x: x.is_integer, "ABS")],
  568. ... "func": "f"
  569. ... }
  570. >>> func = Function('func')
  571. >>> ccode(func(Abs(x) + ceiling(x)), standard='C89', user_functions=custom_functions)
  572. 'f(fabs(x) + CEIL(x))'
  573. or if the C-function takes a subset of the original arguments:
  574. >>> ccode(2**x + 3**x, standard='C99', user_functions={'Pow': [
  575. ... (lambda b, e: b == 2, lambda b, e: 'exp2(%s)' % e),
  576. ... (lambda b, e: b != 2, 'pow')]})
  577. 'exp2(x) + pow(3, x)'
  578. ``Piecewise`` expressions are converted into conditionals. If an
  579. ``assign_to`` variable is provided an if statement is created, otherwise
  580. the ternary operator is used. Note that if the ``Piecewise`` lacks a
  581. default term, represented by ``(expr, True)`` then an error will be thrown.
  582. This is to prevent generating an expression that may not evaluate to
  583. anything.
  584. >>> from sympy import Piecewise
  585. >>> expr = Piecewise((x + 1, x > 0), (x, True))
  586. >>> print(ccode(expr, tau, standard='C89'))
  587. if (x > 0) {
  588. tau = x + 1;
  589. }
  590. else {
  591. tau = x;
  592. }
  593. Support for loops is provided through ``Indexed`` types. With
  594. ``contract=True`` these expressions will be turned into loops, whereas
  595. ``contract=False`` will just print the assignment expression that should be
  596. looped over:
  597. >>> from sympy import Eq, IndexedBase, Idx
  598. >>> len_y = 5
  599. >>> y = IndexedBase('y', shape=(len_y,))
  600. >>> t = IndexedBase('t', shape=(len_y,))
  601. >>> Dy = IndexedBase('Dy', shape=(len_y-1,))
  602. >>> i = Idx('i', len_y-1)
  603. >>> e=Eq(Dy[i], (y[i+1]-y[i])/(t[i+1]-t[i]))
  604. >>> ccode(e.rhs, assign_to=e.lhs, contract=False, standard='C89')
  605. 'Dy[i] = (y[i + 1] - y[i])/(t[i + 1] - t[i]);'
  606. Matrices are also supported, but a ``MatrixSymbol`` of the same dimensions
  607. must be provided to ``assign_to``. Note that any expression that can be
  608. generated normally can also exist inside a Matrix:
  609. >>> from sympy import Matrix, MatrixSymbol
  610. >>> mat = Matrix([x**2, Piecewise((x + 1, x > 0), (x, True)), sin(x)])
  611. >>> A = MatrixSymbol('A', 3, 1)
  612. >>> print(ccode(mat, A, standard='C89'))
  613. A[0] = pow(x, 2);
  614. if (x > 0) {
  615. A[1] = x + 1;
  616. }
  617. else {
  618. A[1] = x;
  619. }
  620. A[2] = sin(x);
  621. """
  622. from sympy.printing.c import c_code_printers
  623. return c_code_printers[standard.lower()](settings).doprint(expr, assign_to)
  624. def print_ccode(expr, **settings):
  625. """Prints C representation of the given expression."""
  626. print(ccode(expr, **settings))
  627. def fcode(expr, assign_to=None, **settings):
  628. """Converts an expr to a string of fortran code
  629. Parameters
  630. ==========
  631. expr : Expr
  632. A SymPy expression to be converted.
  633. assign_to : optional
  634. When given, the argument is used as the name of the variable to which
  635. the expression is assigned. Can be a string, ``Symbol``,
  636. ``MatrixSymbol``, or ``Indexed`` type. This is helpful in case of
  637. line-wrapping, or for expressions that generate multi-line statements.
  638. precision : integer, optional
  639. DEPRECATED. Use type_mappings instead. The precision for numbers such
  640. as pi [default=17].
  641. user_functions : dict, optional
  642. A dictionary where keys are ``FunctionClass`` instances and values are
  643. their string representations. Alternatively, the dictionary value can
  644. be a list of tuples i.e. [(argument_test, cfunction_string)]. See below
  645. for examples.
  646. human : bool, optional
  647. If True, the result is a single string that may contain some constant
  648. declarations for the number symbols. If False, the same information is
  649. returned in a tuple of (symbols_to_declare, not_supported_functions,
  650. code_text). [default=True].
  651. contract: bool, optional
  652. If True, ``Indexed`` instances are assumed to obey tensor contraction
  653. rules and the corresponding nested loops over indices are generated.
  654. Setting contract=False will not generate loops, instead the user is
  655. responsible to provide values for the indices in the code.
  656. [default=True].
  657. source_format : optional
  658. The source format can be either 'fixed' or 'free'. [default='fixed']
  659. standard : integer, optional
  660. The Fortran standard to be followed. This is specified as an integer.
  661. Acceptable standards are 66, 77, 90, 95, 2003, and 2008. Default is 77.
  662. Note that currently the only distinction internally is between
  663. standards before 95, and those 95 and after. This may change later as
  664. more features are added.
  665. name_mangling : bool, optional
  666. If True, then the variables that would become identical in
  667. case-insensitive Fortran are mangled by appending different number
  668. of ``_`` at the end. If False, SymPy Will not interfere with naming of
  669. variables. [default=True]
  670. Examples
  671. ========
  672. >>> from sympy import fcode, symbols, Rational, sin, ceiling, floor
  673. >>> x, tau = symbols("x, tau")
  674. >>> fcode((2*tau)**Rational(7, 2))
  675. ' 8*sqrt(2.0d0)*tau**(7.0d0/2.0d0)'
  676. >>> fcode(sin(x), assign_to="s")
  677. ' s = sin(x)'
  678. Custom printing can be defined for certain types by passing a dictionary of
  679. "type" : "function" to the ``user_functions`` kwarg. Alternatively, the
  680. dictionary value can be a list of tuples i.e. [(argument_test,
  681. cfunction_string)].
  682. >>> custom_functions = {
  683. ... "ceiling": "CEIL",
  684. ... "floor": [(lambda x: not x.is_integer, "FLOOR1"),
  685. ... (lambda x: x.is_integer, "FLOOR2")]
  686. ... }
  687. >>> fcode(floor(x) + ceiling(x), user_functions=custom_functions)
  688. ' CEIL(x) + FLOOR1(x)'
  689. ``Piecewise`` expressions are converted into conditionals. If an
  690. ``assign_to`` variable is provided an if statement is created, otherwise
  691. the ternary operator is used. Note that if the ``Piecewise`` lacks a
  692. default term, represented by ``(expr, True)`` then an error will be thrown.
  693. This is to prevent generating an expression that may not evaluate to
  694. anything.
  695. >>> from sympy import Piecewise
  696. >>> expr = Piecewise((x + 1, x > 0), (x, True))
  697. >>> print(fcode(expr, tau))
  698. if (x > 0) then
  699. tau = x + 1
  700. else
  701. tau = x
  702. end if
  703. Support for loops is provided through ``Indexed`` types. With
  704. ``contract=True`` these expressions will be turned into loops, whereas
  705. ``contract=False`` will just print the assignment expression that should be
  706. looped over:
  707. >>> from sympy import Eq, IndexedBase, Idx
  708. >>> len_y = 5
  709. >>> y = IndexedBase('y', shape=(len_y,))
  710. >>> t = IndexedBase('t', shape=(len_y,))
  711. >>> Dy = IndexedBase('Dy', shape=(len_y-1,))
  712. >>> i = Idx('i', len_y-1)
  713. >>> e=Eq(Dy[i], (y[i+1]-y[i])/(t[i+1]-t[i]))
  714. >>> fcode(e.rhs, assign_to=e.lhs, contract=False)
  715. ' Dy(i) = (y(i + 1) - y(i))/(t(i + 1) - t(i))'
  716. Matrices are also supported, but a ``MatrixSymbol`` of the same dimensions
  717. must be provided to ``assign_to``. Note that any expression that can be
  718. generated normally can also exist inside a Matrix:
  719. >>> from sympy import Matrix, MatrixSymbol
  720. >>> mat = Matrix([x**2, Piecewise((x + 1, x > 0), (x, True)), sin(x)])
  721. >>> A = MatrixSymbol('A', 3, 1)
  722. >>> print(fcode(mat, A))
  723. A(1, 1) = x**2
  724. if (x > 0) then
  725. A(2, 1) = x + 1
  726. else
  727. A(2, 1) = x
  728. end if
  729. A(3, 1) = sin(x)
  730. """
  731. from sympy.printing.fortran import FCodePrinter
  732. return FCodePrinter(settings).doprint(expr, assign_to)
  733. def print_fcode(expr, **settings):
  734. """Prints the Fortran representation of the given expression.
  735. See fcode for the meaning of the optional arguments.
  736. """
  737. print(fcode(expr, **settings))
  738. def cxxcode(expr, assign_to=None, standard='c++11', **settings):
  739. """ C++ equivalent of :func:`~.ccode`. """
  740. from sympy.printing.cxx import cxx_code_printers
  741. return cxx_code_printers[standard.lower()](settings).doprint(expr, assign_to)