glsl.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548
  1. from __future__ import annotations
  2. from sympy.core import Basic, S
  3. from sympy.core.function import Lambda
  4. from sympy.core.numbers import equal_valued
  5. from sympy.printing.codeprinter import CodePrinter
  6. from sympy.printing.precedence import precedence
  7. from functools import reduce
  8. known_functions = {
  9. 'Abs': 'abs',
  10. 'sin': 'sin',
  11. 'cos': 'cos',
  12. 'tan': 'tan',
  13. 'acos': 'acos',
  14. 'asin': 'asin',
  15. 'atan': 'atan',
  16. 'atan2': 'atan',
  17. 'ceiling': 'ceil',
  18. 'floor': 'floor',
  19. 'sign': 'sign',
  20. 'exp': 'exp',
  21. 'log': 'log',
  22. 'add': 'add',
  23. 'sub': 'sub',
  24. 'mul': 'mul',
  25. 'pow': 'pow'
  26. }
  27. class GLSLPrinter(CodePrinter):
  28. """
  29. Rudimentary, generic GLSL printing tools.
  30. Additional settings:
  31. 'use_operators': Boolean (should the printer use operators for +,-,*, or functions?)
  32. """
  33. _not_supported: set[Basic] = set()
  34. printmethod = "_glsl"
  35. language = "GLSL"
  36. _default_settings = dict(CodePrinter._default_settings, **{
  37. 'use_operators': True,
  38. 'zero': 0,
  39. 'mat_nested': False,
  40. 'mat_separator': ',\n',
  41. 'mat_transpose': False,
  42. 'array_type': 'float',
  43. 'glsl_types': True,
  44. 'precision': 9,
  45. 'user_functions': {},
  46. 'contract': True,
  47. })
  48. def __init__(self, settings={}):
  49. CodePrinter.__init__(self, settings)
  50. self.known_functions = dict(known_functions)
  51. userfuncs = settings.get('user_functions', {})
  52. self.known_functions.update(userfuncs)
  53. def _rate_index_position(self, p):
  54. return p*5
  55. def _get_statement(self, codestring):
  56. return "%s;" % codestring
  57. def _get_comment(self, text):
  58. return "// {}".format(text)
  59. def _declare_number_const(self, name, value):
  60. return "float {} = {};".format(name, value)
  61. def _format_code(self, lines):
  62. return self.indent_code(lines)
  63. def indent_code(self, code):
  64. """Accepts a string of code or a list of code lines"""
  65. if isinstance(code, str):
  66. code_lines = self.indent_code(code.splitlines(True))
  67. return ''.join(code_lines)
  68. tab = " "
  69. inc_token = ('{', '(', '{\n', '(\n')
  70. dec_token = ('}', ')')
  71. code = [line.lstrip(' \t') for line in code]
  72. increase = [int(any(map(line.endswith, inc_token))) for line in code]
  73. decrease = [int(any(map(line.startswith, dec_token))) for line in code]
  74. pretty = []
  75. level = 0
  76. for n, line in enumerate(code):
  77. if line in ('', '\n'):
  78. pretty.append(line)
  79. continue
  80. level -= decrease[n]
  81. pretty.append("%s%s" % (tab*level, line))
  82. level += increase[n]
  83. return pretty
  84. def _print_MatrixBase(self, mat):
  85. mat_separator = self._settings['mat_separator']
  86. mat_transpose = self._settings['mat_transpose']
  87. column_vector = (mat.rows == 1) if mat_transpose else (mat.cols == 1)
  88. A = mat.transpose() if mat_transpose != column_vector else mat
  89. glsl_types = self._settings['glsl_types']
  90. array_type = self._settings['array_type']
  91. array_size = A.cols*A.rows
  92. array_constructor = "{}[{}]".format(array_type, array_size)
  93. if A.cols == 1:
  94. return self._print(A[0])
  95. if A.rows <= 4 and A.cols <= 4 and glsl_types:
  96. if A.rows == 1:
  97. return "vec{}{}".format(
  98. A.cols, A.table(self,rowstart='(',rowend=')')
  99. )
  100. elif A.rows == A.cols:
  101. return "mat{}({})".format(
  102. A.rows, A.table(self,rowsep=', ',
  103. rowstart='',rowend='')
  104. )
  105. else:
  106. return "mat{}x{}({})".format(
  107. A.cols, A.rows,
  108. A.table(self,rowsep=', ',
  109. rowstart='',rowend='')
  110. )
  111. elif S.One in A.shape:
  112. return "{}({})".format(
  113. array_constructor,
  114. A.table(self,rowsep=mat_separator,rowstart='',rowend='')
  115. )
  116. elif not self._settings['mat_nested']:
  117. return "{}(\n{}\n) /* a {}x{} matrix */".format(
  118. array_constructor,
  119. A.table(self,rowsep=mat_separator,rowstart='',rowend=''),
  120. A.rows, A.cols
  121. )
  122. elif self._settings['mat_nested']:
  123. return "{}[{}][{}](\n{}\n)".format(
  124. array_type, A.rows, A.cols,
  125. A.table(self,rowsep=mat_separator,rowstart='float[](',rowend=')')
  126. )
  127. def _print_SparseRepMatrix(self, mat):
  128. # do not allow sparse matrices to be made dense
  129. return self._print_not_supported(mat)
  130. def _traverse_matrix_indices(self, mat):
  131. mat_transpose = self._settings['mat_transpose']
  132. if mat_transpose:
  133. rows,cols = mat.shape
  134. else:
  135. cols,rows = mat.shape
  136. return ((i, j) for i in range(cols) for j in range(rows))
  137. def _print_MatrixElement(self, expr):
  138. # print('begin _print_MatrixElement')
  139. nest = self._settings['mat_nested']
  140. glsl_types = self._settings['glsl_types']
  141. mat_transpose = self._settings['mat_transpose']
  142. if mat_transpose:
  143. cols,rows = expr.parent.shape
  144. i,j = expr.j,expr.i
  145. else:
  146. rows,cols = expr.parent.shape
  147. i,j = expr.i,expr.j
  148. pnt = self._print(expr.parent)
  149. if glsl_types and ((rows <= 4 and cols <=4) or nest):
  150. return "{}[{}][{}]".format(pnt, i, j)
  151. else:
  152. return "{}[{}]".format(pnt, i + j*rows)
  153. def _print_list(self, expr):
  154. l = ', '.join(self._print(item) for item in expr)
  155. glsl_types = self._settings['glsl_types']
  156. array_type = self._settings['array_type']
  157. array_size = len(expr)
  158. array_constructor = '{}[{}]'.format(array_type, array_size)
  159. if array_size <= 4 and glsl_types:
  160. return 'vec{}({})'.format(array_size, l)
  161. else:
  162. return '{}({})'.format(array_constructor, l)
  163. _print_tuple = _print_list
  164. _print_Tuple = _print_list
  165. def _get_loop_opening_ending(self, indices):
  166. open_lines = []
  167. close_lines = []
  168. loopstart = "for (int %(varble)s=%(start)s; %(varble)s<%(end)s; %(varble)s++){"
  169. for i in indices:
  170. # GLSL arrays start at 0 and end at dimension-1
  171. open_lines.append(loopstart % {
  172. 'varble': self._print(i.label),
  173. 'start': self._print(i.lower),
  174. 'end': self._print(i.upper + 1)})
  175. close_lines.append("}")
  176. return open_lines, close_lines
  177. def _print_Function_with_args(self, func, func_args):
  178. if func in self.known_functions:
  179. cond_func = self.known_functions[func]
  180. func = None
  181. if isinstance(cond_func, str):
  182. func = cond_func
  183. else:
  184. for cond, func in cond_func:
  185. if cond(func_args):
  186. break
  187. if func is not None:
  188. try:
  189. return func(*[self.parenthesize(item, 0) for item in func_args])
  190. except TypeError:
  191. return '{}({})'.format(func, self.stringify(func_args, ", "))
  192. elif isinstance(func, Lambda):
  193. # inlined function
  194. return self._print(func(*func_args))
  195. else:
  196. return self._print_not_supported(func)
  197. def _print_Piecewise(self, expr):
  198. from sympy.codegen.ast import Assignment
  199. if expr.args[-1].cond != True:
  200. # We need the last conditional to be a True, otherwise the resulting
  201. # function may not return a result.
  202. raise ValueError("All Piecewise expressions must contain an "
  203. "(expr, True) statement to be used as a default "
  204. "condition. Without one, the generated "
  205. "expression may not evaluate to anything under "
  206. "some condition.")
  207. lines = []
  208. if expr.has(Assignment):
  209. for i, (e, c) in enumerate(expr.args):
  210. if i == 0:
  211. lines.append("if (%s) {" % self._print(c))
  212. elif i == len(expr.args) - 1 and c == True:
  213. lines.append("else {")
  214. else:
  215. lines.append("else if (%s) {" % self._print(c))
  216. code0 = self._print(e)
  217. lines.append(code0)
  218. lines.append("}")
  219. return "\n".join(lines)
  220. else:
  221. # The piecewise was used in an expression, need to do inline
  222. # operators. This has the downside that inline operators will
  223. # not work for statements that span multiple lines (Matrix or
  224. # Indexed expressions).
  225. ecpairs = ["((%s) ? (\n%s\n)\n" % (self._print(c),
  226. self._print(e))
  227. for e, c in expr.args[:-1]]
  228. last_line = ": (\n%s\n)" % self._print(expr.args[-1].expr)
  229. return ": ".join(ecpairs) + last_line + " ".join([")"*len(ecpairs)])
  230. def _print_Indexed(self, expr):
  231. # calculate index for 1d array
  232. dims = expr.shape
  233. elem = S.Zero
  234. offset = S.One
  235. for i in reversed(range(expr.rank)):
  236. elem += expr.indices[i]*offset
  237. offset *= dims[i]
  238. return "{}[{}]".format(
  239. self._print(expr.base.label),
  240. self._print(elem)
  241. )
  242. def _print_Pow(self, expr):
  243. PREC = precedence(expr)
  244. if equal_valued(expr.exp, -1):
  245. return '1.0/%s' % (self.parenthesize(expr.base, PREC))
  246. elif equal_valued(expr.exp, 0.5):
  247. return 'sqrt(%s)' % self._print(expr.base)
  248. else:
  249. try:
  250. e = self._print(float(expr.exp))
  251. except TypeError:
  252. e = self._print(expr.exp)
  253. return self._print_Function_with_args('pow', (
  254. self._print(expr.base),
  255. e
  256. ))
  257. def _print_int(self, expr):
  258. return str(float(expr))
  259. def _print_Rational(self, expr):
  260. return "{}.0/{}.0".format(expr.p, expr.q)
  261. def _print_Relational(self, expr):
  262. lhs_code = self._print(expr.lhs)
  263. rhs_code = self._print(expr.rhs)
  264. op = expr.rel_op
  265. return "{} {} {}".format(lhs_code, op, rhs_code)
  266. def _print_Add(self, expr, order=None):
  267. if self._settings['use_operators']:
  268. return CodePrinter._print_Add(self, expr, order=order)
  269. terms = expr.as_ordered_terms()
  270. def partition(p,l):
  271. return reduce(lambda x, y: (x[0]+[y], x[1]) if p(y) else (x[0], x[1]+[y]), l, ([], []))
  272. def add(a,b):
  273. return self._print_Function_with_args('add', (a, b))
  274. # return self.known_functions['add']+'(%s, %s)' % (a,b)
  275. neg, pos = partition(lambda arg: arg.could_extract_minus_sign(), terms)
  276. if pos:
  277. s = pos = reduce(lambda a,b: add(a,b), (self._print(t) for t in pos))
  278. else:
  279. s = pos = self._print(self._settings['zero'])
  280. if neg:
  281. # sum the absolute values of the negative terms
  282. neg = reduce(lambda a,b: add(a,b), (self._print(-n) for n in neg))
  283. # then subtract them from the positive terms
  284. s = self._print_Function_with_args('sub', (pos,neg))
  285. # s = self.known_functions['sub']+'(%s, %s)' % (pos,neg)
  286. return s
  287. def _print_Mul(self, expr, **kwargs):
  288. if self._settings['use_operators']:
  289. return CodePrinter._print_Mul(self, expr, **kwargs)
  290. terms = expr.as_ordered_factors()
  291. def mul(a,b):
  292. # return self.known_functions['mul']+'(%s, %s)' % (a,b)
  293. return self._print_Function_with_args('mul', (a,b))
  294. s = reduce(lambda a,b: mul(a,b), (self._print(t) for t in terms))
  295. return s
  296. def glsl_code(expr,assign_to=None,**settings):
  297. """Converts an expr to a string of GLSL code
  298. Parameters
  299. ==========
  300. expr : Expr
  301. A SymPy expression to be converted.
  302. assign_to : optional
  303. When given, the argument is used for naming the variable or variables
  304. to which the expression is assigned. Can be a string, ``Symbol``,
  305. ``MatrixSymbol`` or ``Indexed`` type object. In cases where ``expr``
  306. would be printed as an array, a list of string or ``Symbol`` objects
  307. can also be passed.
  308. This is helpful in case of line-wrapping, or for expressions that
  309. generate multi-line statements. It can also be used to spread an array-like
  310. expression into multiple assignments.
  311. use_operators: bool, optional
  312. If set to False, then *,/,+,- operators will be replaced with functions
  313. mul, add, and sub, which must be implemented by the user, e.g. for
  314. implementing non-standard rings or emulated quad/octal precision.
  315. [default=True]
  316. glsl_types: bool, optional
  317. Set this argument to ``False`` in order to avoid using the ``vec`` and ``mat``
  318. types. The printer will instead use arrays (or nested arrays).
  319. [default=True]
  320. mat_nested: bool, optional
  321. GLSL version 4.3 and above support nested arrays (arrays of arrays). Set this to ``True``
  322. to render matrices as nested arrays.
  323. [default=False]
  324. mat_separator: str, optional
  325. By default, matrices are rendered with newlines using this separator,
  326. making them easier to read, but less compact. By removing the newline
  327. this option can be used to make them more vertically compact.
  328. [default=',\n']
  329. mat_transpose: bool, optional
  330. GLSL's matrix multiplication implementation assumes column-major indexing.
  331. By default, this printer ignores that convention. Setting this option to
  332. ``True`` transposes all matrix output.
  333. [default=False]
  334. array_type: str, optional
  335. The GLSL array constructor type.
  336. [default='float']
  337. precision : integer, optional
  338. The precision for numbers such as pi [default=15].
  339. user_functions : dict, optional
  340. A dictionary where keys are ``FunctionClass`` instances and values are
  341. their string representations. Alternatively, the dictionary value can
  342. be a list of tuples i.e. [(argument_test, js_function_string)]. See
  343. below for examples.
  344. human : bool, optional
  345. If True, the result is a single string that may contain some constant
  346. declarations for the number symbols. If False, the same information is
  347. returned in a tuple of (symbols_to_declare, not_supported_functions,
  348. code_text). [default=True].
  349. contract: bool, optional
  350. If True, ``Indexed`` instances are assumed to obey tensor contraction
  351. rules and the corresponding nested loops over indices are generated.
  352. Setting contract=False will not generate loops, instead the user is
  353. responsible to provide values for the indices in the code.
  354. [default=True].
  355. Examples
  356. ========
  357. >>> from sympy import glsl_code, symbols, Rational, sin, ceiling, Abs
  358. >>> x, tau = symbols("x, tau")
  359. >>> glsl_code((2*tau)**Rational(7, 2))
  360. '8*sqrt(2)*pow(tau, 3.5)'
  361. >>> glsl_code(sin(x), assign_to="float y")
  362. 'float y = sin(x);'
  363. Various GLSL types are supported:
  364. >>> from sympy import Matrix, glsl_code
  365. >>> glsl_code(Matrix([1,2,3]))
  366. 'vec3(1, 2, 3)'
  367. >>> glsl_code(Matrix([[1, 2],[3, 4]]))
  368. 'mat2(1, 2, 3, 4)'
  369. Pass ``mat_transpose = True`` to switch to column-major indexing:
  370. >>> glsl_code(Matrix([[1, 2],[3, 4]]), mat_transpose = True)
  371. 'mat2(1, 3, 2, 4)'
  372. By default, larger matrices get collapsed into float arrays:
  373. >>> print(glsl_code( Matrix([[1,2,3,4,5],[6,7,8,9,10]]) ))
  374. float[10](
  375. 1, 2, 3, 4, 5,
  376. 6, 7, 8, 9, 10
  377. ) /* a 2x5 matrix */
  378. The type of array constructor used to print GLSL arrays can be controlled
  379. via the ``array_type`` parameter:
  380. >>> glsl_code(Matrix([1,2,3,4,5]), array_type='int')
  381. 'int[5](1, 2, 3, 4, 5)'
  382. Passing a list of strings or ``symbols`` to the ``assign_to`` parameter will yield
  383. a multi-line assignment for each item in an array-like expression:
  384. >>> x_struct_members = symbols('x.a x.b x.c x.d')
  385. >>> print(glsl_code(Matrix([1,2,3,4]), assign_to=x_struct_members))
  386. x.a = 1;
  387. x.b = 2;
  388. x.c = 3;
  389. x.d = 4;
  390. This could be useful in cases where it's desirable to modify members of a
  391. GLSL ``Struct``. It could also be used to spread items from an array-like
  392. expression into various miscellaneous assignments:
  393. >>> misc_assignments = ('x[0]', 'x[1]', 'float y', 'float z')
  394. >>> print(glsl_code(Matrix([1,2,3,4]), assign_to=misc_assignments))
  395. x[0] = 1;
  396. x[1] = 2;
  397. float y = 3;
  398. float z = 4;
  399. Passing ``mat_nested = True`` instead prints out nested float arrays, which are
  400. supported in GLSL 4.3 and above.
  401. >>> mat = Matrix([
  402. ... [ 0, 1, 2],
  403. ... [ 3, 4, 5],
  404. ... [ 6, 7, 8],
  405. ... [ 9, 10, 11],
  406. ... [12, 13, 14]])
  407. >>> print(glsl_code( mat, mat_nested = True ))
  408. float[5][3](
  409. float[]( 0, 1, 2),
  410. float[]( 3, 4, 5),
  411. float[]( 6, 7, 8),
  412. float[]( 9, 10, 11),
  413. float[](12, 13, 14)
  414. )
  415. Custom printing can be defined for certain types by passing a dictionary of
  416. "type" : "function" to the ``user_functions`` kwarg. Alternatively, the
  417. dictionary value can be a list of tuples i.e. [(argument_test,
  418. js_function_string)].
  419. >>> custom_functions = {
  420. ... "ceiling": "CEIL",
  421. ... "Abs": [(lambda x: not x.is_integer, "fabs"),
  422. ... (lambda x: x.is_integer, "ABS")]
  423. ... }
  424. >>> glsl_code(Abs(x) + ceiling(x), user_functions=custom_functions)
  425. 'fabs(x) + CEIL(x)'
  426. If further control is needed, addition, subtraction, multiplication and
  427. division operators can be replaced with ``add``, ``sub``, and ``mul``
  428. functions. This is done by passing ``use_operators = False``:
  429. >>> x,y,z = symbols('x,y,z')
  430. >>> glsl_code(x*(y+z), use_operators = False)
  431. 'mul(x, add(y, z))'
  432. >>> glsl_code(x*(y+z*(x-y)**z), use_operators = False)
  433. 'mul(x, add(y, mul(z, pow(sub(x, y), z))))'
  434. ``Piecewise`` expressions are converted into conditionals. If an
  435. ``assign_to`` variable is provided an if statement is created, otherwise
  436. the ternary operator is used. Note that if the ``Piecewise`` lacks a
  437. default term, represented by ``(expr, True)`` then an error will be thrown.
  438. This is to prevent generating an expression that may not evaluate to
  439. anything.
  440. >>> from sympy import Piecewise
  441. >>> expr = Piecewise((x + 1, x > 0), (x, True))
  442. >>> print(glsl_code(expr, tau))
  443. if (x > 0) {
  444. tau = x + 1;
  445. }
  446. else {
  447. tau = x;
  448. }
  449. Support for loops is provided through ``Indexed`` types. With
  450. ``contract=True`` these expressions will be turned into loops, whereas
  451. ``contract=False`` will just print the assignment expression that should be
  452. looped over:
  453. >>> from sympy import Eq, IndexedBase, Idx
  454. >>> len_y = 5
  455. >>> y = IndexedBase('y', shape=(len_y,))
  456. >>> t = IndexedBase('t', shape=(len_y,))
  457. >>> Dy = IndexedBase('Dy', shape=(len_y-1,))
  458. >>> i = Idx('i', len_y-1)
  459. >>> e=Eq(Dy[i], (y[i+1]-y[i])/(t[i+1]-t[i]))
  460. >>> glsl_code(e.rhs, assign_to=e.lhs, contract=False)
  461. 'Dy[i] = (y[i + 1] - y[i])/(t[i + 1] - t[i]);'
  462. >>> from sympy import Matrix, MatrixSymbol
  463. >>> mat = Matrix([x**2, Piecewise((x + 1, x > 0), (x, True)), sin(x)])
  464. >>> A = MatrixSymbol('A', 3, 1)
  465. >>> print(glsl_code(mat, A))
  466. A[0][0] = pow(x, 2.0);
  467. if (x > 0) {
  468. A[1][0] = x + 1;
  469. }
  470. else {
  471. A[1][0] = x;
  472. }
  473. A[2][0] = sin(x);
  474. """
  475. return GLSLPrinter(settings).doprint(expr,assign_to)
  476. def print_glsl(expr, **settings):
  477. """Prints the GLSL representation of the given expression.
  478. See GLSLPrinter init function for settings.
  479. """
  480. print(glsl_code(expr, **settings))