glsl.py 20 KB

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